diff --git a/README.md b/README.md index aef6162..62fb0bf 100644 --- a/README.md +++ b/README.md @@ -68,6 +68,12 @@ Spring Boot 不自动读取 `.env`,需要通过 shell 导入。默认 profile 数据库只保存对象键,不保存完整 URL。返回 URL 对每段路径编码,访问路径区分大小写;根目录不要填写 URL。跨环境、越界、非法路径会被拒绝。更改环境根目录后,原目录资源不能由该部署访问。 +## 实例连接规则 + +先选定最符合需求的唯一躯干,再沿接口逐层选件。interfaceType 优先确定目标类型,缺失/无效时从 child 的 LINK_ 后解析现有类别;双方 frames[].child 严格一致才连接,name 不参与匹配。每个数组元素独立占用,同款组件可复用为多个实例;明确 quantity 优先,省略时填满所需类型的可匹配接口,单次最多24个实例。汇总和替代均按实例处理。 + +后端只返回实例及接口下标的连接关系,不再计算装配矩阵;原始 urdfInfo 保留,由前端决定摆放。现有类别及默认模板不变,不新增 leg_0 或四足/六足模板。历史结果通过新消息重新生成,无需数据库迁移。 + ## 上传与接口 上传只使用 `POST /admin-api/storage/upload-signature`。新增首次传 `{}`,获得后端编码、一个上传会话令牌和 STEP / URDF 两组授权;编辑传 `componentId`;续签传原 `uploadSessionToken`。申请签名不创建组件记录。 @@ -76,9 +82,9 @@ Spring Boot 不自动读取 `.env`,需要通过 shell 导入。默认 profile 完整请求、响应及浏览器上传代码见 [后台接口文档](cadworld-adminapi/docs/admin-api.md)。 -用户端接口入参、返回和公开模型加载见 [组件匹配文档](cadworld-api/docs/api.md);文字/图片理解、SSE 与自动生成装配方案见 [前端需求联调文档](cadworld-api/docs/robot-demand-api.md)。用户端部署变量、私有附件目录与安装基准约定见 [后端接入说明](cadworld-api/docs/demand-integration.md)。需求解析需配置后端 `ARK_API_KEY`;普通用户组件接口不需要管理员身份、上传令牌或 OSS 凭证。 +用户端接口入参、返回和公开模型加载见 [组件匹配文档](cadworld-api/docs/api.md);文字/图片理解、SSE 与自动生成装配方案见 [前端需求联调文档](cadworld-api/docs/robot-demand-api.md)。用户端部署变量、私有附件目录与接口连接约定见 [后端接入说明](cadworld-api/docs/demand-integration.md)。需求解析需配置后端 `ARK_API_KEY`;普通用户组件接口不需要管理员身份、上传令牌或 OSS 凭证。 -AI 对话流程为:**文字/图片 → 理解需求 → 自动选件与装配校验 → 返回机器人方案**。发送消息后无需追问、确认或接受降级,`analysis.completed` 与状态查询直接返回 `match`。信息不足时使用默认双足模板或可辨认的部位,缺单位、冲突和不支持的要求作为未验证项保留;模型资源与安装坐标仍须有效。SSE 意外断开后任务继续执行,可查询恢复。此次流程优化复用已有五张需求表,无需调整表结构。对话拼装已收敛为 7 个接口,旧确认、重新匹配、按匹配编码查询及接受降级接口已删除;结果统一由消息事件和任务查询返回,需要刷新时发送新消息。 +AI 对话流程为:**文字/图片 → 理解需求 → 自动选件与装配校验 → 返回机器人方案**。发送消息后无需追问、确认或接受降级,`analysis.completed` 与状态查询直接返回 `match`。信息不足时使用默认双足模板或可辨认的部位,缺单位、冲突和不支持的要求作为未验证项保留;组件仍须有STEP和URDF主文件引用;安装基准、位姿和资源清单问题作为提示,不阻塞已有组合。SSE 意外断开后任务继续执行,可查询恢复。此次流程优化复用已有五张需求表,无需调整表结构。对话拼装已收敛为 7 个接口,旧确认、重新匹配、按匹配编码查询及接受降级接口已删除;结果统一由消息事件和任务查询返回,需要刷新时发送新消息。 | 路径 | 方法 | | --- | --- | diff --git a/cadworld-api/docs/api.md b/cadworld-api/docs/api.md index 2f4da6e..8543787 100644 --- a/cadworld-api/docs/api.md +++ b/cadworld-api/docs/api.md @@ -90,7 +90,7 @@ X-Request-Id: frontend-match-001 | --- | --- | --- | --- | | `userInput` | string | 否 | 最多 4000 字符,仅作上下文;后端不解析、不存储,也不覆盖结构化条件 | | `requirements` | string[] | 否 | 最多 32 个关键词,每个非空且最多 128 字符;省略/null 表示无关键词要求 | -| `requiredParts` | string[] | 是 | 非空,最多 24 项;中英文别名归一化后去重,每个角色只选一个实例;未列出躯干时自动补入唯一 `torso_0` | +| `requiredParts` | string[] | 是 | 非空,最多 24 项;中英文别名归一化后去重,组件类型去重但支持同类型多个实例;未列出躯干时自动补入唯一 `torso_0` | | `robotRequirements` | object | 否 | 整机条件,字段见下表 | | `partRequirements` | object[] | 否 | 最多 12 项;每项对应一个角色的条件,字段见下表 | @@ -114,6 +114,7 @@ X-Request-Id: frontend-match-001 | `category` | string | 是 | 组件角色,必须包含在 `requiredParts` 中(躯干固定补入);同一角色不能重复定义条件 | | `componentName` | string | 否 | 组件名称,最多 128 字符;按名称及配置同义词匹配 | | `description` | string | 否 | 描述关键词,最多 20000 字符;仅表示文本相关性 | +| `quantity` | integer | 否 | 1–24;仅接受JSON整数,省略/null表示按可匹配接口填充。躯干固定一个 | | `material` | string | 否 | 材质,最多 128 字符,例如“铝合金” | | `degreesOfFreedom` | integer | 否 | 该部件自由度,非负整数 | | `massKg` | number | 否 | 该部件质量目标,单位 kg,非负 | @@ -164,9 +165,9 @@ X-Request-Id: frontend-match-001 无法覆盖所有角色时返回躯干及可拼的连通部分;选中的躯干没有所需端口时可只返回躯干。没有可用躯干则返回 `NO_MATCH`,不会用其他角色作为根。躯干替代候选用于替换当前躯干,不追加第二个躯干。 -整机自由度和质量按选中组件字段求和,**不重复累加BOM,不从URDF再次计算**。质量为0视为未填写;只要一个组件质量未知,`totals.massKg=null`、`massComplete=false`,已知部分保存在 `knownMassKg`。不能据此宣布满足质量上限。功能命中表示元数据相关,不代表动力学验证。 +整机自由度和质量按选中实例字段求和,同款组件的每个实例分别计入,**不重复累加BOM,不从URDF再次计算**。质量为0视为未填写;只要一个组件质量未知,`totals.massKg=null`、`massComplete=false`,已知部分保存在 `knownMassKg`。不能据此宣布满足质量上限。功能命中表示元数据相关,不代表动力学验证。 -拼装候选必须同时有非空 `step_object_key` 和已上传的 URDF 主文件(非空 `urdf_main_object_key`),且 `urdfInfo` 是包含非空 `rootLink` 和 `frames` 数组的对象。仅上传 STEP 的组件可以查看详情,但不会进入默认方案或替代候选。父帧的 `interfaceType` 对应子角色,连接到子组件的 `rootLink`。结果为无环连通组合,每个端口最多使用一次。异常端口会被忽略,前端应使用返回的 `connections` 完成拼装。 +拼装候选必须同时有非空 STEP 和 URDF 主文件引用,仅上传 STEP 的组件仍只支持详情查询。接口以合法 interfaceType 决定目标 category,缺失/无效时从 child 的 LINK_ 后解析现有类别;双方 frames[].child 非空且严格相同(区分大小写)才能连接,name 不参与判断。每个数组元素为独立接口,同child的多个接口不合并,连接双方各自只能占用一次。固定躯干后优先处理最近层级的接口,先满足所需类型和明确数量,再填充其余可匹配接口,不引入未要求的类型。自动增补不应破坏本可满足的硬要求;例如质量上限或指定总自由度会约束自动填充数量。坐标、安装基准、关节类型和rootLink不作为连接资格的阻塞条件,缺失接口则返回已有连通部分。 `bomList` 和 `urdfInfo` 始终作为原始 JSON 返回,保留嵌套内容;详情里的 `urdfInfo` 也可能是其他对象或数组。接口匹配只评价元数据和连接类型,不验证机械承载或运动性能。 @@ -228,104 +229,261 @@ X-Request-Id: frontend-match-001 ```json { - "code": "OK", "message": "success", "requestId": "example-request", + "code": "OK", + "message": "success", + "requestId": "example-request", "data": { - "status": "MATCHED", "rootCategory": "torso_0", + "status": "MATCHED", + "rootCategory": "torso_0", "parts": [ { "componentCode": "CW-00000000000000000000000000000001", - "componentName": "铝合金躯干", "category": "torso_0", "description": "机器人躯干", - "material": "铝合金", "massKg": 2, "degreesOfFreedom": 0, "rotationAxis": null, - "functionDescription": "支撑", "shape": "宽躯干", "size": "中型", "torqueNm": 0, - "bomList": {"items": [{"code": "BOLT-M4", "quantity": 4}]}, + "componentName": "铝合金躯干", + "category": "torso_0", + "description": "机器人躯干", + "material": "铝合金", + "massKg": 2, + "degreesOfFreedom": 0, + "rotationAxis": null, + "functionDescription": "支撑", + "shape": "宽躯干", + "size": "中型", + "torqueNm": 0, + "bomList": { + "items": [ + { + "code": "BOLT-M4", + "quantity": 4 + } + ] + }, "urdfInfo": { - "robotName": "torso", "rootLink": "BASE", - "frames": [{ - "name": "J1", "kind": "joint", "type": "fixed", "parent": "BASE", - "child": "LINK_arm_r", "interfaceType": "arm_r", "originExplicit": true, - "xyz": [-0.1, 0.01, 0], "rpy": [0, -1.5707963267949, 0], - "axis": [0, 0, 0], "limits": {} - }] + "robotName": "torso", + "rootLink": "BASE", + "frames": [ + { + "name": "J1", + "kind": "joint", + "type": "fixed", + "parent": "BASE", + "child": "LINK_arm_r", + "interfaceType": "arm_r", + "originExplicit": true, + "xyz": [ + -0.1, + 0.01, + 0 + ], + "rpy": [ + 0, + -1.5707963267949, + 0 + ], + "axis": [ + 0, + 0, + 0 + ], + "limits": {} + } + ] }, "version": 1, "stepUrl": "https://models.example.com/cadworld/components/CW-00000000000000000000000000000001/step/batch/model.STEP", - "urdfUrl": "https://models.example.com/cadworld/components/CW-00000000000000000000000000000001/urdf/batch/robot.urdf" + "urdfUrl": "https://models.example.com/cadworld/components/CW-00000000000000000000000000000001/urdf/batch/robot.urdf", + "instanceId": "torso_0:1" }, { "componentCode": "CW-00000000000000000000000000000002", - "componentName": "右臂", "category": "arm_r", "description": "机器人右臂", - "material": "铝合金", "massKg": 1, "degreesOfFreedom": 4, "rotationAxis": null, - "functionDescription": "摆臂", "shape": "", "size": "", "torqueNm": 20, - "bomList": [{"code": "ACTUATOR", "quantity": 4}], - "urdfInfo": {"robotName": "arm", "rootLink": "ARM_BASE", "frames": []}, + "componentName": "右臂", + "category": "arm_r", + "description": "机器人右臂", + "material": "铝合金", + "massKg": 1, + "degreesOfFreedom": 4, + "rotationAxis": null, + "functionDescription": "摆臂", + "shape": "", + "size": "", + "torqueNm": 20, + "bomList": [ + { + "code": "ACTUATOR", + "quantity": 4 + } + ], + "urdfInfo": { + "robotName": "arm", + "rootLink": "ARM_BASE", + "frames": [ + { + "name": "INCOMING_arm_r", + "kind": "joint", + "type": "fixed", + "parent": "ARM_BASE", + "child": "LINK_arm_r", + "interfaceType": "arm_r", + "xyz": [ + 0, + 0, + 0 + ], + "rpy": [ + 0, + 0, + 0 + ] + } + ] + }, "version": 1, "stepUrl": "https://models.example.com/cadworld/components/CW-00000000000000000000000000000002/step/batch/model.STEP", - "urdfUrl": "https://models.example.com/cadworld/components/CW-00000000000000000000000000000002/urdf/batch/robot.urdf" + "urdfUrl": "https://models.example.com/cadworld/components/CW-00000000000000000000000000000002/urdf/batch/robot.urdf", + "instanceId": "arm_r:1" + } + ], + "connections": [ + { + "parentCategory": "torso_0", + "parentComponentCode": "CW-00000000000000000000000000000001", + "parentLink": "BASE", + "frameName": "J1", + "childCategory": "arm_r", + "childComponentCode": "CW-00000000000000000000000000000002", + "childRootLink": "ARM_BASE", + "parentInstanceId": "torso_0:1", + "childInstanceId": "arm_r:1", + "interfaceChild": "LINK_arm_r", + "parentFrameIndex": 0, + "childFrameIndex": 0 } ], - "connections": [{ - "parentCategory": "torso_0", "parentComponentCode": "CW-00000000000000000000000000000001", - "parentLink": "BASE", "frameName": "J1", "childCategory": "arm_r", - "childComponentCode": "CW-00000000000000000000000000000002", "childRootLink": "ARM_BASE", - "xyz": [-0.1, 0.01, 0], "rpy": [0, -1.5707963267949, 0] - }], "alternatives": [ - {"category": "torso_0", "items": []}, + { + "category": "torso_0", + "items": [], + "instanceId": "torso_0:1" + }, { "category": "arm_r", "items": [ { "component": { "componentCode": "CW-00000000000000000000000000000003", - "componentName": "高扭矩右臂", "category": "arm_r", "description": "机器人右臂", - "material": "铝合金", "massKg": 1.2, "degreesOfFreedom": 4, "rotationAxis": null, - "functionDescription": "摆臂", "shape": "", "size": "", "torqueNm": 25, - "bomList": [{"code": "ACTUATOR-25", "quantity": 4, "spec": {"torqueNm": 25}}], - "urdfInfo": {"robotName": "arm_v2", "rootLink": "ARM_V2_BASE", "frames": []}, + "componentName": "高扭矩右臂", + "category": "arm_r", + "description": "机器人右臂", + "material": "铝合金", + "massKg": 1.2, + "degreesOfFreedom": 4, + "rotationAxis": null, + "functionDescription": "摆臂", + "shape": "", + "size": "", + "torqueNm": 25, + "bomList": [ + { + "code": "ACTUATOR-25", + "quantity": 4, + "spec": { + "torqueNm": 25 + } + } + ], + "urdfInfo": { + "robotName": "arm_v2", + "rootLink": "ARM_V2_BASE", + "frames": [ + { + "name": "INCOMING_arm_r", + "kind": "joint", + "type": "fixed", + "parent": "ARM_V2_BASE", + "child": "LINK_arm_r", + "interfaceType": "arm_r", + "xyz": [ + 0, + 0, + 0 + ], + "rpy": [ + 0, + 0, + 0 + ] + } + ] + }, "version": 1, "stepUrl": "https://models.example.com/cadworld/components/CW-00000000000000000000000000000003/step/batch/model.STEP", - "urdfUrl": "https://models.example.com/cadworld/components/CW-00000000000000000000000000000003/urdf/batch/robot.urdf" + "urdfUrl": "https://models.example.com/cadworld/components/CW-00000000000000000000000000000003/urdf/batch/robot.urdf", + "instanceId": "arm_r:1" + }, + "connections": [ + { + "parentCategory": "torso_0", + "parentComponentCode": "CW-00000000000000000000000000000001", + "parentLink": "BASE", + "frameName": "J1", + "childCategory": "arm_r", + "childComponentCode": "CW-00000000000000000000000000000003", + "childRootLink": "ARM_V2_BASE", + "parentInstanceId": "torso_0:1", + "childInstanceId": "arm_r:1", + "interfaceChild": "LINK_arm_r", + "parentFrameIndex": 0, + "childFrameIndex": 0 + } + ], + "totals": { + "degreesOfFreedom": 4, + "massKg": 3.2, + "knownMassKg": 3.2, + "massComplete": true }, - "connections": [{ - "parentCategory": "torso_0", "parentComponentCode": "CW-00000000000000000000000000000001", - "parentLink": "BASE", "frameName": "J1", "childCategory": "arm_r", - "childComponentCode": "CW-00000000000000000000000000000003", "childRootLink": "ARM_V2_BASE", - "xyz": [-0.1, 0.01, 0], "rpy": [0, -1.5707963267949, 0] - }], - "totals": {"degreesOfFreedom": 4, "massKg": 3.2, "knownMassKg": 3.2, "massComplete": true}, "unmetRequirements": [], "unmatchedKeywords": [] } - ] + ], + "instanceId": "arm_r:1" } ], - "totals": {"degreesOfFreedom": 4, "massKg": 3, "knownMassKg": 3, "massComplete": true}, - "unmetRequirements": [], "unmatchedKeywords": [], "missingParts": [], "searchLimited": false + "totals": { + "degreesOfFreedom": 4, + "massKg": 3, + "knownMassKg": 3, + "massComplete": true + }, + "unmetRequirements": [], + "unmatchedKeywords": [], + "missingParts": [], + "searchLimited": false } } ``` +同款组件可重复出现在 parts 中,新增的 instanceId 在结果内唯一,例如 arm_r:1、arm_r:2。单次最多24个实例;数量或搜索达到上限时 searchLimited=true,仍返回已有组合。missingParts 增加 expectedQuantity、actualQuantity 和 missingQuantity,明确数量未达到时返回缺少的数量。默认方案及替代项均按实例累计质量和自由度。 + ### 4.4 连接字段 `connections[]` | 字段 | 类型 | 说明 | | --- | --- | --- | -| `parentCategory` | string | 父组件角色 | -| `parentComponentCode` | string | 父组件编码 | -| `parentLink` | string | 父组件模型内部的连接基准 link | -| `frameName` | string | 父组件用于安装的帧名称 | -| `childCategory` | string | 子组件角色 | -| `childComponentCode` | string | 子组件编码 | -| `childRootLink` | string | 子组件模型根 link | -| `xyz` | number[3] | 相对于父 `parentLink` 的平移 `[x,y,z]`,单位米 | -| `rpy` | number[3] | 相对于父 `parentLink` 的旋转 `[roll,pitch,yaw]`,单位弧度 | +| `parentInstanceId` / `childInstanceId` | string | 连接双方实例标识,格式为 category:序号,序号从1开始 | +| `parentCategory` / `childCategory` | string | 双方组件类型 | +| `parentComponentCode` / `childComponentCode` | string | 双方组件编码,同款可以在多个实例重复使用 | +| `interfaceChild` | string | 双方严格一致的 frames[].child | +| `parentFrameIndex` / `childFrameIndex` | integer | 双方各自原始 frames 数组的零起始下标 | +| `frameName` | string | 父接口原始 name,仅用于辅助定位 | +| `parentLink` / `childRootLink` | string | 原始模型信息,缺失时可为空 | -位姿不是世界坐标。示例中将右臂的 `ARM_BASE` 对齐到躯干 `BASE` 下的给定位姿。不同组件的 link 名称可能相同,应在对应组件实例内查找。 +本接口只返回连接关系,已移除连接摆放用 xyz/rpy,不计算矩阵。前端以双方实例标识和 frame 下标读取原始 urdfInfo,自行决定模型位置。同一 child 的多个接口以数组下标区分,前端不能按 child 或 componentCode 去重。 ### 4.5 替代候选 `alternatives[]` | 字段 | 类型 | 说明 | | --- | --- | --- | -| `category` | string | 当前可替换的角色 | +| `category` | string | 当前可替换的类型 | +| `instanceId` | string | 当前可替换的单个实例 | | `items` | object[] | 0 至 5 个兼容替代项,空数组表示没有提供替代组件 | | `items[].component` | object | 替代组件的完整公开数据,包括 BOM 和 URDF 信息 | | `items[].connections` | object[] | 替换后的**整套**连接,不只是该部件的局部连接 | @@ -333,9 +491,9 @@ X-Request-Id: frontend-match-001 | `items[].unmetRequirements` | object[] | 替换后的未满足条件 | | `items[].unmatchedKeywords` | string[] | 替换后的未命中关键词 | -替代组件兼容当前父组件和全部当前子组件,保持当前父子拓扑;仍可能不满足用户的材质、数值或文本要求。替换父组件时连接位姿可能改变,替换子组件时根 link 可能改变。 +替代组件兼容当前父组件和全部当前子组件,保持当前父子拓扑;仍可能不满足用户的材质、数值或文本要求。替换时重新匹配该实例关联的全部接口,双方 frame 下标或原始模型信息可能改变。 -前端选择一个替代项后,应按角色替换 `parts` 中的组件,并整体采用该项的 `connections`、`totals`、`unmetRequirements` 和 `unmatchedKeywords`。上例替换右臂后,编码变为 `CW-00000000000000000000000000000003`,根 link 变为 `ARM_V2_BASE`,整机质量变为 3.2 kg。 +前端选择一个替代项后,应按 instanceId 替换 `parts` 中的单个实例,并整体采用该项的 `connections`、`totals`、`unmetRequirements` 和 `unmatchedKeywords`。上例替换右臂后,编码变为 `CW-00000000000000000000000000000003`,根 link 变为 `ARM_V2_BASE`,整机质量变为 3.2 kg。 替代项没有独立 `status`,可根据当前 `missingParts` 和替代项的未满足条件/关键词重新展示状态。这些替代项针对本次默认方案计算;多个角色的替代项不能直接任意组合。重新请求会生成新的默认方案,当前接口没有锁定已选编码或校验多部件替换的入参。 @@ -375,7 +533,7 @@ X-Request-Id: frontend-match-001 | `missingParts.reason` | 展示含义 | | --- | --- | | `NO_COMPONENT` | 组件库没有该角色的可用组件 | -| `INVALID_ASSEMBLY_METADATA` | 有该角色的组件,但 URDF 文件或拼装信息不完整 | +| `INVALID_ASSEMBLY_METADATA` | 历史结果兼容原因;新流程不因位姿或安装基准缺失排除组件,缺少匹配接口使用 NO_COMPATIBLE_CONNECTION | | `NO_TORSO` | 有该角色的可用候选,但没有可用躯干,不能形成整机方案 | | `NO_COMPATIBLE_CONNECTION` | 有候选组件,但未找到与当前组合兼容的连接 | | `SEARCH_LIMIT` | 达到搜索限制,本次未找到可加入的组件 | @@ -444,10 +602,23 @@ X-Request-Id: frontend-match-001 { "status": "PARTIAL", "rootCategory": "torso_0", - "totals": {"degreesOfFreedom": 4, "massKg": 3, "knownMassKg": 3, "massComplete": true}, + "totals": { + "degreesOfFreedom": 4, + "massKg": 3, + "knownMassKg": 3, + "massComplete": true + }, "unmetRequirements": [], "unmatchedKeywords": [], - "missingParts": [{"category": "head_0", "reason": "NO_COMPONENT"}], + "missingParts": [ + { + "category": "head_0", + "reason": "NO_COMPONENT", + "expectedQuantity": 1, + "actualQuantity": 0, + "missingQuantity": 1 + } + ], "searchLimited": false } ``` @@ -478,12 +649,31 @@ X-Request-Id: frontend-match-001 "parts": [], "connections": [], "alternatives": [], - "totals": {"degreesOfFreedom": 0, "massKg": null, "knownMassKg": 0, "massComplete": false}, + "totals": { + "degreesOfFreedom": 0, + "massKg": null, + "knownMassKg": 0, + "massComplete": false + }, "unmetRequirements": [], - "unmatchedKeywords": ["跑步"], + "unmatchedKeywords": [ + "跑步" + ], "missingParts": [ - {"category": "torso_0", "reason": "NO_COMPONENT"}, - {"category": "arm_r", "reason": "NO_COMPONENT"} + { + "category": "torso_0", + "reason": "NO_COMPONENT", + "expectedQuantity": 1, + "actualQuantity": 0, + "missingQuantity": 1 + }, + { + "category": "arm_r", + "reason": "NO_COMPONENT", + "expectedQuantity": 1, + "actualQuantity": 0, + "missingQuantity": 1 + } ], "searchLimited": false } @@ -640,8 +830,8 @@ HTTP 200,完整响应示例: ## 7. 前端拼装与模型加载 1. 提交结构化匹配条件,读取 `data.status`;`FALLBACK`、`PARTIAL` 仍可以展示已有模型,同时展示未满足条件和缺件。 -2. 使用 `parts[].urdfUrl` 加载 URDF,用 `componentCode` 区分模型实例;需要 STEP 文件时使用 `stepUrl`。空地址不发起文件请求。 -3. 从 `rootCategory` 对应模型开始,按 `connections` 组装。在父组件实例内部查找 `parentLink`,将子 `childRootLink` 对齐到给定局部 `xyz/rpy`。不要假设连接数组已经按装配顺序排列。 +2. 使用 `parts[].urdfUrl` 加载 URDF,用 `parts[].instanceId` 区分模型实例,组件编码可重复;需要 STEP 文件时使用 `stepUrl`。空地址不发起文件请求。 +3. 从 `rootCategory` 对应模型开始,按 `connections` 组装。按双方 instanceId 与 frame 下标读取各自原始接口数据,由前端决定摆放。不要假设连接数组已经按装配顺序排列。 4. BOM 展示读取 `bomList`;关节、轴、限位等读取原始 `urdfInfo` 或已加载模型。不要重复累加 BOM 的质量和自由度。 5. 选择替代组件后,按 4.5 同时更新组件、连接、汇总及未满足项。 diff --git a/cadworld-api/docs/demand-integration.md b/cadworld-api/docs/demand-integration.md index b839441..c07e263 100644 --- a/cadworld-api/docs/demand-integration.md +++ b/cadworld-api/docs/demand-integration.md @@ -1,6 +1,6 @@ # 需求解析后端接入与部署 -已按 `/Users/edy/Downloads/robot-demand-parser-v1` 的 README、backend-handoff、protocol,以及 `index.mjs` / `mechanical-rules.mjs` 移植 Java 程序校验。自动拼装输出版本为 `multimodal-v1.2-auto-assembly`,目录版本为 `2026-10-14-auto-assembly`。原始来源作为参考保留,当前提示词与 Java 规则已调整为无追问的自动生成流程。来源文件夹保持不变,运行时不依赖 Node、React 或前端解析脚本。 +已按 `/Users/edy/Downloads/robot-demand-parser-v1` 的 README、backend-handoff、protocol,以及 `index.mjs` / `mechanical-rules.mjs` 移植 Java 程序校验。自动拼装输出版本为 `multimodal-v1.3-child-instances`,目录版本为 `2026-10-14-auto-assembly`。原始来源作为参考保留,当前提示词与 Java 规则已调整为无追问的自动生成流程。来源文件夹保持不变,运行时不依赖 Node、React 或前端解析脚本。 业务标准化另外落实躯干优先规则:整机必须且只能有一个躯干,解析时可自动补入基础躯干;明确排除躯干时保留排除项并返回无匹配方案,不追问或偷偷补入。匹配先固定最符合需求的躯干,再搜索与其连通的其他组件。 @@ -12,7 +12,7 @@ 2. 配置 MySQL、公开模型域名与 `ARK_API_KEY`。Key 仅提供给后端,缺失时其他组件接口仍可使用,需求解析返回不可用状态。 3. 为需求图片配置私有可写的持久化目录;不能映射为静态资源或挂载到公开模型目录。 4. 前端通过同站点 HTTPS 代理 `/api`;开发跨端口时配置具体前端 origin。生产 Cookie 设置 Secure。 -5. 机械在组件 `urdfInfo.assembly` 登记安装基准和配对约定;缺失时匹配仍返回组件,但装配阻塞。 +5. 对接组件实际接口:interfaceType 优先确定现有 category,双方 frames[].child 严格一致才可连接;每个 frames 元素是独立接口。无需填写 urdfInfo.assembly,模型摆放由前端处理。 ```bash mvn -pl cadworld-api,cadworld-adminapi -am test @@ -35,7 +35,6 @@ java -jar cadworld-api/target/cadworld-api-0.0.1-SNAPSHOT.jar | `APP_DEMAND_RETENTION` | `P7D`,允许 1 小时至 30 天 | | `APP_DEMAND_CONCURRENT_ANALYSES` | `4`,允许 1–16;当前进程并发上限,无等待队列 | | `APP_DEMAND_ALLOWED_ORIGINS` | `/api/**` 跨域白名单;`test` 默认 `https://dev-cadworld.robotquan.com`,`prod` 默认 `https://cadworld.robotquan.com`;可用逗号分隔的完整 origin 覆盖,显式留空关闭跨域,禁止通配符 | -| `APP_DEMAND_ROOT_IS_MOUNTING_FRAME` | `false`;本项目尚未统一根节点安装约定,保持 false | 用户端跨域支持凭证,允许 `GET / POST / DELETE / OPTIONS`,请求头允许 `Content-Type / X-Request-Id`,向前端暴露 `X-Request-Id`,预检缓存 3600 秒。浏览器请求需要携带访客 Cookie 时,使用 `credentials: 'include'`(Axios 使用 `withCredentials: true`)。公开 OSS/CDN 资源的跨域需在对应资源服务单独配置。 @@ -65,44 +64,41 @@ java -jar cadworld-api/target/cadworld-api-0.0.1-SNAPSHOT.jar 组件组合仍为 MySQL + 同义词词典 + Java 有界搜索。候选查询只扫描同时具有非空 `step_object_key` 和 `urdf_main_object_key` 的组件,只有 STEP 的组件不参与默认方案或替代候选;新增时可先仅上传 STEP,再通过管理端修改补齐 URDF 和元数据。先按躯干单件硬要求、数值差距、偏好及功能/关键词相关性固定唯一躯干;评分相同后比较所需接口覆盖及编码。整机自由度和质量在后续组合求和评价。固定躯干后优先覆盖所需角色;在同等覆盖下,硬要求差距优先于偏好。先搜索其他部件硬条件满足的候选,再提供明确说明的降级结果,两轮共用同一个躯干;不以整机总量或覆盖率更换根。 -没有可用躯干时返回无匹配结果,不再尝试其他角色为根。一个角色只对应一个实例,躯干的中英文别名也归一化到同一个角色。除作为基础部件自动补入的躯干外,不补入其他未要求的中间连接件;一个实例的数量可验证,同角色多个实例的数量要求作为未验证项保留,不追问,也不会静默去重冒充数量达标。躯干替代项只用于替换当前唯一躯干。 +没有可用躯干时返回无匹配结果,不再尝试其他角色为根。同一组件编码可生成多个独立实例,躯干仍固定一个,中英文类别别名先归一化。除作为基础部件自动补入的躯干外,不补入其他未要求的中间连接件;明确部位数量投影到 partRequirements.quantity(1–24);省略时先覆盖所需类型,再填充其可匹配剩余接口。实例标识、接口占用、替代和参数汇总均以实例为单位,不能按类别或组件编码去重。本次不增加类别或四足/六足模板。躯干替代项只用于替换当前唯一躯干。 -`complete/partial/no_match` 描述需求匹配,`assembly.ready/blocked` 只描述已有组件的安装与资源是否有效。缺件通过 `missingParts` 和 `partial` 提示,不进入 `assembly.issues`;缺件、性能不足或未验证能力不要求先接受降级,`degradationAcceptanceRequired` 固定为 false,因此 `partial` 可同时返回 `assembly.ready` 并直接显示已有有效组合。没有可用组件、躯干根不合法、安装基准缺失、坐标图或资源异常仍阻塞。仅有有效躯干时可以显示躯干,连接数组为空。 +`complete/partial/no_match` 描述需求匹配,`assembly.ready/blocked` 只描述是否有可展示组合和已生成的逻辑连接关系。缺件通过 `missingParts` 和 `partial` 提示,不进入 `assembly.issues`;缺件、性能不足或未验证能力不要求先接受降级,`degradationAcceptanceRequired` 固定为 false,因此 `partial` 可同时返回 `assembly.ready` 并直接显示已有有效组合。只有没有可用躯干/组件时才没有可展示组合;安装基准、位姿、活动关节和资源清单问题只返回提示,不阻塞已有组合。仅有有效躯干时可以显示躯干,连接数组为空。 默认组合和替代候选使用相同装配判定。兼容响应中的降级接受标记保留为 false,不提供单独接受流程;缺件、未验证能力和机械/资源问题继续保留。新生成结果不再保存只供接受流程使用的内部 `snapshot`,查询历史数据时仍移除旧快照。升级规则或组件库更新后,发送新消息生成新版本;原消息重放和状态查询不会重算。替代项是相对默认方案的一次替换预览,当前未实现多项替换的服务端验证或装配方案保存。 -## 机械安装数据 +## 接口数据与实例 -每件子组件须显式填写: +已有 category 和默认模板保持不变。接口以合法 interfaceType 确定要查找的 category,缺失或无效时从 child 的 LINK_ 后解析已有类型编码/别名;无法确定类型时不从此接口向外扩展。目标类型必须属于需求,候选还须具有严格相同(区分大小写)的 child。frame 的 name、kind、type、坐标和安装基准不参与连接资格判断。 ```json { - "robotName": "右臂", "rootLink": "ARM_ROOT", - "frames": [], - "assembly": { - "mountingFrame": "ARM_ROOT", - "pairingConvention": "coincident_frames" - } + "frames": [ + { + "name": "incoming", + "child": "LINK_arm_r", + "interfaceType": "arm_r" + } + ] } ``` -这是 `urdfInfo` 的示例;真实帧数组保留完整文件结构。`mountingFrame` 可为 root、可达 link 或 joint,含义是文件内真正的安装坐标系;`coincident_frames` 表示与父接口坐标系直接重合。管理员组件表单仍接受 JSON 对象/数组,不要求所有旧数据立刻补齐;装配校验会诊断缺失项。 +父接口也有 child=LINK_arm_r、目标类型为 arm_r 时,可以连接这件右臂。多个同 child 的 frames 元素为多个独立接口,原始数组不重排;连接双方以实例标识及 frameIndex 占用接口。先处理固定躯干的接口,再逐层扩展,先覆盖需求类型和明确数量,再在尽量满足硬要求的前提下填充其他兼容接口,避免自动增补破坏本可满足的整机参数。 -父接口优先使用 `interfaceType`;缺少时按 `LINK_` 子 link 的已知角色名推导。文件中的 `xyz/rpy` 是相对父 link 的局部原始位姿,后端沿固定关节链累积根到接口的变换。子组件根到安装帧的变换必须取逆,公式为: +结构化结果的实例标识为 category:序号;AI 外层实例标识为 matchId:category:序号,序号从1开始。connection 返回 interfaceChild 和双方 parentFrameIndex/childFrameIndex;不再返回 matrixLayout、装配矩阵或连接摆放用 xyz/rpy。完整 urdfInfo 仍返回原始 JSON,由前端解析各实例模型并定位。资源URL可缓存共享,模型实例必须独立。 -```text -T_parentRoot_childRoot = T_parentRoot_parentInterface × inverse(T_childRoot_childInterface) -``` +每次最多24个实例;达到实例、候选或搜索上限时返回已有组合、searchLimited=true和提示。资源清单仍检查路径安全,非法相对路径跳过;清单不完整只提示。部署前端时须同步切换到实例连接协议。历史快照不会迁移或重算,旧矩阵格式通过新messageId生成新方案。 -矩阵为 column-major,长度单位 m,RPY 为 rad。多个同类父接口未指定配对、循环/不可达图、缺失位姿、活动关节没有状态均阻塞,不猜测翻转角或安装位置。`originExplicit:false` 且位姿缺失时按 URDF 隐式零位姿处理。 - -公开组件同时返回完整 BOM、URDF 信息及 STEP/URDF URL,资源清单保留相对目录和版本。不存在独立用户资源代理。公开资源更新使用新上传批次路径;逻辑删除不撤销之前已发出的公开直链。图片附件为另一套私有资源,不使用公开模型地址。 +公开组件继续返回 BOM、URDF 信息及 STEP/URDF URL,资源清单保留相对目录和版本。公开资源更新使用新上传批次路径;图片附件继续使用另一套私有资源。原 APP_DEMAND_ROOT_IS_MOUNTING_FRAME 配置已移除,后台不再需要根节点安装基准开关。 ## 验证范围 自动测试使用 Java H2 表、模拟模型客户端、本地模拟 Responses HTTP 服务与测试资源域名,不调用真实付费模型、不访问业务 MySQL 或 OSS。 -保留规则包原始 Node 样例,验证四组样例的机械条件投影及证据不变。覆盖新流程无追问、证据和图片归属、单位补充、数值与冲突边界、模型拒绝/超时/异常、SSE、取消和重试、版本和幂等、硬要求/偏好、7 个接口路由及旧路由 404、历史内部快照不暴露、资源版本变化后通过新消息刷新、私有附件过期清理,以及消息自动返回装配、默认模板、图文冲突和缺单位生成、断流查询恢复、选件失败不发布结果、匹配快照保存失败时回滚解析结果、新消息使正在选件的旧任务失效、坐标累积、子安装基准取逆、端口歧义与活动关节阻塞。验证缺件时默认组件与替代候选可直接预览、仅有躯干可显示,同时保留缺件和整机总量未验证提示;机械或资源异常仍阻塞。既有管理端上传、版本控制、逻辑删除与审计测试也参加回归。 +保留规则包原始 Node 样例,验证四组样例的机械条件投影及证据不变。覆盖新流程无追问、证据和图片归属、单位补充、数值与冲突边界、模型拒绝/超时/异常、SSE、取消和重试、版本和幂等、硬要求/偏好、7 个接口路由及旧路由 404、历史内部快照不暴露、资源版本变化后通过新消息刷新、私有附件过期清理,以及消息自动返回装配、默认模板、图文冲突和缺单位生成、断流查询恢复、选件失败不发布结果、匹配快照保存失败时回滚解析结果、新消息使正在选件的旧任务失效、child严格匹配、类型优先与兜底、多个同child接口、四/六个同款实例、数量不足和上限、逐层覆盖需求、单实例替代及按实例汇总。验证缺件时默认组件与替代候选可直接预览、仅有躯干可显示,同时保留缺件和整机总量未验证提示;位姿或资源清单问题只提示,不阻塞已有组合。既有管理端上传、版本控制、逻辑删除与审计测试也参加回归。 真实图片 OCR 和多模态识别质量仍需配置实际模型后使用机械样本验收。修改提示词、Schema 或类别目录时,应同步来源版本、规则校验与一致性样例,不能只替换提示词后直接发布。 diff --git a/cadworld-api/docs/robot-demand-api.md b/cadworld-api/docs/robot-demand-api.md index 0d5dcf4..fd2b3a4 100644 --- a/cadworld-api/docs/robot-demand-api.md +++ b/cadworld-api/docs/robot-demand-api.md @@ -7,7 +7,7 @@ 1. 创建会话,保存 `conversationId`。 2. 有图片时先上传到该会话,保存 `attachmentId`;仅文字可跳过。 3. 发送消息,使用 POST + fetch 接收 SSE;后端在同一任务中完成需求理解、自动选件和装配校验。 -4. 收到 `analysis.completed`,直接读取 `data.match`。当 `match.assembly.status=ready` 时,使用 `match.components` 的资源及 `match.assembly.connections` 加载并拼装;`partial` 也可直接显示有效的已有组合。 +4. 收到 `analysis.completed`,直接读取 `data.match`。当 `match.assembly.status=ready` 时,按 `instanceId` 加载 `match.components` 的资源,再根据 `match.assembly.connections` 定位双方接口并由前端摆放;`partial` 也可直接显示有效的已有组合。 5. 简短展示 `warnings`、缺件及未满足/未验证项;不弹出追问、确认或必须接受降级的页面。`assembly.status=blocked` 或 `status=no_match` 时展示具体原因,不伪造连接位姿。 6. 用户需要调整时,在同一会话发送新消息,例如“改成右臂扭矩至少30N·m”,后端生成新版本并返回新方案。 @@ -27,6 +27,8 @@ AI 对话拼装仅保留以上 7 个接口。原 `confirm`、`rematch`、按 `matchId` 查询和 `accept-degradation` 接口已删除,访问返回 HTTP 404;前端不再调用这些接口。生成结果统一从消息完成事件或 `GET /api/robot-analyses/{analysisId}` 的 `data.match` 获取。 +正常文字生成只需调用“创建会话 → 发送消息”两个接口;图片生成再增加上传接口。预览、状态查询、重试和停止按实际交互调用。 + 既有结构化 `POST /api/robot-matches` 和公开组件详情保留,见 [组件接口文档](api.md)。本流程的状态为小写,与既有接口的 `MATCHED/FALLBACK/PARTIAL/NO_MATCH` 分开使用。 ## 2. 创建会话与上传图片 @@ -163,6 +165,8 @@ async function sendMessage(conversationId, message, onEvent, signal) { 后端发送 LF 分隔的事件,网络读取可能把一个事件拆成多块,需保留 buffer。主动停止调用 DELETE;SSE 意外断开不会取消任务,后端继续生成至完成或超时。连接中断后先 GET 查询状态,`processing` 时可间隔 1.5–2 秒查询;`ready` 时直接使用返回的 `match`;`failed/cancelled` 才提供 retry。不要重发新消息或把查询成功称为 SSE 连接恢复。SSE 开始前的校验错误使用 HTTP 错误响应;开始后模型失败通过 `analysis.failed` 通知。 +重发同一消息以恢复订阅时,已结束任务可能通过 `analysis.completed` 返回最终状态,其中也可能是 `failed`、`cancelled` 或 `superseded`。前端必须检查 `data.status`,只有 `ready` 且 `match` 非空时才进入方案展示,再根据 `match.assembly.status` 判断能否装配;不能仅凭事件名称判断生成成功。 + ### 消息完成与状态查询响应 `analysis.completed` 和 `GET /api/robot-analyses/{analysisId}` 使用同一数据结构: @@ -277,7 +281,7 @@ async function sendMessage(conversationId, message, onEvent, signal) { ] } ], - "schemaVersion": "multimodal-v1.2-auto-assembly", + "schemaVersion": "multimodal-v1.3-child-instances", "canSubmit": true, "status": "ready", "defaultTemplate": "" @@ -314,77 +318,25 @@ async function sendMessage(conversationId, message, onEvent, signal) { ], "assembly": { "status": "ready", - "rootInstanceId": "DM-33333333333333333333333333333333:torso_0", - "matrixLayout": "column-major", + "rootInstanceId": "DM-33333333333333333333333333333333:torso_0:1", "connections": [ { - "parentInstanceId": "DM-33333333333333333333333333333333:torso_0", + "parentInstanceId": "DM-33333333333333333333333333333333:torso_0:1", "parentFrame": "J_ARM", "parentLink": "BASE", - "childInstanceId": "DM-33333333333333333333333333333333:arm_r", - "childFrame": "ARM_ROOT", + "childInstanceId": "DM-33333333333333333333333333333333:arm_r:1", + "childFrame": "INCOMING_arm_r", "childRootLink": "ARM_ROOT", - "parentRootToInterface": [ - 1, - 0, - 0, - 0, - 0, - 1, - 0, - 0, - 0, - 0, - 1, - 0, - 0.1, - 0, - 0, - 1 - ], - "childRootToInterface": [ - 1, - 0, - 0, - 0, - 0, - 1, - 0, - 0, - 0, - 0, - 1, - 0, - 0, - 0, - 0, - 1 - ], - "childRootRelativeToParentRoot": [ - 1, - 0, - 0, - 0, - 0, - 1, - 0, - 0, - 0, - 0, - 1, - 0, - 0.1, - 0, - 0, - 1 - ] + "interfaceChild": "LINK_arm_r", + "parentFrameIndex": 0, + "childFrameIndex": 0 } ], "issues": [] }, "components": [ { - "instanceId": "DM-33333333333333333333333333333333:torso_0", + "instanceId": "DM-33333333333333333333333333333333:torso_0:1", "component": { "componentCode": "CW-TORSO-001", "componentName": "铝合金躯干", @@ -457,7 +409,7 @@ async function sendMessage(conversationId, message, onEvent, signal) { "resourceIssues": [] }, { - "instanceId": "DM-33333333333333333333333333333333:arm_r", + "instanceId": "DM-33333333333333333333333333333333:arm_r:1", "component": { "componentCode": "CW-ARM-001", "componentName": "标准右臂", @@ -485,7 +437,26 @@ async function sendMessage(conversationId, message, onEvent, signal) { "urdfInfo": { "robotName": "右臂", "rootLink": "ARM_ROOT", - "frames": [], + "frames": [ + { + "name": "INCOMING_arm_r", + "kind": "joint", + "type": "fixed", + "parent": "ARM_ROOT", + "child": "LINK_arm_r", + "interfaceType": "arm_r", + "xyz": [ + 0, + 0, + 0 + ], + "rpy": [ + 0, + 0, + 0 + ] + } + ], "assembly": { "mountingFrame": "ARM_ROOT", "pairingConvention": "coincident_frames" @@ -516,11 +487,13 @@ async function sendMessage(conversationId, message, onEvent, signal) { "alternatives": [ { "category": "torso_0", - "items": [] + "items": [], + "instanceId": "DM-33333333333333333333333333333333:torso_0:1" }, { "category": "arm_r", - "items": [] + "items": [], + "instanceId": "DM-33333333333333333333333333333333:arm_r:1" } ] } @@ -549,28 +522,28 @@ async function sendMessage(conversationId, message, onEvent, signal) { ## 4. 机器人方案 -消息完成事件及状态查询的 `data.match` 包含同一份已保存方案。第 3 节示例只指定右臂,后端补入一个躯干作为装配根,同时返回两件组件的资源和连接位姿。示例编码与资源域名均为演示值。 +消息完成事件及状态查询的 `data.match` 包含同一份已保存方案。第 3 节示例只指定右臂,后端补入一个躯干作为装配根,同时返回两件组件的资源和接口连接关系。示例编码与资源域名均为演示值。 | 字段 | 说明 | | --- | --- | | `status` | `complete`:所需角色齐全且硬要求已验证满足;`partial`:缺件、硬要求未满足或未验证;`no_match`:没有可用组件 | | `components[]` | 稳定实例编码 + 完整公开组件 DTO,保留原始 `bomList` 和 `urdfInfo` JSON | -| `alternatives[]` | 每个已选角色最多 5 个兼容替代项,见下文 | +| `alternatives[]` | 每个已选实例最多 5 个兼容替代项,以 `instanceId` 区分,见下文 | | `requirementChecks[]` | 对应 `intentId`,状态 `satisfied` / `unmet` / `unverified`;前端关联解析中的详细需求 | | `unmetRequirements` | 字段差距,包括偏好差距;硬要求判定以详细校验为准 | | `totals` | 组件标称参数求和;不重复统计 BOM。质量未知时 `massKg=null`,`knownMassKg` 为已知部分 | | `missingParts` | 缺失角色和原因,仅提示完整性,不阻塞已有组件装配;没有可用躯干时返回 `no_match`,其他现存角色可标记 `NO_TORSO`;仍是 HTTP 200 | | `searchLimited` | 候选或搜索被截断,本方案不是已证明的全局最优 | | `degradationAcceptanceRequired` | 新生成方案及替代候选固定为 false;缺件和未满足/未验证项作为结果说明,不要求先接受 | -| `assembly.status` | `ready`:已有组件的安装与资源校验通过,可应用返回的连接位姿;`blocked`:展示 issues,不自动拼装。与需求是否完整达标分别判断 | +| `assembly.status` | `ready`:已有连通组合可展示,连接关系已生成;位姿由前端处理,issues/resourceIssues 为提示,不阻止展示。没有可用躯干/组件时为 `blocked` | -公开组件字段与 [组件详情](api.md) 一致,不包含数据库主键和独立 OSS 对象键。`urdfMainPath` 与资源清单中的 `relativePath` 保留目录层级,使用 `resources[].url` 加载模型和 mesh。公开资源 `expiresAt=null`,不是临时签名;`version` 表示组件版本。 +公开组件字段与 [组件详情](api.md) 一致,不包含数据库主键和独立 OSS 对象键。`components[].component.rotationAxis` 和 `alternatives[].items[].component.rotationAxis` 返回 `X`、`Y`、`Z` 或 null;旋转轴非必填,null 表示组件未设置,不能默认成某个轴或覆盖 URDF 中的关节 axis。`urdfMainPath` 与资源清单中的 `relativePath` 保留目录层级,使用 `resources[].url` 加载模型和 mesh。公开资源 `expiresAt=null`,不是临时签名;`version` 表示组件版本。 ### 躯干优先规则 -拼装仅检索同时具备非空 `step_object_key` 和已上传 URDF 主文件(非空 `urdf_main_object_key`)的组件;消息自动生成和替代候选使用同一筛选规则。仅上传 STEP 的组件不会参与拼装。候选仍须满足 `urdfInfo.rootLink`、`frames` 及现有连接元数据规则,装配阶段继续校验安装基准和资源清单。 +拼装仅检索同时具备非空 `step_object_key` 和已上传 URDF 主文件(非空 `urdf_main_object_key`)的组件;消息自动生成和替代候选使用同一筛选规则。仅上传 STEP 的组件不会参与拼装。接口以合法 `interfaceType` 确定目标 category,缺失或无效时从 `child` 的 LINK_ 后解析现有类别;只连接用户需求涉及的类型,且双方原始 `frames[].child` 必须非空并严格一致(区分大小写)。`name` 不参与兼容性判断。无法识别类型或无有效 child 的接口跳过并提示,不阻塞已有组合。 -整机结果始终以 `torso_0` 为根,默认方案中的躯干只有一个。用户未单独提出躯干时,后端在规范化的 `requiredParts` 中补入 `torso_0` 并返回说明;原始对话和提取的用户条目保持其来源。明确要求“不要躯干”时保留排除项,返回 `no_match`、`missingParts.reason=EXCLUDED_TORSO`,不会偷偷补入躯干;多个同类实例要求保留为未验证项,不追问。 +整机结果始终以 `torso_0` 为根,默认方案中的躯干只有一个。用户未单独提出躯干时,后端在规范化的 `requiredParts` 中补入 `torso_0` 并返回说明;原始对话和提取的用户条目保持其来源。明确要求“不要躯干”时保留排除项,返回 `no_match`、`missingParts.reason=EXCLUDED_TORSO`,不会偷偷补入躯干;同款组件支持多个独立实例,躯干始终固定一个。 躯干先按自身硬条件、数值差距、偏好、整机功能文本与关键词相关性排序;这些条件相同后优先选择能接更多所需角色的接口集合,最后按编码稳定排序。整机自由度和质量目标在后续组合阶段评价,不直接当作躯干单件的数值要求。 @@ -578,7 +551,7 @@ async function sendMessage(conversationId, message, onEvent, signal) { ### 缺件时展示已有组合 -`status=partial` 可以同时有 `assembly.status=ready`。例如需要躯干、右臂和头部,库存只有能连接的躯干与右臂,且两件资源和安装基准有效,返回如下片段: +`status=partial` 可以同时有 `assembly.status=ready`。例如需要躯干、右臂和头部,库存只有能连接的躯干与右臂,且两件具有匹配接口,返回如下片段: ```json { @@ -589,24 +562,26 @@ async function sendMessage(conversationId, message, onEvent, signal) { "missingParts": [ { "category": "head_0", - "reason": "NO_COMPONENT" + "reason": "NO_COMPONENT", + "expectedQuantity": 1, + "actualQuantity": 0, + "missingQuantity": 1 } ], "assembly": { "status": "ready", - "rootInstanceId": "DM-33333333333333333333333333333333:torso_0", - "matrixLayout": "column-major", + "rootInstanceId": "DM-33333333333333333333333333333333:torso_0:1", "connections": [ { - "parentInstanceId": "DM-33333333333333333333333333333333:torso_0", + "parentInstanceId": "DM-33333333333333333333333333333333:torso_0:1", "parentFrame": "J_ARM", "parentLink": "BASE", - "childInstanceId": "DM-33333333333333333333333333333333:arm_r", - "childFrame": "ARM_ROOT", + "childInstanceId": "DM-33333333333333333333333333333333:arm_r:1", + "childFrame": "INCOMING_arm_r", "childRootLink": "ARM_ROOT", - "parentRootToInterface": [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 1, 0, 0, 1], - "childRootToInterface": [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1], - "childRootRelativeToParentRoot": [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 1, 0, 0, 1] + "interfaceChild": "LINK_arm_r", + "parentFrameIndex": 0, + "childFrameIndex": 0 } ], "issues": [] @@ -614,9 +589,9 @@ async function sendMessage(conversationId, message, onEvent, signal) { } ``` -前端加载 `components[]` 中已有的模型并应用上述连接,提示“缺少头部”,同时保留降级接受入口。展示模型无需先接受降级,展示不等于用户已经接受。仅有有效躯干时也可返回 `ready`,此时 `connections=[]`,前端显示躯干本身。 +前端直接加载 `components[]` 中已有的模型并应用上述连接,提示“缺少头部”,不展示降级接受入口。仅有有效躯干时也可返回 `ready`,此时 `connections=[]`,前端显示躯干本身。 -缺失角色不返回占位组件或伪造连接。`totals` 仍是已有组件的标称参数之和;所需组件未齐全时,整机总量要求仍可能为 `unverified`。替代候选遵循同一规则。没有可用躯干、安装基准缺失、连接图异常或资源清单不完整仍返回 `blocked`;新结果的 `assembly.issues` 不再包含 `MISSING_PARTS` 或 `DEGRADATION_NOT_ACCEPTED`。 +缺失角色不返回占位组件或伪造连接。`totals` 仍是已有组件的标称参数之和;所需组件未齐全时,整机总量要求仍可能为 `unverified`。替代候选遵循同一规则。只有没有可展示的躯干/组件时才返回 `blocked`;安装基准、位姿、活动关节和资源清单问题仅提示。新结果不要求 `urdfInfo.assembly`,不会因缺少 mountingFrame 而阻塞。 ### 替代项示例 @@ -651,7 +626,26 @@ async function sendMessage(conversationId, message, onEvent, signal) { "urdfInfo": { "robotName": "大扭矩右臂", "rootLink": "ARM_V2_ROOT", - "frames": [], + "frames": [ + { + "name": "INCOMING_arm_r", + "kind": "joint", + "type": "fixed", + "parent": "ARM_V2_ROOT", + "child": "LINK_arm_r", + "interfaceType": "arm_r", + "xyz": [ + 0, + 0, + 0 + ], + "rpy": [ + 0, + 0, + 0 + ] + } + ], "assembly": { "mountingFrame": "ARM_V2_ROOT", "pairingConvention": "coincident_frames" @@ -698,70 +692,18 @@ async function sendMessage(conversationId, message, onEvent, signal) { ], "assembly": { "status": "ready", - "rootInstanceId": "DM-33333333333333333333333333333333:torso_0", - "matrixLayout": "column-major", + "rootInstanceId": "DM-33333333333333333333333333333333:torso_0:1", "connections": [ { - "parentInstanceId": "DM-33333333333333333333333333333333:torso_0", + "parentInstanceId": "DM-33333333333333333333333333333333:torso_0:1", "parentFrame": "J_ARM", "parentLink": "BASE", - "childInstanceId": "DM-33333333333333333333333333333333:arm_r", - "childFrame": "ARM_V2_ROOT", + "childInstanceId": "DM-33333333333333333333333333333333:arm_r:1", + "childFrame": "INCOMING_arm_r", "childRootLink": "ARM_V2_ROOT", - "parentRootToInterface": [ - 1, - 0, - 0, - 0, - 0, - 1, - 0, - 0, - 0, - 0, - 1, - 0, - 0.1, - 0, - 0, - 1 - ], - "childRootToInterface": [ - 1, - 0, - 0, - 0, - 0, - 1, - 0, - 0, - 0, - 0, - 1, - 0, - 0, - 0, - 0, - 1 - ], - "childRootRelativeToParentRoot": [ - 1, - 0, - 0, - 0, - 0, - 1, - 0, - 0, - 0, - 0, - 1, - 0, - 0.1, - 0, - 0, - 1 - ] + "interfaceChild": "LINK_arm_r", + "parentFrameIndex": 0, + "childFrameIndex": 0 } ], "issues": [] @@ -770,97 +712,45 @@ async function sendMessage(conversationId, message, onEvent, signal) { } ``` -替代结果以当前默认方案为基准,包含重新计算的汇总、校验和装配信息。前端切换时替换对应实例的组件与资源并应用该替代项的连接信息。躯干替代项表示替换当前唯一躯干,不能作为第二个躯干追加。多个替代项同时切换不能直接叠加各自预览;当前没有多项替换后的服务端校验/方案保存接口,降级接受接口仅针对服务器保存的默认方案。 +替代结果以当前默认方案为基准,包含重新计算的汇总、校验和装配信息。前端切换时按候选组 instanceId 替换对应实例的组件与资源并应用该替代项的连接信息。躯干替代项表示替换当前唯一躯干,不能作为第二个躯干追加。多个替代项同时切换不能直接叠加各自预览;当前没有多项替换后的服务端校验或方案保存接口。需要重新生成方案时,在同一会话发送新的用户消息。 -## 5. 装配连接与加载 +## 5. 实例、接口连接与加载 -`assembly.connections[]` 示例(属于躯干 + 右臂方案): +同一 `componentCode` 可以出现多次,表示同款组件的不同实例。AI 实例标识格式为 `{matchId}:{category}:{序号}`,序号从 1 开始;前端必须使用外层 `components[].instanceId` 区分模型,不能按组件编码去重。组件 DTO 中不嵌套短实例标识。 + +明确数量优先:例如“拼一个躯干和4个右臂”,归一化 `partRequirements` 中的对应项为 `{"category":"arm_r","quantity":4}`。quantity 为 1–24 的 JSON 整数;省略或为 null 表示先覆盖各个所需类型,再填满这些类型的可匹配剩余接口。自动填充以可验证的硬要求为前提,不为多装组件而破坏本可满足的整机质量或自由度条件;明确数量不足或硬条件无法满足时保留差异。每个物理接口只能连接一个实例;同 child 的多个 frames 元素是不同接口,不合并。本次沿用已有 category 和模板,不新增 leg_0 或四足/六足模板。 + +`missingParts[]` 增加 `expectedQuantity`、`actualQuantity`、`missingQuantity`。明确要求4件但只能连接2件时返回缺少2件;接口不足沿用 `NO_COMPATIBLE_CONNECTION`。单次最多24个实例,达到实例、候选或搜索上限时 `searchLimited=true`,保留已有组合并提示。 + +`assembly.connections[]` 示例: ```json { - "parentInstanceId": "DM-33333333333333333333333333333333:torso_0", + "parentInstanceId": "DM-33333333333333333333333333333333:torso_0:1", "parentFrame": "J_ARM", - "parentLink": "MID", - "childInstanceId": "DM-33333333333333333333333333333333:arm_r", - "childFrame": "MOUNT", + "parentLink": "BASE", + "childInstanceId": "DM-33333333333333333333333333333333:arm_r:1", + "childFrame": "INCOMING_arm_r", "childRootLink": "ARM_ROOT", - "parentRootToInterface": [ - 1, - 0, - 0, - 0, - 0, - 1, - 0, - 0, - 0, - 0, - 1, - 0, - 0.1, - 0, - 0, - 1 - ], - "childRootToInterface": [ - 1, - 0, - 0, - 0, - 0, - 1, - 0, - 0, - 0, - 0, - 1, - 0, - 0.02, - 0, - 0, - 1 - ], - "childRootRelativeToParentRoot": [ - 1, - 0, - 0, - 0, - 0, - 1, - 0, - 0, - 0, - 0, - 1, - 0, - 0.08, - 0, - 0, - 1 - ] + "interfaceChild": "LINK_arm_r", + "parentFrameIndex": 0, + "childFrameIndex": 0 } ``` -矩阵为 16 个数字,column-major,位移单位 m,角度来源为 rad。`childRootRelativeToParentRoot` 是子组件 root 相对父组件 root 的变换;父接口可能位于中间 link,后端已累积路径,不能再次叠加帧原始 xyz/rpy。前端世界变换为 `父组件世界矩阵 × childRootRelativeToParentRoot`。 +`parentFrameIndex`、`childFrameIndex` 是双方各自原始 `urdfInfo.frames` 数组的零起始下标。双方该下标的 child 均等于 `interfaceChild`。frame 名称、root/link 名称仅辅助定位,缺失时允许为空/null;稳定定位应使用实例标识及数组下标。 -`parentRootToInterface`、`childRootToInterface` 分别是两件组件自身根到安装接口的矩阵;连接计算遵循 `父根到接口 × inverse(子根到接口)`。`childFrame` 可以是指定 link 或 joint,`childRootLink` 保留文件原名。 +后端只返回连接关系,不返回 `matrixLayout`、三种装配矩阵或连接摆放用的 xyz/rpy。前端加载每个实例的 URDF 后,根据双方原始 frames 或模型信息决定摆放。原始 `urdfInfo` 中已有的 xyz/rpy、axis、limits 等仍完整保留。旧的 `urdfInfo.assembly` 可以存在,但不参与连接资格判断。 -每件子组件通过 `urdfInfo.assembly` 明确基准: +缺失安装基准、位姿异常、活动关节或资源清单问题均通过 `assembly.issues` / `resourceIssues` 提示,已有组合仍可为 ready。ready 表示逻辑连接关系已生成,不证明安装坐标、承载或运动能力通过验证。 -```json -{ - "mountingFrame": "ARM_ROOT", - "pairingConvention": "coincident_frames" -} -``` +替代候选组包含目标 `instanceId`;仅替换对应实例,应用该候选返回的完整 assembly、totals 和校验结果。多个同类型实例分别有替代组,不按 category 整批替换;多个替代预览不能直接叠加。 -此对象嵌在 `urdfInfo.assembly` 中,安装帧须存在于文件图中。前端不根据草图生成机械坐标。缺少基准、多个同类父接口未配对、连接图异常、活动关节缺状态、资源清单不完整等都会返回 `assembly.status=blocked`。 - -加载模型时保留 URDF 相对路径目录;不要只取文件名,否则 `meshes/...` 引用会失效。OSS/CDN 须允许前端 CORS,组件资源直接加载公开 URL;用户需求图片走私有预览接口,不能复用模型公开域名。 +加载模型时保留 URDF 相对路径目录;OSS/CDN 须允许前端 CORS。每个实例都独立摆放,资源 URL 可以复用或缓存;用户需求图片继续使用需要 Cookie 的私有预览接口。 ## 6. 结果刷新与错误 -已保存方案是本次生成时的快照。调整需求、组件版本变化、补齐资源或需要重新选件时,在同一会话发送新的 `messageId`,例如“按原需求重新生成”,后端重新理解当前有效需求并生成新方案。旧版本查询返回 `superseded`,不会继续返回旧 `match`。重发原消息编号仅恢复原任务或结果,不触发刷新。 +已保存方案是本次生成时的快照;本次升级不回写历史结果,旧矩阵格式或旧阻塞状态需要发送新 messageId 重新生成。调整需求、组件版本变化、补齐资源或需要重新选件时,在同一会话发送新的 `messageId`,例如“按原需求重新生成”,后端重新理解当前有效需求并生成新方案。旧版本查询返回 `superseded`,不会继续返回旧 `match`。重发原消息编号仅恢复原任务或结果,不触发刷新。 `retry` 只用于失败或已停止的当前任务;`processing` 时查询或重订阅原消息,`ready` 时直接显示结果。部分方案无需接受降级;`degradationAcceptanceRequired`、`degradationAccepted` 为兼容字段,新生成结果均为 false。安装基准、坐标或资源异常仍通过 `assembly.issues` 返回,不把未满足或未验证的需求标成已达标。 @@ -880,9 +770,9 @@ async function sendMessage(conversationId, message, onEvent, signal) { | 422 `INVALID_REQUEST` / `DEMAND_INPUT_TOO_LARGE` | 修正输入或新建会话 | | 404 `DEMAND_NOT_FOUND` | 无记录、已过期或不属于当前访客;新建会话 | | 409 `DEMAND_REVISION_CONFLICT` | 查询最新生成结果并使用其版本;重复消息编号内容须一致 | -| 409 `COMPONENT_REVISION_CONFLICT` | 组件已变化,发送新消息重新生成 | +| SSE `COMPONENT_REVISION_CONFLICT` | 生成期间组件已变化,发送新消息重新生成 | | 409 `DEMAND_ATTACHMENT_MISSING` | 原图已失效,重新上传并发送新消息 | -| 429 `DEMAND_BUSY` | 暂无解析容量;查询状态后稍后 retry | +| 429 `DEMAND_BUSY` | 暂无解析容量;已有 `analysisId` 时查询状态后稍后 retry,未取得编码时用原 `messageId` 和原内容重发取得任务状态,再按返回编码重试 | | 503 `DEMAND_UNAVAILABLE` / `DEMAND_ATTACHMENT_UNAVAILABLE` | 暂不可用,稍后 retry 或重传 | | SSE `DEMAND_TIMEOUT` / `DEMAND_PROVIDER_FAILURE` / `DEMAND_INCOMPLETE` / `DEMAND_INVALID_OUTPUT` | 生成失败且没有可用新方案,可重试 | | SSE `DEMAND_CANCELLED` | 已停止;当前版本可 retry | diff --git a/cadworld-api/src/main/java/com/linkerbot/cadworld/api/config/DemandConfiguration.java b/cadworld-api/src/main/java/com/linkerbot/cadworld/api/config/DemandConfiguration.java index c6d91b2..9011f0c 100644 --- a/cadworld-api/src/main/java/com/linkerbot/cadworld/api/config/DemandConfiguration.java +++ b/cadworld-api/src/main/java/com/linkerbot/cadworld/api/config/DemandConfiguration.java @@ -43,7 +43,7 @@ public class DemandConfiguration { DemandNormalizer normalizer, DemandMatchService matches, DemandProperties properties) { return new DemandAnalysisService(repository, attachments, model, normalizer, matches, properties); } - @Bean DemandAssemblyValidator demandAssemblyValidator(DemandProperties properties) { return new DemandAssemblyValidator(properties); } + @Bean DemandAssemblyValidator demandAssemblyValidator() { return new DemandAssemblyValidator(); } @Bean DemandRequirementChecker demandRequirementChecker(ObjectMapper json, MatchTextService text) { return new DemandRequirementChecker(json, text); } @Bean DemandMatchService demandMatchService(ObjectMapper json, RobotMatchingService matching, ComponentMapper mapper, ObjectStorageUrlResolver urls, DemandAssemblyValidator assembly, DemandRequirementChecker requirements) { diff --git a/cadworld-api/src/main/resources/application.yml b/cadworld-api/src/main/resources/application.yml index d91dda9..16821af 100644 --- a/cadworld-api/src/main/resources/application.yml +++ b/cadworld-api/src/main/resources/application.yml @@ -34,8 +34,6 @@ app: retention: ${APP_DEMAND_RETENTION:P7D} concurrent-analyses: ${APP_DEMAND_CONCURRENT_ANALYSES:4} allowed-origins: ${APP_DEMAND_ALLOWED_ORIGINS:} - # 仅在机械明确所有子组件根节点就是安装基准时启用;否则使用 urdfInfo.assembly。 - root-is-mounting-frame: ${APP_DEMAND_ROOT_IS_MOUNTING_FRAME:false} storage: # 配置公开 OSS/CDN 域名,不能填管理端下载代理地址;对象键已包含环境根目录。 public-base-url: ${APP_STORAGE_PUBLIC_BASE_URL:} diff --git a/cadworld-api/src/test/java/com/linkerbot/cadworld/api/DemandFlowApiTest.java b/cadworld-api/src/test/java/com/linkerbot/cadworld/api/DemandFlowApiTest.java index ad62551..28d68e9 100644 --- a/cadworld-api/src/test/java/com/linkerbot/cadworld/api/DemandFlowApiTest.java +++ b/cadworld-api/src/test/java/com/linkerbot/cadworld/api/DemandFlowApiTest.java @@ -57,7 +57,7 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers. "app.storage.public-base-url=https://models.example.test", "logging.file.path=target/test-logs", "logging.level.com.linkerbot.cadworld=INFO", "app.demand.allowed-origins=http://localhost:5173" }) -@AutoConfigureMockMvc +@AutoConfigureMockMvc(print = org.springframework.boot.test.autoconfigure.web.servlet.MockMvcPrint.NONE) class DemandFlowApiTest { private static final String TEXT = "我要机器人躯干和右臂,整体4自由度,质量不超过4kg,右臂扭矩至少20N·m"; private static final Path DIRECTORY = directory(); @@ -161,7 +161,7 @@ class DemandFlowApiTest { for (JsonNode check : match.path("requirementChecks")) assertThat(check.path("status").asText()).isEqualTo("satisfied"); assertThat(match.path("components").get(0).path("component").path("bomList").path("nested").path("parts").get(0).asText()).isEqualTo("BOLT"); assertThat(match.path("components").get(0).path("resources")).hasSize(2); - assertThat(match.path("assembly").path("connections").get(0).path("childRootRelativeToParentRoot").get(12).asDouble()).isEqualTo(1); + assertThat(match.path("assembly").path("connections").get(0).path("interfaceChild").asText()).isEqualTo("LINK_arm_r"); String body = match.toString(); for (String field : List.of("\"id\"", "urdfPrefix", "urdfMainObjectKey", "ownerHash", "snapshot", "model_version", "thinking", "apiKey")) assertThat(body).doesNotContain(field); JsonNode alternate = match.path("alternatives").get(1).path("items").get(0); @@ -178,6 +178,37 @@ class DemandFlowApiTest { .andExpect(jsonPath("$.data.match.snapshot").doesNotExist()); } + @ParameterizedTest + @org.junit.jupiter.params.provider.ValueSource(ints = {4, 6}) + void quantityIntentGeneratesRepeatedInstancesAndConnectionOnlyResults(int count) throws Exception { + components(false, 20); + ObjectNode info = (ObjectNode) json.readTree(jdbc.queryForObject("SELECT urdf_info FROM component WHERE component_code='CW-TORSO'", String.class)); + JsonNode port = info.path("frames").get(0).deepCopy(); + for (int index = 1; index < count; index++) info.withArray("frames").add(port.deepCopy()); + jdbc.update("UPDATE component SET urdf_info=? WHERE component_code='CW-TORSO'", info.toString()); + doAnswer(invocation -> { + ObjectNode raw = raw(invocation.getArgument(0)); + raw.putArray("constraints"); raw.putArray("intentItems"); + intent(raw, "quantity", "右臂", count + "个右臂"); + return raw; + }).when(model).analyze(anyList()); + Session session = create(); + JsonNode generated = submit(session, "m-copies", "拼一个躯干和" + count + "个右臂", List.of()); + JsonNode match = generated.path("match"); + assertThat(generated.path("questions")).isEmpty(); + assertThat(generated.path("result").path("request").path("partRequirements").get(0).path("quantity").asInt()).isEqualTo(count); + assertThat(match.path("components")).hasSize(count + 1); + assertThat(match.path("assembly").path("status").asText()).isEqualTo("ready"); + assertThat(match.path("assembly").path("connections")).hasSize(count); + assertThat(match.path("requirementChecks").get(0).path("actual").asInt()).isEqualTo(count); + assertThat(match.path("requirementChecks").get(0).path("status").asText()).isEqualTo("satisfied"); + assertThat(match.path("components").findValuesAsText("instanceId")).doesNotHaveDuplicates(); + assertThat(match.path("assembly").has("matrixLayout")).isFalse(); + assertThat(match.path("assembly").path("connections").get(0).has("childRootRelativeToParentRoot")).isFalse(); + assertThat(match.path("totals").path("degreesOfFreedom").asInt()).isEqualTo(4 * count); + assertThat(generatedMatch(session, generated.path("analysisId").asText(), 1)).isEqualTo(match); + } + @Test void unspecifiedFormGeneratesDefaultRobotWithoutQuestionsOrInventedParameters() throws Exception { components(true, 20); doAnswer(invocation -> { @@ -415,7 +446,7 @@ class DemandFlowApiTest { assertThat(result.path("degradationAcceptanceRequired").asBoolean()).isFalse(); assertThat(result.path("assembly").path("status").asText()).isEqualTo("ready"); assertThat(result.path("assembly").path("issues")).isEmpty(); - assertThat(result.path("assembly").path("connections").get(0).path("parentInstanceId").asText()).endsWith(":torso_0"); + assertThat(result.path("assembly").path("connections").get(0).path("parentInstanceId").asText()).endsWith(":torso_0:1"); } @Test void missingPartsAllowImmediateAssemblyIncludingAlternatives() throws Exception { @@ -441,7 +472,7 @@ class DemandFlowApiTest { assertThat(result.path("assembly").path("status").asText()).isEqualTo("ready"); assertThat(result.path("assembly").path("issues")).isEmpty(); assertThat(result.path("assembly").path("connections")).hasSize(1); - assertThat(result.path("assembly").path("connections").get(0).path("childRootRelativeToParentRoot")).hasSize(16); + assertThat(result.path("assembly").path("connections").get(0).has("childRootRelativeToParentRoot")).isFalse(); JsonNode alternative = result.path("alternatives").get(1).path("items").get(0); assertThat(alternative.path("degradationAcceptanceRequired").asBoolean()).isFalse(); assertThat(alternative.path("assembly").path("status").asText()).isEqualTo("ready"); @@ -456,9 +487,22 @@ class DemandFlowApiTest { JsonNode invalidResources = submit(session, "m2", TEXT + ",还需要头部", List.of()).path("match"); assertThat(invalidResources.path("status").asText()).isEqualTo("partial"); assertThat(invalidResources.path("missingParts")).isEqualTo(result.path("missingParts")); - assertThat(invalidResources.path("assembly").path("status").asText()).isEqualTo("blocked"); + assertThat(invalidResources.path("assembly").path("status").asText()).isEqualTo("ready"); assertThat(invalidResources.path("assembly").path("issues").findValuesAsText("code")).containsExactly("INCOMPLETE_RESOURCE_MANIFEST"); - assertThat(invalidResources.path("alternatives").get(1).path("items").get(0).path("assembly").path("status").asText()).isEqualTo("blocked"); + assertThat(invalidResources.path("alternatives").get(1).path("items").get(0).path("assembly").path("status").asText()).isEqualTo("ready"); + } + + @Test void unsafeResourceEntriesAreSkippedWithoutBlockingConnectedInstances() throws Exception { + components(false, 20); + jdbc.update("UPDATE component SET urdf_files=? WHERE component_code='CW-ARM'", + "[{\"relativePath\":\"../private.stl\"},{\"relativePath\":\"/absolute.stl\"},{\"relativePath\":\"https://invalid.example/model.stl\"},{\"relativePath\":\"meshes/safe.stl\"}]"); + JsonNode match = submit(create(), "m-safe-resources", TEXT, List.of()).path("match"); + assertThat(match.path("assembly").path("status").asText()).isEqualTo("ready"); + assertThat(match.path("assembly").path("connections")).hasSize(1); + assertThat(match.path("components").get(1).path("resources").findValuesAsText("relativePath")) + .containsExactly("meshes/safe.stl", "robot.urdf"); + assertThat(match.path("components").get(1).path("resources").toString()).doesNotContain("private.stl", "absolute.stl", "invalid.example"); + assertThat(match.path("components").get(1).path("resourceIssues").findValuesAsText("code")).contains("INVALID_RESOURCE_PATH"); } @Test void onlyTorsoCanBeDisplayedWhenAllRequestedChildPartsAreMissing() throws Exception { @@ -471,7 +515,7 @@ class DemandFlowApiTest { assertThat(result.path("components")).hasSize(1); assertThat(result.path("degradationAcceptanceRequired").asBoolean()).isFalse(); assertThat(result.path("assembly").path("status").asText()).isEqualTo("ready"); - assertThat(result.path("assembly").path("rootInstanceId").asText()).endsWith(":torso_0"); + assertThat(result.path("assembly").path("rootInstanceId").asText()).endsWith(":torso_0:1"); assertThat(result.path("assembly").path("connections")).isEmpty(); assertThat(result.path("assembly").path("issues")).isEmpty(); } @@ -485,11 +529,11 @@ class DemandFlowApiTest { jdbc.update("UPDATE component SET urdf_files='[]'"); JsonNode refreshed = submit(session, "m2", TEXT, List.of()).path("match"); assertThat(refreshed.path("components")).hasSize(2); - assertThat(refreshed.path("assembly").path("status").asText()).isEqualTo("blocked"); + assertThat(refreshed.path("assembly").path("status").asText()).isEqualTo("ready"); assertThat(refreshed.path("assembly").path("issues").findValuesAsText("code")).contains("INCOMPLETE_RESOURCE_MANIFEST"); } - @Test void unsupportedQuantitiesReturnPartialAssemblyWithoutQuestions() throws Exception { + @Test void insufficientPortsReportMissingQuantityWithoutQuestions() throws Exception { components(true, 20); doAnswer(invocation -> { List history = invocation.getArgument(0); @@ -508,7 +552,8 @@ class DemandFlowApiTest { assertThat(unsupported.path("questions")).isEmpty(); assertThat(unsupported.path("match").path("status").asText()).isEqualTo("partial"); assertThat(unsupported.path("match").path("assembly").path("status").asText()).isEqualTo("ready"); - assertThat(unsupported.path("match").path("requirementChecks").get(3).path("status").asText()).isEqualTo("unverified"); + assertThat(unsupported.path("match").path("requirementChecks").get(3).path("status").asText()).isEqualTo("unmet"); + assertThat(unsupported.path("match").path("missingParts").get(0).path("missingQuantity").asInt()).isEqualTo(1); } @Test void expiredConversationsCleanOnlyOwnedDemandRowsAndPrivateFiles() throws Exception { @@ -653,8 +698,8 @@ class DemandFlowApiTest { assertThat(result.path("status").asText()).isEqualTo("partial"); assertThat(result.path("degradationAcceptanceRequired").asBoolean()).isFalse(); assertThat(result.path("requirementChecks").get(3).path("status").asText()).isEqualTo("unverified"); - assertThat(result.path("assembly").path("status").asText()).isEqualTo("blocked"); - assertThat(result.path("assembly").path("issues").toString()).contains("MISSING_MOUNTING_REFERENCE").doesNotContain("DEGRADATION_NOT_ACCEPTED"); + assertThat(result.path("assembly").path("status").asText()).isEqualTo("ready"); + assertThat(result.path("assembly").path("issues").toString()).doesNotContain("MISSING_MOUNTING_REFERENCE", "DEGRADATION_NOT_ACCEPTED"); assertThat(result.path("snapshot").isMissingNode()).isTrue(); } @@ -748,6 +793,11 @@ class DemandFlowApiTest { ObjectNode frame = info.withArray("frames").addObject().put("name", "J_ARM").put("kind", "joint").put("type", "fixed").put("parent", "BASE").put("child", "LINK_arm_r").put("interfaceType", "arm_r").put("originExplicit", true); frame.putArray("xyz").add(1).add(0).add(0); frame.putArray("rpy").add(0).add(0).add(0); frame.putArray("axis").add(0).add(0).add(0); frame.putObject("limits"); } + if (!"torso_0".equals(category)) { + ObjectNode incoming = info.withArray("frames").addObject().put("name", "INCOMING").put("kind", "joint").put("type", "revolute") + .put("parent", root).put("child", "LINK_" + category).put("interfaceType", category); + incoming.putArray("xyz").add(0).add(0).add(0); incoming.putArray("rpy").add(0).add(0).add(0); + } if (mount) info.putObject("assembly").put("mountingFrame", root).put("pairingConvention", "coincident_frames"); String prefix = "cadworld/components/" + code + "/urdf/batch/"; jdbc.update("INSERT INTO component (component_code,component_name,category,description,mass_kg,degrees_of_freedom,torque_nm,bom_list,urdf_info,step_object_key,urdf_prefix,urdf_main_object_key,urdf_files) VALUES (?,?,?,'机器人',?,?,?,?,?,?,?,?,?)", diff --git a/cadworld-api/src/test/java/com/linkerbot/cadworld/api/MatchingApiTest.java b/cadworld-api/src/test/java/com/linkerbot/cadworld/api/MatchingApiTest.java index af795e5..e3c226b 100644 --- a/cadworld-api/src/test/java/com/linkerbot/cadworld/api/MatchingApiTest.java +++ b/cadworld-api/src/test/java/com/linkerbot/cadworld/api/MatchingApiTest.java @@ -154,7 +154,9 @@ class MatchingApiTest { MvcResult detail = mvc.perform(get("/api/components/CW-A").header("X-Request-Id", "matching-detail")) .andExpect(status().isOk()).andExpect(jsonPath("$.requestId").value("matching-detail")).andReturn(); JsonNode publicDetail = json.readTree(detail.getResponse().getContentAsString()).path("data"); - assertThat(publicDetail).isEqualTo(selected); + com.fasterxml.jackson.databind.node.ObjectNode expectedDetail = selected.deepCopy(); + expectedDetail.remove("instanceId"); + assertThat(publicDetail).isEqualTo(expectedDetail); assertPublic(publicDetail); Long id = jdbc.queryForObject("SELECT id FROM component WHERE component_code='CW-A'", Long.class); mvc.perform(get("/api/components/" + id)).andExpect(status().isNotFound()); @@ -172,8 +174,8 @@ class MatchingApiTest { assertThat(component.get("urdfInfo")).isEqualTo(info); assertPublic(component); JsonNode result = match(request("torso_0")); - assertThat(result.path("status").asText()).isEqualTo("NO_MATCH"); - assertThat(result.path("missingParts").get(0).path("reason").asText()).isEqualTo("INVALID_ASSEMBLY_METADATA"); + assertThat(result.path("status").asText()).isEqualTo("MATCHED"); + assertThat(result.path("parts")).hasSize(1); } @Test @@ -341,7 +343,7 @@ class MatchingApiTest { assertThat(torsoItems.size()).isEqualTo(1); JsonNode replacement = torsoItems.get(0); assertThat(replacement.path("component").path("componentCode").asText()).isEqualTo("CW-B"); - assertThat(replacement.path("connections").get(0).path("xyz")).isEqualTo(json.readTree("[2,3,4]")); + assertThat(replacement.path("connections").get(0).has("xyz")).isFalse(); assertThat(replacement.path("connections").get(0).path("parentLink").asText()).isEqualTo("BASE_B"); assertThat(replacement.path("totals").path("massKg").decimalValue()).isEqualByComparingTo("4"); assertThat(replacement.path("unmetRequirements").size()).isEqualTo(2); @@ -352,18 +354,19 @@ class MatchingApiTest { void ignoresInvalidAndDuplicatePortsWithoutChangingReturnedMetadata() throws Exception { JsonNode metadata = json.readTree(""" {"rootLink":"BASE","frames":[ - {"name":"duplicate","kind":"joint","type":"fixed","parent":"BASE","child":"A","interfaceType":"arm_r","xyz":[0,0,0],"rpy":[0,0,0]}, - {"name":"duplicate","kind":"joint","type":"fixed","parent":"BASE","child":"B","interfaceType":"arm_r","xyz":[0,0,0],"rpy":[0,0,0]}, + {"name":"duplicate","kind":"joint","type":"fixed","parent":"BASE","child":"LINK_arm_r","interfaceType":"arm_r","xyz":[0,0,0],"rpy":[0,0,0]}, + {"name":"duplicate","kind":"joint","type":"fixed","parent":"BASE","child":"LINK_arm_r","interfaceType":"arm_r","xyz":[0,0,0],"rpy":[0,0,0]}, {"name":"bad_pose","kind":"joint","type":"fixed","parent":"BASE","child":"C","interfaceType":"head_0","xyz":[0,0],"rpy":[0,0,0]}, - {"name":"implicit","kind":"joint","type":"fixed","parent":"BASE","child":"D","interfaceType":"hand_r","originExplicit":false} + {"name":"implicit","kind":"joint","type":"fixed","parent":"BASE","child":"LINK_hand_r","interfaceType":"hand_r","originExplicit":false} ]} """); save("CW-T", "torso_0", 0, "1", "0", "", metadata, json.readTree("[]")); save("CW-R", "arm_r", 1, "1", "0", ""); save("CW-H", "hand_r", 1, "1", "0", ""); JsonNode result = match(request("torso_0", "arm_r", "hand_r")); - assertThat(result.path("parts").size()).isEqualTo(2); - assertThat(result.path("connections").get(0).path("xyz")).isEqualTo(json.readTree("[0,0,0]")); + assertThat(result.path("parts")).hasSize(4); + assertThat(result.path("connections")).hasSize(3); + assertThat(result.path("connections").get(0).has("xyz")).isFalse(); assertThat(part(result, "torso_0").get("urdfInfo")).isEqualTo(metadata); } @@ -516,6 +519,144 @@ class MatchingApiTest { } } + @ParameterizedTest + @org.junit.jupiter.params.provider.ValueSource(ints = {4, 6}) + void sameComponentFillsEachPhysicalInterfaceAndAlternativesTargetOneInstance(int count) throws Exception { + String[] ports = java.util.Collections.nCopies(count, "arm_r").toArray(String[]::new); + save("CW-T", "torso_0", 0, "1", "0", "", metadata("BASE", ports), json.readTree("[]")); + save("CW-ARM", "arm_r", 1, "1", "10", ""); + save("CW-ARM-ALT", "arm_r", 1, "2", "10", ""); + JsonNode result = match(request("arm_r")); + assertThat(result.path("parts")).hasSize(count + 1); + assertThat(result.path("connections")).hasSize(count); + List instances = new ArrayList<>(); + for (JsonNode component : result.path("parts")) { + instances.add(component.path("instanceId").asText()); + if ("arm_r".equals(component.path("category").asText())) assertThat(component.path("componentCode").asText()).isEqualTo("CW-ARM"); + } + assertThat(instances).doesNotHaveDuplicates(); + assertThat(result.path("totals").path("degreesOfFreedom").asInt()).isEqualTo(count); + assertThat(result.path("totals").path("massKg").decimalValue()).isEqualByComparingTo(Integer.toString(count + 1)); + List indexes = new ArrayList<>(); + for (JsonNode edge : result.path("connections")) { + indexes.add(edge.path("parentFrameIndex").asInt()); + assertThat(edge.path("interfaceChild").asText()).isEqualTo("LINK_arm_r"); + assertThat(edge.path("childFrameIndex").asInt()).isZero(); + assertThat(edge.has("xyz")).isFalse(); + } + assertThat(indexes).doesNotHaveDuplicates(); + JsonNode group = result.path("alternatives").get(1); + assertThat(group.path("instanceId").asText()).isEqualTo("arm_r:1"); + JsonNode replacement = group.path("items").get(0); + assertThat(replacement.path("component").path("instanceId").asText()).isEqualTo("arm_r:1"); + assertThat(replacement.path("totals").path("massKg").decimalValue()).isEqualByComparingTo(Integer.toString(count + 2)); + assertThat(replacement.path("connections").findValuesAsText("childComponentCode")).filteredOn((String code) -> code.equals("CW-ARM-ALT")).hasSize(1); + } + + @Test void explicitQuantityCapsCopiesAndReportsInsufficientPorts() throws Exception { + save("CW-T", "torso_0", 0, "1", "0", "", metadata("BASE", "arm_r", "arm_r", "arm_r", "arm_r"), json.readTree("[]")); + save("CW-A", "arm_r", 1, "1", "0", ""); + Map body = new LinkedHashMap<>(request("arm_r")); + body.put("partRequirements", List.of(Map.of("category", "arm_r", "quantity", 2))); + assertThat(match(body).path("parts")).hasSize(3); + body.put("partRequirements", List.of(Map.of("category", "arm_r", "quantity", 6))); + JsonNode result = match(body); + assertThat(result.path("parts")).hasSize(5); + assertThat(result.path("missingParts").get(0).path("expectedQuantity").asInt()).isEqualTo(6); + assertThat(result.path("missingParts").get(0).path("actualQuantity").asInt()).isEqualTo(4); + assertThat(result.path("missingParts").get(0).path("missingQuantity").asInt()).isEqualTo(2); + } + + @Test void matchingUsesChildAndInterfaceTypeWithFallbackRegardlessOfNamesOrPoses() throws Exception { + save("CW-T", "torso_0", 0, "1", "0", "", metadata("BASE", "head_0"), json.readTree("[]")); + save("CW-A", "arm_r", 0, "1", "0", ""); + save("CW-H", "head_0", 0, "1", "0", ""); + com.fasterxml.jackson.databind.node.ObjectNode torso = (com.fasterxml.jackson.databind.node.ObjectNode) components.get("CW-T").urdfInfo(); + com.fasterxml.jackson.databind.node.ObjectNode port = (com.fasterxml.jackson.databind.node.ObjectNode) torso.path("frames").get(0); + port.put("interfaceType", "arm_r").put("name", "SAME_NAME").put("type", "revolute"); + port.remove("xyz"); torso.remove("rootLink"); + jdbc.update("UPDATE component SET urdf_info=? WHERE component_code='CW-T'", torso.toString()); + com.fasterxml.jackson.databind.node.ObjectNode arm = (com.fasterxml.jackson.databind.node.ObjectNode) components.get("CW-A").urdfInfo(); + ((com.fasterxml.jackson.databind.node.ObjectNode) arm.path("frames").get(0)).put("child", "LINK_head_0"); + jdbc.update("UPDATE component SET urdf_info=? WHERE component_code='CW-A'", arm.toString()); + JsonNode result = match(request("arm_r", "head_0")); + assertThat(result.path("parts").findValuesAsText("category")).containsExactly("torso_0", "arm_r"); + port.put("interfaceType", "invalid"); + jdbc.update("UPDATE component SET urdf_info=? WHERE component_code='CW-T'", torso.toString()); + result = match(request("arm_r", "head_0")); + assertThat(result.path("parts").findValuesAsText("category")).containsExactly("torso_0", "head_0"); + port.put("child", "LINK_HEAD_0"); + jdbc.update("UPDATE component SET urdf_info=? WHERE component_code='CW-T'", torso.toString()); + assertThat(match(request("head_0")).path("parts")).hasSize(1); + } + + @Test void instanceLimitReturnsBoundedCombination() throws Exception { + save("CW-T", "torso_0", 0, "1", "0", "", metadata("BASE", java.util.Collections.nCopies(25, "arm_r").toArray(String[]::new)), json.readTree("[]")); + save("CW-A", "arm_r", 0, "1", "0", ""); + JsonNode result = match(request("arm_r")); + assertThat(result.path("parts")).hasSize(24); + assertThat(result.path("searchLimited").asBoolean()).isTrue(); + } + + @Test void fillsRequiredDownstreamTypesBeforeAutomaticExtraCopiesReachLimit() throws Exception { + save("CW-T", "torso_0", 0, "1", "0", "", metadata("BASE", java.util.Collections.nCopies(25, "arm_r").toArray(String[]::new)), json.readTree("[]")); + save("CW-A", "arm_r", 0, "1", "0", "", metadata("ARM", "head_0"), json.readTree("[]")); + save("CW-H", "head_0", 0, "1", "0", ""); + Map body = new LinkedHashMap<>(request("arm_r", "head_0")); + body.put("partRequirements", List.of(Map.of("category", "arm_r", "quantity", 24))); + JsonNode result = match(body); + assertThat(result.path("parts")).hasSize(24); + assertThat(result.path("parts").findValuesAsText("category")).contains("head_0"); + assertThat(result.path("missingParts").get(0).path("missingQuantity").asInt()).isEqualTo(2); + assertThat(result.path("searchLimited").asBoolean()).isTrue(); + } + + @Test void providedHeadTorsoWaistDataReturnsConnectedPartAndMissingWaistUntilInterfacesMatch() throws Exception { + try (java.io.InputStream stream = getClass().getResourceAsStream("/fixtures/head-torso-waist-components.json")) { + assertThat(stream).isNotNull(); + for (JsonNode row : json.readTree(stream)) { + jdbc.update("INSERT INTO component (component_code,component_name,category,bom_list,urdf_info,step_object_key,urdf_main_object_key) VALUES (?,?,?,'[]',?,'model.step','robot.urdf')", + row.path("component_code").asText(), row.path("component_name").asText(), row.path("category").asText(), row.path("urdf_info").toString()); + } + } + JsonNode result = match(request("head_0", "torso_0", "waist_0")); + assertThat(part(result, "torso_0").path("componentCode").asText()).isEqualTo("CW-BFXXH6TAVTBATHRV"); + assertThat(result.path("parts")).hasSize(2); + assertThat(result.path("missingParts").get(0).path("category").asText()).isEqualTo("waist_0"); + assertThat(result.path("connections").get(0).path("interfaceChild").asText()).isEqualTo("LINK_HEAD_0"); + com.fasterxml.jackson.databind.node.ObjectNode waist = (com.fasterxml.jackson.databind.node.ObjectNode) components.get("CW-HANKCSXC8XRV1BRP").urdfInfo(); + waist.withArray("frames").addObject().put("name", "inbound").put("child", "LINK_WAIST_0").put("interfaceType", "waist_0"); + jdbc.update("UPDATE component SET urdf_info=? WHERE component_code='CW-HANKCSXC8XRV1BRP'", waist.toString()); + JsonNode matched = match(request("head_0", "torso_0", "waist_0")); + assertThat(matched.path("parts")).hasSize(3); + assertThat(matched.path("connections")).hasSize(2); + assertThat(matched.path("missingParts")).isEmpty(); + } + + @Test void automaticCopiesRespectFeasibleWholeRobotNumericRequirements() throws Exception { + save("CW-T", "torso_0", 0, "1", "0", "", metadata("BASE", "arm_r", "arm_r", "arm_r", "arm_r"), json.readTree("[]")); + save("CW-A", "arm_r", 1, "1", "0", ""); + Map body = new LinkedHashMap<>(request("arm_r")); + body.put("robotRequirements", Map.of("massKg", 2, "operators", Map.of("massKg", "lte"))); + JsonNode result = match(body); + assertThat(result.path("parts")).hasSize(2); + assertThat(result.path("unmetRequirements")).isEmpty(); + body.put("robotRequirements", Map.of("degreesOfFreedom", 3)); + result = match(body); + assertThat(result.path("parts")).hasSize(4); + assertThat(result.path("totals").path("degreesOfFreedom").asInt()).isEqualTo(3); + assertThat(result.path("unmetRequirements")).isEmpty(); + } + + @Test void quantitiesRejectFractionsStringsAndOutOfRangeIntegers() throws Exception { + for (Object value : List.of(0, -1, 25, 1.5, "4")) { + mvc.perform(post("/api/robot-matches").contentType(MediaType.APPLICATION_JSON) + .content(json.writeValueAsBytes(Map.of("requiredParts", List.of("arm_r"), + "partRequirements", List.of(Map.of("category", "arm_r", "quantity", value)))))) + .andExpect(status().isUnprocessableEntity()); + } + } + private Map request(String... roles) { return Map.of("requiredParts", List.of(roles)); } private JsonNode match(Map body) throws Exception { @@ -559,6 +700,14 @@ class MatchingApiTest { } private void save(String code, String category, int degrees, String mass, String torque, String material, JsonNode info, JsonNode bom) throws Exception { + String role = com.linkerbot.cadworld.service.matching.ComponentRole.find(category).orElseThrow().code(); + if (!"torso_0".equals(role) && info.isObject()) { + ((com.fasterxml.jackson.databind.node.ObjectNode) info).withArray("frames").addObject() + .put("name", "INCOMING").put("kind", "joint").put("type", "fixed").put("parent", info.path("rootLink").asText()) + .put("child", "LINK_" + role).put("interfaceType", role).put("originExplicit", true) + .putArray("xyz").add(0).add(0).add(0); + ((com.fasterxml.jackson.databind.node.ObjectNode) info.path("frames").get(info.path("frames").size() - 1)).putArray("rpy").add(0).add(0).add(0); + } jdbc.update(""" INSERT INTO component (component_code,component_name,category,mass_kg,degrees_of_freedom,torque_nm, material,bom_list,urdf_info,step_object_key,urdf_main_object_key) diff --git a/cadworld-api/src/test/resources/fixtures/head-torso-waist-components.json b/cadworld-api/src/test/resources/fixtures/head-torso-waist-components.json new file mode 100644 index 0000000..0f51039 --- /dev/null +++ b/cadworld-api/src/test/resources/fixtures/head-torso-waist-components.json @@ -0,0 +1,332 @@ +[ + { + "component_code": "CW-BFXXH6TAVTBATHRV", + "component_name": "躯干_0_八边棱柱", + "category": "torso_0", + "urdf_info": { + "frames": [ + { + "rpy": [ + -1.5708, + 0, + 0 + ], + "xyz": [ + 0, + 0.08835, + 0.07156 + ], + "axis": [ + 0, + 0, + 0 + ], + "kind": "joint", + "name": "LINK_HAND_L", + "type": "fixed", + "child": "LINK_HAND_L", + "limits": {}, + "parent": "base_link", + "interfaceType": "hand_l", + "originExplicit": true + }, + { + "rpy": [ + 1.5708, + 1.5708, + 0 + ], + "xyz": [ + 0, + -0.08835, + 0.07156 + ], + "axis": [ + 0, + 0, + 0 + ], + "kind": "joint", + "name": "LINK_HAND_R", + "type": "fixed", + "child": "LINK_HAND_R", + "limits": {}, + "parent": "base_link", + "interfaceType": "hand_r", + "originExplicit": true + }, + { + "rpy": [ + 0, + 0, + 0 + ], + "xyz": [ + 0, + 0, + 0.109 + ], + "axis": [ + 0, + 0, + 0 + ], + "kind": "joint", + "name": "LINK_HEAD_0", + "type": "fixed", + "child": "LINK_HEAD_0", + "limits": {}, + "parent": "base_link", + "interfaceType": "head_0", + "originExplicit": true + }, + { + "rpy": [ + 0, + 0, + 0 + ], + "xyz": [ + 0, + 0, + 0 + ], + "axis": [ + 0, + 0, + 0 + ], + "kind": "joint", + "name": "LINK_WAIST_0", + "type": "fixed", + "child": "LINK_WAIST_0", + "limits": {}, + "parent": "base_link", + "interfaceType": "waist_0", + "originExplicit": true + } + ], + "rootLink": "base_link", + "robotName": "躯干_0_八边棱柱" + } + }, + { + "component_code": "CW-HANKCSXC8XRV1BRP", + "component_name": "腰_0_八边棱柱(腰固定)", + "category": "waist_0", + "urdf_info": { + "frames": [ + { + "rpy": [ + 3.14159265358979, + 0, + 3.14159265358979 + ], + "xyz": [ + 0, + 0.0725, + -0.05035 + ], + "axis": [ + 0, + 0, + 1 + ], + "kind": "joint", + "name": "LINK_LEG_L", + "type": "fixed", + "child": "LINK_LEG_L", + "limits": { + "effort": 100, + "velocity": 50 + }, + "parent": "LINK_WAIST_0", + "interfaceType": "leg_l", + "originExplicit": true + }, + { + "rpy": [ + 3.14159265358979, + 0, + 3.14159265358979 + ], + "xyz": [ + 0, + -0.0725, + -0.05035 + ], + "axis": [ + 0, + 0, + 1 + ], + "kind": "joint", + "name": "LINK_LEG_R", + "type": "fixed", + "child": "LINK_LEG_R", + "limits": { + "effort": 100, + "velocity": 50 + }, + "parent": "LINK_WAIST_0", + "interfaceType": "leg_r", + "originExplicit": true + } + ], + "rootLink": "LINK_WAIST_0", + "robotName": "腰_0_八边棱柱(腰固定)" + } + }, + { + "component_code": "CW-DA36W433NBBHXJJE", + "component_name": "头_0_卤蛋形状零自由度头", + "category": "head_0", + "urdf_info": { + "frames": [ + { + "rpy": [ + 0, + 0, + 0 + ], + "xyz": [ + 7.21972081179142e-05, + 0, + -0.005 + ], + "axis": [ + 0, + 0, + 1 + ], + "kind": "joint", + "name": "LINK_HEAD_0", + "type": "revolute", + "child": "LINK_HEAD_0", + "limits": { + "lower": -1.8, + "upper": 1.8, + "effort": 100, + "velocity": 50 + }, + "parent": "base_link", + "interfaceType": "head_0", + "originExplicit": true + } + ], + "rootLink": "base_link", + "robotName": "头_0_卤蛋形状零自由度头" + } + }, + { + "component_code": "CW-7CYFG066SE849X84", + "component_name": "躯干_0_宽躯躯干", + "category": "torso_0", + "urdf_info": { + "frames": [ + { + "rpy": [ + 1.5707963267949, + 0, + 0 + ], + "xyz": [ + 0, + -0.100381817826158, + 0.00999999999999999 + ], + "axis": [ + 0, + 0, + 0 + ], + "kind": "joint", + "name": "J1", + "type": "fixed", + "child": "LINK_arm_r", + "limits": {}, + "parent": "BASE", + "interfaceType": "arm_r", + "originExplicit": true + }, + { + "rpy": [ + 0, + 0, + 0 + ], + "xyz": [ + 0, + 0, + 0.0434269852498788 + ], + "axis": [ + 0, + 0, + 0 + ], + "kind": "joint", + "name": "J2", + "type": "fixed", + "child": "LINK_head_0", + "limits": {}, + "parent": "BASE", + "interfaceType": "head_0", + "originExplicit": true + }, + { + "rpy": [ + -1.5707963267949, + 0, + 0 + ], + "xyz": [ + 0, + 0.100381817826158, + 0.01 + ], + "axis": [ + 0, + 0, + 0 + ], + "kind": "joint", + "name": "J3", + "type": "fixed", + "child": "LINK_arm_l", + "limits": {}, + "parent": "BASE", + "interfaceType": "arm_l", + "originExplicit": true + }, + { + "rpy": [ + 3.14159265358979, + 0, + 0 + ], + "xyz": [ + 0, + 0, + -0.0984730140388012 + ], + "axis": [ + 0, + 0, + 0 + ], + "kind": "joint", + "name": "J4", + "type": "fixed", + "child": "LINK_waist_0", + "limits": {}, + "parent": "BASE", + "interfaceType": "waist_0", + "originExplicit": true + } + ], + "rootLink": "BASE", + "robotName": "躯干_0_宽躯躯干" + } + } +] diff --git a/cadworld-bean/src/main/java/com/linkerbot/cadworld/dto/matching/PartRequirements.java b/cadworld-bean/src/main/java/com/linkerbot/cadworld/dto/matching/PartRequirements.java index 4766841..2d3989b 100644 --- a/cadworld-bean/src/main/java/com/linkerbot/cadworld/dto/matching/PartRequirements.java +++ b/cadworld-bean/src/main/java/com/linkerbot/cadworld/dto/matching/PartRequirements.java @@ -4,6 +4,7 @@ import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.linkerbot.cadworld.dto.component.DegreesOfFreedomDeserializer; import jakarta.validation.constraints.Digits; import jakarta.validation.constraints.Min; +import jakarta.validation.constraints.Max; import jakarta.validation.constraints.NotBlank; import jakarta.validation.constraints.PositiveOrZero; import jakarta.validation.constraints.Size; @@ -21,9 +22,15 @@ public record PartRequirements( @Size(max = 128) String size, Map operators, @Size(max = 128) String componentName, - @Size(max = 20000) String description) { + @Size(max = 20000) String description, + @Min(1) @Max(24) @JsonDeserialize(using = QuantityDeserializer.class) Integer quantity) { + public PartRequirements(String category, String material, Integer degreesOfFreedom, BigDecimal massKg, + BigDecimal torqueNm, String functionDescription, String shape, String size, Map operators, + String componentName, String description) { + this(category, material, degreesOfFreedom, massKg, torqueNm, functionDescription, shape, size, operators, componentName, description, null); + } public PartRequirements(String category, String material, Integer degreesOfFreedom, BigDecimal massKg, BigDecimal torqueNm, String functionDescription, String shape, String size, Map operators) { - this(category, material, degreesOfFreedom, massKg, torqueNm, functionDescription, shape, size, operators, null, null); + this(category, material, degreesOfFreedom, massKg, torqueNm, functionDescription, shape, size, operators, null, null, null); } } diff --git a/cadworld-bean/src/main/java/com/linkerbot/cadworld/dto/matching/PublicComponentResponse.java b/cadworld-bean/src/main/java/com/linkerbot/cadworld/dto/matching/PublicComponentResponse.java index 0efb1c3..338a366 100644 --- a/cadworld-bean/src/main/java/com/linkerbot/cadworld/dto/matching/PublicComponentResponse.java +++ b/cadworld-bean/src/main/java/com/linkerbot/cadworld/dto/matching/PublicComponentResponse.java @@ -10,7 +10,20 @@ public record PublicComponentResponse( String componentCode, String componentName, String category, String description, String material, BigDecimal massKg, Integer degreesOfFreedom, @JsonInclude(JsonInclude.Include.ALWAYS) RotationAxis rotationAxis, String functionDescription, String shape, String size, - BigDecimal torqueNm, JsonNode bomList, JsonNode urdfInfo, Long version, String stepUrl, String urdfUrl) { + BigDecimal torqueNm, JsonNode bomList, JsonNode urdfInfo, Long version, String stepUrl, String urdfUrl, + @JsonInclude(JsonInclude.Include.NON_NULL) String instanceId) { + public PublicComponentResponse(String componentCode, String componentName, String category, String description, String material, + BigDecimal massKg, Integer degreesOfFreedom, RotationAxis rotationAxis, + String functionDescription, String shape, String size, BigDecimal torqueNm, + JsonNode bomList, JsonNode urdfInfo, Long version, String stepUrl, String urdfUrl) { + this(componentCode, componentName, category, description, material, massKg, degreesOfFreedom, rotationAxis, + functionDescription, shape, size, torqueNm, bomList, urdfInfo, version, stepUrl, urdfUrl, null); + } + + public PublicComponentResponse withInstanceId(String value) { + return new PublicComponentResponse(componentCode, componentName, category, description, material, massKg, + degreesOfFreedom, rotationAxis, functionDescription, shape, size, torqueNm, bomList, urdfInfo, version, stepUrl, urdfUrl, value); + } @Override public String toString() { return "PublicComponentResponse[componentCode=" + componentCode + ", category=" + category + ", version=" + version + "]"; diff --git a/cadworld-bean/src/main/java/com/linkerbot/cadworld/dto/matching/QuantityDeserializer.java b/cadworld-bean/src/main/java/com/linkerbot/cadworld/dto/matching/QuantityDeserializer.java new file mode 100644 index 0000000..ed1717d --- /dev/null +++ b/cadworld-bean/src/main/java/com/linkerbot/cadworld/dto/matching/QuantityDeserializer.java @@ -0,0 +1,18 @@ +package com.linkerbot.cadworld.dto.matching; + +import com.fasterxml.jackson.core.JsonParser; +import com.fasterxml.jackson.core.JsonToken; +import com.fasterxml.jackson.databind.DeserializationContext; +import com.fasterxml.jackson.databind.deser.std.StdDeserializer; +import java.io.IOException; + +/** 实例数量仅接受 JSON 整数,避免小数截断和字符串隐式转换。 */ +public class QuantityDeserializer extends StdDeserializer { + public QuantityDeserializer() { super(Integer.class); } + + @Override + public Integer deserialize(JsonParser parser, DeserializationContext context) throws IOException { + if (!parser.hasToken(JsonToken.VALUE_NUMBER_INT)) return context.reportInputMismatch(Integer.class, "组件数量必须为整数"); + return parser.getIntValue(); + } +} diff --git a/cadworld-bean/src/main/java/com/linkerbot/cadworld/dto/matching/RobotMatchResponse.java b/cadworld-bean/src/main/java/com/linkerbot/cadworld/dto/matching/RobotMatchResponse.java index a707abb..a033907 100644 --- a/cadworld-bean/src/main/java/com/linkerbot/cadworld/dto/matching/RobotMatchResponse.java +++ b/cadworld-bean/src/main/java/com/linkerbot/cadworld/dto/matching/RobotMatchResponse.java @@ -11,16 +11,19 @@ public record RobotMatchResponse( public record Connection(String parentCategory, String parentComponentCode, String parentLink, String frameName, String childCategory, String childComponentCode, - String childRootLink, List xyz, List rpy) { } + String childRootLink, String parentInstanceId, String childInstanceId, + String interfaceChild, int parentFrameIndex, int childFrameIndex) { } public record Totals(long degreesOfFreedom, BigDecimal massKg, BigDecimal knownMassKg, boolean massComplete) { } public record UnmetRequirement(String scope, String category, String field, String operator, Object expected, Object actual, String reason) { } - public record MissingPart(String category, String reason) { } + public record MissingPart(String category, String reason, int expectedQuantity, int actualQuantity, int missingQuantity) { + public MissingPart(String category, String reason) { this(category, reason, 1, 0, 1); } + } - public record Alternatives(String category, List items) { } + public record Alternatives(String category, String instanceId, List items) { } public record Replacement(PublicComponentResponse component, List connections, Totals totals, List unmetRequirements, List unmatchedKeywords) { } diff --git a/cadworld-service/src/main/java/com/linkerbot/cadworld/config/DemandProperties.java b/cadworld-service/src/main/java/com/linkerbot/cadworld/config/DemandProperties.java index 6f3901b..795d277 100644 --- a/cadworld-service/src/main/java/com/linkerbot/cadworld/config/DemandProperties.java +++ b/cadworld-service/src/main/java/com/linkerbot/cadworld/config/DemandProperties.java @@ -21,7 +21,6 @@ public record DemandProperties( @DefaultValue("P7D") Duration retention, @Min(1) @Max(16) @DefaultValue("4") int concurrentAnalyses, @DefaultValue("false") boolean secureCookie, - @DefaultValue("false") boolean rootIsMountingFrame, List allowedOrigins) { @AssertTrue(message = "解析超时须为1秒至5分钟,保存时长须为1小时至30天") public boolean isDurationConfigurationValid() { diff --git a/cadworld-service/src/main/java/com/linkerbot/cadworld/service/demand/DemandAssemblyValidator.java b/cadworld-service/src/main/java/com/linkerbot/cadworld/service/demand/DemandAssemblyValidator.java index 930e603..010c5bd 100644 --- a/cadworld-service/src/main/java/com/linkerbot/cadworld/service/demand/DemandAssemblyValidator.java +++ b/cadworld-service/src/main/java/com/linkerbot/cadworld/service/demand/DemandAssemblyValidator.java @@ -1,168 +1,66 @@ package com.linkerbot.cadworld.service.demand; import com.fasterxml.jackson.databind.JsonNode; -import com.linkerbot.cadworld.config.DemandProperties; import com.linkerbot.cadworld.dto.matching.PublicComponentResponse; import com.linkerbot.cadworld.dto.matching.RobotMatchResponse; +import com.linkerbot.cadworld.service.matching.AssemblyMetadata; import java.util.ArrayList; -import java.util.HashSet; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; -import java.util.Set; -/** 校验已有组件的安装与坐标;缺件及需求降级由匹配结果提示,不阻塞有效组件展示。 */ +/** 将已匹配的接口转换为实例连接;位姿由前端处理,元数据问题只作为提示。 */ public final class DemandAssemblyValidator { - private final DemandProperties properties; - public DemandAssemblyValidator(DemandProperties properties) { this.properties = properties; } public Assembly validate(String matchId, RobotMatchResponse match) { List issues = new ArrayList<>(); List connections = new ArrayList<>(); Map parts = new LinkedHashMap<>(); - match.parts().forEach((PublicComponentResponse part) -> parts.put(part.componentCode(), part)); - if (parts.isEmpty()) issues.add(new Issue("NO_COMPONENTS", null, null, "没有可用于装配的组件")); - long torsoCount = match.parts().stream().filter((PublicComponentResponse part) -> "torso_0".equals(part.category())).count(); - if (!parts.isEmpty() && (torsoCount != 1 || !"torso_0".equals(match.rootCategory()))) { - issues.add(new Issue("INVALID_TORSO_ROOT", "torso_0", null, "整机必须且只能包含一个躯干,并以躯干为根")); - return new Assembly("blocked", null, "column-major", List.of(), List.copyOf(issues)); + for (PublicComponentResponse part : match.parts()) { + parts.put(part.instanceId(), part); + for (AssemblyMetadata.Problem problem : AssemblyMetadata.read(part.urdfInfo()).problems()) { + issues.add(new Issue(problem.code(), part.category(), part.componentCode(), problem.message(), instance(matchId, part.instanceId()), problem.frameIndex())); + } + if (part.urdfInfo() == null || part.urdfInfo().path("rootLink").asText().isBlank()) { + issues.add(new Issue("MISSING_ROOT_LINK", part.category(), part.componentCode(), "未提供根节点,模型定位由前端处理", instance(matchId, part.instanceId()), null)); + } + if (part.urdfInfo() != null) for (JsonNode frame : part.urdfInfo().path("frames")) { + if (!validPose(frame.path("xyz")) || !validPose(frame.path("rpy"))) { + issues.add(new Issue("INVALID_ORIGIN", part.category(), part.componentCode(), "接口位姿信息不完整,由前端处理摆放", instance(matchId, part.instanceId()), null)); + break; + } + } } - Map graphs = new LinkedHashMap<>(); - for (PublicComponentResponse part : parts.values()) { - try { graphs.put(part.componentCode(), new FrameGraph(part.urdfInfo())); } - catch (AssemblyProblem exception) { issues.add(new Issue(exception.code, part.category(), part.componentCode(), exception.getMessage())); } + if (parts.isEmpty()) { + issues.add(new Issue("NO_COMPONENTS", null, null, "没有可展示的组件", null, null)); + return new Assembly("blocked", null, List.of(), List.copyOf(issues)); + } + PublicComponentResponse torso = match.parts().stream().filter((PublicComponentResponse part) -> "torso_0".equals(part.category())).findFirst().orElse(null); + if (torso == null || !"torso_0".equals(match.rootCategory())) { + issues.add(new Issue("INVALID_TORSO_ROOT", "torso_0", null, "整机需要以躯干为根", null, null)); + return new Assembly("blocked", null, List.of(), List.copyOf(issues)); } for (RobotMatchResponse.Connection edge : match.connections()) { - PublicComponentResponse parent = parts.get(edge.parentComponentCode()); - PublicComponentResponse child = parts.get(edge.childComponentCode()); - try { - if (parent == null || child == null) throw problem("INVALID_CONNECTION", "连接引用的组件不存在"); - FrameGraph parentGraph = graphs.get(parent.componentCode()); - FrameGraph childGraph = graphs.get(child.componentCode()); - if (parentGraph == null || childGraph == null) continue; - long ports = parentGraph.frames.stream().filter((JsonNode frame) -> edge.childCategory().equals(interfaceRole(frame))).count(); - if (ports != 1) throw problem("AMBIGUOUS_PARENT_INTERFACE", "父组件有多个同类接口,尚未明确配对"); - JsonNode assembly = child.urdfInfo().path("assembly"); - String childFrame = assembly.path("mountingFrame").asText(); - String convention = assembly.path("pairingConvention").asText(); - if (childFrame.isBlank() && properties.rootIsMountingFrame()) { childFrame = childGraph.root; convention = "coincident_frames"; } - if (childFrame.isBlank() || !"coincident_frames".equals(convention)) throw problem("MISSING_MOUNTING_REFERENCE", "子组件缺少明确安装基准或接口配对约定"); - double[] parentTransform = parentGraph.frame(edge.frameName()); - double[] childTransform = childGraph.frame(childFrame); - double[] childRootTransform = multiply(parentTransform, inverse(childTransform)); - connections.add(new Connection(instance(matchId, parent.category()), edge.frameName(), edge.parentLink(), - instance(matchId, child.category()), childFrame, childGraph.root, list(parentTransform), list(childTransform), list(childRootTransform))); - } catch (AssemblyProblem exception) { - issues.add(new Issue(exception.code, edge.childCategory(), edge.childComponentCode(), exception.getMessage())); - } + PublicComponentResponse child = parts.get(edge.childInstanceId()); + JsonNode childFrame = child == null || child.urdfInfo() == null ? null : child.urdfInfo().path("frames").path(edge.childFrameIndex()); + connections.add(new Connection(instance(matchId, edge.parentInstanceId()), edge.frameName(), emptyToNull(edge.parentLink()), + instance(matchId, edge.childInstanceId()), childFrame == null ? null : emptyToNull(childFrame.path("name").asText()), + emptyToNull(edge.childRootLink()), edge.interfaceChild(), edge.parentFrameIndex(), edge.childFrameIndex())); } - String root = match.rootCategory() == null ? null : instance(matchId, match.rootCategory()); - return new Assembly(issues.isEmpty() ? "ready" : "blocked", root, "column-major", List.copyOf(connections), List.copyOf(issues)); + if (match.searchLimited()) issues.add(new Issue("SEARCH_LIMIT", null, null, "候选、实例数量或搜索达到上限,已返回当前可用组合", null, null)); + return new Assembly("ready", instance(matchId, torso.instanceId()), List.copyOf(connections), List.copyOf(issues)); } - public static String instance(String matchId, String category) { return matchId + ":" + category; } - - private static String interfaceRole(JsonNode frame) { - String value = frame.path("interfaceType").asText(); - if (value.isBlank() && frame.path("child").asText().startsWith("LINK_")) { - value = frame.path("child").asText().substring(5); - if (List.of("head", "torso", "waist", "tail").contains(value)) value += "_0"; - } - return com.linkerbot.cadworld.service.matching.ComponentRole.find(value).map(com.linkerbot.cadworld.service.matching.ComponentRole::code).orElse(""); + public static String instance(String matchId, String instanceId) { return matchId + ":" + instanceId; } + private static String emptyToNull(String value) { return value == null || value.isBlank() ? null : value; } + private boolean validPose(JsonNode pose) { + if (!pose.isArray() || pose.size() != 3) return false; + for (JsonNode value : pose) if (!value.isNumber() || !Double.isFinite(value.doubleValue())) return false; + return true; } - private static final class FrameGraph { - private final String root; - private final List frames = new ArrayList<>(); - private final Map byName = new LinkedHashMap<>(); - private final Map byChild = new LinkedHashMap<>(); - private FrameGraph(JsonNode info) { - root = info.path("rootLink").asText(); - if (root.isBlank() || !info.path("frames").isArray()) throw problem("INVALID_FRAME_GRAPH", "URDF根节点或帧清单不完整"); - for (JsonNode frame : info.path("frames")) { - if (!"joint".equals(frame.path("kind").asText())) continue; - String name = frame.path("name").asText(); - String child = frame.path("child").asText(); - if (name.isBlank() || child.isBlank() || frame.path("parent").asText().isBlank() - || byName.putIfAbsent(name, frame) != null || byChild.putIfAbsent(child, frame) != null) throw problem("INVALID_FRAME_GRAPH", "URDF帧重名或连接关系不完整"); - frames.add(frame); - } - Set reachable = new HashSet<>(); - reachable.add(root); - for (String child : byChild.keySet()) { - Set visiting = new HashSet<>(); - String current = child; - if (child.equals(root)) throw problem("INVALID_FRAME_GRAPH", "URDF根节点不能同时作为子节点"); - while (!reachable.contains(current)) { - if (!visiting.add(current)) throw problem("INVALID_FRAME_GRAPH", "URDF连接存在环"); - JsonNode joint = byChild.get(current); - if (joint == null) throw problem("UNREACHABLE_FRAME", "URDF帧无法从组件根节点定位"); - current = joint.path("parent").asText(); - } - reachable.addAll(visiting); - } - } - private double[] frame(String name) { - if (name.equals(root)) return identity(); - JsonNode joint = byName.get(name); - return link(joint == null ? name : joint.path("child").asText(), new HashSet<>()); - } - private double[] link(String name, Set visited) { - if (name.equals(root)) return identity(); - if (!visited.add(name)) throw problem("INVALID_FRAME_GRAPH", "URDF连接存在环"); - JsonNode joint = byChild.get(name); - if (joint == null) throw problem("UNREACHABLE_FRAME", "安装接口无法从组件根节点定位"); - if (!"fixed".equals(joint.path("type").asText())) throw problem("MOVABLE_INTERFACE_REQUIRES_STATE", "安装路径包含活动关节,缺少确定的关节状态"); - double[] parent = link(joint.path("parent").asText(), visited); - double[] xyz = pose(joint.get("xyz"), joint.path("originExplicit").isBoolean() && !joint.path("originExplicit").asBoolean()); - double[] rpy = pose(joint.get("rpy"), joint.path("originExplicit").isBoolean() && !joint.path("originExplicit").asBoolean()); - return multiply(parent, origin(xyz, rpy)); - } - } - - private static double[] pose(JsonNode value, boolean implicit) { - if ((value == null || value.isNull()) && implicit) return new double[3]; - if (value == null || !value.isArray() || value.size() != 3) throw problem("INVALID_ORIGIN", "URDF安装位姿不完整"); - double[] result = new double[3]; - for (int i = 0; i < 3; i++) { - if (!value.get(i).isNumber() || !Double.isFinite(value.get(i).doubleValue())) throw problem("INVALID_ORIGIN", "URDF安装位姿不合法"); - result[i] = value.get(i).doubleValue(); - } - return result; - } - private static double[] origin(double[] xyz, double[] rpy) { - double cr = Math.cos(rpy[0]), sr = Math.sin(rpy[0]); - double cp = Math.cos(rpy[1]), sp = Math.sin(rpy[1]); - double cy = Math.cos(rpy[2]), sy = Math.sin(rpy[2]); - return new double[] {cy*cp, sy*cp, -sp, 0, cy*sp*sr-sy*cr, sy*sp*sr+cy*cr, cp*sr, 0, - cy*sp*cr+sy*sr, sy*sp*cr-cy*sr, cp*cr, 0, xyz[0], xyz[1], xyz[2], 1}; - } - private static double[] identity() { return new double[] {1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1}; } - private static double[] multiply(double[] left, double[] right) { - double[] result = new double[16]; - for (int column = 0; column < 4; column++) for (int row = 0; row < 4; row++) { - for (int k = 0; k < 4; k++) result[column*4+row] += left[k*4+row]*right[column*4+k]; - if (!Double.isFinite(result[column*4+row])) throw problem("INVALID_ORIGIN", "安装变换超出支持范围"); - } - return result; - } - private static double[] inverse(double[] matrix) { - double[] result = identity(); - for (int column = 0; column < 3; column++) for (int row = 0; row < 3; row++) result[column*4+row] = matrix[row*4+column]; - for (int row = 0; row < 3; row++) result[12+row] = -(result[row]*matrix[12] + result[4+row]*matrix[13] + result[8+row]*matrix[14]); - return result; - } - private static List list(double[] matrix) { - List result = new ArrayList<>(); for (double value : matrix) result.add(value); return List.copyOf(result); - } - private static AssemblyProblem problem(String code, String message) { return new AssemblyProblem(code, message); } - private static final class AssemblyProblem extends RuntimeException { - private final String code; - private AssemblyProblem(String code, String message) { super(message); this.code = code; } - } - public record Assembly(String status, String rootInstanceId, String matrixLayout, List connections, List issues) { } + public record Assembly(String status, String rootInstanceId, List connections, List issues) { } public record Connection(String parentInstanceId, String parentFrame, String parentLink, String childInstanceId, - String childFrame, String childRootLink, List parentRootToInterface, - List childRootToInterface, List childRootRelativeToParentRoot) { } - public record Issue(String code, String category, String componentCode, String message) { } + String childFrame, String childRootLink, String interfaceChild, int parentFrameIndex, int childFrameIndex) { } + public record Issue(String code, String category, String componentCode, String message, String instanceId, Integer frameIndex) { } } diff --git a/cadworld-service/src/main/java/com/linkerbot/cadworld/service/demand/DemandMatchService.java b/cadworld-service/src/main/java/com/linkerbot/cadworld/service/demand/DemandMatchService.java index fc4398e..1e60645 100644 --- a/cadworld-service/src/main/java/com/linkerbot/cadworld/service/demand/DemandMatchService.java +++ b/cadworld-service/src/main/java/com/linkerbot/cadworld/service/demand/DemandMatchService.java @@ -83,14 +83,14 @@ public final class DemandMatchService { result.set("assembly", assemblyWithResources(matchId, response, components)); ArrayNode alternatives = result.putArray("alternatives"); for (RobotMatchResponse.Alternatives group : response.alternatives()) { - ArrayNode items = alternatives.addObject().put("category", group.category()).putArray("items"); + ArrayNode items = alternatives.addObject().put("category", group.category()).put("instanceId", DemandAssemblyValidator.instance(matchId, group.instanceId())).putArray("items"); for (RobotMatchResponse.Replacement replacement : group.items()) { - List replacedParts = response.parts().stream().map((PublicComponentResponse part) -> part.category().equals(group.category()) ? replacement.component() : part).toList(); + List replacedParts = response.parts().stream().map((PublicComponentResponse part) -> part.instanceId().equals(group.instanceId()) ? replacement.component() : part).toList(); RobotMatchResponse replaced = new RobotMatchResponse(response.status(), response.rootCategory(), replacedParts, replacement.connections(), List.of(), replacement.totals(), replacement.unmetRequirements(), replacement.unmatchedKeywords(), response.missingParts(), response.searchLimited()); ArrayNode replacementChecks = requirements.check(analysis.result(), replaced); ObjectNode item = items.addObject(); - item.set("component", json.valueToTree(replacement.component())); + item.set("component", json.valueToTree(replacement.component().withInstanceId(null))); ObjectNode replacedComponent = component(matchId, replacement.component()); item.set("resources", replacedComponent.get("resources")); item.set("resourceIssues", replacedComponent.get("resourceIssues")); @@ -100,7 +100,7 @@ public final class DemandMatchService { item.set("unmatchedKeywords", json.valueToTree(replacement.unmatchedKeywords())); item.set("requirementChecks", replacementChecks); ArrayNode replacedResources = json.createArrayNode(); - for (JsonNode original : components) replacedResources.add(group.category().equals(original.path("component").path("category").asText()) ? replacedComponent : original); + for (JsonNode original : components) replacedResources.add(DemandAssemblyValidator.instance(matchId, group.instanceId()).equals(original.path("instanceId").asText()) ? replacedComponent : original); item.set("assembly", assemblyWithResources(matchId, replaced, replacedResources)); item.put("degradationAcceptanceRequired", false); } @@ -112,8 +112,8 @@ public final class DemandMatchService { Component stored = mapper.selectOne(new LambdaQueryWrapper().select(Component::getComponentCode, Component::getVersion, Component::getUrdfPrefix, Component::getUrdfMainObjectKey, Component::getUrdfFiles).eq(Component::getComponentCode, part.componentCode())); if (stored == null || !part.version().equals(stored.getVersion())) throw changed(); - ObjectNode result = json.createObjectNode().put("instanceId", DemandAssemblyValidator.instance(matchId, part.category())); - result.set("component", json.valueToTree(part)); + ObjectNode result = json.createObjectNode().put("instanceId", DemandAssemblyValidator.instance(matchId, part.instanceId())); + result.set("component", json.valueToTree(part.withInstanceId(null))); ArrayNode resources = result.putArray("resources"); ArrayNode issues = result.putArray("resourceIssues"); String prefix = stored.getUrdfPrefix(); @@ -146,7 +146,6 @@ public final class DemandMatchService { private JsonNode assemblyWithResources(String matchId, RobotMatchResponse response, JsonNode components) { ObjectNode result = json.valueToTree(assembly.validate(matchId, response)); for (JsonNode component : components) for (JsonNode issue : component.path("resourceIssues")) result.withArray("issues").add(issue); - if (!result.path("issues").isEmpty()) result.put("status", "blocked"); return result; } diff --git a/cadworld-service/src/main/java/com/linkerbot/cadworld/service/demand/DemandMechanicalNormalizer.java b/cadworld-service/src/main/java/com/linkerbot/cadworld/service/demand/DemandMechanicalNormalizer.java index 4945fd9..fe82970 100644 --- a/cadworld-service/src/main/java/com/linkerbot/cadworld/service/demand/DemandMechanicalNormalizer.java +++ b/cadworld-service/src/main/java/com/linkerbot/cadworld/service/demand/DemandMechanicalNormalizer.java @@ -14,7 +14,7 @@ import java.util.Set; /** 条件合并、冲突保留和模板展开;未明确的参数不阻塞自动选件。 */ final class DemandMechanicalNormalizer { - private static final Set NUMERIC = Set.of("degreesOfFreedom", "massKg", "torqueNm"); + private static final Set NUMERIC = Set.of("degreesOfFreedom", "massKg", "torqueNm", "quantity"); private static final Map TEXT_LIMITS = Map.of("componentName", 128, "material", 128, "shape", 128, "size", 128, "functionDescription", 512, "description", 20000); private final ObjectMapper json; @@ -75,11 +75,18 @@ final class DemandMechanicalNormalizer { String field = rows.get(0).path("field").asText(); String target = rows.get(0).path("target").asText(); try { + if ("quantity".equals(field) && ("robot".equals(target) || rows.stream().anyMatch((ObjectNode row) -> !"eq".equals(row.path("operator").asText())))) { + throw new IllegalArgumentException("组件数量只支持明确部位的等值要求"); + } Condition condition = NUMERIC.contains(field) ? number(field, rows, numericSources) : text(field, rows); ObjectNode container = "robot".equals(target) ? robot : parts.computeIfAbsent(target, (String key) -> json.createObjectNode().put("category", key)); if (condition.number() != null) { - if ("degreesOfFreedom".equals(field)) container.put(field, condition.number().intValueExact()); + if ("quantity".equals(field)) { + int quantity = condition.number().intValueExact(); + if (quantity < 1 || quantity > 24) throw new IllegalArgumentException("组件数量须为1至24的整数"); + container.put(field, quantity); + } else if ("degreesOfFreedom".equals(field)) container.put(field, condition.number().intValueExact()); else container.put(field, condition.number()); } else container.put(field, condition.text()); if (!"eq".equals(condition.operator())) container.withObject("operators").put(field, condition.operator()); diff --git a/cadworld-service/src/main/java/com/linkerbot/cadworld/service/demand/DemandNormalizer.java b/cadworld-service/src/main/java/com/linkerbot/cadworld/service/demand/DemandNormalizer.java index f489796..326a49b 100644 --- a/cadworld-service/src/main/java/com/linkerbot/cadworld/service/demand/DemandNormalizer.java +++ b/cadworld-service/src/main/java/com/linkerbot/cadworld/service/demand/DemandNormalizer.java @@ -62,7 +62,7 @@ public final class DemandNormalizer { if (inferred || (!"exclusion".equals(item.path("dimension").asText()) && counterexample(sources, images))) intent.put("priority", "context"); intent.put("evidence", combined(sources)); if ("quantity".equals(item.path("dimension").asText()) && "must".equals(intent.path("priority").asText()) && !DemandRequirementChecker.quantitySupported(intent)) { - warnings.add("当前每个部位仅支持一个组件实例,超出支持范围的数量要求保留为未验证项。"); + warnings.add("数量要求超出1至24或无法可靠映射到现有部位,已保留为未验证项。"); } } ObjectNode base = json.createObjectNode().put("summary", raw.path("summary").asText()); @@ -104,6 +104,21 @@ public final class DemandNormalizer { if ("unclear".equals(image.path("usage").asText())) warnings.add("图片用途未明确,按可辨认结构生成参考方案。"); } base.set("warnings", json.valueToTree(warnings)); + // 数量条目可以直接承载明确部位数量;不把跨部位合计数量误分配给每个部位。 + for (JsonNode intent : raw.path("intentItems")) { + if (!"quantity".equals(intent.path("dimension").asText()) || !"explicit".equals(intent.path("source").asText()) + || !"must".equals(intent.path("priority").asText()) || !DemandRequirementChecker.quantitySupported(intent)) continue; + List roles = DemandRequirementChecker.roles(intent.path("subject").asText(), intent.path("requirement").asText()); + if (roles.size() != 1) continue; + int quantity = DemandRequirementChecker.quantity(intent); + List sources = resolve(intent, evidence); + String quote = combined(sources); + if (!DemandNumberParser.inEvidence("quantity", Integer.toString(quantity), quote, List.of())) continue; + ObjectNode condition = base.withArray("constraints").addObject().put("scope", "part").put("field", "quantity") + .put("value", quantity).put("upperValue", "").put("operator", "eq").put("evidence", quote); + condition.putArray("categories").add(roles.get(0)); + numericSources.put(quote, sources.stream().map((JsonNode source) -> source.path("content").asText()).toList()); + } DemandResult result = new DemandMechanicalNormalizer(json, rules.catalog()).build(base, numericSources); List originals = new ArrayList<>(); for (DemandMessage message : messages.values()) { @@ -121,7 +136,7 @@ public final class DemandNormalizer { for (JsonNode item : raw.path("keywords")) keywordEvidence.addObject().put("term", item.path("term").asText()).set("evidenceIds", item.get("evidenceIds")); warnings.addAll(DemandMechanicalNormalizer.texts(analysis.path("warnings"))); analysis.set("warnings", json.valueToTree(warnings)); - analysis.put("schemaVersion", "multimodal-v1.2-auto-assembly"); + analysis.put("schemaVersion", "multimodal-v1.3-child-instances"); analysis.putArray("questions"); analysis.put("canSubmit", true).put("status", "ready"); return result; diff --git a/cadworld-service/src/main/java/com/linkerbot/cadworld/service/demand/DemandNumberParser.java b/cadworld-service/src/main/java/com/linkerbot/cadworld/service/demand/DemandNumberParser.java index 2901948..a47a771 100644 --- a/cadworld-service/src/main/java/com/linkerbot/cadworld/service/demand/DemandNumberParser.java +++ b/cadworld-service/src/main/java/com/linkerbot/cadworld/service/demand/DemandNumberParser.java @@ -28,19 +28,21 @@ public final class DemandNumberParser { Matcher match = Pattern.compile("^(\\d+(?:\\.\\d+)?)\\s*(.*?)$").matcher(sourceNumber(raw.trim())); if (!match.matches()) throw new IllegalArgumentException("数值格式不明确"); String unit = match.group(2).toLowerCase(Locale.ROOT).replaceAll("\\s", ""); - String factor = "degreesOfFreedom".equals(field) + String factor = "quantity".equals(field) + ? List.of("", "个", "件", "条", "只", "套", "支").contains(unit) ? "1" : null + : "degreesOfFreedom".equals(field) ? List.of("", "dof", "自由度", "个自由度").contains(unit) ? "1" : null : "massKg".equals(field) ? MASS.get(unit) : TORQUE.get(unit); if (factor == null) throw new IllegalArgumentException("单位缺失或尚未支持"); BigDecimal value = new BigDecimal(match.group(1)).multiply(new BigDecimal(factor)).stripTrailingZeros(); - if ("degreesOfFreedom".equals(field)) { + if ("degreesOfFreedom".equals(field) || "quantity".equals(field)) { try { value.intValueExact(); } catch (ArithmeticException exception) { - throw new IllegalArgumentException("自由度须为非负整数且不超过2147483647"); + throw new IllegalArgumentException("quantity".equals(field) ? "组件数量须为1至24的整数" : "自由度须为非负整数且不超过2147483647"); } } else if (value.scale() > 6 || value.compareTo(new BigDecimal("1000000000000")) >= 0) { throw new IllegalArgumentException("数值超出后端DECIMAL(18,6)支持范围"); } - if (!"degreesOfFreedom".equals(field) && BigDecimal.valueOf(value.doubleValue()).compareTo(value) != 0) { + if (!"degreesOfFreedom".equals(field) && !"quantity".equals(field) && BigDecimal.valueOf(value.doubleValue()).compareTo(value) != 0) { throw new IllegalArgumentException("数值超出浏览器可精确序列化范围"); } return value; @@ -65,12 +67,19 @@ public final class DemandNumberParser { static boolean inEvidence(String field, String raw, String evidence, List fragments) { BigDecimal expected = parse(field, raw); + if ("quantity".equals(field)) { + Matcher labelled = Pattern.compile("(?:数量|数目)(?:为|是|:|:)?\\s*(" + NUMBERS + ")").matcher(evidence); + while (labelled.find()) { + try { if (parse(field, labelled.group(1)).compareTo(expected) == 0) return true; } + catch (IllegalArgumentException exception) { /* 不将小数截断为数量。 */ } + } + } Matcher matches = evidencePattern(field).matcher(evidence); while (matches.find()) { try { if (parse(field, matches.group()).compareTo(expected) == 0) return true; } catch (IllegalArgumentException exception) { /* 不使用歧义数值。 */ } } - if ("degreesOfFreedom".equals(field) || fragments.size() < 2) return false; + if ("degreesOfFreedom".equals(field) || "quantity".equals(field) || fragments.size() < 2) return false; Matcher split = Pattern.compile("^(\\d+(?:\\.\\d+)?)\\s*(.*?)$").matcher(sourceNumber(raw.trim())); if (!split.matches() || split.group(2).isEmpty()) return false; for (int i = 0; i < fragments.size(); i++) { @@ -87,9 +96,13 @@ public final class DemandNumberParser { return false; } - private static Pattern evidencePattern(String field) { return Pattern.compile(NUMBERS + "\\s*" + units(field), Pattern.CASE_INSENSITIVE); } + private static Pattern evidencePattern(String field) { + String boundary = "quantity".equals(field) ? "(? "(?:个|件|条|只|套|支)"; case "massKg" -> "(?:千克|公斤|kg|克|g|吨|t|斤)"; case "torqueNm" -> "(?:N\\s*[·.*]?\\s*(?:cm|m)|牛顿·?米|牛·?米)"; default -> "(?:个?自由度|dof)?"; diff --git a/cadworld-service/src/main/java/com/linkerbot/cadworld/service/demand/DemandRequirementChecker.java b/cadworld-service/src/main/java/com/linkerbot/cadworld/service/demand/DemandRequirementChecker.java index bb33820..ef60c95 100644 --- a/cadworld-service/src/main/java/com/linkerbot/cadworld/service/demand/DemandRequirementChecker.java +++ b/cadworld-service/src/main/java/com/linkerbot/cadworld/service/demand/DemandRequirementChecker.java @@ -112,22 +112,28 @@ public final class DemandRequirementChecker { JsonNode expected = target.get(field); if (expected == null || expected.isNull() || !intentContains(field, expected, intent, analysis)) { allMapped = false; break; } String role = target.path("category").asText(); - JsonNode actual; - if (role.isEmpty()) actual = "degreesOfFreedom".equals(field) ? json.valueToTree(match.totals().degreesOfFreedom()) : json.valueToTree(match.totals().massKg()); + List actuals = new ArrayList<>(); + if (role.isEmpty()) actuals.add("degreesOfFreedom".equals(field) ? json.valueToTree(match.totals().degreesOfFreedom()) : json.valueToTree(match.totals().massKg())); else { - PublicComponentResponse part = match.parts().stream().filter((PublicComponentResponse candidate) -> role.equals(candidate.category())).findFirst().orElse(null); - actual = part == null ? json.nullNode() : json.valueToTree(part).get(field); - if ("massKg".equals(field) && (actual == null || actual.isNull() || actual.decimalValue().signum() <= 0)) actual = json.nullNode(); + for (PublicComponentResponse part : match.parts()) if (role.equals(part.category())) { + JsonNode actual = json.valueToTree(part).get(field); + if ("massKg".equals(field) && (actual == null || actual.isNull() || actual.decimalValue().signum() <= 0)) actual = json.nullNode(); + actuals.add(actual == null ? json.nullNode() : actual); + } } - check.put("field", field); check.set("expected", expected); check.set("actual", actual == null ? json.nullNode() : actual); - if (!role.isEmpty()) { actualByRole.set(role, actual == null ? json.nullNode() : actual); expectedByRole.set(role, expected); } - if (actual == null || actual.isNull()) { unknown = true; continue; } - if (expected.isNumber()) { - int compared = actual.decimalValue().compareTo(expected.decimalValue()); - String operator = target.path("operators").path(field).asText("eq"); - allSatisfied &= "gte".equals(operator) ? compared >= 0 : "lte".equals(operator) ? compared <= 0 : compared == 0; - } else allSatisfied &= Set.of("material", "componentName").contains(field) - ? text.equivalent(actual.asText(), expected.asText()) : text.matches(actual.asText(), expected.asText()); + if (actuals.isEmpty()) actuals.add(json.nullNode()); + for (JsonNode actual : actuals) { + if (actual == null || actual.isNull()) { unknown = true; continue; } + if (expected.isNumber()) { + int compared = actual.decimalValue().compareTo(expected.decimalValue()); + String operator = target.path("operators").path(field).asText("eq"); + allSatisfied &= "gte".equals(operator) ? compared >= 0 : "lte".equals(operator) ? compared <= 0 : compared == 0; + } else allSatisfied &= Set.of("material", "componentName").contains(field) + ? text.equivalent(actual.asText(), expected.asText()) : text.matches(actual.asText(), expected.asText()); + } + JsonNode actual = actuals.size() == 1 ? actuals.get(0) : json.valueToTree(actuals); + check.put("field", field); check.set("expected", expected); check.set("actual", actual); + if (!role.isEmpty()) { actualByRole.set(role, actual); expectedByRole.set(role, expected); } } if (allMapped) { if (roles.size() > 1) { check.set("actual", actualByRole); check.set("expected", expectedByRole); } @@ -175,7 +181,7 @@ public final class DemandRequirementChecker { if (Set.of("task", "motion", "environment").contains(intent.path("dimension").asText())) return "functionDescription"; return null; } - private static List roles(String subject, String requirement) { + static List roles(String subject, String requirement) { String value = subject.matches(".*(?:整机|整体|全机|机器人).*") && !"exclusion".equals(subject) ? subject : subject + " " + requirement; // 禁止项常以整机为对象,具体排除角色写在 requirement 中。 if (requirement.matches(".*(?:不配备|不要|禁止|不包含|无尾).*")) value += " " + requirement; @@ -187,19 +193,19 @@ public final class DemandRequirementChecker { static boolean quantitySupported(JsonNode intent) { Integer expected = quantity(intent); - if (expected == null || expected <= 0) return false; + if (expected == null || expected < 1 || expected > 24) return false; List roles = roles(intent.path("subject").asText(), intent.path("requirement").asText()); - return roles.isEmpty() ? expected == 1 && intent.path("subject").asText().matches(".*(?:整机|整体|全机|机器人).*") : expected == roles.size(); + return roles.isEmpty() ? expected == 1 && intent.path("subject").asText().matches(".*(?:整机|整体|全机|机器人).*") : roles.size() == 1 || expected == roles.size(); } - private static Integer quantity(JsonNode intent) { - String numberPattern = "([0-9]+|[零一二两三四五六七八九十百]+)"; + static Integer quantity(JsonNode intent) { + String numberPattern = "(? ports, int invalidPorts) { - private static final Set JOINT_TYPES = Set.of("fixed", "revolute", "continuous", "prismatic", "floating", "planar"); - private static final List ZERO_POSE = List.of(BigDecimal.ZERO, BigDecimal.ZERO, BigDecimal.ZERO); +import java.util.Locale; +/** 接口兼容性只比较原始child;数组下标标识接口,不合并同child的多个安装位置。 */ +public record AssemblyMetadata(String rootLink, List ports, List problems) { static AssemblyMetadata read(Component component) { - JsonNode info = component.getUrdfInfo(); - if (NormalizedMatchRequest.text(component.getStepObjectKey()).isEmpty() - || NormalizedMatchRequest.text(component.getUrdfMainObjectKey()).isEmpty() || info == null || !info.isObject() - || !info.path("rootLink").isTextual() || info.path("rootLink").asText().isBlank() - || !info.path("frames").isArray()) return null; - Map nameCounts = new HashMap<>(); - for (JsonNode frame : info.path("frames")) { - if (frame.path("name").isTextual()) nameCounts.merge(frame.path("name").asText(), 1, Integer::sum); - } + return read(component.getUrdfInfo()); + } + + public static AssemblyMetadata read(JsonNode info) { List ports = new ArrayList<>(); - int invalid = 0; - for (JsonNode frame : info.path("frames")) { - // 没有interfaceType的普通URDF关节不是对外安装端口。 - boolean explicitInterface = frame.hasNonNull("interfaceType") && !frame.path("interfaceType").asText().isBlank(); - String childName = frame.path("child").asText(); - String inferredInterface = childName.startsWith("LINK_") ? childName.substring(5) : ""; - if ("head".equals(inferredInterface)) inferredInterface = "head_0"; - if ("torso".equals(inferredInterface)) inferredInterface = "torso_0"; - if ("waist".equals(inferredInterface)) inferredInterface = "waist_0"; - if ("tail".equals(inferredInterface)) inferredInterface = "tail_0"; - ComponentRole inferredRole = ComponentRole.find(inferredInterface).orElse(null); - if (!explicitInterface && inferredRole == null) continue; - ComponentRole role = explicitInterface && frame.path("interfaceType").isTextual() - ? ComponentRole.find(frame.path("interfaceType").asText()).orElse(null) : explicitInterface ? null : inferredRole; - String name = frame.path("name").isTextual() ? frame.path("name").asText() : ""; - boolean implicitOrigin = frame.path("originExplicit").isBoolean() && !frame.path("originExplicit").asBoolean(); - List xyz = pose(frame.get("xyz"), implicitOrigin); - List rpy = pose(frame.get("rpy"), implicitOrigin); - if (role == null || name.isBlank() || nameCounts.getOrDefault(name, 0) != 1 - || !"joint".equals(frame.path("kind").asText()) || !JOINT_TYPES.contains(frame.path("type").asText()) - || !frame.path("parent").isTextual() || frame.path("parent").asText().isBlank() - || !frame.path("child").isTextual() || frame.path("child").asText().isBlank() - || xyz == null || rpy == null) { - invalid++; + List problems = new ArrayList<>(); + String root = info == null ? "" : info.path("rootLink").asText(""); + if (info == null || !info.isObject() || !info.path("frames").isArray()) { + problems.add(new Problem("INVALID_INTERFACE_LIST", null, "组件缺少有效的frames接口清单")); + return new AssemblyMetadata(root, List.of(), List.copyOf(problems)); + } + for (int index = 0; index < info.path("frames").size(); index++) { + JsonNode frame = info.path("frames").get(index); + if (!frame.path("child").isTextual() || frame.path("child").asText().isBlank()) { + problems.add(new Problem("INVALID_INTERFACE_CHILD", index, "接口child为空或格式不正确,已跳过")); continue; } - ports.add(new Port(name, role, frame.path("parent").asText(), xyz, rpy)); + String child = frame.path("child").asText(); + ComponentRole role = ComponentRole.find(frame.path("interfaceType").asText()).orElse(null); + if (role == null) role = roleFromChild(child); + if (role == null) problems.add(new Problem("UNKNOWN_INTERFACE_TYPE", index, "接口类型无法识别,不能从此接口向外扩展")); + ports.add(new Port(index, frame.path("name").asText(""), child, role, frame.path("parent").asText(""))); } - ports.sort(java.util.Comparator.comparing(Port::name)); - return new AssemblyMetadata(info.path("rootLink").asText(), List.copyOf(ports), invalid); + return new AssemblyMetadata(root, List.copyOf(ports), List.copyOf(problems)); } + private static ComponentRole roleFromChild(String child) { + if (!child.regionMatches(true, 0, "LINK_", 0, 5)) return null; + String code = child.substring(5).toLowerCase(Locale.ROOT); + if (List.of("head", "torso", "waist", "tail").contains(code)) code += "_0"; + return ComponentRole.find(code).orElse(null); + } + + int invalidPorts() { return problems.size(); } + int interfaceMask() { int mask = 0; - for (Port port : ports) mask |= port.role().bit(); + for (Port port : ports) if (port.role() != null) mask |= port.role().bit(); return mask; } - private static List pose(JsonNode value, boolean implicitOrigin) { - if (value == null || value.isNull()) return implicitOrigin ? ZERO_POSE : null; - if (!value.isArray() || value.size() != 3) return null; - List result = new ArrayList<>(3); - for (JsonNode number : value) { - if (!number.isNumber() || !Double.isFinite(number.doubleValue())) return null; - result.add(number.decimalValue()); - } - return List.copyOf(result); + String signature() { + return ports.stream().map((Port port) -> port.role() + ":" + port.child()) + .sorted().collect(java.util.stream.Collectors.joining("\u0000")); } - record Port(String name, ComponentRole role, String parentLink, List xyz, List rpy) { } + record Port(int index, String name, String child, ComponentRole role, String parentLink) { } + public record Problem(String code, Integer frameIndex, String message) { } } diff --git a/cadworld-service/src/main/java/com/linkerbot/cadworld/service/matching/AssemblySearchEngine.java b/cadworld-service/src/main/java/com/linkerbot/cadworld/service/matching/AssemblySearchEngine.java index 931413b..cd9a879 100644 --- a/cadworld-service/src/main/java/com/linkerbot/cadworld/service/matching/AssemblySearchEngine.java +++ b/cadworld-service/src/main/java/com/linkerbot/cadworld/service/matching/AssemblySearchEngine.java @@ -17,9 +17,11 @@ public class AssemblySearchEngine { private final MatchingProperties properties; private final RequirementEvaluator evaluator; - static final Comparator FINAL_ORDER = Comparator.comparingInt((ScoredState state) -> state.state().parts().size()).reversed() + static final Comparator FINAL_ORDER = Comparator.comparingInt(ScoredState::missingTypes) + .thenComparingInt(ScoredState::missingMinimum) .thenComparingInt((ScoredState state) -> state.evaluation().hardUnmetCount()) .thenComparing((ScoredState state) -> state.evaluation().deviation()) + .thenComparing(Comparator.comparingInt((ScoredState state) -> state.state().parts().size()).reversed()) .thenComparingInt((ScoredState state) -> state.evaluation().preferredUnmetCount()) .thenComparing((ScoredState state) -> state.evaluation().preferredDeviation()) .thenComparing(Comparator.comparingInt((ScoredState state) -> state.evaluation().keywordScore()).reversed()) @@ -28,12 +30,14 @@ public class AssemblySearchEngine { .thenComparing(ScoredState::key); private static final Comparator BEAM_ORDER = Comparator.comparingInt((ScoredState state) -> state.estimate().possibleParts()).reversed() + .thenComparingInt(ScoredState::missingTypes) + .thenComparingInt(ScoredState::missingMinimum) .thenComparingInt((ScoredState state) -> state.estimate().unmet()) .thenComparing((ScoredState state) -> state.estimate().deviation()) .thenComparing(Comparator.comparingInt((ScoredState state) -> state.estimate().keywordScore()).reversed()) .thenComparing(FINAL_ORDER); - /** 两轮搜索共用已选定的躯干,不再以覆盖数量或整机总量替换根组件。 */ + /** 先固定躯干;只从已连接实例向外扩展,且优先处理距离躯干最近的可用接口。 */ Result search(CandidatePool.Result pool, NormalizedMatchRequest request, int budget, MatchingCandidate torso) { if (torso == null) return new Result(null, pool.limited(), 0); if (torso.role() != ComponentRole.TORSO) throw new IllegalArgumentException("Assembly root must be a torso"); @@ -41,12 +45,9 @@ public class AssemblySearchEngine { pool.candidates().forEach((ComponentRole role, List candidates) -> { if (!candidates.isEmpty()) summaries.put(role, RequirementEvaluator.summarize(candidates, request.keywords().size())); }); - List beam = new ArrayList<>(); - beam.add(score(AssemblyState.root(torso), request, summaries)); - ScoredState best = beam.stream().min(FINAL_ORDER).orElseThrow(); - boolean limited = pool.limited() || beam.size() > properties.beamWidth(); - beam.sort(BEAM_ORDER); - beam = new ArrayList<>(beam.subList(0, Math.min(beam.size(), properties.beamWidth()))); + List beam = List.of(score(AssemblyState.root(torso), request, summaries)); + ScoredState best = beam.get(0); + boolean limited = pool.limited(); int expansions = 0; boolean budgetExhausted = false; while (!beam.isEmpty()) { @@ -55,18 +56,23 @@ public class AssemblySearchEngine { expansion: for (ScoredState current : beam) { AssemblyState state = current.state(); - for (Map.Entry parent : state.parts().entrySet()) { + boolean coverTypes = hasMinimumAttachment(state, pool, request, true); + boolean coverMinimum = coverTypes || hasMinimumAttachment(state, pool, request, false); + int frontierDepth = Integer.MAX_VALUE; + for (Map.Entry parent : state.parts().entrySet()) { + int depth = state.depth(parent.getKey()); + if (depth > frontierDepth) continue; for (AssemblyMetadata.Port port : parent.getValue().metadata().ports()) { - if (state.parts().containsKey(port.role()) || state.portUsed(parent.getKey(), port.name())) continue; - for (MatchingCandidate child : pool.candidates().getOrDefault(port.role(), List.of())) { - if (expansions >= budget) { - budgetExhausted = true; - break expansion; - } + if (port.role() == null || !request.canAdd(port.role(), state.count(port.role())) || state.portUsed(parent.getKey(), port.index())) continue; + if (coverMinimum && state.count(port.role()) >= request.minimum(port.role())) continue; + if (coverTypes && state.count(port.role()) > 0) continue; + for (CandidatePool.Attachment target : pool.targets(port.role(), port.child())) { + frontierDepth = Math.min(frontierDepth, depth); + if (state.parts().size() >= AssemblyState.MAX_INSTANCES) { limited = true; continue; } + if (expansions >= budget) { budgetExhausted = true; break expansion; } expansions++; - AssemblyState attached = state.attach(parent.getKey(), port, child); - String key = attached.key(); - if (!seen.add(key)) continue; + AssemblyState attached = state.attach(parent.getKey(), port, target.candidate(), target.port()); + if (!seen.add(attached.key())) continue; ScoredState scored = score(attached, request, summaries); if (FINAL_ORDER.compare(scored, best) < 0) best = scored; next.add(scored); @@ -82,13 +88,26 @@ public class AssemblySearchEngine { return new Result(best, limited, expansions); } - ScoredState score(AssemblyState state, NormalizedMatchRequest request, - Map summaries) { + ScoredState score(AssemblyState state, NormalizedMatchRequest request, Map summaries) { RequirementEvaluator.Evaluation evaluation = evaluator.evaluate(state, request); - return new ScoredState(state, evaluation, evaluator.estimate(state, evaluation, summaries, request), state.key()); + int missing = request.roles().stream().mapToInt((ComponentRole role) -> Math.max(0, request.minimum(role) - state.count(role))).sum(); + int missingTypes = (int) request.roles().stream().filter((ComponentRole role) -> state.count(role) == 0).count(); + return new ScoredState(state, evaluation, evaluator.estimate(state, evaluation, summaries, request), state.key(), missing, missingTypes); + } + + private boolean hasMinimumAttachment(AssemblyState state, CandidatePool.Result pool, NormalizedMatchRequest request, boolean uncoveredOnly) { + for (Map.Entry parent : state.parts().entrySet()) { + for (AssemblyMetadata.Port port : parent.getValue().metadata().ports()) { + if (port.role() == null || !request.canAdd(port.role(), state.count(port.role())) + || state.count(port.role()) >= request.minimum(port.role()) || state.portUsed(parent.getKey(), port.index())) continue; + if (uncoveredOnly && state.count(port.role()) > 0) continue; + if (!pool.targets(port.role(), port.child()).isEmpty()) return true; + } + } + return false; } record ScoredState(AssemblyState state, RequirementEvaluator.Evaluation evaluation, - RequirementEvaluator.Estimate estimate, String key) { } + RequirementEvaluator.Estimate estimate, String key, int missingMinimum, int missingTypes) { } record Result(ScoredState best, boolean limited, int expansions) { } } diff --git a/cadworld-service/src/main/java/com/linkerbot/cadworld/service/matching/AssemblyState.java b/cadworld-service/src/main/java/com/linkerbot/cadworld/service/matching/AssemblyState.java index 752e737..96e4886 100644 --- a/cadworld-service/src/main/java/com/linkerbot/cadworld/service/matching/AssemblyState.java +++ b/cadworld-service/src/main/java/com/linkerbot/cadworld/service/matching/AssemblyState.java @@ -3,98 +3,107 @@ package com.linkerbot.cadworld.service.matching; import com.linkerbot.cadworld.dto.matching.RobotMatchResponse.Connection; import java.util.ArrayList; import java.util.Collections; -import java.util.Comparator; -import java.util.EnumMap; import java.util.HashSet; +import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Set; -record AssemblyState(ComponentRole root, Map parts, List edges) { +/** 结果内实例独立;同款组件可复用,每个接口下标在每个实例中只能占用一次。 */ +record AssemblyState(ComponentRole root, Map parts, List edges) { + static final int MAX_INSTANCES = 24; + AssemblyState { - if (root != ComponentRole.TORSO || !parts.containsKey(ComponentRole.TORSO)) { + if (root != ComponentRole.TORSO || parts.values().stream().filter((MatchingCandidate item) -> item.role() == ComponentRole.TORSO).count() != 1) { throw new IllegalArgumentException("Assembly must contain exactly one torso as its root"); } - Map copy = new EnumMap<>(ComponentRole.class); - copy.putAll(parts); - parts = Collections.unmodifiableMap(copy); - edges = edges.stream().sorted(Comparator.comparingInt((Edge edge) -> edge.child().ordinal())).toList(); + parts = Collections.unmodifiableMap(new LinkedHashMap<>(parts)); + edges = List.copyOf(edges); } static AssemblyState root(MatchingCandidate candidate) { - return new AssemblyState(candidate.role(), Map.of(candidate.role(), candidate), List.of()); + return new AssemblyState(ComponentRole.TORSO, Map.of("torso_0:1", candidate), List.of()); } - AssemblyState attach(ComponentRole parent, AssemblyMetadata.Port port, MatchingCandidate child) { - if (!parts.containsKey(parent) || parts.containsKey(child.role()) || child.role() == ComponentRole.TORSO - || port.role() != child.role() || portUsed(parent, port.name())) { - throw new IllegalArgumentException("Invalid or duplicate assembly component attachment"); + int count(ComponentRole role) { + return (int) parts.values().stream().filter((MatchingCandidate candidate) -> candidate.role() == role).count(); + } + + AssemblyState attach(String parent, AssemblyMetadata.Port parentPort, MatchingCandidate candidate, AssemblyMetadata.Port childPort) { + if (!parts.containsKey(parent) || candidate.role() == ComponentRole.TORSO || parts.size() >= MAX_INSTANCES + || parentPort.role() != candidate.role() || !parentPort.child().equals(childPort.child()) || portUsed(parent, parentPort.index())) { + throw new IllegalArgumentException("Invalid assembly component attachment"); } - Map next = new EnumMap<>(ComponentRole.class); - next.putAll(parts); - next.put(child.role(), child); + String child = candidate.role().code() + ":" + (count(candidate.role()) + 1); + Map next = new LinkedHashMap<>(parts); + next.put(child, candidate); List connections = new ArrayList<>(edges); - connections.add(new Edge(parent, port, child.role())); + connections.add(new Edge(parent, parentPort, child, childPort)); return new AssemblyState(root, next, connections); } - boolean portUsed(ComponentRole parent, String name) { - return edges.stream().anyMatch((Edge edge) -> edge.parent() == parent && edge.port().name().equals(name)); + boolean portUsed(String instance, int index) { + return edges.stream().anyMatch((Edge edge) -> (edge.parent().equals(instance) && edge.parentPort().index() == index) + || (edge.child().equals(instance) && edge.childPort().index() == index)); } - AssemblyState replace(MatchingCandidate replacement) { - ComponentRole role = replacement.role(); - Map next = new EnumMap<>(ComponentRole.class); - next.putAll(parts); - next.put(role, replacement); + int depth(String instance) { + int depth = 0; + String current = instance; + for (Edge edge : edges.reversed()) { + if (edge.child().equals(current)) { depth++; current = edge.parent(); } + } + return depth; + } + + AssemblyState replace(String instance, MatchingCandidate replacement) { + if (parts.get(instance).role() != replacement.role()) return null; + Map next = new LinkedHashMap<>(parts); + next.put(instance, replacement); List connections = new ArrayList<>(); - Set used = new HashSet<>(); + Set used = new HashSet<>(); for (Edge edge : edges) { - if (edge.parent() != role) { - connections.add(edge); - continue; - } + boolean parent = edge.parent().equals(instance); + boolean child = edge.child().equals(instance); + if (!parent && !child) { connections.add(edge); continue; } + AssemblyMetadata.Port old = parent ? edge.parentPort() : edge.childPort(); AssemblyMetadata.Port port = replacement.metadata().ports().stream() - .filter((AssemblyMetadata.Port available) -> available.role() == edge.child() && !used.contains(available.name())) - .sorted(Comparator.comparing((AssemblyMetadata.Port available) -> !available.name().equals(edge.port().name())) - .thenComparing(AssemblyMetadata.Port::name)) + .filter((AssemblyMetadata.Port item) -> !used.contains(item.index()) && item.child().equals(old.child()) + && (!parent || item.role() == parts.get(edge.child()).role())) + .sorted(java.util.Comparator.comparing((AssemblyMetadata.Port item) -> item.index() != old.index()) + .thenComparingInt(AssemblyMetadata.Port::index)) .findFirst().orElse(null); if (port == null) return null; - used.add(port.name()); - connections.add(new Edge(role, port, edge.child())); + used.add(port.index()); + connections.add(new Edge(edge.parent(), parent ? port : edge.parentPort(), edge.child(), child ? port : edge.childPort())); } return new AssemblyState(root, next, connections); } List connections() { - return edges.stream().map((Edge edge) -> new Connection(edge.parent().code(), parts.get(edge.parent()).code(), - edge.port().parentLink(), edge.port().name(), edge.child().code(), parts.get(edge.child()).code(), - parts.get(edge.child()).metadata().rootLink(), edge.port().xyz(), edge.port().rpy())).toList(); + return edges.stream().map((Edge edge) -> { + MatchingCandidate parent = parts.get(edge.parent()); + MatchingCandidate child = parts.get(edge.child()); + return new Connection(parent.role().code(), parent.code(), edge.parentPort().parentLink(), edge.parentPort().name(), + child.role().code(), child.code(), child.metadata().rootLink(), edge.parent(), edge.child(), + edge.parentPort().child(), edge.parentPort().index(), edge.childPort().index()); + }).toList(); } int selectedMask() { int mask = 0; - for (ComponentRole role : parts.keySet()) mask |= role.bit(); + for (MatchingCandidate candidate : parts.values()) mask |= candidate.role().bit(); return mask; } String key() { StringBuilder key = new StringBuilder(); - key.append(root.ordinal()).append('/'); - parts.forEach((ComponentRole role, MatchingCandidate candidate) -> { - key.append(role.ordinal()).append(':'); - appendToken(key, candidate.code()); - }); - for (Edge edge : edges) { - key.append(edge.parent().ordinal()).append('>').append(edge.child().ordinal()).append(':'); - appendToken(key, edge.port().name()); - } + parts.forEach((String instance, MatchingCandidate candidate) -> key.append(instance).append(':') + .append(candidate.code().length()).append(':').append(candidate.code()).append('/')); + for (Edge edge : edges) key.append(edge.parent()).append('@').append(edge.parentPort().index()) + .append('>').append(edge.child()).append('@').append(edge.childPort().index()).append('/'); return key.toString(); } - private static void appendToken(StringBuilder target, String value) { - target.append(value.length()).append(':').append(value).append('/'); - } - - record Edge(ComponentRole parent, AssemblyMetadata.Port port, ComponentRole child) { } + record Edge(String parent, AssemblyMetadata.Port parentPort, String child, AssemblyMetadata.Port childPort) { } } diff --git a/cadworld-service/src/main/java/com/linkerbot/cadworld/service/matching/CandidatePool.java b/cadworld-service/src/main/java/com/linkerbot/cadworld/service/matching/CandidatePool.java index a0c11d0..ab7ce78 100644 --- a/cadworld-service/src/main/java/com/linkerbot/cadworld/service/matching/CandidatePool.java +++ b/cadworld-service/src/main/java/com/linkerbot/cadworld/service/matching/CandidatePool.java @@ -19,6 +19,7 @@ final class CandidatePool { private final MatchingProperties properties; private final Map accumulators = new EnumMap<>(ComponentRole.class); private final Comparator demandOrder; + private final Comparator demandScore; private int scanned; private int invalidMetadata; private int invalidPorts; @@ -29,13 +30,14 @@ final class CandidatePool { this.evaluator = evaluator; this.properties = properties; int requestedMask = request.roles().stream().mapToInt(ComponentRole::bit).reduce(0, (int left, int right) -> left | right); - this.demandOrder = Comparator.comparingInt((MatchingCandidate candidate) -> candidate.assessment().hardUnmetCount()) + this.demandScore = Comparator.comparingInt((MatchingCandidate candidate) -> candidate.assessment().hardUnmetCount()) .thenComparing((MatchingCandidate candidate) -> candidate.assessment().deviation()) .thenComparingInt((MatchingCandidate candidate) -> candidate.assessment().preferredUnmetCount()) .thenComparing((MatchingCandidate candidate) -> candidate.assessment().preferredDeviation()) .thenComparing((MatchingCandidate candidate) -> !candidate.assessment().robotFunctionMatched()) .thenComparing(Comparator.comparingInt((MatchingCandidate candidate) -> - java.util.Arrays.stream(candidate.assessment().keywordScores()).sum()).reversed()) + java.util.Arrays.stream(candidate.assessment().keywordScores()).sum()).reversed()); + this.demandOrder = demandScore .thenComparing(Comparator.comparingInt((MatchingCandidate candidate) -> Integer.bitCount(candidate.metadata().interfaceMask() & requestedMask & ~ComponentRole.TORSO.bit())).reversed()) .thenComparing(MatchingCandidate::code); @@ -48,11 +50,7 @@ final class CandidatePool { accumulator.observed++; scanned++; AssemblyMetadata metadata = AssemblyMetadata.read(component); - if (metadata == null) { - invalidMetadata++; - sampleInvalidCode(component.getComponentCode()); - return; - } + if (metadata.problems().stream().anyMatch((AssemblyMetadata.Problem item) -> "INVALID_INTERFACE_LIST".equals(item.code()))) invalidMetadata++; invalidPorts += metadata.invalidPorts(); if (metadata.invalidPorts() > 0) sampleInvalidCode(component.getComponentCode()); MatchingCandidate candidate = new MatchingCandidate(component, role, metadata, evaluator.assess(component, role, request)); @@ -61,6 +59,23 @@ final class CandidatePool { List invalidCodeSamples() { return List.copyOf(invalidCodeSamples); } + MatchingCandidate torso(Result pool) { + return pool.candidates().getOrDefault(ComponentRole.TORSO, List.of()).stream() + .min(demandScore.thenComparing(Comparator.comparingInt((MatchingCandidate candidate) -> compatibleCoverage(candidate, pool)).reversed()) + .thenComparing(MatchingCandidate::code)).orElse(null); + } + + private int compatibleCoverage(MatchingCandidate candidate, Result pool) { + int covered = 0; + for (ComponentRole role : request.roles()) { + if (role == ComponentRole.TORSO) continue; + long ports = candidate.metadata().ports().stream().filter((AssemblyMetadata.Port port) -> port.role() == role + && !pool.targets(role, port.child()).isEmpty()).count(); + covered += (int) Math.min(request.minimum(role), ports); + } + return covered; + } + private void sampleInvalidCode(String code) { if (invalidCodeSamples.size() < 5) invalidCodeSamples.add(code); } @@ -83,7 +98,7 @@ final class CandidatePool { private final class Accumulator { private final List best = new ArrayList<>(); - private final Map interfaces = new HashMap<>(); + private final Map interfaces = new HashMap<>(); private MatchingCandidate minimumDegrees; private MatchingCandidate maximumDegrees; private MatchingCandidate minimumMass; @@ -96,8 +111,7 @@ final class CandidatePool { best.add(candidate); best.sort(demandOrder); if (best.size() > properties.candidatesPerRole()) best.remove(best.size() - 1); - int requestedMask = request.roles().stream().mapToInt(ComponentRole::bit).reduce(0, (int left, int right) -> left | right); - int signature = candidate.metadata().interfaceMask() & requestedMask; + String signature = candidate.metadata().signature(); interfaces.merge(signature, candidate, (MatchingCandidate left, MatchingCandidate right) -> demandOrder.compare(left, right) <= 0 ? left : right); minimumDegrees = extreme(minimumDegrees, candidate, (MatchingCandidate value) -> @@ -122,9 +136,8 @@ final class CandidatePool { add(selected, maximumMass); } interfaces.entrySet().stream() - .sorted(Comparator.>comparingInt((Map.Entry entry) -> - Integer.bitCount(entry.getKey())).reversed().thenComparing(Map.Entry::getValue, demandOrder)) - .forEach((Map.Entry entry) -> add(selected, entry.getValue())); + .sorted(Map.Entry.comparingByValue(demandOrder)) + .forEach((Map.Entry entry) -> add(selected, entry.getValue())); best.forEach((MatchingCandidate candidate) -> add(selected, candidate)); return selected.values().stream().sorted(demandOrder).toList(); } @@ -142,6 +155,31 @@ final class CandidatePool { } } + record Attachment(MatchingCandidate candidate, AssemblyMetadata.Port port) { } + record Result(Map> candidates, Map observed, - Map eligible, boolean limited, int scanned, int invalidMetadata, int invalidPorts) { } + Map eligible, boolean limited, int scanned, int invalidMetadata, int invalidPorts, + Map>> interfaces) { + Result(Map> candidates, Map observed, + Map eligible, boolean limited, int scanned, int invalidMetadata, int invalidPorts) { + this(candidates, observed, eligible, limited, scanned, invalidMetadata, invalidPorts, index(candidates)); + } + + List targets(ComponentRole role, String child) { + return interfaces.getOrDefault(role, Map.of()).getOrDefault(child, List.of()); + } + + private static Map>> index(Map> candidates) { + Map>> result = new EnumMap<>(ComponentRole.class); + candidates.forEach((ComponentRole role, List items) -> { + Map> byChild = new LinkedHashMap<>(); + for (MatchingCandidate candidate : items) for (AssemblyMetadata.Port port : candidate.metadata().ports()) { + byChild.computeIfAbsent(port.child(), (String key) -> new ArrayList<>()).add(new Attachment(candidate, port)); + } + byChild.replaceAll((String key, List values) -> List.copyOf(values)); + result.put(role, Map.copyOf(byChild)); + }); + return Map.copyOf(result); + } + } } diff --git a/cadworld-service/src/main/java/com/linkerbot/cadworld/service/matching/NormalizedMatchRequest.java b/cadworld-service/src/main/java/com/linkerbot/cadworld/service/matching/NormalizedMatchRequest.java index 99a033a..f0c9064 100644 --- a/cadworld-service/src/main/java/com/linkerbot/cadworld/service/matching/NormalizedMatchRequest.java +++ b/cadworld-service/src/main/java/com/linkerbot/cadworld/service/matching/NormalizedMatchRequest.java @@ -36,10 +36,11 @@ record NormalizedMatchRequest(List roles, List keywords, ComponentRole role = ComponentRole.require(part.category()); if (!roles.contains(role)) throw invalid("部件条件的category必须包含在requiredParts中"); if (parts.containsKey(role)) throw invalid("同一组件角色不得重复定义部件条件"); + if (part.quantity() != null && (part.quantity() < 1 || part.quantity() > 24)) throw invalid("组件数量必须为1至24的整数"); parts.put(role, new PartRequirements(role.code(), text(part.material()), part.degreesOfFreedom(), part.massKg(), part.torqueNm(), text(part.functionDescription()), text(part.shape()), text(part.size()), operators(part.operators(), numericValues(part.degreesOfFreedom(), part.massKg(), part.torqueNm())), - text(part.componentName()), text(part.description()))); + text(part.componentName()), text(part.description()), part.quantity())); } Set keywords = new LinkedHashSet<>(); for (String keyword : request.requirements() == null ? List.of() : request.requirements()) { @@ -50,6 +51,14 @@ record NormalizedMatchRequest(List roles, List keywords, boolean preferred(String category, String field) { return softFields.contains((category == null ? "robot" : category) + ":" + field); } + Integer quantity(ComponentRole role) { return parts.containsKey(role) ? parts.get(role).quantity() : null; } + + int minimum(ComponentRole role) { return quantity(role) == null ? 1 : quantity(role); } + + boolean canAdd(ComponentRole role, int current) { + return role != ComponentRole.TORSO && roles.contains(role) && (quantity(role) == null || current < quantity(role)); + } + private static Map numericValues(Integer degrees, java.math.BigDecimal mass, java.math.BigDecimal torque) { Map values = new LinkedHashMap<>(); values.put("degreesOfFreedom", degrees); diff --git a/cadworld-service/src/main/java/com/linkerbot/cadworld/service/matching/PublicComponentQueryService.java b/cadworld-service/src/main/java/com/linkerbot/cadworld/service/matching/PublicComponentQueryService.java index 9a30452..4d61354 100644 --- a/cadworld-service/src/main/java/com/linkerbot/cadworld/service/matching/PublicComponentQueryService.java +++ b/cadworld-service/src/main/java/com/linkerbot/cadworld/service/matching/PublicComponentQueryService.java @@ -36,7 +36,9 @@ public class PublicComponentQueryService { .isNotNull(Component::getStepObjectKey).ne(Component::getStepObjectKey, "") .isNotNull(Component::getUrdfMainObjectKey).ne(Component::getUrdfMainObjectKey, "") .gt(Component::getId, cursor).orderByAsc(Component::getId).last("LIMIT 200")); - for (Component component : page) consumer.accept(component); + for (Component component : page) { + if (!component.getStepObjectKey().isBlank() && !component.getUrdfMainObjectKey().isBlank()) consumer.accept(component); + } if (page.size() < 200) return; cursor = page.get(page.size() - 1).getId(); } diff --git a/cadworld-service/src/main/java/com/linkerbot/cadworld/service/matching/RequirementEvaluator.java b/cadworld-service/src/main/java/com/linkerbot/cadworld/service/matching/RequirementEvaluator.java index 26e58a9..fbff586 100644 --- a/cadworld-service/src/main/java/com/linkerbot/cadworld/service/matching/RequirementEvaluator.java +++ b/cadworld-service/src/main/java/com/linkerbot/cadworld/service/matching/RequirementEvaluator.java @@ -121,16 +121,20 @@ public class RequirementEvaluator { mergeScores(scores, candidate.assessment().keywordScores()); } for (Map.Entry entry : summaries.entrySet()) { - if ((possible & ~selected & entry.getKey().bit()) == 0) continue; + ComponentRole role = entry.getKey(); + if ((possible & role.bit()) == 0 || role == ComponentRole.TORSO) continue; + int remainingMin = Math.max(0, request.minimum(role) - state.count(role)); + int remainingMax = request.quantity(role) == null ? AssemblyState.MAX_INSTANCES - state.parts().size() : remainingMin; + if (remainingMax == 0) continue; PoolSummary summary = entry.getValue(); - minimumDegrees = minimumDegrees.add(summary.minimumDegrees()); - maximumDegrees = maximumDegrees.add(summary.maximumDegrees()); - minimumMass = minimumMass.add(summary.minimumMass()); - maximumMass = maximumMass.add(summary.maximumMass()); + minimumDegrees = minimumDegrees.add(summary.minimumDegrees().multiply(BigDecimal.valueOf(remainingMin))); + maximumDegrees = maximumDegrees.add(summary.maximumDegrees().multiply(BigDecimal.valueOf(remainingMax))); + minimumMass = minimumMass.add(summary.minimumMass().multiply(BigDecimal.valueOf(remainingMin))); + maximumMass = maximumMass.add(summary.maximumMass().multiply(BigDecimal.valueOf(remainingMax))); massKnown &= summary.hasKnownMass(); functionMatched |= summary.functionMatched(); - unmet += summary.minimumUnmet(); - deviation = deviation.add(summary.minimumDeviation()); + unmet += summary.minimumUnmet() * remainingMin; + deviation = deviation.add(summary.minimumDeviation().multiply(BigDecimal.valueOf(remainingMin))); mergeScores(scores, summary.keywordScores()); } RobotRequirements robot = request.robot(); @@ -144,7 +148,13 @@ public class RequirementEvaluator { if (massGap.signum() > 0) unmet++; if (!request.preferred(null, "functionDescription") && !NormalizedMatchRequest.text(robot.functionDescription()).isEmpty() && !functionMatched) unmet++; int score = java.util.Arrays.stream(scores).sum(); - return new Estimate(Integer.bitCount(possible), unmet, deviation.add(degreesGap).add(massGap), score); + int potential = state.parts().size(); + for (ComponentRole role : request.roles()) { + if (role == ComponentRole.TORSO || (possible & role.bit()) == 0) continue; + potential += request.quantity(role) == null ? AssemblyState.MAX_INSTANCES - state.parts().size() + : Math.max(0, request.minimum(role) - state.count(role)); + } + return new Estimate(Math.min(AssemblyState.MAX_INSTANCES, potential), unmet, deviation.add(degreesGap).add(massGap), score); } static PoolSummary summarize(List candidates, int keywordCount) { diff --git a/cadworld-service/src/main/java/com/linkerbot/cadworld/service/matching/RobotMatchingService.java b/cadworld-service/src/main/java/com/linkerbot/cadworld/service/matching/RobotMatchingService.java index 69bb954..a73eac5 100644 --- a/cadworld-service/src/main/java/com/linkerbot/cadworld/service/matching/RobotMatchingService.java +++ b/cadworld-service/src/main/java/com/linkerbot/cadworld/service/matching/RobotMatchingService.java @@ -14,6 +14,7 @@ import java.util.ArrayList; import java.util.Comparator; import java.util.EnumMap; import java.util.LinkedHashSet; +import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Set; @@ -53,19 +54,19 @@ public class RobotMatchingService { CandidatePool collector = new CandidatePool(request, evaluator, properties); components.scan(request.roles(), collector::accept); CandidatePool.Result pool = collector.finish(); - MatchingCandidate torso = pool.candidates().getOrDefault(ComponentRole.TORSO, List.of()).stream().findFirst().orElse(null); + MatchingCandidate torso = collector.torso(pool); log.info("躯干选择完成 requestId={} candidateCount={} componentCode={} hardUnmetCount={} preferredUnmetCount={}", RequestIdHolder.get(), pool.eligible().get(ComponentRole.TORSO), torso == null ? null : torso.code(), torso == null ? null : torso.assessment().hardUnmetCount(), torso == null ? null : torso.assessment().preferredUnmetCount()); AssemblySearchEngine.Result result; if (strictFirst) { - Map> strictCandidates = new java.util.EnumMap<>(ComponentRole.class); + Map> strictCandidates = new EnumMap<>(ComponentRole.class); pool.candidates().forEach((ComponentRole role, List candidates) -> strictCandidates.put(role, candidates.stream().filter((MatchingCandidate candidate) -> candidate.assessment().hardUnmetCount() == 0).toList())); CandidatePool.Result strictPool = new CandidatePool.Result(Map.copyOf(strictCandidates), pool.observed(), pool.eligible(), pool.limited(), pool.scanned(), pool.invalidMetadata(), pool.invalidPorts()); result = search.search(strictPool, request, Math.max(1, properties.maxStateExpansions() / 2), torso); - if (result.best() == null || result.best().state().parts().size() != request.roles().size() + if (result.best() == null || result.best().missingMinimum() > 0 || result.best().evaluation().hardUnmetCount() > 0) { AssemblySearchEngine.Result fallback = search.search(pool, request, properties.maxStateExpansions() - result.expansions(), torso); AssemblySearchEngine.ScoredState best = result.best(); @@ -100,39 +101,39 @@ public class RobotMatchingService { } AssemblyState selected = result.best().state(); RequirementEvaluator.Evaluation evaluation = result.best().evaluation(); - Map> alternatives = replacements(selected, pool, request); + Map> alternatives = replacements(selected, pool, request); Set codes = new LinkedHashSet<>(); selected.parts().values().forEach((MatchingCandidate candidate) -> codes.add(candidate.code())); alternatives.values().forEach((List items) -> items.forEach((ReplacementState item) -> codes.add(item.candidate().code()))); Map publicComponents = components.load(codes); - List parts = selected.parts().values().stream() - .map((MatchingCandidate candidate) -> publicComponents.get(candidate.code())).toList(); + List parts = selected.parts().entrySet().stream() + .map((Map.Entry entry) -> publicComponents.get(entry.getValue().code()).withInstanceId(entry.getKey())).toList(); List publicAlternatives = new ArrayList<>(); - alternatives.forEach((ComponentRole role, List items) -> publicAlternatives.add(new Alternatives(role.code(), - items.stream().map((ReplacementState item) -> new Replacement(publicComponents.get(item.candidate().code()), + alternatives.forEach((String instance, List items) -> publicAlternatives.add(new Alternatives(selected.parts().get(instance).role().code(), instance, + items.stream().map((ReplacementState item) -> new Replacement(publicComponents.get(item.candidate().code()).withInstanceId(instance), item.state().connections(), item.evaluation().totals(), item.evaluation().unmet(), item.evaluation().unmatched())).toList()))); String status = !missing.isEmpty() ? "PARTIAL" : !evaluation.unmet().isEmpty() || !evaluation.unmatched().isEmpty() ? "FALLBACK" : "MATCHED"; return new RobotMatchResponse(status, selected.root().code(), parts, selected.connections(), List.copyOf(publicAlternatives), evaluation.totals(), evaluation.unmet(), evaluation.unmatched(), missing, result.limited()); } - private Map> replacements(AssemblyState selected, CandidatePool.Result pool, + private Map> replacements(AssemblyState selected, CandidatePool.Result pool, NormalizedMatchRequest request) { - Map> result = new EnumMap<>(ComponentRole.class); + Map> result = new LinkedHashMap<>(); Comparator order = Comparator.comparingInt((ReplacementState item) -> item.evaluation().hardUnmetCount()) .thenComparing((ReplacementState item) -> item.evaluation().deviation()) .thenComparingInt((ReplacementState item) -> item.evaluation().preferredUnmetCount()) .thenComparing((ReplacementState item) -> item.evaluation().preferredDeviation()) .thenComparing(Comparator.comparingInt((ReplacementState item) -> item.evaluation().keywordScore()).reversed()) .thenComparing((ReplacementState item) -> item.candidate().code()); - selected.parts().forEach((ComponentRole role, MatchingCandidate current) -> { + selected.parts().forEach((String instance, MatchingCandidate current) -> { List compatible = new ArrayList<>(); - for (MatchingCandidate candidate : pool.candidates().get(role)) { + for (MatchingCandidate candidate : pool.candidates().get(current.role())) { if (candidate.code().equals(current.code())) continue; - AssemblyState replaced = selected.replace(candidate); + AssemblyState replaced = selected.replace(instance, candidate); if (replaced != null) compatible.add(new ReplacementState(candidate, replaced, evaluator.evaluate(replaced, request))); } - result.put(role, compatible.stream().sorted(order).limit(5).toList()); + result.put(instance, compatible.stream().sorted(order).limit(5).toList()); }); return result; } @@ -140,11 +141,13 @@ public class RobotMatchingService { private List missing(NormalizedMatchRequest request, CandidatePool.Result pool, AssemblySearchEngine.Result result) { List missing = new ArrayList<>(); for (ComponentRole role : request.roles()) { - if (result.best() != null && result.best().state().parts().containsKey(role)) continue; + int actual = result.best() == null ? 0 : result.best().state().count(role); + int expected = request.minimum(role); + if (actual >= expected) continue; String reason = pool.observed().get(role) == 0 ? "NO_COMPONENT" : pool.eligible().get(role) == 0 ? "INVALID_ASSEMBLY_METADATA" : pool.candidates().get(ComponentRole.TORSO).isEmpty() ? "NO_TORSO" : result.limited() ? "SEARCH_LIMIT" : "NO_COMPATIBLE_CONNECTION"; - missing.add(new MissingPart(role.code(), reason)); + missing.add(new MissingPart(role.code(), reason, expected, actual, expected - actual)); } return List.copyOf(missing); } diff --git a/cadworld-service/src/main/resources/robot-demand/model-output.schema.json b/cadworld-service/src/main/resources/robot-demand/model-output.schema.json index d3fe07c..81909f2 100644 --- a/cadworld-service/src/main/resources/robot-demand/model-output.schema.json +++ b/cadworld-service/src/main/resources/robot-demand/model-output.schema.json @@ -367,7 +367,8 @@ "size", "torqueNm", "massKg", - "description" + "description", + "quantity" ] }, "value": { diff --git a/cadworld-service/src/main/resources/robot-demand/system-prompt.txt b/cadworld-service/src/main/resources/robot-demand/system-prompt.txt index 326f033..040cba6 100644 --- a/cadworld-service/src/main/resources/robot-demand/system-prompt.txt +++ b/cadworld-service/src/main/resources/robot-demand/system-prompt.txt @@ -10,7 +10,7 @@ 二、有效需求 7. intentItems 按当前有效需求逐条拆分,一条只表达一个条件。dimension 使用 Schema 中的形态、任务、运动、场景、外观、性能、材料、尺寸、预算、安全、数量、排除或其他分类。subject 保留整机、具体部件、机械左右、每个或总和范围;requirement 保留数值、单位、比较词和限定条件。priority=must 明确要求,prefer 偏好,context 背景或推断;source=explicit/inferred。每项唯一 id 和非空 evidenceIds。未提供的参数不填 0,也不要求补齐。 -8. 同一数值需求同时进入 intentItems 和 constraints。预算、载荷、速度、续航、安全、数量等暂无字段的需求同时进入 intentItems 和 unmodeled,reason 说明能力或目录缺口。已明确但暂不支持的要求不能丢弃,后端会把它们作为未验证项展示。 +8. 同一数值需求同时进入 intentItems 和 constraints。预算、载荷、速度、续航、安全等暂无字段的需求同时进入 intentItems 和 unmodeled,reason 说明能力或目录缺口。已明确但暂不支持的要求不能丢弃,后端会把它们作为未验证项展示。 9. keywords 提取主体、仿生对象、形态、功能、环境、材料、尺寸、数值、偏好及禁止项;规范化同义词但保留否定。source=explicit 或 inferred,推断注明 reason,不能推断数字、牌号或性能。否定词保留在 term 中,如“不要飞行”。 10. 后续明确修改覆盖旧值,补充累加;不得把各轮旧值全部 AND 叠加。用户后来补充“单位是N·m”时结合之前用户数值,将两轮证据都引用,不能从助手示例获取数值。用户否定旧需求后,将其从当前有效关键词和约束中移除。 @@ -18,11 +18,11 @@ 11. 配置目录:{{CATALOG_JSON}}。robotTypes 只使用目录中的模板 id;程序展开 requiredParts,你不输出该字段。能辨认形态时选对应模板,图片推断标 inferred。未指定形态时 robotTypes=[],后端使用默认模板并说明。目录不代表库存齐全或能力达标。 12. 未配置的四足、轮式、履带、鸟形等保留为 unmodeled,不谎称双足能够满足;后端可返回默认参考方案并保留差异。“仿生鸟类”保留机器人、仿生、鸟类等关键词,可将双足作为 inferred 候选;飞行能力保留为未验证,企鹅、鸵鸟或明确不飞行时不推断飞行。 13. 类别为 torso_0 躯干、head_0 头、waist_0 腰、arm_l/r 臂、hand_l/r 手、pedal_l/r 足、foot_l/r 脚、tail_0 尾。0 不分左右,l/r 是机械左右,足和脚不同。双臂明确展开两侧;单侧部件未说明左右时按右侧生成 inferred 参考部位,并在 reason 中说明默认选择,不伪装成用户明确要求。 -14. 明确排除的部件放 excludedCategories,不作为正向包含。仅凭草图没画出某部件不能当作排除。翅膀、轮子、旋翼、电池、传感器、爪等目录外部件放 unmodeled,不造类别或把手臂当翅膀。一个角色只有一个实例,四只手、多头等超出支持范围的数量需求保留,不通过分类去重冒充数量达标。 -15. 解析器不生成安装接口、坐标、旋转、父子关系或配对方案。LINK_head/link-head 是接口类型,不证明跨文件姿态;真实连接来自后端组件数据,多个同类端口不随机配对,不按草图像素生成 3D 安装位置。 +14. 明确排除的部件放 excludedCategories,不作为正向包含。仅凭草图没画出某部件不能当作排除。翅膀、轮子、旋翼、电池、传感器、爪等目录外部件放 unmodeled,不造类别或把手臂当翅膀。现有部位支持同款组件的多个独立实例;明确数量写入quantity维度intentItems,并以part范围、field=quantity、operator=eq写入constraints,value保留原始数量,支持1至24。跨多个部位的合计数量仅保留intentItems,不平均分配。数量缺失时不要补1;后端按需求类型和实际可用接口填充。整机固定一个躯干。不要新增目录外类别或四足、六足模板。 +15. 解析器不生成安装接口、坐标、旋转、父子关系或配对方案。真实连接来自后端组件数据:interfaceType优先决定目标部位,双方frames.child严格一致才能连接;同child的多个接口独立处理,后端只返回实例连接关系,摆放由前端处理。不要从草图像素生成3D位置。 四、机械条件 -16. 只使用 componentName、degreesOfFreedom、material、functionDescription、shape、size、torqueNm、massKg、description。scope=robot 整机、part 指定部件、unspecified 对象未明确;categories 仅 part 使用。整体 20 自由度不能给每个部件 20;双臂总质量 2kg 不能给每臂 2kg,组合约束保留为 unmodeled。不把“机器人”当作用户指定名称。 +16. 只使用 componentName、degreesOfFreedom、material、functionDescription、shape、size、torqueNm、massKg、description、quantity。quantity只用于明确部位数量且operator=eq。scope=robot 整机、part 指定部件、unspecified 对象未明确;categories 仅 part 使用。整体 20 自由度不能给每个部件 20;双臂总质量 2kg 不能给每臂 2kg,组合约束保留为 unmodeled。不把“机器人”当作用户指定名称。 17. 质量、扭矩、自由度的 value 保留原数字和单位,例如“二十”“500克”“20N·m”“200N·cm”,由后端换算。缺单位时保留原文和缺口,不默认 kg/N·m,也不提问。明确 0 保留,未知值省略。size 保留完整尺寸与单位,不凭图片猜尺寸或材质牌号。 18. operator=eq/lte/gte/lt/gt/neq/range,range 的 value/upperValue 分别为上下界,其他 upperValue=""。同字段多条件分别保留,矛盾也保留;无法投影的严格比较、范围、排除属性由后端保留为未验证项,不擅自放宽或丢弃原要求。 19. “最好/尽量/大概/偏好/轻一点/小一点”保留为偏好,不能提升为硬数值。硬 constraints 只来自明确文字或清晰 OCR。图片推断和不清晰信息不能标 must 或成为硬数值。 diff --git a/cadworld-service/src/test/java/com/linkerbot/cadworld/service/demand/ArkDemandModelClientTest.java b/cadworld-service/src/test/java/com/linkerbot/cadworld/service/demand/ArkDemandModelClientTest.java index 6257159..4ee9b9e 100644 --- a/cadworld-service/src/test/java/com/linkerbot/cadworld/service/demand/ArkDemandModelClientTest.java +++ b/cadworld-service/src/test/java/com/linkerbot/cadworld/service/demand/ArkDemandModelClientTest.java @@ -92,7 +92,7 @@ class ArkDemandModelClientTest { } private ArkDemandModelClient client(String key, Duration timeout) throws Exception { - return new ArkDemandModelClient(json, new DemandRules(json), new DemandProperties(key, "test-model", endpoint, timeout, "target/private-test", Duration.ofDays(7), 1, false, false, List.of())); + return new ArkDemandModelClient(json, new DemandRules(json), new DemandProperties(key, "test-model", endpoint, timeout, "target/private-test", Duration.ofDays(7), 1, false, List.of())); } private void assertCode(ArkDemandModelClient client, String code) { assertThatThrownBy(() -> client.analyze(List.of(new DemandMessage("m1", "user", "机器人", List.of())))) diff --git a/cadworld-service/src/test/java/com/linkerbot/cadworld/service/demand/DemandAssemblyValidatorTest.java b/cadworld-service/src/test/java/com/linkerbot/cadworld/service/demand/DemandAssemblyValidatorTest.java index df436ca..bc00076 100644 --- a/cadworld-service/src/test/java/com/linkerbot/cadworld/service/demand/DemandAssemblyValidatorTest.java +++ b/cadworld-service/src/test/java/com/linkerbot/cadworld/service/demand/DemandAssemblyValidatorTest.java @@ -1,119 +1,87 @@ package com.linkerbot.cadworld.service.demand; +import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.ObjectNode; -import com.linkerbot.cadworld.config.DemandProperties; import com.linkerbot.cadworld.dto.matching.PublicComponentResponse; import com.linkerbot.cadworld.dto.matching.RobotMatchResponse; import java.math.BigDecimal; -import java.time.Duration; import java.util.List; import org.junit.jupiter.api.Test; - import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.within; class DemandAssemblyValidatorTest { private final ObjectMapper json = new ObjectMapper(); - private final DemandAssemblyValidator validator = new DemandAssemblyValidator(new DemandProperties("", "model", "http://localhost", Duration.ofSeconds(1), "target/private", Duration.ofDays(7), 1, false, false, List.of())); + private final DemandAssemblyValidator validator = new DemandAssemblyValidator(); - @Test void composesParentChainAndInvertsTranslatedChildMount() { - ObjectNode parent = info("BASE"); - joint(parent, "J0", "BASE", "MID", "", 1, 0, Math.PI / 2); - joint(parent, "J_ARM", "MID", "LINK_arm_r", "arm_r", 2, 0, 0); - ObjectNode child = info("ARM_ROOT"); - joint(child, "J_MOUNT", "ARM_ROOT", "MOUNT", "", 0, 1, 0); - child.putObject("assembly").put("mountingFrame", "MOUNT").put("pairingConvention", "coincident_frames"); - DemandAssemblyValidator.Assembly result = validator.validate("DM-test", match(parent, child)); + @Test void returnsInstancesAndOriginalFrameIndexesWithoutMatrices() { + RobotMatchResponse match = match(info("BASE"), info("ARM_ROOT")); + DemandAssemblyValidator.Assembly result = validator.validate("DM-test", match); assertThat(result.status()).isEqualTo("ready"); - List matrix = result.connections().get(0).childRootRelativeToParentRoot(); - assertThat(matrix.get(12)).isCloseTo(2, within(1e-10)); - assertThat(matrix.get(13)).isCloseTo(2, within(1e-10)); - assertThat(matrix.get(0)).isCloseTo(0, within(1e-10)); - assertThat(matrix.get(1)).isCloseTo(1, within(1e-10)); - assertThat(result.matrixLayout()).isEqualTo("column-major"); - } - - @Test void invertsChildMountRotationWithoutAssumedFlips() { - ObjectNode parent = info("BASE"); joint(parent, "J_ARM", "BASE", "LINK_arm_r", "arm_r", 0, 0, 0); - ObjectNode child = info("ARM_ROOT"); joint(child, "MOUNT", "ARM_ROOT", "C_MOUNT", "", 1, 0, Math.PI / 2); - child.putObject("assembly").put("mountingFrame", "MOUNT").put("pairingConvention", "coincident_frames"); - List matrix = validator.validate("DM-test", match(parent, child)).connections().get(0).childRootRelativeToParentRoot(); - assertThat(matrix.get(12)).isCloseTo(0, within(1e-10)); - assertThat(matrix.get(13)).isCloseTo(1, within(1e-10)); - assertThat(matrix.get(1)).isCloseTo(-1, within(1e-10)); - } - - @Test void missingMountAmbiguousPortsAndCyclesBlockAssembly() { - ObjectNode parent = info("BASE"); joint(parent, "J_ARM", "BASE", "LINK_arm_r", "arm_r", 0, 0, 0); - ObjectNode child = info("ARM_ROOT"); - assertIssue(parent, child, "MISSING_MOUNTING_REFERENCE"); - child.putObject("assembly").put("mountingFrame", "ARM_ROOT").put("pairingConvention", "coincident_frames"); - joint(parent, "J_ARM_2", "BASE", "LINK_arm_r_2", "arm_r", 0, 0, 0); - assertIssue(parent, child, "AMBIGUOUS_PARENT_INTERFACE"); - parent.withArray("frames").remove(1); - ((ObjectNode) parent.path("frames").get(0)).put("parent", "LINK_arm_r"); - assertIssue(parent, child, "INVALID_FRAME_GRAPH"); - } - - @Test void movableJointAndUnknownOriginAreNotInvented() { - ObjectNode parent = info("BASE"); joint(parent, "J_ARM", "BASE", "LINK_arm_r", "arm_r", 0, 0, 0); - ObjectNode child = info("ARM_ROOT"); child.putObject("assembly").put("mountingFrame", "ARM_ROOT").put("pairingConvention", "coincident_frames"); - ObjectNode frame = (ObjectNode) parent.path("frames").get(0); - frame.put("type", "revolute"); assertIssue(parent, child, "MOVABLE_INTERFACE_REQUIRES_STATE"); - frame.put("type", "fixed"); frame.remove("xyz"); assertIssue(parent, child, "INVALID_ORIGIN"); - frame.put("originExplicit", false); - assertThat(validator.validate("DM-test", match(parent, child)).status()).isEqualTo("ready"); - } - - @Test void assembliesWithNoTorsoOrTwoTorsosAreBlocked() { - RobotMatchResponse valid = match(info("BASE"), info("ARM_ROOT")); - List duplicate = List.of(valid.parts().get(0), part("SECOND_TORSO", "torso_0", info("BASE_2")), valid.parts().get(1)); - RobotMatchResponse twoTorsos = new RobotMatchResponse("MATCHED", "torso_0", duplicate, List.of(), List.of(), valid.totals(), List.of(), List.of(), List.of(), false); - DemandAssemblyValidator.Assembly result = validator.validate("DM-test", twoTorsos); - assertThat(result.status()).isEqualTo("blocked"); - assertThat(result.issues()).extracting(DemandAssemblyValidator.Issue::code).contains("INVALID_TORSO_ROOT"); - RobotMatchResponse armRoot = new RobotMatchResponse("MATCHED", "arm_r", List.of(valid.parts().get(1)), List.of(), List.of(), valid.totals(), List.of(), List.of(), List.of(), false); - assertThat(validator.validate("DM-test", armRoot).status()).isEqualTo("blocked"); - } - - @Test void missingRequestedPartsDoNotBlockExistingConnections() { - ObjectNode parent = info("BASE"); joint(parent, "J_ARM", "BASE", "LINK_arm_r", "arm_r", 1, 0, 0); - ObjectNode child = info("ARM_ROOT"); - child.putObject("assembly").put("mountingFrame", "ARM_ROOT").put("pairingConvention", "coincident_frames"); - RobotMatchResponse selected = match(parent, child); - RobotMatchResponse partial = new RobotMatchResponse("PARTIAL", selected.rootCategory(), selected.parts(), selected.connections(), List.of(), - selected.totals(), List.of(), List.of(), List.of(new RobotMatchResponse.MissingPart("head_0", "NO_COMPONENT")), false); - - DemandAssemblyValidator.Assembly result = validator.validate("DM-test", partial); - assertThat(result.status()).isEqualTo("ready"); - assertThat(result.issues()).isEmpty(); + assertThat(result.rootInstanceId()).isEqualTo("DM-test:torso_0:1"); assertThat(result.connections()).hasSize(1); - assertThat(result.connections().get(0).childRootRelativeToParentRoot().get(12)).isEqualTo(1); - - child.remove("assembly"); - DemandAssemblyValidator.Assembly invalid = validator.validate("DM-test", partial); - assertThat(invalid.status()).isEqualTo("blocked"); - assertThat(invalid.connections()).isEmpty(); - assertThat(invalid.issues()).extracting(DemandAssemblyValidator.Issue::code).containsExactly("MISSING_MOUNTING_REFERENCE"); + assertThat(result.connections().get(0).parentInstanceId()).isEqualTo("DM-test:torso_0:1"); + assertThat(result.connections().get(0).childInstanceId()).isEqualTo("DM-test:arm_r:1"); + assertThat(result.connections().get(0).interfaceChild()).isEqualTo("LINK_arm_r"); + JsonNode body = json.valueToTree(result); + assertThat(body.has("matrixLayout")).isFalse(); + assertThat(body.path("connections").get(0).has("childRootRelativeToParentRoot")).isFalse(); } - private void assertIssue(ObjectNode parent, ObjectNode child, String code) { + @Test void missingMountMovableJointsAndMalformedPosesRemainDisplayable() { + ObjectNode parent = info("BASE"); + ObjectNode child = info("ARM_ROOT"); + ObjectNode frame = (ObjectNode) child.path("frames").get(0); + frame.put("type", "revolute").put("parent", "LINK_arm_r"); + frame.remove("xyz"); DemandAssemblyValidator.Assembly result = validator.validate("DM-test", match(parent, child)); - assertThat(result.status()).isEqualTo("blocked"); - assertThat(result.issues()).extracting(DemandAssemblyValidator.Issue::code).contains(code); - assertThat(result.connections()).isEmpty(); + assertThat(result.status()).isEqualTo("ready"); + assertThat(result.connections()).hasSize(1); + assertThat(result.issues()).extracting(DemandAssemblyValidator.Issue::code).contains("INVALID_ORIGIN").doesNotContain("MISSING_MOUNTING_REFERENCE"); } - private ObjectNode info(String root) { ObjectNode result = json.createObjectNode().put("rootLink", root); result.putArray("frames"); return result; } - private void joint(ObjectNode info, String name, String parent, String child, String role, double x, double y, double yaw) { - ObjectNode frame = info.withArray("frames").addObject().put("name", name).put("kind", "joint").put("type", "fixed").put("parent", parent).put("child", child).put("interfaceType", role).put("originExplicit", true); - frame.putArray("xyz").add(x).add(y).add(0); frame.putArray("rpy").add(0).add(0).add(yaw); + + @Test void repeatedComponentCodesRemainIndependentInstances() { + RobotMatchResponse base = match(info("BASE"), info("ARM_ROOT")); + PublicComponentResponse second = base.parts().get(1).withInstanceId("arm_r:2"); + RobotMatchResponse.Connection edge = new RobotMatchResponse.Connection("torso_0", "PARENT", "BASE", "J2", "arm_r", "CHILD", "ARM_ROOT", + "torso_0:1", "arm_r:2", "LINK_arm_r", 1, 0); + RobotMatchResponse repeated = new RobotMatchResponse("MATCHED", "torso_0", List.of(base.parts().get(0), base.parts().get(1), second), + List.of(base.connections().get(0), edge), List.of(), base.totals(), List.of(), List.of(), List.of(), false); + DemandAssemblyValidator.Assembly result = validator.validate("DM-test", repeated); + assertThat(result.status()).isEqualTo("ready"); + assertThat(result.connections()).extracting(DemandAssemblyValidator.Connection::childInstanceId) + .containsExactly("DM-test:arm_r:1", "DM-test:arm_r:2"); + } + + @Test void missingRequestedPartsAndMetadataWarningsDoNotBlockExistingCombination() { + RobotMatchResponse base = match(info("BASE"), info("ARM_ROOT")); + RobotMatchResponse partial = new RobotMatchResponse("PARTIAL", "torso_0", base.parts(), base.connections(), List.of(), base.totals(), + List.of(), List.of(), List.of(new RobotMatchResponse.MissingPart("head_0", "NO_COMPONENT")), false); + assertThat(validator.validate("DM-test", partial).status()).isEqualTo("ready"); + assertThat(validator.validate("DM-test", partial).connections()).hasSize(1); + } + + @Test void noComponentsOrNoTorsoHaveNoDisplayableRobot() { + RobotMatchResponse base = match(info("BASE"), info("ARM_ROOT")); + RobotMatchResponse empty = new RobotMatchResponse("NO_MATCH", null, List.of(), List.of(), List.of(), base.totals(), List.of(), List.of(), List.of(), false); + assertThat(validator.validate("DM-test", empty).status()).isEqualTo("blocked"); + RobotMatchResponse noTorso = new RobotMatchResponse("NO_MATCH", null, List.of(base.parts().get(1)), List.of(), List.of(), base.totals(), List.of(), List.of(), List.of(), false); + assertThat(validator.validate("DM-test", noTorso).status()).isEqualTo("blocked"); + } + + private ObjectNode info(String root) { + ObjectNode info = json.createObjectNode().put("rootLink", root); + ObjectNode frame = info.putArray("frames").addObject().put("name", "J").put("parent", root).put("child", "LINK_arm_r").put("interfaceType", "arm_r"); + frame.putArray("xyz").add(0).add(0).add(0); frame.putArray("rpy").add(0).add(0).add(0); + return info; } private PublicComponentResponse part(String code, String role, ObjectNode info) { - return new PublicComponentResponse(code, code, role, "", "", BigDecimal.ONE, 0, null, "", "", "", BigDecimal.ZERO, json.createArrayNode(), info, 1L, "https://model/a.step", "https://model/a.urdf"); + return new PublicComponentResponse(code, code, role, "", "", BigDecimal.ONE, 0, null, "", "", "", BigDecimal.ZERO, json.createArrayNode(), info, 1L, "https://model/a.step", "https://model/a.urdf").withInstanceId(role + ":1"); } private RobotMatchResponse match(ObjectNode parent, ObjectNode child) { - RobotMatchResponse.Connection edge = new RobotMatchResponse.Connection("torso_0", "PARENT", "BASE", "J_ARM", "arm_r", "CHILD", "ARM_ROOT", List.of(), List.of()); - return new RobotMatchResponse("MATCHED", "torso_0", List.of(part("PARENT", "torso_0", parent), part("CHILD", "arm_r", child)), List.of(edge), List.of(), new RobotMatchResponse.Totals(0, BigDecimal.valueOf(2), BigDecimal.valueOf(2), true), List.of(), List.of(), List.of(), false); + RobotMatchResponse.Connection edge = new RobotMatchResponse.Connection("torso_0", "PARENT", "BASE", "J", "arm_r", "CHILD", "ARM_ROOT", + "torso_0:1", "arm_r:1", "LINK_arm_r", 0, 0); + return new RobotMatchResponse("MATCHED", "torso_0", List.of(part("PARENT", "torso_0", parent), part("CHILD", "arm_r", child)), List.of(edge), List.of(), + new RobotMatchResponse.Totals(0, BigDecimal.valueOf(2), BigDecimal.valueOf(2), true), List.of(), List.of(), List.of(), false); } } diff --git a/cadworld-service/src/test/java/com/linkerbot/cadworld/service/demand/DemandNormalizerTest.java b/cadworld-service/src/test/java/com/linkerbot/cadworld/service/demand/DemandNormalizerTest.java index 3d6f5af..32dc178 100644 --- a/cadworld-service/src/test/java/com/linkerbot/cadworld/service/demand/DemandNormalizerTest.java +++ b/cadworld-service/src/test/java/com/linkerbot/cadworld/service/demand/DemandNormalizerTest.java @@ -35,7 +35,7 @@ class DemandNormalizerTest { assertThat(actual.analysis().path("status").asText()).isEqualTo("ready"); assertThat(actual.analysis().path("canSubmit").asBoolean()).isTrue(); assertThat(actual.analysis().path("questions")).isEmpty(); - assertThat(actual.analysis().path("schemaVersion").asText()).isEqualTo("multimodal-v1.2-auto-assembly"); + assertThat(actual.analysis().path("schemaVersion").asText()).isEqualTo("multimodal-v1.3-child-instances"); assertThat(actual.analysis().path("catalogVersion").asText()).isEqualTo("2026-10-14-auto-assembly"); } @@ -171,6 +171,53 @@ class DemandNormalizerTest { assertThatThrownBy(() -> DemandNumberParser.parse("degreesOfFreedom", "2147483648自由度")).isInstanceOf(IllegalArgumentException.class); } + @ParameterizedTest + @ValueSource(strings = {"一", "四", "六", "24"}) + void projectsExplicitPartQuantitiesWithoutNewCategoriesOrTemplates(String count) { + String input = count + "个右臂"; + ObjectNode raw = minimal(input); + raw.putArray("robotTypes"); + raw.withArray("partCategories").addObject().put("category", "arm_r").put("source", "explicit").put("reason", "用户明确部位").putArray("evidenceIds").add("e1"); + raw.withArray("intentItems").addObject().put("id", "q1").put("dimension", "quantity").put("subject", "右臂") + .put("requirement", input).put("priority", "must").put("source", "explicit").putArray("evidenceIds").add("e1"); + DemandResult result = normalizer.normalize(raw, text(input)); + assertThat(result.request().path("partRequirements").get(0).path("quantity").asInt()) + .isEqualTo(DemandNumberParser.parse("quantity", count).intValueExact()); + assertThat(result.request().path("requiredParts")).hasSize(2); + assertThat(result.analysis().path("questions")).isEmpty(); + assertThat(result.analysis().path("warnings").toString()).doesNotContain("仅支持一个"); + } + + @Test void doesNotInventOrTruncateInvalidQuantities() { + for (String count : List.of("0", "25", "1.5", "-1")) { + String input = count + "个右臂"; + ObjectNode raw = minimal(input); + raw.putArray("robotTypes"); + constraint(raw, "part", "quantity", count, "eq", "arm_r", "e1"); + raw.withArray("intentItems").addObject().put("id", "q1").put("dimension", "quantity").put("subject", "右臂") + .put("requirement", input).put("priority", "must").put("source", "explicit").putArray("evidenceIds").add("e1"); + DemandResult result = normalizer.normalize(raw, text(input)); + assertThat(result.request().path("partRequirements").findValues("quantity")).isEmpty(); + assertThat(result.analysis().path("unmodeled")).isNotEmpty(); + } + } + + @Test void partQuantityNeedsCountEvidenceAndDoesNotReuseTorqueOrMassNumbers() { + assertThat(DemandNumberParser.inEvidence("quantity", "1", "-1个右臂", List.of())).isFalse(); + assertThat(DemandNumberParser.inEvidence("quantity", "1", "负一个右臂", List.of())).isFalse(); + ObjectNode raw = minimal("右臂扭矩20N·m"); + raw.putArray("robotTypes"); + constraint(raw, "part", "quantity", "20", "eq", "arm_r", "e1"); + DemandResult result = normalizer.normalize(raw, text("右臂扭矩20N·m")); + assertThat(result.request().path("partRequirements").findValues("quantity")).isEmpty(); + assertThat(result.analysis().path("unmodeled")).isNotEmpty(); + raw = minimal("右臂数量为4"); + raw.putArray("robotTypes"); + constraint(raw, "part", "quantity", "4", "eq", "arm_r", "e1"); + result = normalizer.normalize(raw, text("右臂数量为4")); + assertThat(result.request().path("partRequirements").get(0).path("quantity").asInt()).isEqualTo(4); + } + private JsonNode fixture(String name) throws Exception { try (InputStream stream = getClass().getResourceAsStream("/robot-demand/" + name + ".json")) { return json.readTree(stream); } }