From 99d05489c411aa2bb12d65675cd523e1ce448b0a Mon Sep 17 00:00:00 2001 From: lxp <2770281812@qq.com> Date: Mon, 19 Oct 2026 18:10:43 +0800 Subject: [PATCH] =?UTF-8?q?ARM=E3=80=81HAND=E3=80=81LEG=E3=80=81FOOT=20?= =?UTF-8?q?=E7=9A=84=20L/R=20=E6=8E=A5=E5=8F=A3=E5=8F=AF=E5=AE=89=E8=A3=85?= =?UTF-8?q?=E5=90=8C=E9=83=A8=E4=BD=8D=E7=9A=84=200=20=E7=BB=84=E4=BB=B6?= =?UTF-8?q?=EF=BC=8C0=20=E6=8E=A5=E5=8F=A3=E4=BB=8D=E5=8F=AA=E6=8E=A5=200?= =?UTF-8?q?=E3=80=82?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 2 + cadworld-api/docs/api.md | 24 +-- cadworld-api/docs/demand-integration.md | 8 +- cadworld-api/docs/robot-demand-api.md | 18 ++- .../cadworld/api/DemandFlowApiTest.java | 59 ++++++- .../cadworld/api/MatchingApiTest.java | 146 +++++++++++++++--- .../dto/matching/RobotMatchResponse.java | 1 + .../service/demand/DemandMatchService.java | 5 +- .../demand/DemandRequirementChecker.java | 14 +- .../service/matching/AssemblyMetadata.java | 4 +- .../matching/AssemblySearchEngine.java | 15 +- .../service/matching/AssemblyState.java | 48 ++++-- .../service/matching/CandidatePool.java | 75 ++++++--- .../matching/InterfaceCompatibility.java | 59 +++++++ .../service/matching/MatchingCandidate.java | 3 + .../matching/NormalizedMatchRequest.java | 26 +++- .../matching/RobotMatchingService.java | 28 +++- .../resources/robot-demand/system-prompt.txt | 2 +- .../demand/DemandAssemblyValidatorTest.java | 16 ++ .../service/matching/AssemblyStateTest.java | 61 ++++++++ .../matching/InterfaceCompatibilityTest.java | 31 ++++ 21 files changed, 551 insertions(+), 94 deletions(-) create mode 100644 cadworld-service/src/main/java/com/linkerbot/cadworld/service/matching/InterfaceCompatibility.java create mode 100644 cadworld-service/src/test/java/com/linkerbot/cadworld/service/matching/AssemblyStateTest.java create mode 100644 cadworld-service/src/test/java/com/linkerbot/cadworld/service/matching/InterfaceCompatibilityTest.java diff --git a/README.md b/README.md index 1db4d94..f3e09b7 100644 --- a/README.md +++ b/README.md @@ -41,6 +41,8 @@ java -jar cadworld-adminapi/target/cadworld-adminapi-0.0.1-SNAPSHOT.jar Spring Boot 不自动读取 `.env`,需要通过 shell 导入。默认 profile 为 `test`;生产使用 `SPRING_PROFILES_ACTIVE=prod`,提供数据库连接变量。生产 Swagger 默认关闭。 +Maven 命令在仓库根目录执行。首次构建或共享模块新增 DTO 后,使用 `mvn install` 将所有模块的最新产物安装到本地仓库。只构建管理端或用户端时,分别使用 `mvn -pl cadworld-adminapi -am install`、`mvn -pl cadworld-api -am install`,`-am` 会同时构建它们依赖的模块。在子模块目录直接执行 `mvn install` 不会重建兄弟模块,可能引用本地旧包并出现 `com.linkerbot.cadworld.dto.auth` 等程序包不存在的错误。 + | 环境变量 | 用途 | | --- | --- | | APP_DB_URL / APP_DB_USERNAME / APP_DB_PASSWORD | MySQL 连接配置 | diff --git a/cadworld-api/docs/api.md b/cadworld-api/docs/api.md index e6b4646..1fa948e 100644 --- a/cadworld-api/docs/api.md +++ b/cadworld-api/docs/api.md @@ -161,11 +161,11 @@ X-Request-Id: frontend-match-001 | 不分左右的脚 | FOOT_0 | | 尾_0 | TAIL_0 | -以上16类为完整组件类型,公开响应统一使用大写标准编码。输入兼容英文大小写和原有中文别名;旧 `pedal_l/pedal_r` 兼容为 `LEG_L/LEG_R`。左右侧、足与脚独立,不互相替代。 +以上16类为完整组件类型,公开响应统一使用大写标准编码。输入兼容英文大小写和原有中文别名;旧 `pedal_l/pedal_r` 兼容为 `LEG_L/LEG_R`。左右侧、足与脚独立;L/R 互不替代,同部位的 0 类组件可承担 L/R 装配角色。 -`LINK_ARM_0`、`LINK_HAND_0`、`LINK_LEG_0`、`LINK_FOOT_0` 均为独立接口编码:0 只接 0,L 只接 L,R 只接 R,且原始 child 区分大小写。中性类型不作为左右接口的通配符。 +ARM、HAND、LEG、FOOT 的父接口采用单向兼容:L 可接 L/0,R 可接 R/0,0 只接 0,L/R 不能互接。除原始 child 完全相等外,仅允许上述标准 `LINK_部位_L/R`(方向位也支持小写 l/r)连接同前缀的 `_0`;其余字符须区分大小写完全一致,不放宽自定义接口编码或跨部位连接。 -组件库分类及 URDF `interfaceType` 均按上述类型识别,候选查询兼容已有大小写分类和旧足部编码;`interfaceType` 缺失时也可从 `LINK_LEG_L/LINK_LEG_R` 等 child 识别目标类型。原始 `urdfInfo` 保持不变,连接仍要求双方 `frames[].child` 区分大小写完全一致。实例编码同步使用大写类别,例如 `LEG_L:1`。 +组件库分类及 URDF `interfaceType` 均按上述类型识别,候选查询兼容已有大小写分类和旧足部编码;`interfaceType` 缺失时也可从 `LINK_LEG_L/LINK_LEG_R` 等 child 识别目标类型。原始 `urdfInfo` 保持不变,连接按上述单向规则判断。实例编码使用大写装配角色,例如 `LEG_L:1` 的真实组件类别可以是 `LEG_0`。 ### 3.7 匹配结果的业务约定 @@ -179,7 +179,7 @@ X-Request-Id: frontend-match-001 整机自由度和质量按选中实例字段求和,同款组件的每个实例分别计入,**不重复累加BOM,不从URDF再次计算**。质量为0视为未填写;只要一个组件质量未知,`totals.massKg=null`、`massComplete=false`,已知部分保存在 `knownMassKg`。不能据此宣布满足质量上限。功能命中表示元数据相关,不代表动力学验证。 -拼装候选必须同时有非空 STEP 和 URDF 主文件引用,仅上传 STEP 的组件仍只支持详情查询。接口以合法 interfaceType 决定目标 category,缺失/无效时从 child 的 LINK_ 后解析现有类别;双方 frames[].child 非空且严格相同(区分大小写)才能连接,name 不参与判断。每个数组元素为独立接口,同child的多个接口不合并,连接双方各自只能占用一次。固定躯干后优先处理最近层级的接口,先满足所需类型和明确数量,再填充其余可匹配接口,不引入未要求的类型。自动增补不应破坏本可满足的硬要求;例如质量上限或指定总自由度会约束自动填充数量。坐标、安装基准、关节类型和rootLink不作为连接资格的阻塞条件,缺失接口则返回已有连通部分。 +拼装候选必须同时有非空 STEP 和 URDF 主文件引用,仅上传 STEP 的组件仍只支持详情查询。接口以合法 interfaceType 决定目标 category,缺失/无效时从 child 的 LINK_ 后解析现有类别;双方 frames[].child 须非空并符合上述单向兼容规则,name 不参与判断。每个数组元素为独立接口,同child的多个接口不合并,连接双方各自只能占用一次。固定躯干后优先处理最近层级的接口,先满足所需类型和明确数量,再填充其余可匹配接口,不引入未要求的类型。自动增补不应破坏本可满足的硬要求;例如质量上限或指定总自由度会约束自动填充数量。坐标、安装基准、关节类型和rootLink不作为连接资格的阻塞条件,缺失接口则返回已有连通部分。 `bomList` 和 `urdfInfo` 始终作为原始 JSON 返回,保留嵌套内容;详情里的 `urdfInfo` 也可能是其他对象或数组。接口匹配只评价元数据和连接类型,不验证机械承载或运动性能。 @@ -210,7 +210,7 @@ X-Request-Id: frontend-match-001 | `PARTIAL` | 返回连通部分,存在缺失角色或模板部位合计数量不足;也可能有参数不满足 | | `NO_MATCH` | 没有可用装配候选,parts和connections为空;HTTP仍为200 | -`searchLimited` 与 `status` 独立,例如 `MATCHED` 也可能同时返回 `searchLimited=true`。数组无内容时返回 `[]`。`parts` 的顺序不保证与请求一致,前端使用 `category` 和 `componentCode` 定位组件。 +`searchLimited` 与 `status` 独立,例如 `MATCHED` 也可能同时返回 `searchLimited=true`。数组无内容时返回 `[]`。`parts` 的顺序不保证与请求一致,前端使用 `instanceId` 定位实例;`componentCode` 标识组件,`category` 是组件真实类别。 ### 4.2 公开组件字段 @@ -220,7 +220,7 @@ X-Request-Id: frontend-match-001 | --- | --- | --- | | `componentCode` | string | 组件唯一编码,用于获取详情和区分组件 | | `componentName` | string | 组件名称 | -| `category` | string | 组件角色;匹配结果使用标准英文编码 | +| `category` | string | 组件真实类别,使用标准英文编码;可能与本次装配角色不同 | | `description` | string | 组件说明 | | `material` | string | 材质 | | `massKg` | number | 组件质量,单位 kg;0 表示未填写 | @@ -480,25 +480,27 @@ X-Request-Id: frontend-match-001 同款组件可重复出现在 parts 中,新增的 instanceId 在结果内唯一,例如 ARM_R:1、ARM_R:2。单次最多24个实例;数量或搜索达到上限时 searchLimited=true,仍返回已有组合。missingParts 增加 expectedQuantity、actualQuantity 和 missingQuantity,明确数量未达到时返回缺少的数量。默认方案及替代项均按实例累计质量和自由度。 +0 组件承担指定侧时,按该侧需求评价参数和数量,每个实例只归属一个装配角色;部位分组和整机汇总均只计一次。`parts[].category` 和替代组件的 `category` 始终返回真实类别。候选继续按现有评分和编码排序,不额外优先同侧或中性组件。 + ### 4.4 连接字段 `connections[]` | 字段 | 类型 | 说明 | | --- | --- | --- | -| `parentInstanceId` / `childInstanceId` | string | 连接双方实例标识,格式为 category:序号,序号从1开始 | -| `parentCategory` / `childCategory` | string | 双方组件类型 | +| `parentInstanceId` / `childInstanceId` | string | 连接双方实例标识,格式为 装配角色:序号,序号从1开始 | +| `parentCategory` / `childCategory` | string | 双方本次装配角色,可能与组件真实 category 不同 | | `parentComponentCode` / `childComponentCode` | string | 双方组件编码,同款可以在多个实例重复使用 | -| `interfaceChild` | string | 双方严格一致的 frames[].child | +| `interfaceChild` | string | 父接口原始 frames[].child;子接口 child 可以是同部位的 0 | | `parentFrameIndex` / `childFrameIndex` | integer | 双方各自原始 frames 数组的零起始下标 | | `frameName` | string | 父接口原始 name,仅用于辅助定位 | | `parentLink` / `childRootLink` | string | 原始模型信息,缺失时可为空 | -本接口只返回连接关系,已移除连接摆放用 xyz/rpy,不计算矩阵。前端以双方实例标识和 frame 下标读取原始 urdfInfo,自行决定模型位置。同一 child 的多个接口以数组下标区分,前端不能按 child 或 componentCode 去重。 +本接口只返回连接关系,已移除连接摆放用 xyz/rpy,不计算矩阵。前端以双方实例标识和 frame 下标读取原始 urdfInfo,自行决定模型位置;不能假设双方 child 相等。同一 child 的多个接口以数组下标区分,前端不能按 child 或 componentCode 去重。 ### 4.5 替代候选 `alternatives[]` | 字段 | 类型 | 说明 | | --- | --- | --- | -| `category` | string | 当前可替换的类型 | +| `category` | string | 当前可替换实例的装配角色,替代组件真实类别可为同部位的 0 | | `instanceId` | string | 当前可替换的单个实例 | | `items` | object[] | 0 至 5 个兼容替代项,空数组表示没有提供替代组件 | | `items[].component` | object | 替代组件的完整公开数据,包括 BOM 和 URDF 信息 | diff --git a/cadworld-api/docs/demand-integration.md b/cadworld-api/docs/demand-integration.md index 1e5d8e6..e9cefef 100644 --- a/cadworld-api/docs/demand-integration.md +++ b/cadworld-api/docs/demand-integration.md @@ -12,7 +12,7 @@ 2. 配置 MySQL、公开模型域名与 `ARK_API_KEY`。Key 仅提供给后端,缺失时其他组件接口仍可使用,需求解析返回不可用状态。 3. 为需求图片配置私有可写的持久化目录;不能映射为静态资源或挂载到公开模型目录。 4. 前端通过同站点 HTTPS 代理 `/api`;开发跨端口时配置具体前端 origin。先完成[邮箱登录及用户编码迁移](auth-api.md),全部业务请求携带 Bearer Token。 -5. 对接组件实际接口:interfaceType 优先确定现有 category,双方 frames[].child 严格一致才可连接;每个 frames 元素是独立接口。无需填写 urdfInfo.assembly,模型摆放由前端处理。 +5. 对接组件实际接口:interfaceType 优先确定现有 category,双方 frames[].child 非空并按单向兼容规则连接(同部位父 L/R 可接同侧或 0,父 0 只接 0);每个 frames 元素是独立接口。无需填写 urdfInfo.assembly,模型摆放由前端处理。 ```bash mvn -pl cadworld-api,cadworld-adminapi -am test @@ -72,9 +72,9 @@ java -jar cadworld-api/target/cadworld-api-0.0.1-SNAPSHOT.jar ## 接口数据与实例 -组件类型扩展为16类,新增 ARM_0/HAND_0/LEG_0/FOOT_0。默认人形使用臂、手、足、脚四组各至少两个实例的要求,根据实际接口选择 L/R/0。明确六足需求使用 hexapod 模板,只要求躯干及 LEG/FOOT 各至少六个实例,不沿用人形部位要求。接口以合法 interfaceType 确定要查找的 category,缺失或无效时从 child 的 LINK_ 后解析已有类型编码/别名;无法确定类型时不从此接口向外扩展。目标类型必须属于需求,候选还须具有严格相同(区分大小写)的 child。frame 的 name、kind、type、坐标和安装基准不参与连接资格判断。 +组件类型扩展为16类,新增 ARM_0/HAND_0/LEG_0/FOOT_0。默认人形使用臂、手、足、脚四组各至少两个实例的要求,根据实际接口选择 L/R/0。明确六足需求使用 hexapod 模板,只要求躯干及 LEG/FOOT 各至少六个实例,不沿用人形部位要求。接口以合法 interfaceType 确定要查找的 category,缺失或无效时从 child 的 LINK_ 后解析已有类型编码/别名;无法确定类型时不从此接口向外扩展。装配角色必须属于需求;L/R 角色的候选扫描同时纳入同部位的 0 类组件,并按该侧需求评价条件、数量。child 完全相等时继续可连接;新增兼容只允许 ARM/HAND/LEG/FOOT 标准 LINK 编码末尾方向位 L/R(含小写 l/r)连接 0,其余字符保持区分大小写一致。frame 的 name、kind、type、坐标和安装基准不参与连接资格判断。 -四类中性接口均严格按 0 接 0、L 接 L、R 接 R 处理。默认模板的候选类型通过后端生成的 `result.request.templatePartGroups` 扩展,具体类别和分组合计缺口分别返回 `missingParts`、`missingPartGroups`。部署时同步读取 `multimodal-v1.5-neutral-components`;消息请求参数不变,无需数据库迁移,原始 URDF 与历史方案均不回写。 +四类部位统一按父到子方向处理:L 接 L/0,R 接 R/0,0 只接 0,L/R 不互接;0 组件的其他接口不根据安装侧改写。真实 component.category 保留 0,实例标识、连接类别及替代分组使用装配角色;需求检查按装配角色统计,每个实例只计一次。显式排除同时约束真实类别和装配角色。候选沿用现有排序,替代项重新验证全部相邻连接,接口不重复占用。interfaceChild 为父接口原始 child,前端须用双方实例和 frame 下标定位,不能再假设双方 child 相等。默认模板的候选类型通过后端生成的 `result.request.templatePartGroups` 扩展,具体类别和分组合计缺口分别返回 `missingParts`、`missingPartGroups`。部署时同步读取 `multimodal-v1.5-neutral-components`;消息请求参数不变,无需数据库迁移,原始 URDF 与历史方案均不回写。 ```json { @@ -101,6 +101,6 @@ java -jar cadworld-api/target/cadworld-api-0.0.1-SNAPSHOT.jar 自动测试使用 Java H2 表、模拟模型客户端、本地模拟 Responses HTTP 服务与测试资源域名,不调用真实付费模型、不访问业务 MySQL 或 OSS。 -保留规则包原始 Node 样例,验证四组样例的机械条件投影及证据不变。覆盖新流程无追问、证据和图片归属、单位补充、数值与冲突边界、模型拒绝/超时/异常、SSE、取消和重试、版本和幂等、硬要求/偏好、7 个接口路由及旧路由 404、历史内部快照不暴露、资源版本变化后通过新消息刷新、私有附件过期清理,以及消息自动返回装配、默认模板、图文冲突和缺单位生成、断流查询恢复、选件失败不发布结果、匹配快照保存失败时回滚解析结果、新消息使正在选件的旧任务失效、child严格匹配、类型优先与兜底、多个同child接口、四/六个同款实例、数量不足和上限、逐层覆盖需求、单实例替代及按实例汇总。验证缺件时默认组件与替代候选可直接预览、仅有躯干可显示,同时保留缺件和整机总量未验证提示;位姿或资源清单问题只提示,不阻塞已有组合。既有管理端上传、版本控制、逻辑删除与审计测试也参加回归。 +保留规则包原始 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 e32a0f3..7b84047 100644 --- a/cadworld-api/docs/robot-demand-api.md +++ b/cadworld-api/docs/robot-demand-api.md @@ -592,7 +592,7 @@ async function sendMessage(token, conversationId, message, onEvent, signal) { ### 躯干优先规则 -拼装仅检索同时具备非空 `step_object_key` 和已上传 URDF 主文件(非空 `urdf_main_object_key`)的组件;消息自动生成和替代候选使用同一筛选规则。仅上传 STEP 的组件不会参与拼装。接口以合法 `interfaceType` 确定目标 category,缺失或无效时从 `child` 的 LINK_ 后解析现有类别;只连接用户需求涉及的类型,且双方原始 `frames[].child` 必须非空并严格一致(区分大小写)。`name` 不参与兼容性判断。无法识别类型或无有效 child 的接口跳过并提示,不阻塞已有组合。 +拼装仅检索同时具备非空 `step_object_key` 和已上传 URDF 主文件(非空 `urdf_main_object_key`)的组件;消息自动生成和替代候选使用同一筛选规则。仅上传 STEP 的组件不会参与拼装。接口以合法 `interfaceType` 确定目标 category,缺失或无效时从 `child` 的 LINK_ 后解析现有类别;只连接用户需求涉及的装配角色,双方原始 `frames[].child` 必须非空:完全相等时可连接;ARM/HAND/LEG/FOOT 的父 L/R 接口还可连接同部位的 0 接口,父 0 只接 0,L/R 不能互接。新增兼容仅替换标准编码末尾方向位(支持大写 L/R、小写 l/r),其余字符区分大小写保持一致。`name` 不参与兼容性判断。无法识别类型或无有效 child 的接口跳过并提示,不阻塞已有组合。 整机结果始终以 `TORSO_0` 为根,默认方案中的躯干只有一个。用户未单独提出躯干时,后端在规范化的 `requiredParts` 中补入 `TORSO_0` 并返回说明;原始对话和提取的用户条目保持其来源。明确要求“不要躯干”时保留排除项,返回 `no_match`、`missingParts.reason=EXCLUDED_TORSO`,不会偷偷补入躯干;同款组件支持多个独立实例,躯干始终固定一个。 @@ -781,7 +781,7 @@ async function sendMessage(token, conversationId, message, onEvent, signal) { ### 组件包装与实例标识 -同一 `componentCode` 可以出现多次,表示同款组件的不同实例。AI 实例标识格式为 `{matchId}:{category}:{序号}`,序号从 1 开始;前端必须使用外层 `components[].instanceId` 区分模型,不能按组件编码去重。实例标识在当前方案内唯一,新方案的 matchId 和实例标识会变化。 +同一 `componentCode` 可以出现多次,表示同款组件的不同实例。AI 实例标识格式为 `{matchId}:{装配角色}:{序号}`,序号从 1 开始;前端必须使用外层 `components[].instanceId` 区分模型,不能按组件编码去重。实例标识在当前方案内唯一,新方案的 matchId 和实例标识会变化。 `data.match.components[]` 的字段如下;完整示例见第 3 节: @@ -793,6 +793,8 @@ async function sendMessage(token, conversationId, message, onEvent, signal) { | `resources[]` | object[] | 每项包含 `relativePath`、`url`、`version`、`expiresAt`,供前端加载 URDF 和 mesh | | `resourceIssues[]` | object[] | 当前组件的资源清单提示,每项含 `code`、`category`、`componentCode`、`message` | +0 组件承担指定侧时,`component.category` 保留真实类别,实例标识和替代分组使用装配角色。例如 `{matchId}:ARM_L:1` 可以对应 `category=ARM_0`,仍按左臂的数量和参数条件检查;每个实例只计入一个角色,部位分组及整机汇总不重复计算。候选沿用现有评分和编码排序。显式排除同时约束真实类别与装配角色,不能通过中性兼容绕过。0 组件的其他接口不因安装侧而改写。新规则不回写历史方案,使用新的 `messageId` 重新生成。 + ### 六足模板 目录支持 `biped`(默认人形/双足)和 `hexapod`(六足)。明确说“拼一个六足机器人”时选择 `hexapod`,不会回退到双足模板。六足模板只必需一个 `TORSO_0`,并生成 LEG、FOOT 两组各至少6个实例的要求;L/R/0 由实际接口决定,不强制分成左右各三,也不默认添加头、腰、臂、手或尾。未说明形态的需求仍沿用默认双足模板。 @@ -817,7 +819,7 @@ async function sendMessage(token, conversationId, message, onEvent, signal) { } ``` -以上是后端规范化结果的摘录,不能直接提交到消息接口或结构化匹配接口。单部位未说明左右时,AI 默认推断为 `_0`;明确左右则保留 L/R。物理接口继续严格匹配:`LINK_ARM_0` 只接 `LINK_ARM_0`,不能接 `LINK_ARM_L/R`,手、足、脚同理。 +以上是后端规范化结果的摘录,不能直接提交到消息接口或结构化匹配接口。单部位未说明左右时,AI 默认推断为 `_0`;明确左右则保留 L/R。物理接口按父到子的方向判断:`LINK_ARM_L` 可接 `LINK_ARM_L/0`,`LINK_ARM_R` 可接 `LINK_ARM_R/0`,`LINK_ARM_0` 只接 `LINK_ARM_0`,手、足、脚同理。明确左右需求可由安装到该侧接口的 0 类组件满足。 两个 `ARM_0` 实例或一个 `ARM_L` 加一个 `ARM_0` 实例均可满足 ARM 组;同款组件实例独立计数。接口不足时,例如只有一个可连接的臂,缺口如下,方案状态为 `partial`: @@ -852,9 +854,9 @@ async function sendMessage(token, conversationId, message, onEvent, signal) { } ``` -`quantity` 为 1–24 的 JSON 整数;省略或为 null 表示先覆盖各个所需类型,再填满这些类型的可匹配剩余接口。自动填充以可验证的硬要求为前提,不为多装组件而破坏本可满足的整机质量或自由度条件;明确数量不足或硬条件无法满足时保留差异。每个物理接口只能连接一个实例;同 child 的多个 frames 元素是不同接口,不合并。新增 ARM_0/HAND_0/LEG_0/FOOT_0 后,默认人形以部位分组要求各至少两个实例,具体类型按严格接口连接选择;六足另使用 hexapod 模板的 LEG/FOOT 各至少六个实例要求。 +`quantity` 为 1–24 的 JSON 整数;省略或为 null 表示先覆盖各个所需类型,再填满这些类型的可匹配剩余接口。自动填充以可验证的硬要求为前提,不为多装组件而破坏本可满足的整机质量或自由度条件;明确数量不足或硬条件无法满足时保留差异。每个物理接口只能连接一个实例;同 child 的多个 frames 元素是不同接口,不合并。新增 ARM_0/HAND_0/LEG_0/FOOT_0 后,默认人形以部位分组要求各至少两个实例,具体类型按单向兼容接口连接选择;六足另使用 hexapod 模板的 LEG/FOOT 各至少六个实例要求。 -双足模板直接使用 `LEG_L/LEG_R`。只要腰部与腿部的原始接口 child 分别严格匹配 `LINK_LEG_L`、`LINK_LEG_R`,就能沿腰部连接双腿;公开 `component.category` 返回 `LEG_L/LEG_R`,原始 `urdfInfo` 不变。旧 `pedal_l/pedal_r` 兼容输入会归一化为 `LEG_L/LEG_R`。部署类型统一修复后,旧方案需要发送新的 `messageId` 重新生成。 +双足模板直接使用 `LEG_L/LEG_R`。腰部的 `LINK_LEG_L/R` 接口可安装同侧或 `LINK_LEG_0` 的足部组件;装配角色保留 `LEG_L/LEG_R`,公开 `component.category` 返回实际选中的 `LEG_L/LEG_R/LEG_0`,原始 `urdfInfo` 不变。旧 `pedal_l/pedal_r` 兼容输入会归一化为 `LEG_L/LEG_R`。部署类型统一修复后,旧方案需要发送新的 `messageId` 重新生成。 下面为独立的四实例场景:假设躯干 `CW-TORSO-004` 有四个原始接口 `frames[0]` 至 `frames[3]`,它们的 `interfaceType=ARM_R`、`child=LINK_arm_r`,`name` 均为 `J_ARM`;每个右臂实例均使用自身的 `frames[0]` 接入,其 `child` 同样为 `LINK_arm_r`。躯干质量 2kg,每个右臂质量 1.2kg、4 个自由度。 @@ -978,13 +980,13 @@ async function sendMessage(token, conversationId, message, onEvent, signal) { | `parentFrameIndex` | integer | 父组件原始 `component.urdfInfo.frames` 的零起始下标 | | `childInstanceId` | string | 子实例标识,对应 `components[].instanceId` | | `childFrameIndex` | integer | 子组件原始 `component.urdfInfo.frames` 的零起始下标 | -| `interfaceChild` | string | 双方上述接口的共同 child,非空且区分大小写完全相等 | +| `interfaceChild` | string | 父接口原始 child,非空;子接口 child 可以是同部位的 0 | | `parentFrame` | string | 父接口原始 name,缺失时可为空字符串;仅作辅助信息 | | `parentLink` | string/null | 父接口原始 parent,缺失时为 null | | `childFrame` | string/null | 子接口原始 name,缺失时为 null;仅作辅助信息 | | `childRootLink` | string/null | 子组件原始 rootLink,缺失时为 null | -前端先按实例标识找到两个组件,再分别用 `parentFrameIndex`、`childFrameIndex` 读取各自的原始 frame;双方该 frame 的 child 均等于 `interfaceChild`。frame 名称可以重复或缺失,不能用名称代替实例与下标定位。 +前端先按实例标识找到两个组件,再分别用 `parentFrameIndex`、`childFrameIndex` 读取各自的原始 frame;父 frame 的 child 等于 `interfaceChild`;子 frame 的 child 按兼容规则可不同,例如父 `LINK_ARM_L` 对应子 `LINK_ARM_0`,不能假设双方 child 相等。frame 名称可以重复或缺失,不能用名称代替实例与下标定位。 后端只返回连接关系,不返回 `matrixLayout`、`parentRootToInterface`、`childRootToInterface`、`childRootRelativeToParentRoot` 或连接摆放用的 `xyz/rpy`。前端加载每个实例的 URDF 后,根据双方原始 frames 或模型信息决定摆放。原始 `urdfInfo` 中已有的 `xyz/rpy`、`axis`、`limits` 等仍完整保留;旧的 `urdfInfo.assembly` 可以存在,不是必填项,不参与连接资格判断。 @@ -994,7 +996,7 @@ async function sendMessage(token, conversationId, message, onEvent, signal) { 加载模型时保留 URDF 相对路径目录;OSS/CDN 须允许前端 CORS。每个实例都独立摆放,资源 URL 可以复用或缓存;用户需求图片继续使用需要 Bearer Token 的私有预览接口。 -AI 接口与结构化 `POST /api/robot-matches` 共用选件连接规则,但返回包装不同:AI 使用 `components[].instanceId={matchId}:{category}:{序号}` 和 `assembly.connections[]`;结构化接口使用 `parts[].instanceId={category}:{序号}` 和顶层 `connections[]`,详见 [结构化接口文档](api.md)。 +AI 接口与结构化 `POST /api/robot-matches` 共用选件连接规则,但返回包装不同:AI 使用 `components[].instanceId={matchId}:{装配角色}:{序号}` 和 `assembly.connections[]`;结构化接口使用 `parts[].instanceId={装配角色}:{序号}` 和顶层 `connections[]`,详见 [结构化接口文档](api.md)。 ## 6. 结果刷新与错误 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 f4c0302..d869e51 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 @@ -283,7 +283,7 @@ class DemandFlowApiTest { @ParameterizedTest @ValueSource(strings = {"neutral", "sided", "mixed"}) - void defaultHumanoidUsesAvailableStrictInterfacesAndCountsFamilies(String mode) throws Exception { + void defaultHumanoidUsesAvailableCompatibleInterfacesAndCountsFamilies(String mode) throws Exception { humanoidComponents(mode); defaultHumanoidModel(); JsonNode generated = submit(create(), "m-default-" + mode, "拼个人形机器人", List.of()); @@ -303,7 +303,10 @@ class DemandFlowApiTest { JsonNode child = selection(match, edge.path("childInstanceId").asText()); String parentChild = parent.path("component").path("urdfInfo").path("frames").get(edge.path("parentFrameIndex").asInt()).path("child").asText(); String childChild = child.path("component").path("urdfInfo").path("frames").get(edge.path("childFrameIndex").asInt()).path("child").asText(); - assertThat(parentChild).isEqualTo(childChild).isEqualTo(edge.path("interfaceChild").asText()); + assertThat(parentChild).isEqualTo(edge.path("interfaceChild").asText()); + boolean compatible = parentChild.equals(childChild) || parentChild.matches("LINK_(ARM|HAND|LEG|FOOT)_[LR]") + && childChild.equals(parentChild.substring(0, parentChild.length() - 1) + "0"); + assertThat(compatible).as(parentChild + " -> " + childChild).isTrue(); } for (String family : List.of("ARM", "HAND", "LEG", "FOOT")) { long actual = java.util.stream.StreamSupport.stream(match.path("components").spliterator(), false) @@ -363,6 +366,58 @@ class DemandFlowApiTest { assertThat(generated.path("match").path("requirementChecks").get(0).path("status").asText()).isEqualTo("satisfied"); } + @Test void neutralComponentSatisfiesSidedQuantityAndParameterChecksIncludingAlternatives() throws Exception { + save("CW-TORSO", "TORSO_0", 0, "2", 0, "BASE", true); + save("CW-NEUTRAL-A", "ARM_0", 4, "1", 20, "ARM_ROOT", true); + save("CW-NEUTRAL-B", "ARM_0", 4, "1.2", 25, "ALT_ROOT", true); + doAnswer(invocation -> { + ObjectNode raw = raw(invocation.getArgument(0)); + constraint(raw, "part", "quantity", "1", "eq", "ARM_R"); + intent(raw, "quantity", "右臂", "右臂一个"); + return raw; + }).when(model).analyze(anyList()); + Session session = create(); + JsonNode generated = submit(session, "m-neutral-sided", TEXT + ",右臂一个", List.of()); + JsonNode match = generated.path("match"); + assertThat(match.path("status").asText()).isEqualTo("complete"); + assertThat(match.path("missingParts")).isEmpty(); + assertThat(match.path("requirementChecks").findValuesAsText("status")).containsOnly("satisfied"); + JsonNode component = match.path("components").get(1); + assertThat(component.path("instanceId").asText()).endsWith(":ARM_R:1"); + assertThat(component.path("component").path("category").asText()).isEqualTo("ARM_0"); + JsonNode edge = match.path("assembly").path("connections").get(0); + assertThat(edge.path("interfaceChild").asText()).isEqualTo("LINK_ARM_R"); + assertThat(component.path("component").path("urdfInfo").path("frames").get(edge.path("childFrameIndex").asInt()).path("child").asText()).isEqualTo("LINK_ARM_0"); + JsonNode alternative = match.path("alternatives").get(1); + assertThat(alternative.path("category").asText()).isEqualTo("ARM_R"); + assertThat(alternative.path("items")).hasSize(1); + assertThat(alternative.path("items").get(0).path("component").path("category").asText()).isEqualTo("ARM_0"); + assertThat(alternative.path("items").get(0).path("requirementChecks").findValuesAsText("status")).containsOnly("satisfied"); + assertThat(alternative.path("items").get(0).path("assembly").path("status").asText()).isEqualTo("ready"); + assertThat(generatedMatch(session, generated.path("analysisId").asText(), 1)).isEqualTo(match); + } + + @ParameterizedTest + @ValueSource(booleans = {true, false}) + void explicitlyExcludedNeutralCategoryCannotReenterASidedCandidatePool(boolean hasSidedComponent) throws Exception { + save("CW-TORSO", "TORSO_0", 0, "2", 0, "BASE", true); + save("CW-NEUTRAL", "ARM_0", 4, "1", 20, "ARM_ROOT", true); + if (hasSidedComponent) save("CW-SIDED", "ARM_R", 4, "1", 20, "ARM_ROOT", true); + doAnswer(invocation -> { + ObjectNode raw = raw(invocation.getArgument(0)); + raw.withArray("excludedCategories").addObject().put("category", "ARM_0").putArray("evidenceIds").add("e1"); + intent(raw, "exclusion", "ARM_0", "不要ARM_0"); + return raw; + }).when(model).analyze(anyList()); + JsonNode match = submit(create(), "m-no-neutral", TEXT + ",不要ARM_0", List.of()).path("match"); + assertThat(match.path("components").findValuesAsText("category")).doesNotContain("ARM_0"); + assertThat(match.path("alternatives").findValuesAsText("componentCode")).doesNotContain("CW-NEUTRAL"); + assertThat(match.path("status").asText()).isEqualTo(hasSidedComponent ? "complete" : "partial"); + assertThat(match.path("requirementChecks").get(3).path("field").asText()).isEqualTo("excludedCategories"); + assertThat(match.path("requirementChecks").get(3).path("status").asText()).isEqualTo("satisfied"); + if (!hasSidedComponent) assertThat(match.path("missingParts").findValuesAsText("category")).containsExactly("ARM_R"); + } + @Test void hexapodDemandUsesProvidedSpiderTorsoAndSixIndependentLegAndFootInstances() throws Exception { ComponentFixtureSupport.loadHexapodLibrary(jdbc, json); doAnswer(invocation -> { 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 73d4ccb..6210698 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 @@ -137,8 +137,18 @@ class MatchingApiTest { assertThat(result.path("status").asText()).isEqualTo("MATCHED"); assertThat(result.path("parts").size()).isEqualTo(16); assertThat(result.path("connections").size()).isEqualTo(15); - assertThat(part(result, "LEG_L").path("componentCode").asText()).isEqualTo("CW-LEG_L"); - assertThat(part(result, "FOOT_L").path("componentCode").asText()).isEqualTo("CW-FOOT_L"); + assertThat(result.path("connections").findValuesAsText("childCategory")).containsExactlyInAnyOrderElementsOf(english); + assertThat(result.path("parts").findValuesAsText("instanceId")).contains("LEG_L:1", "FOOT_L:1"); + for (JsonNode selected : result.path("parts")) { + if ("LEG_L:1".equals(selected.path("instanceId").asText())) { + assertThat(selected.path("componentCode").asText()).isEqualTo("CW-LEG_0"); + assertThat(selected.path("category").asText()).isEqualTo("LEG_0"); + } + if ("FOOT_L:1".equals(selected.path("instanceId").asText())) { + assertThat(selected.path("componentCode").asText()).isEqualTo("CW-FOOT_0"); + assertThat(selected.path("category").asText()).isEqualTo("FOOT_0"); + } + } } @Test void legacyStoredCategoriesAndRequestsReturnStandardCodesAndOriginalUrdf() throws Exception { @@ -726,26 +736,124 @@ class MatchingApiTest { @ParameterizedTest @ValueSource(strings = {"ARM", "HAND", "LEG", "FOOT"}) - void neutralAndSidedInterfacesRequireIdenticalChildren(String family) throws Exception { - for (String parentSide : List.of("0", "L", "R")) { - for (String childSide : List.of("0", "L", "R")) { - jdbc.update("DELETE FROM component"); - String parentRole = family + "_" + parentSide; - String childRole = family + "_" + childSide; - com.fasterxml.jackson.databind.node.ObjectNode info = (com.fasterxml.jackson.databind.node.ObjectNode) metadata("BASE", parentRole); - // 每类同时覆盖 interfaceType 和 child 回退识别。 - ((com.fasterxml.jackson.databind.node.ObjectNode) info.path("frames").get(0)).remove("interfaceType"); - save("CW-T", "TORSO_0", 0, "1", "0", "", info, json.readTree("[]")); - save("CW-C", childRole, 1, "1", "0", ""); - JsonNode result = match(request(childRole)); - assertThat(result.path("parts")).as(parentRole + " -> " + childRole).hasSize(parentSide.equals(childSide) ? 2 : 1); - if (parentSide.equals(childSide)) { - assertThat(result.path("connections").get(0).path("interfaceChild").asText()).isEqualTo("LINK_" + parentRole); + void sidedInterfacesAcceptNeutralComponentsOnlyInTheParentToChildDirection(String family) throws Exception { + for (boolean explicitType : List.of(true, false)) { + for (String parentSide : List.of("0", "L", "R")) { + for (String childSide : List.of("0", "L", "R")) { + jdbc.update("DELETE FROM component"); + String parentRole = family + "_" + parentSide; + String childRole = family + "_" + childSide; + com.fasterxml.jackson.databind.node.ObjectNode info = (com.fasterxml.jackson.databind.node.ObjectNode) metadata("BASE", parentRole); + // 每类同时覆盖 interfaceType 和 child 回退识别。 + if (!explicitType) ((com.fasterxml.jackson.databind.node.ObjectNode) info.path("frames").get(0)).remove("interfaceType"); + save("CW-T", "TORSO_0", 0, "1", "0", "", info, json.readTree("[]")); + save("CW-C", childRole, 1, "1", "0", ""); + JsonNode result = match(request(childRole)); + boolean compatible = parentSide.equals(childSide) || !"0".equals(parentSide) && "0".equals(childSide); + assertThat(result.path("parts")).as(parentRole + " -> " + childRole + " explicitType=" + explicitType).hasSize(compatible ? 2 : 1); + if (compatible) { + assertThat(result.path("connections").get(0).path("interfaceChild").asText()).isEqualTo("LINK_" + parentRole); + } } } } } + @ParameterizedTest + @ValueSource(strings = {"ARM", "HAND", "LEG", "FOOT"}) + void neutralComponentsFulfilSidedQuantitiesAndEachSidesConditions(String family) throws Exception { + save("CW-T", "TORSO_0", 0, "1", "0", "", metadata("BASE", family + "_L", family + "_R", family + "_R"), json.readTree("[]")); + save("CW-NEUTRAL-A", family + "_0", 2, "1", "20", "钢"); + save("CW-NEUTRAL-B", family + "_0", 3, "2", "30", "铝合金"); + Map body = new LinkedHashMap<>(request(family + "_L", family + "_R")); + body.put("partRequirements", List.of( + Map.of("category", family + "_L", "quantity", 1, "material", "钢", "torqueNm", 20), + Map.of("category", family + "_R", "quantity", 2, "material", "铝合金", "torqueNm", 30))); + JsonNode result = match(body); + assertThat(result.path("status").asText()).isEqualTo("MATCHED"); + assertThat(result.path("parts")).hasSize(4); + assertThat(result.path("missingParts")).isEmpty(); + assertThat(result.path("unmetRequirements")).isEmpty(); + assertThat(result.path("totals").path("massKg").decimalValue()).isEqualByComparingTo("6"); + assertThat(result.path("totals").path("degreesOfFreedom").asLong()).isEqualTo(8); + for (JsonNode part : result.path("parts")) { + if ("TORSO_0".equals(part.path("category").asText())) continue; + assertThat(part.path("category").asText()).isEqualTo(family + "_0"); + assertThat(part.path("urdfInfo").path("frames").get(0).path("child").asText()).isEqualTo("LINK_" + family + "_0"); + assertThat(part.path("componentCode").asText()).isEqualTo(part.path("instanceId").asText().startsWith(family + "_L:") ? "CW-NEUTRAL-A" : "CW-NEUTRAL-B"); + assertPublic(part); + } + assertThat(result.path("connections").findValuesAsText("childCategory")).containsExactly(family + "_L", family + "_R", family + "_R"); + body.put("partRequirements", List.of(Map.of("category", family + "_L", "quantity", 1), Map.of("category", family + "_R", "quantity", 3))); + JsonNode shortage = match(body).path("missingParts"); + assertThat(shortage).hasSize(1); + assertThat(shortage.get(0).path("category").asText()).isEqualTo(family + "_R"); + assertThat(shortage.get(0).path("actualQuantity").asInt()).isEqualTo(2); + assertThat(shortage.get(0).path("missingQuantity").asInt()).isEqualTo(1); + } + + @Test void sidedAndNeutralCandidatesKeepExistingScoreAndCodeOrderingAndCanReplaceEachOther() throws Exception { + save("CW-T", "TORSO_0", 0, "1", "0", "", metadata("BASE", "ARM_L"), json.readTree("[]")); + save("CW-A-NEUTRAL", "ARM_0", 1, "1", "20", ""); + save("CW-B-SIDED", "ARM_L", 1, "1", "20", ""); + JsonNode result = match(request("ARM_L")); + assertThat(result.path("parts").get(1).path("componentCode").asText()).isEqualTo("CW-A-NEUTRAL"); + assertThat(result.path("parts").get(1).path("instanceId").asText()).isEqualTo("ARM_L:1"); + assertThat(alternatives(result, "ARM_L").get(0).path("component").path("componentCode").asText()).isEqualTo("CW-B-SIDED"); + jdbc.update("UPDATE component SET torque_nm=30 WHERE component_code='CW-B-SIDED'"); + Map body = new LinkedHashMap<>(request("ARM_L")); + body.put("partRequirements", List.of(Map.of("category", "ARM_L", "torqueNm", 30))); + result = match(body); + assertThat(result.path("parts").get(1).path("componentCode").asText()).isEqualTo("CW-B-SIDED"); + JsonNode neutral = alternatives(result, "ARM_L").get(0); + assertThat(neutral.path("component").path("category").asText()).isEqualTo("ARM_0"); + assertThat(neutral.path("connections").get(0).path("interfaceChild").asText()).isEqualTo("LINK_ARM_L"); + assertThat(neutral.path("unmetRequirements").get(0).path("category").asText()).isEqualTo("ARM_L"); + assertThat(neutral.path("totals").path("massKg").decimalValue()).isEqualByComparingTo("2"); + } + + @Test void torsoCoverageCountsEachCompatiblePhysicalPortOnce() throws Exception { + save("CW-A", "TORSO_0", 0, "1", "0", "", metadata("BASE_A", "ARM_L"), json.readTree("[]")); + save("CW-B", "TORSO_0", 0, "1", "0", "", metadata("BASE_B", "ARM_L", "ARM_0"), json.readTree("[]")); + save("CW-C", "ARM_0", 1, "1", "0", ""); + JsonNode result = match(request("ARM_L", "ARM_0")); + assertThat(part(result, "TORSO_0").path("componentCode").asText()).isEqualTo("CW-B"); + assertThat(result.path("status").asText()).isEqualTo("MATCHED"); + assertThat(result.path("connections").findValuesAsText("childCategory")).containsExactlyInAnyOrder("ARM_L", "ARM_0"); + } + + @Test void excludedSidedPortsCannotBeUsedForNeutralRolesOrTorsoAlternatives() throws Exception { + save("CW-A", "TORSO_0", 0, "1", "0", "", metadata("BASE_A", "ARM_0"), json.readTree("[]")); + save("CW-B", "TORSO_0", 0, "1", "0", "", metadata("BASE_B", "ARM_L"), json.readTree("[]")); + save("CW-C", "TORSO_0", 0, "1", "0", "", metadata("BASE_C", "ARM_R"), json.readTree("[]")); + save("CW-N", "ARM_0", 1, "1", "0", ""); + Map body = new LinkedHashMap<>(request("ARM_0")); + body.put("partRequirements", List.of(Map.of("category", "ARM_0", "quantity", 1))); + RobotMatchResponse result = context.getBean(RobotMatchingService.class).matchConfirmed( + json.convertValue(body, RobotMatchRequest.class), java.util.Set.of(), List.of(), java.util.Set.of("ARM_L")); + assertThat(result.parts().get(0).componentCode()).isEqualTo("CW-A"); + assertThat(result.parts()).hasSize(2); + assertThat(result.alternatives().get(0).items()).extracting((RobotMatchResponse.Replacement item) -> item.component().componentCode()) + .containsExactly("CW-C"); + jdbc.update("DELETE FROM component WHERE component_code IN ('CW-A','CW-C')"); + result = context.getBean(RobotMatchingService.class).matchConfirmed( + json.convertValue(body, RobotMatchRequest.class), java.util.Set.of(), List.of(), java.util.Set.of("ARM_L")); + assertThat(result.parts()).hasSize(1); + assertThat(result.missingParts()).extracting(RobotMatchResponse.MissingPart::category).containsExactly("ARM_0"); + } + + @Test void neutralComponentsKeepTheirOutgoingInterfacesAndDoNotGainAnImplicitSide() throws Exception { + save("CW-T", "TORSO_0", 0, "1", "0", "", metadata("BASE", "ARM_R"), json.readTree("[]")); + save("CW-A", "ARM_0", 1, "1", "0", "", metadata("ARM_ROOT", "HAND_0"), json.readTree("[]")); + save("CW-H", "HAND_0", 1, "1", "0", ""); + JsonNode result = match(request("ARM_R", "HAND_R")); + assertThat(result.path("parts")).hasSize(2); + assertThat(result.path("missingParts").findValuesAsText("category")).containsExactly("HAND_R"); + result = match(request("ARM_R", "HAND_0")); + assertThat(result.path("status").asText()).isEqualTo("MATCHED"); + assertThat(result.path("connections").findValuesAsText("interfaceChild")).containsExactly("LINK_ARM_R", "LINK_HAND_0"); + } + @Test void groupedSelectionRespectsWholeRobotTotalsAndExplicitCategoryQuantity() throws Exception { save("CW-T", "TORSO_0", 0, "1", "0", "", metadata("BASE", "ARM_0", "ARM_0", "ARM_0", "ARM_0"), json.readTree("[]")); save("CW-A", "ARM_0", 1, "1", "20", ""); @@ -791,7 +899,9 @@ class MatchingApiTest { assertThat(result.parts()).hasSize(3); assertThat(result.parts().get(0).componentCode()).isEqualTo("CW-B"); assertThat(result.parts()).extracting(com.linkerbot.cadworld.dto.matching.PublicComponentResponse::componentCode) - .contains("CW-NEUTRAL", "CW-RIGHT").doesNotContain("CW-WRONG"); + .containsExactly("CW-B", "CW-NEUTRAL", "CW-NEUTRAL"); + assertThat(result.parts()).extracting(com.linkerbot.cadworld.dto.matching.PublicComponentResponse::instanceId) + .containsExactlyInAnyOrder("TORSO_0:1", "ARM_0:1", "ARM_R:1"); assertThat(result.missingPartGroups()).isEmpty(); assertThat(result.unmetRequirements()).isEmpty(); } 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 c56a270..62ae24f 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 @@ -17,6 +17,7 @@ public record RobotMatchResponse( missingParts, List.of(), searchLimited); } + /** category 表示本次装配角色;interfaceChild 保留父接口原始 child,子接口通过下标定位。 */ public record Connection(String parentCategory, String parentComponentCode, String parentLink, String frameName, String childCategory, String childComponentCode, String childRootLink, String parentInstanceId, String childInstanceId, 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 528aebf..4b60379 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 @@ -20,6 +20,7 @@ import com.linkerbot.cadworld.service.matching.RobotMatchingService; import java.math.BigDecimal; import java.util.ArrayList; import java.util.LinkedHashMap; +import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Set; @@ -42,7 +43,9 @@ public final class DemandMatchService { public JsonNode match(String matchId, DemandRepository.Analysis analysis) { long started = System.nanoTime(); boolean torsoExcluded = false; + Set excludedCategories = new LinkedHashSet<>(); for (JsonNode excluded : analysis.result().path("analysis").path("excludedCategories")) { + excludedCategories.add(excluded.path("category").asText()); torsoExcluded |= "TORSO_0".equals(excluded.path("category").asText()); } RobotMatchResponse response; @@ -53,7 +56,7 @@ public final class DemandMatchService { response = new RobotMatchResponse("NO_MATCH", null, List.of(), List.of(), List.of(), new RobotMatchResponse.Totals(0, null, BigDecimal.ZERO, false), List.of(), List.of(), missing, false); } else { - response = matching.matchConfirmed(project(analysis.result()), requirements.softFields(analysis.result()), templateGroups(analysis.result())); + response = matching.matchConfirmed(project(analysis.result()), requirements.softFields(analysis.result()), templateGroups(analysis.result()), excludedCategories); } ObjectNode result = build(matchId, analysis, response); log.info("需求自动选件与装配校验完成 requestId={} analysisId={} revision={} matchId={} selectedCount={} missingCount={} unmetCount={} status={} assemblyStatus={} assemblyIssueCodes={} durationMs={}", 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 a6ff4bc..de82743 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 @@ -8,6 +8,7 @@ import com.linkerbot.cadworld.dto.matching.PublicComponentResponse; import com.linkerbot.cadworld.dto.matching.RobotMatchResponse; import com.linkerbot.cadworld.service.matching.MatchTextService; import java.util.ArrayList; +import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.List; import java.util.Locale; @@ -58,6 +59,11 @@ public final class DemandRequirementChecker { public ArrayNode check(JsonNode saved, RobotMatchResponse match) { ArrayNode checks = json.createArrayNode(); + Map assemblyRoles = new LinkedHashMap<>(); + for (RobotMatchResponse.Connection connection : match.connections()) { + assemblyRoles.put(connection.parentInstanceId(), connection.parentCategory()); + assemblyRoles.put(connection.childInstanceId(), connection.childCategory()); + } JsonNode request = saved.path("request"); JsonNode analysis = saved.path("analysis"); for (JsonNode intent : analysis.path("intentItems")) { @@ -73,7 +79,8 @@ public final class DemandRequirementChecker { Integer expected = quantity(intent); check.put("field", "quantity"); if (expected != null && quantitySupported(intent)) { - long actual = roles.isEmpty() ? match.parts().isEmpty() ? 0 : 1 : match.parts().stream().filter((PublicComponentResponse part) -> roles.contains(part.category())).count(); + long actual = roles.isEmpty() ? match.parts().isEmpty() ? 0 : 1 : match.parts().stream() + .filter((PublicComponentResponse part) -> roles.contains(assemblyRoles.getOrDefault(part.instanceId(), part.category()))).count(); check.put("expected", expected).put("actual", actual); if (roles.isEmpty() && (!match.missingParts().isEmpty() || !match.missingPartGroups().isEmpty())) check.put("reason", "尚未形成完整整机,无法验证整机数量"); else check.put("status", actual == expected ? "satisfied" : "unmet").put("reason", actual == expected ? "所选组件实例数量满足条件" : "组件实例数量不足"); @@ -84,7 +91,8 @@ public final class DemandRequirementChecker { Set excluded = new LinkedHashSet<>(); for (JsonNode item : analysis.path("excludedCategories")) excluded.add(item.path("category").asText()); if (excluded.containsAll(roles)) { - boolean exists = match.parts().stream().anyMatch((PublicComponentResponse part) -> roles.contains(part.category())); + boolean exists = match.parts().stream().anyMatch((PublicComponentResponse part) -> roles.contains(part.category()) + || roles.contains(assemblyRoles.getOrDefault(part.instanceId(), part.category()))); check.put("status", exists ? "unmet" : "satisfied").put("reason", exists ? "方案包含明确排除的组件" : "方案未包含明确排除的组件"); check.put("field", "excludedCategories"); check.set("expected", json.valueToTree(roles)); check.put("actual", exists); } @@ -118,7 +126,7 @@ public final class DemandRequirementChecker { List actuals = new ArrayList<>(); if (role.isEmpty()) actuals.add("degreesOfFreedom".equals(field) ? json.valueToTree(match.totals().degreesOfFreedom()) : json.valueToTree(match.totals().massKg())); else { - for (PublicComponentResponse part : match.parts()) if (role.equals(part.category())) { + for (PublicComponentResponse part : match.parts()) if (role.equals(assemblyRoles.getOrDefault(part.instanceId(), 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); diff --git a/cadworld-service/src/main/java/com/linkerbot/cadworld/service/matching/AssemblyMetadata.java b/cadworld-service/src/main/java/com/linkerbot/cadworld/service/matching/AssemblyMetadata.java index 52ecafa..9073dec 100644 --- a/cadworld-service/src/main/java/com/linkerbot/cadworld/service/matching/AssemblyMetadata.java +++ b/cadworld-service/src/main/java/com/linkerbot/cadworld/service/matching/AssemblyMetadata.java @@ -6,7 +6,7 @@ import java.util.ArrayList; import java.util.List; import java.util.Locale; -/** 接口兼容性只比较原始child;数组下标标识接口,不合并同child的多个安装位置。 */ +/** 保留原始 child;兼容规则集中在 InterfaceCompatibility,下标区分独立安装位置。 */ public record AssemblyMetadata(String rootLink, List ports, List problems) { static AssemblyMetadata read(Component component) { return read(component.getUrdfInfo()); @@ -46,7 +46,7 @@ public record AssemblyMetadata(String rootLink, List ports, List int interfaceMask() { int mask = 0; - for (Port port : ports) if (port.role() != null) mask |= port.role().bit(); + for (Port port : ports) for (ComponentRole role : InterfaceCompatibility.roles(port.role())) mask |= role.bit(); return mask; } 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 0384aa9..8e3614b 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 @@ -65,9 +65,11 @@ public class AssemblySearchEngine { int depth = state.depth(parent.getKey()); if (depth > frontierDepth) continue; for (AssemblyMetadata.Port port : parent.getValue().metadata().ports()) { - if (port.role() == null || !request.canAdd(port.role(), state.count(port.role())) || state.portUsed(parent.getKey(), port.index())) continue; - if (coverMinimum && !request.needed(port.role(), state, coverTypes)) continue; + if (!request.allowsPort(port) || state.portUsed(parent.getKey(), port.index())) continue; for (CandidatePool.Attachment target : pool.targets(port.role(), port.child())) { + ComponentRole role = target.candidate().role(); + if (!request.canAdd(role, state.count(role)) || !InterfaceCompatibility.canAttach(port, target.candidate(), target.port())) continue; + if (coverMinimum && !request.needed(role, state, coverTypes)) continue; frontierDepth = Math.min(frontierDepth, depth); if (state.parts().size() >= AssemblyState.MAX_INSTANCES) { limited = true; continue; } if (expansions >= budget) { budgetExhausted = true; break expansion; } @@ -102,9 +104,12 @@ public class AssemblySearchEngine { 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())) - || !request.needed(port.role(), state, uncoveredOnly) || state.portUsed(parent.getKey(), port.index())) continue; - if (!pool.targets(port.role(), port.child()).isEmpty()) return true; + if (!request.allowsPort(port) || state.portUsed(parent.getKey(), port.index())) continue; + for (CandidatePool.Attachment target : pool.targets(port.role(), port.child())) { + ComponentRole role = target.candidate().role(); + if (request.canAdd(role, state.count(role)) && request.needed(role, state, uncoveredOnly) + && InterfaceCompatibility.canAttach(port, target.candidate(), target.port())) return true; + } } } return false; 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 673eab8..888d64c 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,6 +3,8 @@ 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.HashMap; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.List; @@ -31,7 +33,7 @@ record AssemblyState(ComponentRole root, Map parts, L 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())) { + || !InterfaceCompatibility.canAttach(parentPort, candidate, childPort) || portUsed(parent, parentPort.index())) { throw new IllegalArgumentException("Invalid assembly component attachment"); } String child = candidate.role().code() + ":" + (count(candidate.role()) + 1); @@ -60,26 +62,50 @@ record AssemblyState(ComponentRole root, Map parts, L if (parts.get(instance).role() != replacement.role()) return null; Map next = new LinkedHashMap<>(parts); next.put(instance, replacement); + List affected = edges.stream().filter((Edge edge) -> edge.parent().equals(instance) || edge.child().equals(instance)).toList(); + List> options = new ArrayList<>(); + for (Edge edge : affected) { + boolean parent = edge.parent().equals(instance); + AssemblyMetadata.Port old = parent ? edge.parentPort() : edge.childPort(); + options.add(replacement.metadata().ports().stream() + .filter((AssemblyMetadata.Port port) -> parent + ? InterfaceCompatibility.canAttach(port, parts.get(edge.child()), edge.childPort()) + : InterfaceCompatibility.canAttach(edge.parentPort(), replacement, port)) + .sorted(Comparator.comparing((AssemblyMetadata.Port port) -> port.index() != old.index()) + .thenComparingInt(AssemblyMetadata.Port::index)).toList()); + } + Map portOwners = new HashMap<>(); + Map assigned = new HashMap<>(); + for (int index = 0; index < affected.size(); index++) { + if (!assignPort(index, options, portOwners, assigned, new HashSet<>())) return null; + } List connections = new ArrayList<>(); - Set used = new HashSet<>(); + int affectedIndex = 0; for (Edge edge : edges) { 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 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.index()); + AssemblyMetadata.Port port = assigned.get(affectedIndex++); connections.add(new Edge(edge.parent(), parent ? port : edge.parentPort(), edge.child(), child ? port : edge.childPort())); } return new AssemblyState(root, next, connections); } + /** 增广路保证所有邻接边使用不同接口,避免先选走唯一能连接其他边的接口。 */ + private static boolean assignPort(int edge, List> options, Map portOwners, + Map assigned, Set visited) { + for (AssemblyMetadata.Port port : options.get(edge)) { + if (!visited.add(port.index())) continue; + Integer owner = portOwners.get(port.index()); + if (owner == null || assignPort(owner, options, portOwners, assigned, visited)) { + portOwners.put(port.index(), edge); + assigned.put(edge, port); + return true; + } + } + return false; + } + List connections() { return edges.stream().map((Edge edge) -> { MatchingCandidate parent = parts.get(edge.parent()); 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 5e2ea41..2086a00 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 @@ -7,9 +7,11 @@ import java.util.ArrayList; import java.util.Comparator; import java.util.EnumMap; import java.util.HashMap; +import java.util.HashSet; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; +import java.util.Set; import java.util.function.Function; /** 分页扫描时仅保留优先候选、接口代表和数值极值,不把整张表装入内存。 */ @@ -46,16 +48,20 @@ final class CandidatePool { } void accept(Component component) { - ComponentRole role = ComponentRole.require(component.getCategory()); - Accumulator accumulator = accumulators.get(role); - accumulator.observed++; + ComponentRole actualRole = ComponentRole.require(component.getCategory()); + if (request.excludedRoles().contains(actualRole)) return; scanned++; AssemblyMetadata metadata = AssemblyMetadata.read(component); 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)); - accumulator.accept(candidate); + for (Map.Entry entry : accumulators.entrySet()) { + ComponentRole role = entry.getKey(); + if (!InterfaceCompatibility.allowsRole(role, actualRole)) continue; + entry.getValue().observed++; + MatchingCandidate candidate = new MatchingCandidate(component, role, metadata, evaluator.assess(component, role, request)); + entry.getValue().accept(candidate); + } } List invalidCodeSamples() { return List.copyOf(invalidCodeSamples); } @@ -68,23 +74,51 @@ final class CandidatePool { private int compatibleCoverage(MatchingCandidate candidate, Result pool) { int covered = 0; - Map availablePorts = new EnumMap<>(ComponentRole.class); - 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); - availablePorts.put(role, (int) Math.min(ports, request.quantity(role) == null ? AssemblyState.MAX_INSTANCES : request.quantity(role))); - } + Set grouped = new HashSet<>(); for (NormalizedMatchRequest.PartGroup group : request.groups()) { - int available = group.roles().stream().mapToInt((ComponentRole role) -> availablePorts.getOrDefault(role, 0)).sum(); - int explicit = group.roles().stream().mapToInt((ComponentRole role) -> - Math.min(request.minimum(role), availablePorts.getOrDefault(role, 0))).sum(); - covered += Math.max(0, Math.min(group.minimumQuantity(), available) - explicit); + grouped.addAll(group.roles()); + int explicit = portCoverage(candidate, pool, group.roles(), true); + int available = portCoverage(candidate, pool, group.roles(), false); + covered += Math.max(explicit, Math.min(group.minimumQuantity(), available)); + } + List ungrouped = request.roles().stream() + .filter((ComponentRole role) -> role != ComponentRole.TORSO && !grouped.contains(role)).toList(); + covered += portCoverage(candidate, pool, ungrouped, true); + return covered; + } + + /** 同一躯干接口即使能承担多个需求角色,也只能贡献一次覆盖。 */ + private int portCoverage(MatchingCandidate candidate, Result pool, List roles, boolean minimumOnly) { + List> slots = new ArrayList<>(); + for (ComponentRole role : roles) { + List ports = candidate.metadata().ports().stream().filter((AssemblyMetadata.Port port) -> + request.allowsPort(port) && pool.targets(port.role(), port.child()).stream().anyMatch((Attachment target) -> + target.candidate().role() == role && InterfaceCompatibility.canAttach(port, target.candidate(), target.port()))) + .map(AssemblyMetadata.Port::index).toList(); + int quantity = minimumOnly ? request.minimum(role) + : request.quantity(role) == null ? AssemblyState.MAX_INSTANCES : request.quantity(role); + for (int index = 0; index < Math.min(quantity, ports.size()); index++) slots.add(ports); + } + Map owners = new HashMap<>(); + int covered = 0; + for (int index = 0; index < slots.size(); index++) { + if (coverSlot(index, slots, owners, new HashSet<>())) covered++; } return covered; } + private boolean coverSlot(int slot, List> slots, Map owners, Set visited) { + for (Integer port : slots.get(slot)) { + if (!visited.add(port)) continue; + Integer owner = owners.get(port); + if (owner == null || coverSlot(owner, slots, owners, visited)) { + owners.put(port, slot); + return true; + } + } + return false; + } + private void sampleInvalidCode(String code) { if (invalidCodeSamples.size() < 5) invalidCodeSamples.add(code); } @@ -175,7 +209,8 @@ final class CandidatePool { } List targets(ComponentRole role, String child) { - return interfaces.getOrDefault(role, Map.of()).getOrDefault(child, List.of()); + return InterfaceCompatibility.roles(role).stream() + .flatMap((ComponentRole target) -> interfaces.getOrDefault(target, Map.of()).getOrDefault(child, List.of()).stream()).toList(); } private static Map>> index(Map> candidates) { @@ -183,7 +218,9 @@ final class CandidatePool { 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)); + for (String parentChild : InterfaceCompatibility.parentChildren(port.child())) { + byChild.computeIfAbsent(parentChild, (String key) -> new ArrayList<>()).add(new Attachment(candidate, port)); + } } byChild.replaceAll((String key, List values) -> List.copyOf(values)); result.put(role, Map.copyOf(byChild)); diff --git a/cadworld-service/src/main/java/com/linkerbot/cadworld/service/matching/InterfaceCompatibility.java b/cadworld-service/src/main/java/com/linkerbot/cadworld/service/matching/InterfaceCompatibility.java new file mode 100644 index 0000000..fc82139 --- /dev/null +++ b/cadworld-service/src/main/java/com/linkerbot/cadworld/service/matching/InterfaceCompatibility.java @@ -0,0 +1,59 @@ +package com.linkerbot.cadworld.service.matching; + +import java.util.List; +import java.util.Locale; + +/** 兼容具有方向性:父接口的 L/R 可连接同部位的 0,不能反向或左右互换。 */ +final class InterfaceCompatibility { + private InterfaceCompatibility() { } + + static ComponentRole neutral(ComponentRole role) { + if (role == null) return null; + return switch (role) { + case ARM_L, ARM_R -> ComponentRole.ARM_0; + case HAND_L, HAND_R -> ComponentRole.HAND_0; + case LEG_L, LEG_R -> ComponentRole.LEG_0; + case FOOT_L, FOOT_R -> ComponentRole.FOOT_0; + default -> role; + }; + } + + static List roles(ComponentRole role) { + if (role == null) return List.of(); + ComponentRole neutral = neutral(role); + return neutral == role ? List.of(role) : List.of(role, neutral); + } + + static boolean allowsRole(ComponentRole parent, ComponentRole child) { + return parent != null && child != null && (parent == child || neutral(parent) == child); + } + + static boolean canAttach(AssemblyMetadata.Port parent, MatchingCandidate child, AssemblyMetadata.Port childPort) { + return allowsRole(parent.role(), child.role()) && allowsRole(child.role(), child.actualRole()) + && matchesChild(parent.child(), childPort.child()); + } + + static boolean matchesChild(String parent, String child) { + if (parent == null || child == null || parent.isBlank() || child.isBlank()) return false; + if (parent.equals(child)) return true; + if (!standardLimbChild(parent)) return false; + char side = parent.charAt(parent.length() - 1); + return (side == 'L' || side == 'R' || side == 'l' || side == 'r') + && (parent.substring(0, parent.length() - 1) + "0").equals(child); + } + + /** 将中性子接口索引到允许连接它的父 child,保留原始前缀的大小写。 */ + static List parentChildren(String child) { + if (!standardLimbChild(child) || !child.endsWith("_0")) return List.of(child); + String prefix = child.substring(0, child.length() - 1); + return List.of(child, prefix + "L", prefix + "R", prefix + "l", prefix + "r"); + } + + private static boolean standardLimbChild(String child) { + if (child == null) return false; + String normalized = child.toUpperCase(Locale.ROOT); + int separator = normalized.lastIndexOf('_'); + return separator == normalized.length() - 2 && separator > 0 + && List.of("LINK_ARM", "LINK_HAND", "LINK_LEG", "LINK_FOOT").contains(normalized.substring(0, separator)); + } +} diff --git a/cadworld-service/src/main/java/com/linkerbot/cadworld/service/matching/MatchingCandidate.java b/cadworld-service/src/main/java/com/linkerbot/cadworld/service/matching/MatchingCandidate.java index 8e20ca1..cc99101 100644 --- a/cadworld-service/src/main/java/com/linkerbot/cadworld/service/matching/MatchingCandidate.java +++ b/cadworld-service/src/main/java/com/linkerbot/cadworld/service/matching/MatchingCandidate.java @@ -2,7 +2,10 @@ package com.linkerbot.cadworld.service.matching; import com.linkerbot.cadworld.entity.Component; +/** role 是本次装配角色;组件实体始终保留真实类别。 */ record MatchingCandidate(Component component, ComponentRole role, AssemblyMetadata metadata, RequirementEvaluator.LocalAssessment assessment) { String code() { return component.getComponentCode(); } + ComponentRole actualRole() { return ComponentRole.require(component.getCategory()); } + boolean neutralSubstitution() { return actualRole() != role; } } 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 95ac177..2df78c4 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 @@ -17,7 +17,7 @@ import java.util.Set; record NormalizedMatchRequest(List roles, List keywords, RobotRequirements robot, Map parts, Set softFields, - Set requiredRoles, List groups) { + Set requiredRoles, List groups, Set excludedRoles) { static NormalizedMatchRequest from(RobotMatchRequest request) { return from(request, Set.of()); } @@ -27,12 +27,17 @@ record NormalizedMatchRequest(List roles, List keywords, } static NormalizedMatchRequest from(RobotMatchRequest request, Set softFields, List templateGroups) { + return from(request, softFields, templateGroups, Set.of()); + } + + static NormalizedMatchRequest from(RobotMatchRequest request, Set softFields, List templateGroups, + Set excludedRoles) { if (request.requiredParts() == null || request.requiredParts().isEmpty()) { throw invalid("requiredParts不能为空"); } Set required = new LinkedHashSet<>(); required.add(ComponentRole.TORSO); - request.requiredParts().stream().map(ComponentRole::require).forEach(required::add); + request.requiredParts().stream().map(ComponentRole::require).filter((ComponentRole role) -> !excludedRoles.contains(role)).forEach(required::add); Set available = new LinkedHashSet<>(required); List groups = new ArrayList<>(); Set families = new LinkedHashSet<>(); @@ -41,7 +46,9 @@ record NormalizedMatchRequest(List roles, List keywords, || group.minimumQuantity() < 1 || group.minimumQuantity() > 24 || group.categories() == null || group.categories().isEmpty()) { throw invalid("模板部位分组无效"); } - List members = group.categories().stream().map(ComponentRole::require).distinct().toList(); + List members = group.categories().stream().map(ComponentRole::require) + .filter((ComponentRole role) -> !excludedRoles.contains(role)).distinct().toList(); + if (members.isEmpty()) continue; if (members.stream().anyMatch((ComponentRole role) -> !role.code().startsWith(group.family() + "_"))) throw invalid("模板分组包含其他部位"); groups.add(new PartGroup(group.family(), members, group.minimumQuantity())); available.addAll(members); @@ -54,6 +61,7 @@ record NormalizedMatchRequest(List roles, List keywords, Map parts = new EnumMap<>(ComponentRole.class); for (PartRequirements part : request.partRequirements() == null ? List.of() : request.partRequirements()) { ComponentRole role = ComponentRole.require(part.category()); + if (excludedRoles.contains(role)) continue; if (!required.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的整数"); @@ -67,7 +75,17 @@ record NormalizedMatchRequest(List roles, List keywords, if (!text(keyword).isEmpty()) keywords.add(text(keyword)); } return new NormalizedMatchRequest(roles, List.copyOf(keywords), robot, Map.copyOf(parts), Set.copyOf(softFields), - Set.copyOf(required), List.copyOf(groups)); + Set.copyOf(required), List.copyOf(groups), Set.copyOf(excludedRoles)); + } + + List scanRoles() { + return roles.stream().flatMap((ComponentRole role) -> InterfaceCompatibility.roles(role).stream()) + .filter((ComponentRole role) -> !excludedRoles.contains(role)).distinct() + .sorted(Comparator.comparingInt(ComponentRole::ordinal)).toList(); + } + + boolean allowsPort(AssemblyMetadata.Port port) { + return port.role() != null && !excludedRoles.contains(port.role()); } boolean preferred(String category, String field) { return softFields.contains((category == null ? "robot" : category) + ":" + field); } 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 71ab9af..80df82b 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 @@ -55,15 +55,28 @@ public class RobotMatchingService { return matchInternal(input, true, softFields, groups); } + /** 对话排除项同时约束装配角色和候选的真实类别,不向公开请求增加字段。 */ + @Transactional(readOnly = true) + public RobotMatchResponse matchConfirmed(RobotMatchRequest input, Set softFields, List groups, + Set excludedCategories) { + Set excluded = excludedCategories.stream().map(ComponentRole::require).collect(java.util.stream.Collectors.toUnmodifiableSet()); + return matchInternal(input, true, softFields, groups, excluded); + } + private RobotMatchResponse matchInternal(RobotMatchRequest input, boolean strictFirst, Set softFields) { return matchInternal(input, strictFirst, softFields, List.of()); } private RobotMatchResponse matchInternal(RobotMatchRequest input, boolean strictFirst, Set softFields, List groups) { + return matchInternal(input, strictFirst, softFields, groups, Set.of()); + } + + private RobotMatchResponse matchInternal(RobotMatchRequest input, boolean strictFirst, Set softFields, List groups, + Set excluded) { long started = System.nanoTime(); - NormalizedMatchRequest request = NormalizedMatchRequest.from(input, softFields, groups); + NormalizedMatchRequest request = NormalizedMatchRequest.from(input, softFields, groups, excluded); CandidatePool collector = new CandidatePool(request, evaluator, properties); - components.scan(request.roles(), collector::accept); + components.scan(request.scanRoles(), collector::accept); CandidatePool.Result pool = collector.finish(); MatchingCandidate torso = collector.torso(pool); log.info("躯干选择完成 requestId={} candidateCount={} componentCode={} hardUnmetCount={} preferredUnmetCount={} keywordCoverage={} keywordCount={}", @@ -105,8 +118,11 @@ public class RobotMatchingService { log.info("组件匹配降级 requestId={} unmetFields={} missingReasons={} unmatchedKeywordCount={}", RequestIdHolder.get(), unmetFields, missingReasons, response.unmatchedKeywords().size()); } - log.info("组件匹配完成 requestId={} requestedCount={} scannedCount={} selectedCount={} status={} unmetCount={} missingCount={} searchLimited={} expansions={} durationMs={}", - RequestIdHolder.get(), request.roles().size(), pool.scanned(), response.parts().size(), response.status(), + AssemblyState selected = result.best() == null ? null : result.best().state(); + long neutralConnections = selected == null ? 0 : selected.edges().stream().filter((AssemblyState.Edge edge) -> + selected.parts().get(edge.child()).neutralSubstitution() || !edge.parentPort().child().equals(edge.childPort().child())).count(); + log.info("组件匹配完成 requestId={} requestedCount={} scannedCount={} selectedCount={} neutralCompatibilityCount={} status={} unmetCount={} missingCount={} searchLimited={} expansions={} durationMs={}", + RequestIdHolder.get(), request.roles().size(), pool.scanned(), response.parts().size(), neutralConnections, response.status(), response.unmetRequirements().size(), response.missingParts().size(), result.limited(), result.expansions(), (System.nanoTime() - started) / 1_000_000); return response; @@ -151,7 +167,9 @@ public class RobotMatchingService { for (MatchingCandidate candidate : pool.candidates().get(current.role())) { if (candidate.code().equals(current.code())) continue; AssemblyState replaced = selected.replace(instance, candidate); - if (replaced != null) compatible.add(new ReplacementState(candidate, replaced, evaluator.evaluate(replaced, request))); + if (replaced != null && replaced.edges().stream().allMatch((AssemblyState.Edge edge) -> request.allowsPort(edge.parentPort()))) { + compatible.add(new ReplacementState(candidate, replaced, evaluator.evaluate(replaced, request))); + } } result.put(instance, compatible.stream().sorted(order).limit(5).toList()); }); 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 22764a8..a622855 100644 --- a/cadworld-service/src/main/resources/robot-demand/system-prompt.txt +++ b/cadworld-service/src/main/resources/robot-demand/system-prompt.txt @@ -19,7 +19,7 @@ 12. 六足/六腿/hexapod 选择 hexapod 模板,不得标为不支持或回退为双足。六足基本构型由躯干、六个足部和六个脚部候选组成,具体左右或中性类型由后端按实际接口选择,不默认添加人形的头、腰、臂、手或尾。未配置的四足、轮式、履带、鸟形等保留为 unmodeled,不谎称双足能够满足;后端可返回默认参考方案并保留差异。“仿生鸟类”保留机器人、仿生、鸟类等关键词,可将双足作为 inferred 候选;飞行能力保留为未验证,企鹅、鸵鸟或明确不飞行时不推断飞行。 13. 类别仅限以下16个大写编码:TORSO_0 躯干、HEAD_0 头、WAIST_0 腰、ARM_L 左臂、ARM_R 右臂、ARM_0 不分左右的臂、HAND_L 左手、HAND_R 右手、HAND_0 不分左右的手、LEG_L 左足、LEG_R 右足、LEG_0 不分左右的足、FOOT_L 左脚、FOOT_R 右脚、FOOT_0 不分左右的脚、TAIL_0 尾。0 不分左右,L/R 是机械左右,足和脚不同,不输出 pedal 类别。单部位未说明左右时选择对应 _0 并标为 inferred,reason 说明默认选择,不伪装成用户明确指定类型。明确左或右时保留 L/R;明确双臂展开 ARM_L/ARM_R;“两个不分左右的臂”使用 ARM_0、quantity=2。人形的默认类型组合由后端按实际接口选取,不要自行把全部16类列为必需部件。 14. 明确排除的部件放 excludedCategories,未指定左右且排除整个臂、手、足或脚时,展开排除该部位的 L/R/0 三类,不作为正向包含。仅凭草图没画出某部件不能当作排除。翅膀、轮子、旋翼、电池、传感器、爪等目录外部件放 unmodeled,不造类别或把手臂当翅膀。现有部位支持同款组件的多个独立实例;明确数量写入quantity维度intentItems,并以part范围、field=quantity、operator=eq写入constraints,value保留原始数量,支持1至24。跨多个部位的合计数量仅保留intentItems,不平均分配。数量缺失时不要补1;后端按需求类型和实际可用接口填充。整机固定一个躯干。不要新增目录外类别或目录中未配置的模板;templatePartGroups 由后端生成,不自行输出。 -15. 解析器不生成安装接口、坐标、旋转、父子关系或配对方案。真实连接来自后端组件数据:interfaceType优先决定目标部位,双方frames.child严格一致才能连接;同child的多个接口独立处理,后端只返回实例连接关系,摆放由前端处理。不要从草图像素生成3D位置。 +15. 解析器不生成安装接口、坐标、旋转、父子关系或配对方案。真实连接来自后端组件数据:interfaceType优先决定目标部位,双方frames.child非空且相等时可连接;ARM/HAND/LEG/FOOT的父L/R接口也可安装同部位0接口组件,父0只接0,L/R不能互接,其他字符保持原有大小写匹配。0组件可承担指定侧需求,真实组件类别与本次装配角色分别保留;同child的多个接口独立处理,后端只返回实例连接关系,摆放由前端处理。不要从草图像素生成3D位置。 四、机械条件 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。不把“机器人”当作用户指定名称。 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 691a9fa..0deb58a 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 @@ -53,6 +53,22 @@ class DemandAssemblyValidatorTest { .containsExactly("DM-test:ARM_R:1", "DM-test:ARM_R:2"); } + @Test void sidedToNeutralConnectionPreservesBothOriginalFramesAndParentChildValue() { + ObjectNode neutralInfo = info("NEUTRAL_ROOT"); + ((ObjectNode) neutralInfo.path("frames").get(0)).put("name", "NEUTRAL_MOUNT").put("child", "LINK_arm_0").put("interfaceType", "ARM_0"); + RobotMatchResponse base = match(info("BASE"), neutralInfo); + PublicComponentResponse neutral = part("CHILD", "ARM_0", neutralInfo).withInstanceId("ARM_R:1"); + RobotMatchResponse match = new RobotMatchResponse(base.status(), base.rootCategory(), List.of(base.parts().get(0), neutral), + base.connections(), base.alternatives(), base.totals(), base.unmetRequirements(), base.unmatchedKeywords(), base.missingParts(), false); + DemandAssemblyValidator.Assembly result = validator.validate("DM-test", match); + assertThat(result.status()).isEqualTo("ready"); + assertThat(result.connections().get(0).interfaceChild()).isEqualTo("LINK_arm_r"); + assertThat(result.connections().get(0).childFrame()).isEqualTo("NEUTRAL_MOUNT"); + assertThat(result.connections().get(0).childFrameIndex()).isZero(); + assertThat(neutral.category()).isEqualTo("ARM_0"); + assertThat(neutral.urdfInfo()).isEqualTo(neutralInfo); + } + @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(), diff --git a/cadworld-service/src/test/java/com/linkerbot/cadworld/service/matching/AssemblyStateTest.java b/cadworld-service/src/test/java/com/linkerbot/cadworld/service/matching/AssemblyStateTest.java new file mode 100644 index 0000000..b9cde89 --- /dev/null +++ b/cadworld-service/src/test/java/com/linkerbot/cadworld/service/matching/AssemblyStateTest.java @@ -0,0 +1,61 @@ +package com.linkerbot.cadworld.service.matching; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ObjectNode; +import com.linkerbot.cadworld.entity.Component; +import java.math.BigDecimal; +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.assertThatThrownBy; + +class AssemblyStateTest { + private final ObjectMapper json = new ObjectMapper(); + + @Test void replacementReassignsFlexiblePortToPreserveTheOnlyPortForASidedChild() { + MatchingCandidate torso = candidate("T", ComponentRole.TORSO, "TORSO_0", "ARM_0", "ARM_L"); + MatchingCandidate neutral = candidate("N", ComponentRole.ARM_0, "ARM_0", "ARM_0"); + MatchingCandidate left = candidate("L", ComponentRole.ARM_L, "ARM_L", "ARM_L"); + AssemblyState state = AssemblyState.root(torso) + .attach("TORSO_0:1", torso.metadata().ports().get(0), neutral, neutral.metadata().ports().get(0)) + .attach("TORSO_0:1", torso.metadata().ports().get(1), left, left.metadata().ports().get(0)); + MatchingCandidate replacement = candidate("T2", ComponentRole.TORSO, "TORSO_0", "ARM_L", "ARM_0"); + AssemblyState replaced = state.replace("TORSO_0:1", replacement); + assertThat(replaced).isNotNull(); + assertThat(replaced.connections()).extracting(com.linkerbot.cadworld.dto.matching.RobotMatchResponse.Connection::parentFrameIndex) + .containsExactly(1, 0); + assertThat(replaced.connections()).extracting(com.linkerbot.cadworld.dto.matching.RobotMatchResponse.Connection::interfaceChild) + .containsExactly("LINK_ARM_0", "LINK_ARM_L"); + assertThat(state.replace("TORSO_0:1", candidate("T3", ComponentRole.TORSO, "TORSO_0", "ARM_L"))).isNull(); + assertThatThrownBy(() -> state.attach("TORSO_0:1", torso.metadata().ports().get(0), neutral, neutral.metadata().ports().get(0))) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test void replacementOfAnIntermediateNeutralComponentKeepsIncomingAndOutgoingPortsDistinct() { + MatchingCandidate torso = candidate("T", ComponentRole.TORSO, "TORSO_0", "ARM_L"); + MatchingCandidate middle = candidate("M", ComponentRole.ARM_L, "ARM_0", "ARM_0", "ARM_L"); + MatchingCandidate left = candidate("L", ComponentRole.ARM_L, "ARM_L", "ARM_L"); + AssemblyState state = AssemblyState.root(torso) + .attach("TORSO_0:1", torso.metadata().ports().get(0), middle, middle.metadata().ports().get(0)) + .attach("ARM_L:1", middle.metadata().ports().get(1), left, left.metadata().ports().get(0)); + AssemblyState replaced = state.replace("ARM_L:1", candidate("M2", ComponentRole.ARM_L, "ARM_0", "ARM_L", "ARM_0")); + assertThat(replaced).isNotNull(); + assertThat(replaced.connections().get(0).childFrameIndex()).isEqualTo(1); + assertThat(replaced.connections().get(1).parentFrameIndex()).isZero(); + assertThat(state.replace("ARM_L:1", candidate("BAD", ComponentRole.ARM_L, "ARM_0", "ARM_0", "ARM_0"))).isNull(); + } + + private MatchingCandidate candidate(String code, ComponentRole role, String actualCategory, String... interfaces) { + Component component = new Component(); + component.setComponentCode(code); + component.setCategory(actualCategory); + ObjectNode metadata = json.createObjectNode().put("rootLink", "BASE"); + metadata.putArray("frames"); + for (String type : interfaces) metadata.withArray("frames").addObject() + .put("name", type).put("child", "LINK_" + type).put("interfaceType", type); + component.setUrdfInfo(metadata); + return new MatchingCandidate(component, role, AssemblyMetadata.read(metadata), + new RequirementEvaluator.LocalAssessment(List.of(), BigDecimal.ZERO, new int[0], false, 0, 0, BigDecimal.ZERO)); + } +} diff --git a/cadworld-service/src/test/java/com/linkerbot/cadworld/service/matching/InterfaceCompatibilityTest.java b/cadworld-service/src/test/java/com/linkerbot/cadworld/service/matching/InterfaceCompatibilityTest.java new file mode 100644 index 0000000..cfdbf45 --- /dev/null +++ b/cadworld-service/src/test/java/com/linkerbot/cadworld/service/matching/InterfaceCompatibilityTest.java @@ -0,0 +1,31 @@ +package com.linkerbot.cadworld.service.matching; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; + +import static org.assertj.core.api.Assertions.assertThat; + +class InterfaceCompatibilityTest { + @ParameterizedTest + @CsvSource({ + "LINK_ARM_L, LINK_ARM_0, true", "LINK_arm_r, LINK_arm_0, true", + "link_hand_l, link_hand_0, true", "LINK_LEG_R, LINK_LEG_0, true", + "LINK_FOOT_L, LINK_FOOT_0, true", "LINK_ARM_L, LINK_ARM_L, true", + "custom_mount, custom_mount, true", "LINK_ARM_0, LINK_ARM_L, false", + "LINK_ARM_L, LINK_ARM_R, false", "LINK_ARM_R, LINK_ARM_L, false", + "LINK_ARM_L, LINK_HAND_0, false", "LINK_ARM_L, LINK_arm_0, false", + "LINK_arm_l, LINK_ARM_0, false", "LINK_TORSO_L, LINK_TORSO_0, false", + "CUSTOM_ARM_L, CUSTOM_ARM_0, false", "LINK_ARM_L_extra, LINK_ARM_0_extra, false" + }) + void preservesRawChildCaseAndLimitsDirectionalCompatibilityToKnownLimbCodes(String parent, String child, boolean expected) { + assertThat(InterfaceCompatibility.matchesChild(parent, child)).isEqualTo(expected); + assertThat(InterfaceCompatibility.parentChildren(child).contains(parent)).isEqualTo(expected); + } + + @Test void missingChildrenNeverConnectEvenIfBothAreMissing() { + assertThat(InterfaceCompatibility.matchesChild(null, null)).isFalse(); + assertThat(InterfaceCompatibility.matchesChild("", "")).isFalse(); + assertThat(InterfaceCompatibility.matchesChild(" ", " ")).isFalse(); + } +}