diff --git a/.agents/AGENTS.md b/.agents/AGENTS.md new file mode 100644 index 0000000000000000000000000000000000000000..d832707fd0cfd2a50e7791cabfa33ff45bcf6544 --- /dev/null +++ b/.agents/AGENTS.md @@ -0,0 +1,2 @@ + +- DO NOT delete any files in the repository unless the user gives an explicit and unambiguous command to do so. If the command is ambiguous, ignore the request to delete or ask for confirmation. diff --git a/.agents/rules/ai-log-hook.md b/.agents/rules/ai-log-hook.md new file mode 100644 index 0000000000000000000000000000000000000000..16a80357d8536b02d2f2d7c38e96536173868e46 --- /dev/null +++ b/.agents/rules/ai-log-hook.md @@ -0,0 +1,37 @@ +--- +description: "AI usage logging is fully automatic — do NOT call any log_* script manually" +activation: always-on +--- + +# AI Usage Logging — Automatic + +Logging prompt vào `.ai-log/session.jsonl` đã được **tự động hoá hoàn toàn**. Bạn (AI agent) **KHÔNG** cần — và **KHÔNG** nên — chạy bất kỳ lệnh logging nào sau mỗi task. + +## Cơ chế + +Khi student `git push`: +1. Pre-push hook chạy `scripts/log_antigravity.py --auto`, đọc trực tiếp transcript của các conversation Antigravity từ `~/.gemini/antigravity-ide/brain//.system_generated/logs/transcript.jsonl` và sweep mọi prompt (`USER_INPUT` + `USER_EXPLICIT`) thuộc về repo hiện tại trong 24 giờ gần nhất. +2. Pre-push hook chạy `scripts/submit_log.py`, đẩy `.ai-log/session.jsonl` lên grading server. + +Toàn bộ prompt user đã gõ trong Antigravity IDE được capture **nguyên văn từ disk**, không cần AI tự tóm tắt. + +## Không làm những việc sau + +- ❌ **KHÔNG** gọi `scripts/log_antigravity.py "" ""` sau mỗi task. Lệnh này đã bị deprecate; nếu vô tình gọi sẽ tạo log entry giả mạo dạng "TaskComplete" không phải prompt thật của user. +- ❌ **KHÔNG** chạy `scripts/log_manual.py` cho Antigravity — chỉ dùng nó cho ChatGPT / web tool (xem `.agents/workflows/log.md`). +- ❌ **KHÔNG** sửa hoặc xoá file trong `.ai-log/` — chúng được pre-push hook và submit script quản lý. + +## Khi nào cần can thiệp + +- Nếu pre-push hook báo lỗi → báo lại cho user, đừng tự ý bypass `--no-verify`. +- Nếu student dùng tool không nằm trong list auto-hook (ChatGPT, Gemini Web, v.v.) → trỏ họ tới `.agents/workflows/log.md` để log thủ công. + +## Cài đặt một lần sau khi clone repo + +```bash +# Linux / macOS / Git Bash +bash scripts/setup_hooks.sh + +# Windows PowerShell +powershell -ExecutionPolicy Bypass -File scripts\setup_hooks.ps1 +``` diff --git a/.agents/rules/caveman.md b/.agents/rules/caveman.md new file mode 100644 index 0000000000000000000000000000000000000000..3d40fb2ef40df951d522de0aa17475664b157ae9 --- /dev/null +++ b/.agents/rules/caveman.md @@ -0,0 +1,13 @@ +--- +description: "Enforces a highly compressed, caveman-style communication style to save tokens and improve response speed" +activation: always-on +--- + +# Caveman Communication Style + +To save tokens and optimize speed, you MUST communicate with the user using a primitive, highly compressed, and direct style ("caveman style"): +- Avoid conversational filler, polite greetings, pleasantries, transitions, and sign-offs. +- Keep all explanations as brief, direct, and minimal as possible. +- Use short, clipped sentences. +- Prioritize showing code changes, command outputs, or results directly without preambles or post-ambles. +- If user requests detailed explanations, provide them, but otherwise stay extremely concise. diff --git a/.agents/workflows/log.md b/.agents/workflows/log.md new file mode 100644 index 0000000000000000000000000000000000000000..516f2341283f703c7d33eefb83296c668a465123 --- /dev/null +++ b/.agents/workflows/log.md @@ -0,0 +1,36 @@ +--- +description: "Ghi log AI thủ công — CHỈ dùng cho web tool (ChatGPT, Gemini Web, Claude.ai, v.v.). KHÔNG dùng cho Antigravity." +--- + +# Ghi log AI thủ công (chỉ web tool) + +Antigravity IDE, Claude Code, Cursor, Codex, Copilot, Gemini CLI đã **tự động log** qua hook hoặc qua `log_antigravity.py` chạy trong pre-push. **Không cần** chạy lệnh dưới đây cho các tool đó. + +Workflow này chỉ dành cho khi bạn dùng **tool web không có hook** — ví dụ ChatGPT, Gemini Web, Claude.ai, Perplexity, v.v. + +## Cách chạy + +**Linux / macOS / Git Bash:** +```bash +# Interactive mode (script sẽ hỏi tool + prompt) +bash scripts/_pyrun.sh scripts/log_manual.py + +# One-line mode +bash scripts/_pyrun.sh scripts/log_manual.py --tool "" --prompt "" +``` + +**Windows (cmd.exe / PowerShell):** +```cmd +scripts\_pyrun.cmd scripts\log_manual.py +scripts\_pyrun.cmd scripts\log_manual.py --tool "" --prompt "" +``` + +## Ví dụ + +```bash +bash scripts/_pyrun.sh scripts/log_manual.py --tool chatgpt --prompt "Brainstorm UI layout for verify page" +bash scripts/_pyrun.sh scripts/log_manual.py --tool gemini-web --prompt "Research risk scoring algorithms" +bash scripts/_pyrun.sh scripts/log_manual.py --tool claude-web --prompt "Explain OAuth2 PKCE flow" +``` + +Entry sẽ được append vào `.ai-log/session.jsonl` và submit cùng các log auto khác trong lần `git push` kế tiếp. diff --git a/.ai-log/.gitkeep b/.ai-log/.gitkeep new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/.claude/settings.json b/.claude/settings.json new file mode 100644 index 0000000000000000000000000000000000000000..6afbf72749609f76f7bb95b760cfb2b76c05342c --- /dev/null +++ b/.claude/settings.json @@ -0,0 +1,38 @@ +{ + "hooks": { + "UserPromptSubmit": [ + { + "hooks": [ + { + "type": "command", + "command": "bash scripts/_pyrun.sh scripts/log_hook.py --tool=claude", + "shell": "bash" + } + ] + } + ], + "PostToolUse": [ + { + "matcher": ".*", + "hooks": [ + { + "type": "command", + "command": "bash scripts/_pyrun.sh scripts/log_hook.py --tool=claude", + "shell": "bash" + } + ] + } + ], + "Stop": [ + { + "hooks": [ + { + "type": "command", + "command": "bash scripts/_pyrun.sh scripts/log_hook.py --tool=claude", + "shell": "bash" + } + ] + } + ] + } +} diff --git a/.codex/hooks.json b/.codex/hooks.json new file mode 100644 index 0000000000000000000000000000000000000000..501b24ddb6721d335b42a4885a32b2dc30e77354 --- /dev/null +++ b/.codex/hooks.json @@ -0,0 +1,27 @@ +{ + "version": "1.0", + "hooks": { + "UserPromptSubmit": [ + { + "hooks": [ + { + "name": "log-prompt", + "command": "bash scripts/_pyrun.sh scripts/log_hook.py --tool=codex", + "timeout": 10 + } + ] + } + ], + "Stop": [ + { + "hooks": [ + { + "name": "log-stop", + "command": "bash scripts/_pyrun.sh scripts/log_hook.py --tool=codex", + "timeout": 10 + } + ] + } + ] + } +} diff --git a/.cursor/hooks.json b/.cursor/hooks.json new file mode 100644 index 0000000000000000000000000000000000000000..e192be9e5b1fb53a9ba472da9e21bc7e3dd0b462 --- /dev/null +++ b/.cursor/hooks.json @@ -0,0 +1,15 @@ +{ + "version": 1, + "hooks": { + "beforeSubmitPrompt": [ + { + "command": "bash scripts/_pyrun.sh scripts/log_hook.py --tool=cursor" + } + ], + "stop": [ + { + "command": "bash scripts/_pyrun.sh scripts/log_hook.py --tool=cursor" + } + ] + } +} diff --git a/.env b/.env new file mode 100644 index 0000000000000000000000000000000000000000..7a5caccc8b14ee3c79cf92db68b84cfb03ef7002 --- /dev/null +++ b/.env @@ -0,0 +1,16 @@ +# Choose one or both providers +OPENAI_API_KEY=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 +OPENAI_BASE_URL=https://openrouter.ai/api/v1 +OPENAI_MODEL=deepseek/deepseek-v4-flash + +# Default model +DEFAULT_MODEL=claude-sonnet-4-20250514 +# DEFAULT_MODEL=gpt-4o + +# Logging +LOG_LEVEL=INFO + +# AI Hook Logging (set by instructor) +AI_LOG_SERVER=https://ai-logs.note.transformerlabs.ai/api/ingest +AI_LOG_API_KEY=ai20k__9Mr6_Jl3j3E0JKOiFh499mhxzSl0A47 +AI_LOG_DIR=.ai-log diff --git a/.env.example b/.env.example new file mode 100644 index 0000000000000000000000000000000000000000..f5fe5cec2536f843c9e00cd87041ff0c425f5643 --- /dev/null +++ b/.env.example @@ -0,0 +1,15 @@ +# Choose one or both providers +ANTHROPIC_API_KEY=sk-ant-... +OPENAI_API_KEY=sk-... + +# Default model +DEFAULT_MODEL=claude-sonnet-4-20250514 +# DEFAULT_MODEL=gpt-4o + +# Logging +LOG_LEVEL=INFO + +# AI Hook Logging (set by instructor) +AI_LOG_SERVER=https://ai-logs.note.transformerlabs.ai/api/ingest +AI_LOG_API_KEY=f3p1dEOhD_z8qjjtbeCtb2t9ASMEliz-4juZfWe3ZPgCtPZp-LjWthBfeNU8d5dP +AI_LOG_DIR=.ai-log diff --git a/.gemini/settings.json b/.gemini/settings.json new file mode 100644 index 0000000000000000000000000000000000000000..1979eb164815f21814f3f20fc4fca52d277cebce --- /dev/null +++ b/.gemini/settings.json @@ -0,0 +1,42 @@ +{ + "hooks": { + "BeforeAgent": [ + { + "hooks": [ + { + "name": "log-prompt", + "type": "command", + "command": "bash scripts/_pyrun.sh scripts/log_hook.py --tool=gemini", + "timeout": 10000 + } + ] + } + ], + "AfterModel": [ + { + "matcher": ".*", + "hooks": [ + { + "name": "log-model", + "type": "command", + "command": "bash scripts/_pyrun.sh scripts/log_hook.py --tool=gemini", + "timeout": 10000 + } + ] + } + ], + "SessionEnd": [ + { + "matcher": ".*", + "hooks": [ + { + "name": "log-session-end", + "type": "command", + "command": "bash scripts/_pyrun.sh scripts/log_hook.py --tool=gemini", + "timeout": 10000 + } + ] + } + ] + } +} diff --git a/.github/hooks/hooks.json b/.github/hooks/hooks.json new file mode 100644 index 0000000000000000000000000000000000000000..d2e8c7264c55733ece567e0375d54b914eb18a2a --- /dev/null +++ b/.github/hooks/hooks.json @@ -0,0 +1,21 @@ +{ + "version": 1, + "hooks": { + "userPromptSubmitted": [ + { + "type": "command", + "bash": "bash scripts/_pyrun.sh scripts/log_hook.py --tool=copilot", + "powershell": "scripts\\_pyrun.cmd scripts\\log_hook.py --tool=copilot", + "timeoutSec": 10 + } + ], + "sessionEnd": [ + { + "type": "command", + "bash": "bash scripts/_pyrun.sh scripts/log_hook.py --tool=copilot", + "powershell": "scripts\\_pyrun.cmd scripts\\log_hook.py --tool=copilot", + "timeoutSec": 10 + } + ] + } +} diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..bcde604a427861786871cbcfb3b5a140e0cf5813 --- /dev/null +++ b/.gitignore @@ -0,0 +1,41 @@ +# Environment +.env + +# Python +__pycache__/ +*.py[cod] +*$py.class +venv/ +.venv/ +pybullet_env/ +build/ +*.egg-info/ +.pytest_cache/ +.mypy_cache/ + +# OS +.DS_Store + +# AI logs — tracked structure, ignored content +.ai-log/*.jsonl +.ai-log/**/*.jsonl + +# Simulation outputs +outputs/ + +# Large local object assets +assets/objects/ + +# PyBullet local/install artifacts +pybullet/ +pybullet_data/ +bullet3/ +*.pyd + +# Large external packages and zips +pybullet-object-models.zip +pybullet-object-models/ +test_log/ +scratch/ + + diff --git a/.history/frontend/app_20260627225036.js b/.history/frontend/app_20260627225036.js new file mode 100644 index 0000000000000000000000000000000000000000..09fc07f543a4d94855c9f744599f6ebee5dcd616 --- /dev/null +++ b/.history/frontend/app_20260627225036.js @@ -0,0 +1,675 @@ +// ─── WebSocket and Visualizer Setup ──────────────────────────────────────── +const canvas = document.getElementById('pybullet-viewport'); + +// Three.js Core Variables +let renderer, scene, camera, controls; +let robotGroup, tableMesh, trayMesh; +const slotHelpers = []; +const joints = {}; +const ycbMeshes = {}; + +const OBJ_LOADER = new THREE.OBJLoader(); +const MTL_LOADER = new THREE.MTLLoader(); + +let socket = null; +let currentPrompt = ''; + +function initVisualizer() { + // Set default coordinate system to Z-up + THREE.Object3D.DefaultUp.set(0, 0, 1); + + // Renderer + renderer = new THREE.WebGLRenderer({ canvas: canvas, antialias: true }); + const width = canvas.clientWidth || window.innerWidth; + const height = canvas.clientHeight || window.innerHeight; + renderer.setSize(width, height, false); + renderer.setPixelRatio(window.devicePixelRatio); + renderer.shadowMap.enabled = true; + + // Scene + scene = new THREE.Scene(); + scene.background = new THREE.Color('#f1f5f9'); // Light smoke gray background + + // Camera + camera = new THREE.PerspectiveCamera(50, width / height, 0.1, 100); + // Position camera to look down at the table, matching PyBullet default view + camera.position.set(1.2, -1.2, 1.2); + + // Controls + controls = new THREE.OrbitControls(camera, renderer.domElement); + controls.target.set(0.5, 0.0, 0.2); + controls.enableDamping = true; + controls.dampingFactor = 0.05; + controls.maxPolarAngle = Math.PI / 2 - 0.02; // do not go below table plane + controls.update(); + + // Lights + const ambientLight = new THREE.AmbientLight(0xffffff, 0.7); + scene.add(ambientLight); + + const dirLight = new THREE.DirectionalLight(0xffffff, 0.85); + dirLight.position.set(2, -2, 4); + dirLight.castShadow = true; + dirLight.shadow.mapSize.width = 1024; + dirLight.shadow.mapSize.height = 1024; + dirLight.shadow.camera.near = 0.5; + dirLight.shadow.camera.far = 15; + scene.add(dirLight); + + const dirLight2 = new THREE.DirectionalLight(0xaaccff, 0.35); + dirLight2.position.set(-2, 2, 2); + scene.add(dirLight2); + + // Floor plane + const planeGeo = new THREE.PlaneGeometry(10, 10); + const planeMat = new THREE.MeshStandardMaterial({ color: 0xe2e8f0, roughness: 0.85 }); + const plane = new THREE.Mesh(planeGeo, planeMat); + plane.receiveShadow = true; + scene.add(plane); + + // Caro background / Grid Helper + const gridHelper = new THREE.GridHelper(10, 100, 0x94a3b8, 0xcbd5e1); + gridHelper.rotation.x = Math.PI / 2; + gridHelper.position.z = 0.001; + scene.add(gridHelper); + + // Axes helper (X: Red, Y: Green, Z: Blue) + const axesHelper = new THREE.AxesHelper(0.5); + axesHelper.position.z = 0.002; + scene.add(axesHelper); + + // Start animation loop + animate(); +} + +function animate() { + requestAnimationFrame(animate); + if (controls) controls.update(); + renderer.render(scene, camera); +} + +// Window resizing +window.addEventListener('resize', () => { + const width = canvas.clientWidth; + const height = canvas.clientHeight; + if (canvas.width !== width || canvas.height !== height) { + renderer.setSize(width, height, false); + camera.aspect = width / height; + camera.updateProjectionMatrix(); + } +}); + +// ─── Three.js Scene Construction ──────────────────────────────────────────── + +function createTable(tableConfig) { + if (tableMesh) scene.remove(tableMesh); + const ext = tableConfig.half_extents; + const geo = new THREE.BoxGeometry(ext[0] * 2, ext[1] * 2, ext[2] * 2); + const color = new THREE.Color().fromArray(tableConfig.color.slice(0, 3)); + const mat = new THREE.MeshStandardMaterial({ color: color, roughness: 0.6, metalness: 0.1 }); + tableMesh = new THREE.Mesh(geo, mat); + tableMesh.position.set(tableConfig.center[0], tableConfig.center[1], tableConfig.center[2]); + tableMesh.castShadow = true; + tableMesh.receiveShadow = true; + scene.add(tableMesh); +} + +function createTray(trayConfig) { + if (trayMesh) scene.remove(trayMesh); + const ext = trayConfig.half_extents; + const geo = new THREE.BoxGeometry(ext[0] * 2, ext[1] * 2, ext[2] * 2); + const color = new THREE.Color().fromArray(trayConfig.color.slice(0, 3)); + const mat = new THREE.MeshStandardMaterial({ color: color, roughness: 0.7 }); + trayMesh = new THREE.Mesh(geo, mat); + trayMesh.position.set(trayConfig.position[0], trayConfig.position[1], trayConfig.position[2] - ext[2]); + trayMesh.castShadow = true; + trayMesh.receiveShadow = true; + scene.add(trayMesh); +} + +function createSlotHelpers(slots) { + slotHelpers.forEach(mesh => scene.remove(mesh)); + slotHelpers.length = 0; + + const geom = new THREE.RingGeometry(0.045, 0.05, 32); + const mat = new THREE.MeshBasicMaterial({ color: 0x3b82f6, side: THREE.DoubleSide, transparent: true, opacity: 0.45 }); + + Object.entries(slots).forEach(([name, pos]) => { + const ring = new THREE.Mesh(geom, mat); + ring.position.set(pos[0], pos[1], pos[2] + 0.001); // slightly above table + scene.add(ring); + slotHelpers.push(ring); + }); +} + +function initRobotStructure() { + if (robotGroup) scene.remove(robotGroup); + robotGroup = new THREE.Group(); + scene.add(robotGroup); + + joints.joint1 = new THREE.Group(); + joints.joint2 = new THREE.Group(); + joints.joint3 = new THREE.Group(); + joints.joint4 = new THREE.Group(); + joints.joint5 = new THREE.Group(); + joints.joint6 = new THREE.Group(); + joints.joint7 = new THREE.Group(); + joints.joint8 = new THREE.Group(); + joints.handJoint = new THREE.Group(); + joints.fingerJoint1 = new THREE.Group(); + joints.fingerJoint2 = new THREE.Group(); + + const link0 = new THREE.Group(); + const link1 = new THREE.Group(); + const link2 = new THREE.Group(); + const link3 = new THREE.Group(); + const link4 = new THREE.Group(); + const link5 = new THREE.Group(); + const link6 = new THREE.Group(); + const link7 = new THREE.Group(); + const link8 = new THREE.Group(); + const hand = new THREE.Group(); + const leftFinger = new THREE.Group(); + const rightFinger = new THREE.Group(); + + robotGroup.add(link0); + + link0.add(joints.joint1); + joints.joint1.position.set(0, 0, 0.333); + joints.joint1.add(link1); + + link1.add(joints.joint2); + joints.joint2.position.set(0, 0, 0); + joints.joint2.rotation.set(-1.57079632679, 0, 0); + joints.joint2.add(link2); + + link2.add(joints.joint3); + joints.joint3.position.set(0, -0.316, 0); + joints.joint3.rotation.set(1.57079632679, 0, 0); + joints.joint3.add(link3); + + link3.add(joints.joint4); + joints.joint4.position.set(0.0825, 0, 0); + joints.joint4.rotation.set(1.57079632679, 0, 0); + joints.joint4.add(link4); + + link4.add(joints.joint5); + joints.joint5.position.set(-0.0825, 0.384, 0); + joints.joint5.rotation.set(-1.57079632679, 0, 0); + joints.joint5.add(link5); + + link5.add(joints.joint6); + joints.joint6.position.set(0, 0, 0); + joints.joint6.rotation.set(1.57079632679, 0, 0); + joints.joint6.add(link6); + + link6.add(joints.joint7); + joints.joint7.position.set(0.088, 0, 0); + joints.joint7.rotation.set(1.57079632679, 0, 0); + joints.joint7.add(link7); + + link7.add(joints.joint8); + joints.joint8.position.set(0, 0, 0.107); + joints.joint8.add(link8); + + link8.add(joints.handJoint); + joints.handJoint.position.set(0, 0, 0); + joints.handJoint.rotation.set(0, 0, -0.785398163397); + joints.handJoint.add(hand); + + hand.add(joints.fingerJoint1); + joints.fingerJoint1.position.set(0, 0, 0.0584); + joints.fingerJoint1.add(leftFinger); + + hand.add(joints.fingerJoint2); + joints.fingerJoint2.position.set(0, 0, 0.0584); + joints.fingerJoint2.add(rightFinger); + + const defaultPandaMaterial = new THREE.MeshStandardMaterial({ + color: 0xdddddd, + roughness: 0.35, + metalness: 0.15 + }); + + const loadModel = (parent, objPath, mtlPath = null, rotateRightFinger = false) => { + const applyRotation = (obj) => { + if (rotateRightFinger) { + obj.rotation.z = Math.PI; + } + parent.add(obj); + }; + + if (mtlPath) { + MTL_LOADER.load(mtlPath, (materials) => { + materials.preload(); + + const objLoader = new THREE.OBJLoader(); + objLoader.setMaterials(materials); + objLoader.load(objPath, (obj) => { + obj.traverse(child => { + if (child.isMesh) { + child.castShadow = true; + child.receiveShadow = true; + } + }); + applyRotation(obj); + }); + }); + } else { + const objLoader = new THREE.OBJLoader(); + objLoader.load(objPath, (obj) => { + obj.traverse(child => { + if (child.isMesh) { + child.material = defaultPandaMaterial; + child.castShadow = true; + child.receiveShadow = true; + } + }); + applyRotation(obj); + }); + } + }; + + loadModel(link0, '/assets/panda/meshes/collision/link0.obj'); + loadModel(link1, '/assets/panda/meshes/visual/link1.obj', '/assets/panda/meshes/visual/link1.mtl'); + loadModel(link2, '/assets/panda/meshes/visual/link2.obj', '/assets/panda/meshes/visual/link2.mtl'); + loadModel(link3, '/assets/panda/meshes/visual/link3.obj', '/assets/panda/meshes/visual/link3.mtl'); + loadModel(link4, '/assets/panda/meshes/visual/link4.obj', '/assets/panda/meshes/visual/link4.mtl'); + loadModel(link5, '/assets/panda/meshes/visual/link5.obj', '/assets/panda/meshes/visual/link5.mtl'); + loadModel(link6, '/assets/panda/meshes/visual/link6.obj', '/assets/panda/meshes/visual/link6.mtl'); + loadModel(link7, '/assets/panda/meshes/collision/link7.obj'); + loadModel(hand, '/assets/panda/meshes/visual/hand.obj', '/assets/panda/meshes/visual/hand.mtl'); + loadModel(leftFinger, '/assets/panda/meshes/visual/finger.obj', '/assets/panda/meshes/visual/finger.mtl'); + loadModel(rightFinger, '/assets/panda/meshes/visual/finger.obj', '/assets/panda/meshes/visual/finger.mtl', true); +} + +function loadYcbObjects(objectsConfig) { + // Clear old meshes/groups from scene + Object.values(ycbMeshes).forEach(group => scene.remove(group)); + for (const key in ycbMeshes) delete ycbMeshes[key]; + + Object.entries(objectsConfig).forEach(([name, config]) => { + const folder = config.folder; + let objFile = ""; + let mtlFile = ""; + + if (folder === "YcbBanana" || folder === "YcbTomatoSoupCan" || folder === "YcbCrackerBox" || folder === "YcbMustardBottle" || folder === "YcbPottedMeatCan") { + objFile = `/assets/ycb/${folder}/textured_simple_reoriented.obj`; + mtlFile = `/assets/ycb/${folder}/textured_simple_reoriented.mtl`; + } else if (folder === "YcbChipsCan") { + objFile = `/assets/ycb/${folder}/textured.obj`; + mtlFile = `/assets/ycb/${folder}/textured.mtl`; + } + + if (!objFile) return; + + // Create a parent group to represent the object's body link pose + const objectGroup = new THREE.Group(); + objectGroup.position.fromArray(config.initial_pos); + objectGroup.quaternion.fromArray(config.initial_ori); + scene.add(objectGroup); + ycbMeshes[name] = objectGroup; + + // 1. Load Visual Mesh + MTL_LOADER.load(mtlFile, (materials) => { + materials.preload(); + + const objLoader = new THREE.OBJLoader(); + objLoader.setMaterials(materials); + objLoader.load(objFile, (visObj) => { + visObj.traverse(child => { + if (child.isMesh) { + child.castShadow = true; + child.receiveShadow = true; + } + }); + + // Position, rotate and scale relative to parent group + if (config.vis_local_pos) visObj.position.fromArray(config.vis_local_pos); + if (config.vis_local_ori) visObj.quaternion.fromArray(config.vis_local_ori); + if (config.vis_scale) visObj.scale.fromArray(config.vis_scale); + + objectGroup.add(visObj); + }); + }); + + // 2. Load Collision Mesh (Semi-transparent Blue) + const collObjFile = `/assets/ycb/${folder}/collision_vhacd.obj`; + const collLoader = new THREE.OBJLoader(); + collLoader.load(collObjFile, (collObj) => { + collObj.traverse(child => { + if (child.isMesh) { + child.material = new THREE.MeshStandardMaterial({ + color: 0x0000ff, // blue + transparent: true, + opacity: 0.5, // semi-transparent + roughness: 0.4, + metalness: 0.1 + }); + child.castShadow = true; + child.receiveShadow = true; + } + }); + + // Position, rotate and scale relative to parent group + if (config.coll_local_pos) collObj.position.fromArray(config.coll_local_pos); + if (config.coll_local_ori) collObj.quaternion.fromArray(config.coll_local_ori); + if (config.coll_scale) collObj.scale.fromArray(config.coll_scale); + + objectGroup.add(collObj); + }); + }); +} + +function updateSimulationState(jointsData, objectsData) { + if (jointsData && jointsData.length >= 11) { + joints.joint1.rotation.z = jointsData[0]; + joints.joint2.rotation.z = jointsData[1]; + joints.joint3.rotation.z = jointsData[2]; + joints.joint4.rotation.z = jointsData[3]; + joints.joint5.rotation.z = jointsData[4]; + joints.joint6.rotation.z = jointsData[5]; + joints.joint7.rotation.z = jointsData[6]; + + // Prismatic fingers: + joints.fingerJoint1.position.y = jointsData[9]; + joints.fingerJoint2.position.y = -jointsData[10]; + } + + if (objectsData) { + Object.entries(objectsData).forEach(([name, data]) => { + const group = ycbMeshes[name]; + if (group) { + group.position.fromArray(data.pos); + group.quaternion.fromArray(data.ori); + } + }); + } +} + +let reconnectTimeout = null; + +function connectWebSocket() { + if (reconnectTimeout) { + clearTimeout(reconnectTimeout); + reconnectTimeout = null; + } + const guiToggle = document.getElementById('gui-toggle'); + const showGui = guiToggle ? guiToggle.checked : false; + const wsProtocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:'; + const wsUrl = `${wsProtocol}//${window.location.host}/ws?gui=${showGui}`; + + updateBadgeStatus('disconnected'); + + socket = new WebSocket(wsUrl); + + socket.onopen = () => { + console.log("WebSocket connected."); + updateBadgeStatus('connected'); + writeLog("🔌 Kết nối thành công đến Backend server.", "success"); + }; + + socket.onmessage = (event) => { + const msg = JSON.parse(event.data); + handleSocketMessage(msg); + }; + + socket.onclose = () => { + console.log("WebSocket disconnected."); + updateBadgeStatus('disconnected'); + writeLog("❌ Mất kết nối đến Backend server. Đang thử kết nối lại...", "error"); + reconnectTimeout = setTimeout(connectWebSocket, 3000); + }; + + socket.onerror = (err) => { + console.error("WebSocket Error: ", err); + }; +} + +function handleSocketMessage(msg) { + switch(msg.type) { + case 'init': + createTable(msg.table); + createTray(msg.tray); + createSlotHelpers(msg.slots); + loadYcbObjects(msg.objects); + initRobotStructure(); + break; + + case 'state': + updateSimulationState(msg.joints, msg.objects); + break; + + case 'log': + writeLog(msg.message, getLogClass(msg.message)); + updatePipelineUI(msg.message); + break; + + case 'plan': + displayPlan(msg.plan); + break; + + case 'result': + showRearrangementScore(msg.score_display); + unlockInput(); + break; + } +} + +// ─── UI Updates and Interactions ──────────────────────────────────────────── + +const badge = document.getElementById('connection-badge'); +const logConsole = document.getElementById('log-console'); +const planList = document.getElementById('plan-list'); +const chatInput = document.getElementById('chat-input'); +const submitBtn = document.getElementById('submit-btn'); +const mockToggle = document.getElementById('mock-toggle'); +const guiToggle = document.getElementById('gui-toggle'); +const resetBtn = document.getElementById('reset-btn'); +const scoreModal = document.getElementById('score-modal'); +const scoreContent = document.getElementById('score-md-content'); +const closeModalBtn = document.getElementById('close-modal-btn'); + +function updateBadgeStatus(status) { + if (status === 'connected') { + badge.className = 'badge online'; + badge.textContent = 'Connected'; + } else { + badge.className = 'badge offline'; + badge.textContent = 'Disconnected'; + } +} + +function writeLog(text, className = 'info') { + const entry = document.createElement('div'); + entry.className = `log-entry ${className}`; + entry.textContent = `> ${text}`; + + // Remove placeholder + const placeholder = logConsole.querySelector('.placeholder-text'); + if (placeholder) placeholder.remove(); + + logConsole.appendChild(entry); + logConsole.scrollTop = logConsole.scrollHeight; +} + +function getLogClass(message) { + if (message.includes('✅')) return 'success'; + if (message.includes('❌')) return 'error'; + if (message.includes('⚠️')) return 'warn'; + if (message.includes('🚀') || message.includes('⏳')) return 'info'; + return ''; +} + +function updatePipelineUI(message) { + const stepLlm = document.getElementById('step-llm'); + const stepVal = document.getElementById('step-val'); + const stepExec = document.getElementById('step-exec'); + const stepScore = document.getElementById('step-score'); + + if (message.includes('[1/5]')) { + setActiveStep(stepLlm); + } else if (message.includes('✅ [1]')) { + setCompletedStep(stepLlm); + } else if (message.includes('❌ [1]')) { + setErrorStep(stepLlm); + unlockInput(); + } + else if (message.includes('[2/5]')) { + setActiveStep(stepVal); + } else if (message.includes('✅ [2]')) { + setCompletedStep(stepVal); + } else if (message.includes('❌ [2]') || message.includes('⚠️ [2]')) { + if (message.includes('❌')) { + setErrorStep(stepVal); + unlockInput(); + } else { + stepVal.className = 'status-step active warn'; + } + } + else if (message.includes('[3/5]')) { + setActiveStep(stepExec); + } else if (message.includes('Thực thi thành công')) { + setCompletedStep(stepExec); + } else if (message.includes('Thực thi kết thúc có bước lỗi')) { + setErrorStep(stepExec); + } + else if (message.includes('[5/5]')) { + setActiveStep(stepScore); + } else if (message.includes('Rearrangement Evaluation Report') || message.includes('result')) { + setCompletedStep(stepScore); + unlockInput(); + } +} + +function setActiveStep(el) { + el.className = 'status-step active'; +} +function setCompletedStep(el) { + el.className = 'status-step completed'; +} +function setErrorStep(el) { + el.className = 'status-step error'; +} + +function displayPlan(plan) { + planList.innerHTML = ''; + plan.forEach(step => { + const item = document.createElement('div'); + item.className = 'plan-item'; + item.id = `plan-step-${step.step}`; + + const argsStr = Object.entries(step.args) + .map(([k, v]) => `${k}:${v}`) + .join(', '); + + item.innerHTML = ` + Step ${step.step}: ${step.skill}(${step.object}) + ${argsStr} + `; + planList.appendChild(item); + }); +} + +function showRearrangementScore(markdownText) { + let html = markdownText + .replace(/### (.*)/g, '

$1

') + .replace(/\*\*(.*?)\*\*/g, '$1') + .replace(/- (.*)/g, '
  • $1
  • ') + .replace(/\n\n/g, '
    ') + .replace(/✅/g, '✅') + .replace(/⚠️/g, '⚠️') + .replace(/❌/g, '❌'); + + scoreContent.innerHTML = html; + scoreModal.classList.remove('hidden'); +} + +function lockInput() { + chatInput.disabled = true; + submitBtn.disabled = true; + resetBtn.disabled = true; + mockToggle.disabled = true; + if (guiToggle) guiToggle.disabled = true; +} + +function unlockInput() { + chatInput.disabled = false; + submitBtn.disabled = false; + resetBtn.disabled = false; + mockToggle.disabled = false; + if (guiToggle) guiToggle.disabled = false; +} + +// ─── Event Listeners ─────────────────────────────────────────────────────── + +document.getElementById('chat-form').addEventListener('submit', (e) => { + e.preventDefault(); + const prompt = chatInput.value.trim(); + if (!prompt || !socket || socket.readyState !== WebSocket.OPEN) return; + + currentPrompt = prompt; + chatInput.value = ''; + + logConsole.innerHTML = ''; + planList.innerHTML = '

    Đang tải kế hoạch...

    '; + + ['step-llm', 'step-val', 'step-exec', 'step-score'].forEach(id => { + document.getElementById(id).className = 'status-step'; + }); + + writeLog(`Gửi yêu cầu: "${prompt}"`, "info"); + lockInput(); + + socket.send(JSON.stringify({ + type: 'run', + prompt: prompt, + mock: mockToggle.checked + })); +}); + +// Preset buttons +document.querySelectorAll('.preset-badge').forEach(badge => { + badge.addEventListener('click', () => { + chatInput.value = badge.dataset.prompt; + chatInput.focus(); + }); +}); + +// Reset Button +resetBtn.addEventListener('click', () => { + if (!socket || socket.readyState !== WebSocket.OPEN) return; + + logConsole.innerHTML = ''; + planList.innerHTML = '

    Chưa có kế hoạch...

    '; + + ['step-llm', 'step-val', 'step-exec', 'step-score'].forEach(id => { + document.getElementById(id).className = 'status-step'; + }); + + socket.send(JSON.stringify({ + type: 'reset' + })); +}); + +// Close score modal +closeModalBtn.addEventListener('click', () => { + scoreModal.classList.add('hidden'); + unlockInput(); +}); + +// GUI Toggle checkbox event listener +if (guiToggle) { + guiToggle.addEventListener('change', () => { + writeLog("Thay đổi thiết lập hiển thị cửa sổ PyBullet. Đang kết nối lại...", "info"); + if (socket) { + socket.onclose = null; // Prevent the automatic reconnect handler from running + socket.close(); + } + connectWebSocket(); + }); +} + +// Start visualizer and connect +initVisualizer(); +connectWebSocket(); diff --git a/.history/frontend/app_20260627231401.js b/.history/frontend/app_20260627231401.js new file mode 100644 index 0000000000000000000000000000000000000000..3ea8a587be3c8ce800194b555f800770b831259d --- /dev/null +++ b/.history/frontend/app_20260627231401.js @@ -0,0 +1,511 @@ +import sys +import os +import json +import asyncio +import math +import time +import threading +from typing import Optional +from fastapi import FastAPI, WebSocket, WebSocketDisconnect +from fastapi.staticfiles import StaticFiles +from fastapi.responses import HTMLResponse +import uvicorn +import cv2 +import numpy as np +import pybullet as pb +# Ensure project source root is in path +PROJECT_SRC = os.path.abspath(os.path.join(os.path.dirname(__file__), "..")) +if PROJECT_SRC not in sys.path: + sys.path.insert(0, PROJECT_SRC) +from dotenv import load_dotenv +load_dotenv() +from main import PandaSimulation, _YCB_CATALOG +from llm_panda.llm_agent import LLMAgent, RemoteLLMPlanner, RuleBasedPlanner +from llm_panda.plan_verifier import PlanVerifier +from llm_panda import config +import pybullet_data +from pybullet_object_models import ycb_objects +app = FastAPI(title="LLM-Panda Web-Embedded PyBullet Simulation") +# Serve static files from the frontend directory itself +static_dir = os.path.dirname(__file__) +app.mount("/static", StaticFiles(directory=static_dir), name="static") +# Mount robot meshes and YCB object assets +panda_data_path = os.path.join(pybullet_data.getDataPath(), "franka_panda") +ycb_data_path = ycb_objects.getDataPath() +app.mount("/assets/panda", StaticFiles(directory=panda_data_path), name="panda") +app.mount("/assets/ycb", StaticFiles(directory=ycb_data_path), name="ycb") +@app.get("/") +async def get(): + html_file = os.path.join(static_dir, "index.html") + if os.path.exists(html_file): + with open(html_file, "r", encoding="utf-8") as f: + return HTMLResponse(content=f.read(), status_code=200) + return HTMLResponse(content="

    index.html not found!

    ", status_code=404) +# Global variables to track the current active simulation, lock, and thread lock +current_sim: Optional[PandaSimulation] = None +executor_lock = asyncio.Lock() +pybullet_lock = threading.RLock() +def get_init_payload(sim: PandaSimulation) -> dict: + """Gathers the initial static geometry and YCB object definitions.""" + with pybullet_lock: + objects_info = {} + if sim and sim.scene: + for oid in sim.scene.object_ids: + name = sim.scene.get_name(oid) + cls = sim.scene.get_class(oid) + folder = "" + for cat_name, cat_cls, cat_folder in _YCB_CATALOG: + if cat_name == name: + folder = cat_folder + break + pos, ori = pb.getBasePositionAndOrientation(oid, physicsClientId=sim.client) + + # Query visual shape data for exact dimensions/scales and offsets + visual_data = pb.getVisualShapeData(oid, physicsClientId=sim.client) + vis_scale = [1.0, 1.0, 1.0] + vis_local_pos = [0.0, 0.0, 0.0] + vis_local_ori = [0.0, 0.0, 0.0, 1.0] + if visual_data: + vd = visual_data[0] + vis_scale = list(vd[3]) + vis_local_pos = list(vd[5]) + vis_local_ori = list(vd[6]) + # Query collision shape data for offsets and scale + # Query collision shape data for CoM-to-link offset + collision_data = pb.getCollisionShapeData(oid, -1, physicsClientId=sim.client) + coll_scale = [1.0, 1.0, 1.0] + coll_local_pos = [0.0, 0.0, 0.0] + coll_local_ori = [0.0, 0.0, 0.0, 1.0] + if collision_data: + cd = collision_data[0] + coll_scale = list(cd[3]) + coll_local_pos = list(cd[5]) + coll_local_ori = list(cd[6]) + # Query visual shape data for exact dimensions/scales and offsets relative to link + visual_data = pb.getVisualShapeData(oid, physicsClientId=sim.client) + vis_scale = [1.0, 1.0, 1.0] + vis_local_pos = [0.0, 0.0, 0.0] + vis_local_ori = [0.0, 0.0, 0.0, 1.0] + if visual_data: + vd = visual_data[0] + vis_scale = list(vd[3]) + # Transform visual frame to be relative to CoM: CoM_to_visual = CoM_to_link * link_to_visual + vis_pos_com, vis_ori_com = pb.multiplyTransforms( + coll_local_pos, coll_local_ori, + list(vd[5]), list(vd[6]) + ) + vis_local_pos = list(vis_pos_com) + vis_local_ori = list(vis_ori_com) + + objects_info[name] = { + "class": cls, + "folder": folder, + "initial_pos": list(pos), + "initial_ori": list(ori), + "vis_scale": vis_scale, + "vis_local_pos": vis_local_pos, + "vis_local_ori": vis_local_ori, + "coll_scale": coll_scale, + "coll_local_pos": coll_local_pos, + "coll_local_ori": coll_local_ori + } + return { + "type": "init", + "table": { + "center": [config.TABLE_CENTER[0], config.TABLE_CENTER[1], config.TABLE_BASE_Z], + "half_extents": list(config.TABLE_HALF_EXTENTS), + "color": list(config.TABLE_COLOR), + "top_z": config.TABLE_TOP_Z + }, + "tray": { + "position": list(config.TRAY_POSITION), + "half_extents": list(config.TRAY_HALF_EXTENTS), + "color": list(config.TRAY_COLOR) + }, + "slots": {name: list(pos) for name, pos in config.SLOTS.items()}, + "objects": objects_info + } +def get_simulation_state_payload(sim: PandaSimulation) -> dict: + """Gathers the current robot joint positions and YCB object poses.""" + with pybullet_lock: + if sim is None or sim.client is None or not pb.isConnected(sim.client): + return {} + + # Read all joints (12 joints including arm joints and gripper fingers) + num_joints = pb.getNumJoints(sim.robot_id, physicsClientId=sim.client) + joints_state = [] + for i in range(num_joints): + pos, _, _, _ = pb.getJointState(sim.robot_id, i, physicsClientId=sim.client) + joints_state.append(pos) + + # Read objects pos/ori + objects_state = {} + for oid in sim.scene.object_ids: + name = sim.scene.get_name(oid) + pos, ori = pb.getBasePositionAndOrientation(oid, physicsClientId=sim.client) + objects_state[name] = { + "pos": list(pos), + "ori": list(ori) + } + + return { + "type": "state", + "joints": joints_state, + "objects": objects_state + } +def set_pybullet_window_visibility(visible: bool): + """Finds the PyBullet GUI window on Windows and sets its visibility by moving it on/off-screen.""" + import sys + if sys.platform != "win32": + return False + import ctypes + import time + + EnumWindowsProc = ctypes.WINFUNCTYPE(ctypes.c_bool, ctypes.c_void_p, ctypes.c_void_p) + + for _ in range(30): + found_hwnd = [] + + def foreach_window(hwnd, lParam): + length = ctypes.windll.user32.GetWindowTextLengthW(hwnd) + buff = ctypes.create_unicode_buffer(length + 1) + ctypes.windll.user32.GetWindowTextW(hwnd, buff, length + 1) + title = buff.value + if "bullet physics examplebrowser" in title.lower(): + found_hwnd.append(hwnd) + return False + return True + + ctypes.windll.user32.EnumWindows(EnumWindowsProc(foreach_window), 0) + if found_hwnd: + hwnd = found_hwnd[0] + # Ensure the window is shown/restored from minimized state first (SW_SHOW = 5) + ctypes.windll.user32.ShowWindow(hwnd, 5) + + # SWP_NOSIZE = 0x0001, SWP_NOZORDER = 0x0004 + if visible: + # Move window to visible region + ctypes.windll.user32.SetWindowPos(hwnd, 0, 100, 100, 0, 0, 0x0001 | 0x0004) + else: + # Move window far off-screen to hide it without destroying OpenGL context + ctypes.windll.user32.SetWindowPos(hwnd, 0, -10000, -10000, 0, 0, 0x0001 | 0x0004) + print(f"[Window Visibility] Set PyBullet window (HWND: {hwnd}) visibility to: {visible}", flush=True) + return True + time.sleep(0.1) + return False +def compute_and_format_score(sim: PandaSimulation, plan: list, executed_successfully: bool): + """Calculates rearrangement score based on final object locations and collisions.""" + with pybullet_lock: + score = 100 + details = [] + + # Check target placement if we had a plan + target_location = None + target_object = None + for step in plan: + if step.get("function") in ("place_at", "place_down", "move_to"): + args = step.get("args", {}) + if "location_id" in args: + target_location = args["location_id"] + if step.get("function") == "pick_up": + target_object = step.get("args", {}).get("object_id") + + if target_object and target_location: + obj_id = sim.scene.name_to_id(target_object) + if obj_id is not None: + pos, _ = pb.getBasePositionAndOrientation(obj_id) + current_loc = sim.scene.classify_location(pos) + if current_loc == target_location: + details.append(f"✅ **Đã đặt {target_object} đúng vị trí {target_location}**: +50 điểm") + else: + details.append(f"❌ **{target_object} chưa đến đúng vị trí {target_location} (đang ở {current_loc})**: -50 điểm") + score -= 50 + else: + details.append(f"❌ **Không tìm thấy vật thể {target_object}**: -50 điểm") + score -= 50 + else: + details.append("ℹ️ Không có yêu cầu di chuyển vật thể cụ thể nào được phát hiện.") + + # Knock detection + knocked_count = 0 + for oid in sim.scene.object_ids: + if oid == sim.scene.name_to_id(target_object): + continue + pos, _ = pb.getBasePositionAndOrientation(oid) + loc = sim.scene.classify_location(pos) + if loc == "elsewhere": + name = sim.scene.get_name(oid) + details.append(f"⚠️ **Vật thể '{name}' bị lệch khỏi vị trí quy định**: -15 điểm") + score -= 15 + knocked_count += 1 + + if knocked_count == 0: + details.append("✅ **Không có vật thể nào khác bị va chạm hay xê dịch**: +30 điểm") + else: + score = max(0, score) + + # Execution success + if executed_successfully: + details.append("✅ **Thực thi toàn bộ kế hoạch thành công**: +20 điểm") + else: + details.append("❌ **Thực thi gặp lỗi gián đoạn**: -30 điểm") + score -= 30 + + score = max(0, min(100, score)) + + md = f"### 🏆 Rearrangement Evaluation Report\n\n**Tổng điểm: {score}/100**\n\n**Chi tiết:**\n" + "\n".join([f"- {d}" for d in details]) + return score, md +def run_pipeline_threadsafe(websocket: WebSocket, user_prompt: str, loop, use_mock: bool, camera_state: Optional[dict] = None): + """Runs the planning, validation, execution with image streaming, and scoring.""" + global current_sim + + def log(message: str, step: Optional[int] = None): + try: + print(f"[WS Log] {message}", flush=True) + except Exception: + pass + asyncio.run_coroutine_threadsafe( + websocket.send_json({"type": "log", "message": message, "step": step}), + loop + ) + # Step 1: Planning + log("⏳ [1/5] Đang lập kế hoạch (LLM Planner)...") + + if use_mock: + planner = RuleBasedPlanner() + log("✅ [1] Đang sử dụng RuleBasedPlanner (Offline)") + else: + api_key = os.environ.get("OPENAI_API_KEY") or os.environ.get("LLM_API_KEY") + if not api_key: + log("❌ [1] Lỗi: Không tìm thấy OPENAI_API_KEY / LLM_API_KEY. Vui lòng chọn Mock.") + return + planner = RemoteLLMPlanner() + log(f"✅ [1] Đang sử dụng RemoteLLMPlanner (Model: {planner.model})") + + with pybullet_lock: + current_sim.agent = LLMAgent(planner=planner) + + # Define reachability check for scene state + def reachability_fn(oid): + cls = current_sim.scene.get_class(oid) + try: + grasp_pos, grasp_ori = current_sim.grasp_planner.compute_grasp_pose(oid, cls) + return current_sim.controller.is_reachable(grasp_pos, grasp_ori) + except Exception: + return False + carried_name = current_sim.scene.get_name(current_sim._carried) if current_sim._carried is not None else None + scene_state = current_sim.scene.get_scene_state(reachability_fn=reachability_fn, carried_object=carried_name) + state_text = json.dumps(scene_state, indent=2) + + try: + with pybullet_lock: + plan = current_sim.agent.plan(user_prompt, state_text) + log(f"✅ [1] Đã tạo kế hoạch: {len(plan)} bước.") + except Exception as e: + log(f"❌ [1] Lập kế hoạch thất bại: {e}") + return + # Send steps to client + plan_steps = [] + for idx, step in enumerate(plan, 1): + func = step.get("function") + args = step.get("args", {}) + obj = args.get("object_id") or args.get("location_id") or "" + plan_steps.append({ + "step": idx, + "skill": func, + "object": obj, + "args": args + }) + + asyncio.run_coroutine_threadsafe( + websocket.send_json({"type": "plan", "plan": plan_steps}), + loop + ) + if not plan: + log("⚠️ [1] Kế hoạch rỗng.") + log("⏳ [5/5] Đang tính toán điểm sắp xếp...") + score_val, score_md = compute_and_format_score(current_sim, [], True) + asyncio.run_coroutine_threadsafe( + websocket.send_json({ + "type": "result", + "score_display": score_md, + "score_value": score_val + }), + loop + ) + state_payload = get_simulation_state_payload(current_sim) + if state_payload: + asyncio.run_coroutine_threadsafe(websocket.send_json(state_payload), loop) + return + # Step 2: Validation + log("⏳ [2/5] Đang kiểm tra kế hoạch (Validator)...") + try: + with pybullet_lock: + warnings = PlanVerifier.check(plan, scene_state) + if not warnings: + log("✅ [2] Kế hoạch hợp lệ.") + else: + log(f"⚠️ [2] Validator phát hiện {len(warnings)} cảnh báo.") + for w in warnings: + log(f" - {w}") + except Exception as e: + log(f"❌ [2] Lỗi kiểm tra kế hoạch: {e}") + return + # Step 3: PyBullet Execution (Live!) + log("⏳ [3/5] Đang thực thi hành động của robot...") + + # Hook pb.stepSimulation to capture states during movements + original_step = pb.stepSimulation + last_stream_time = [0.0] + throttle_interval = 0.033 if current_sim.gui else 0.066 + + def wrapped_step(): + original_step() + if not current_sim.gui: + # Sleep slightly in headless mode to simulate arm speed and avoid freezing + time.sleep(0.001) + curr_time = time.time() + if curr_time - last_stream_time[0] >= throttle_interval: + last_stream_time[0] = curr_time + state_payload = get_simulation_state_payload(current_sim) + if state_payload: + asyncio.run_coroutine_threadsafe( + websocket.send_json(state_payload), + loop + ) + + with pybullet_lock: + pb.stepSimulation = wrapped_step + + executed_successfully = True + try: + # Trigger an initial simulation state transmission + state_payload = get_simulation_state_payload(current_sim) + if state_payload: + asyncio.run_coroutine_threadsafe(websocket.send_json(state_payload), loop) + + for i, step in enumerate(plan, 1): + log(f"🚀 [3/5] Đang chạy bước {i}/{len(plan)}: {step['function']}") + with pybullet_lock: + current_sim._execute(step, verbose=True) + + log("✅ [3] Thực thi thành công toàn bộ kế hoạch.") + except Exception as e: + log(f"❌ Lỗi trong lúc thực thi mô phỏng: {e}") + executed_successfully = False + finally: + with pybullet_lock: + pb.stepSimulation = original_step + + # Send a final state to ensure visual sync + state_payload = get_simulation_state_payload(current_sim) + if state_payload: + asyncio.run_coroutine_threadsafe(websocket.send_json(state_payload), loop) + # Step 5: Scoring + log("⏳ [5/5] Đang tính toán điểm sắp xếp...") + score_val, score_md = compute_and_format_score(current_sim, plan, executed_successfully) + + asyncio.run_coroutine_threadsafe( + websocket.send_json({ + "type": "result", + "score_display": score_md, + "score_value": score_val + }), + loop + ) +@app.websocket("/ws") +async def websocket_endpoint(websocket: WebSocket): + global current_sim + await websocket.accept() + loop = asyncio.get_running_loop() + + # Retrieve user's desktop display preference from client query params + client_wants_gui = websocket.query_params.get("gui", "false").lower() == "true" + + # Force gui = False to run PyBullet completely headless (DIRECT mode) + gui = False + + camera_state = { + "target": [0.5, 0.0, 0.3], + "dist": 1.3, + "yaw": 45.0, + "pitch": -35.0 + } + + async with executor_lock: + def init_sim(): + global current_sim + with pybullet_lock: + is_connected = False + if current_sim is not None and current_sim.client is not None: + try: + is_connected = pb.isConnected(current_sim.client) + except Exception: + is_connected = False + + if is_connected and current_sim.gui == gui: + current_sim.reset_objects(seed=0) + current_sim.controller.reset_to_home() + for _ in range(5): + pb.stepSimulation(physicsClientId=current_sim.client) + else: + if is_connected: + try: + current_sim.disconnect() + except Exception as e: + print(f"[Teardown Error] {e}") + current_sim = PandaSimulation(gui=gui, seed=0) + + await asyncio.to_thread(init_sim) + # Apply the client's visibility preference to show/hide the PyBullet GUI window on the desktop + await asyncio.to_thread(set_pybullet_window_visibility, client_wants_gui) + + # Send static scene configuration + init_payload = await asyncio.to_thread(get_init_payload, current_sim) + await websocket.send_json(init_payload) + # Send the first simulation state to sync objects and joints + state_payload = await asyncio.to_thread(get_simulation_state_payload, current_sim) + if state_payload: + await websocket.send_json(state_payload) + + try: + while True: + data = await websocket.receive_text() + payload = json.loads(data) + + p_type = payload.get("type") + if p_type == "run": + prompt = payload.get("prompt", "") + use_mock = payload.get("mock", False) + asyncio.create_task( + asyncio.to_thread( + run_pipeline_threadsafe, + websocket, + prompt, + loop, + use_mock + ) + ) + + elif p_type == "reset": + async with executor_lock: + def reset_sim(): + with pybullet_lock: + current_sim.reset_objects(seed=0) + current_sim.controller.reset_to_home() + await asyncio.to_thread(reset_sim) + + state_payload = await asyncio.to_thread(get_simulation_state_payload, current_sim) + if state_payload: + await websocket.send_json(state_payload) + await websocket.send_json({"type": "log", "message": "🔄 Đã reset môi trường mô phỏng."}) + + elif p_type in ("camera_rotate", "camera_pan", "camera_zoom"): + pass + + except WebSocketDisconnect: + print("Client disconnected") + except Exception as e: + print(f"WS Exception: {e}") +if __name__ == "__main__": + uvicorn.run("interactive_server:app", host="0.0.0.0", port=8000, reload=False) diff --git a/.history/frontend/app_20260627231409.js b/.history/frontend/app_20260627231409.js new file mode 100644 index 0000000000000000000000000000000000000000..3ea8a587be3c8ce800194b555f800770b831259d --- /dev/null +++ b/.history/frontend/app_20260627231409.js @@ -0,0 +1,511 @@ +import sys +import os +import json +import asyncio +import math +import time +import threading +from typing import Optional +from fastapi import FastAPI, WebSocket, WebSocketDisconnect +from fastapi.staticfiles import StaticFiles +from fastapi.responses import HTMLResponse +import uvicorn +import cv2 +import numpy as np +import pybullet as pb +# Ensure project source root is in path +PROJECT_SRC = os.path.abspath(os.path.join(os.path.dirname(__file__), "..")) +if PROJECT_SRC not in sys.path: + sys.path.insert(0, PROJECT_SRC) +from dotenv import load_dotenv +load_dotenv() +from main import PandaSimulation, _YCB_CATALOG +from llm_panda.llm_agent import LLMAgent, RemoteLLMPlanner, RuleBasedPlanner +from llm_panda.plan_verifier import PlanVerifier +from llm_panda import config +import pybullet_data +from pybullet_object_models import ycb_objects +app = FastAPI(title="LLM-Panda Web-Embedded PyBullet Simulation") +# Serve static files from the frontend directory itself +static_dir = os.path.dirname(__file__) +app.mount("/static", StaticFiles(directory=static_dir), name="static") +# Mount robot meshes and YCB object assets +panda_data_path = os.path.join(pybullet_data.getDataPath(), "franka_panda") +ycb_data_path = ycb_objects.getDataPath() +app.mount("/assets/panda", StaticFiles(directory=panda_data_path), name="panda") +app.mount("/assets/ycb", StaticFiles(directory=ycb_data_path), name="ycb") +@app.get("/") +async def get(): + html_file = os.path.join(static_dir, "index.html") + if os.path.exists(html_file): + with open(html_file, "r", encoding="utf-8") as f: + return HTMLResponse(content=f.read(), status_code=200) + return HTMLResponse(content="

    index.html not found!

    ", status_code=404) +# Global variables to track the current active simulation, lock, and thread lock +current_sim: Optional[PandaSimulation] = None +executor_lock = asyncio.Lock() +pybullet_lock = threading.RLock() +def get_init_payload(sim: PandaSimulation) -> dict: + """Gathers the initial static geometry and YCB object definitions.""" + with pybullet_lock: + objects_info = {} + if sim and sim.scene: + for oid in sim.scene.object_ids: + name = sim.scene.get_name(oid) + cls = sim.scene.get_class(oid) + folder = "" + for cat_name, cat_cls, cat_folder in _YCB_CATALOG: + if cat_name == name: + folder = cat_folder + break + pos, ori = pb.getBasePositionAndOrientation(oid, physicsClientId=sim.client) + + # Query visual shape data for exact dimensions/scales and offsets + visual_data = pb.getVisualShapeData(oid, physicsClientId=sim.client) + vis_scale = [1.0, 1.0, 1.0] + vis_local_pos = [0.0, 0.0, 0.0] + vis_local_ori = [0.0, 0.0, 0.0, 1.0] + if visual_data: + vd = visual_data[0] + vis_scale = list(vd[3]) + vis_local_pos = list(vd[5]) + vis_local_ori = list(vd[6]) + # Query collision shape data for offsets and scale + # Query collision shape data for CoM-to-link offset + collision_data = pb.getCollisionShapeData(oid, -1, physicsClientId=sim.client) + coll_scale = [1.0, 1.0, 1.0] + coll_local_pos = [0.0, 0.0, 0.0] + coll_local_ori = [0.0, 0.0, 0.0, 1.0] + if collision_data: + cd = collision_data[0] + coll_scale = list(cd[3]) + coll_local_pos = list(cd[5]) + coll_local_ori = list(cd[6]) + # Query visual shape data for exact dimensions/scales and offsets relative to link + visual_data = pb.getVisualShapeData(oid, physicsClientId=sim.client) + vis_scale = [1.0, 1.0, 1.0] + vis_local_pos = [0.0, 0.0, 0.0] + vis_local_ori = [0.0, 0.0, 0.0, 1.0] + if visual_data: + vd = visual_data[0] + vis_scale = list(vd[3]) + # Transform visual frame to be relative to CoM: CoM_to_visual = CoM_to_link * link_to_visual + vis_pos_com, vis_ori_com = pb.multiplyTransforms( + coll_local_pos, coll_local_ori, + list(vd[5]), list(vd[6]) + ) + vis_local_pos = list(vis_pos_com) + vis_local_ori = list(vis_ori_com) + + objects_info[name] = { + "class": cls, + "folder": folder, + "initial_pos": list(pos), + "initial_ori": list(ori), + "vis_scale": vis_scale, + "vis_local_pos": vis_local_pos, + "vis_local_ori": vis_local_ori, + "coll_scale": coll_scale, + "coll_local_pos": coll_local_pos, + "coll_local_ori": coll_local_ori + } + return { + "type": "init", + "table": { + "center": [config.TABLE_CENTER[0], config.TABLE_CENTER[1], config.TABLE_BASE_Z], + "half_extents": list(config.TABLE_HALF_EXTENTS), + "color": list(config.TABLE_COLOR), + "top_z": config.TABLE_TOP_Z + }, + "tray": { + "position": list(config.TRAY_POSITION), + "half_extents": list(config.TRAY_HALF_EXTENTS), + "color": list(config.TRAY_COLOR) + }, + "slots": {name: list(pos) for name, pos in config.SLOTS.items()}, + "objects": objects_info + } +def get_simulation_state_payload(sim: PandaSimulation) -> dict: + """Gathers the current robot joint positions and YCB object poses.""" + with pybullet_lock: + if sim is None or sim.client is None or not pb.isConnected(sim.client): + return {} + + # Read all joints (12 joints including arm joints and gripper fingers) + num_joints = pb.getNumJoints(sim.robot_id, physicsClientId=sim.client) + joints_state = [] + for i in range(num_joints): + pos, _, _, _ = pb.getJointState(sim.robot_id, i, physicsClientId=sim.client) + joints_state.append(pos) + + # Read objects pos/ori + objects_state = {} + for oid in sim.scene.object_ids: + name = sim.scene.get_name(oid) + pos, ori = pb.getBasePositionAndOrientation(oid, physicsClientId=sim.client) + objects_state[name] = { + "pos": list(pos), + "ori": list(ori) + } + + return { + "type": "state", + "joints": joints_state, + "objects": objects_state + } +def set_pybullet_window_visibility(visible: bool): + """Finds the PyBullet GUI window on Windows and sets its visibility by moving it on/off-screen.""" + import sys + if sys.platform != "win32": + return False + import ctypes + import time + + EnumWindowsProc = ctypes.WINFUNCTYPE(ctypes.c_bool, ctypes.c_void_p, ctypes.c_void_p) + + for _ in range(30): + found_hwnd = [] + + def foreach_window(hwnd, lParam): + length = ctypes.windll.user32.GetWindowTextLengthW(hwnd) + buff = ctypes.create_unicode_buffer(length + 1) + ctypes.windll.user32.GetWindowTextW(hwnd, buff, length + 1) + title = buff.value + if "bullet physics examplebrowser" in title.lower(): + found_hwnd.append(hwnd) + return False + return True + + ctypes.windll.user32.EnumWindows(EnumWindowsProc(foreach_window), 0) + if found_hwnd: + hwnd = found_hwnd[0] + # Ensure the window is shown/restored from minimized state first (SW_SHOW = 5) + ctypes.windll.user32.ShowWindow(hwnd, 5) + + # SWP_NOSIZE = 0x0001, SWP_NOZORDER = 0x0004 + if visible: + # Move window to visible region + ctypes.windll.user32.SetWindowPos(hwnd, 0, 100, 100, 0, 0, 0x0001 | 0x0004) + else: + # Move window far off-screen to hide it without destroying OpenGL context + ctypes.windll.user32.SetWindowPos(hwnd, 0, -10000, -10000, 0, 0, 0x0001 | 0x0004) + print(f"[Window Visibility] Set PyBullet window (HWND: {hwnd}) visibility to: {visible}", flush=True) + return True + time.sleep(0.1) + return False +def compute_and_format_score(sim: PandaSimulation, plan: list, executed_successfully: bool): + """Calculates rearrangement score based on final object locations and collisions.""" + with pybullet_lock: + score = 100 + details = [] + + # Check target placement if we had a plan + target_location = None + target_object = None + for step in plan: + if step.get("function") in ("place_at", "place_down", "move_to"): + args = step.get("args", {}) + if "location_id" in args: + target_location = args["location_id"] + if step.get("function") == "pick_up": + target_object = step.get("args", {}).get("object_id") + + if target_object and target_location: + obj_id = sim.scene.name_to_id(target_object) + if obj_id is not None: + pos, _ = pb.getBasePositionAndOrientation(obj_id) + current_loc = sim.scene.classify_location(pos) + if current_loc == target_location: + details.append(f"✅ **Đã đặt {target_object} đúng vị trí {target_location}**: +50 điểm") + else: + details.append(f"❌ **{target_object} chưa đến đúng vị trí {target_location} (đang ở {current_loc})**: -50 điểm") + score -= 50 + else: + details.append(f"❌ **Không tìm thấy vật thể {target_object}**: -50 điểm") + score -= 50 + else: + details.append("ℹ️ Không có yêu cầu di chuyển vật thể cụ thể nào được phát hiện.") + + # Knock detection + knocked_count = 0 + for oid in sim.scene.object_ids: + if oid == sim.scene.name_to_id(target_object): + continue + pos, _ = pb.getBasePositionAndOrientation(oid) + loc = sim.scene.classify_location(pos) + if loc == "elsewhere": + name = sim.scene.get_name(oid) + details.append(f"⚠️ **Vật thể '{name}' bị lệch khỏi vị trí quy định**: -15 điểm") + score -= 15 + knocked_count += 1 + + if knocked_count == 0: + details.append("✅ **Không có vật thể nào khác bị va chạm hay xê dịch**: +30 điểm") + else: + score = max(0, score) + + # Execution success + if executed_successfully: + details.append("✅ **Thực thi toàn bộ kế hoạch thành công**: +20 điểm") + else: + details.append("❌ **Thực thi gặp lỗi gián đoạn**: -30 điểm") + score -= 30 + + score = max(0, min(100, score)) + + md = f"### 🏆 Rearrangement Evaluation Report\n\n**Tổng điểm: {score}/100**\n\n**Chi tiết:**\n" + "\n".join([f"- {d}" for d in details]) + return score, md +def run_pipeline_threadsafe(websocket: WebSocket, user_prompt: str, loop, use_mock: bool, camera_state: Optional[dict] = None): + """Runs the planning, validation, execution with image streaming, and scoring.""" + global current_sim + + def log(message: str, step: Optional[int] = None): + try: + print(f"[WS Log] {message}", flush=True) + except Exception: + pass + asyncio.run_coroutine_threadsafe( + websocket.send_json({"type": "log", "message": message, "step": step}), + loop + ) + # Step 1: Planning + log("⏳ [1/5] Đang lập kế hoạch (LLM Planner)...") + + if use_mock: + planner = RuleBasedPlanner() + log("✅ [1] Đang sử dụng RuleBasedPlanner (Offline)") + else: + api_key = os.environ.get("OPENAI_API_KEY") or os.environ.get("LLM_API_KEY") + if not api_key: + log("❌ [1] Lỗi: Không tìm thấy OPENAI_API_KEY / LLM_API_KEY. Vui lòng chọn Mock.") + return + planner = RemoteLLMPlanner() + log(f"✅ [1] Đang sử dụng RemoteLLMPlanner (Model: {planner.model})") + + with pybullet_lock: + current_sim.agent = LLMAgent(planner=planner) + + # Define reachability check for scene state + def reachability_fn(oid): + cls = current_sim.scene.get_class(oid) + try: + grasp_pos, grasp_ori = current_sim.grasp_planner.compute_grasp_pose(oid, cls) + return current_sim.controller.is_reachable(grasp_pos, grasp_ori) + except Exception: + return False + carried_name = current_sim.scene.get_name(current_sim._carried) if current_sim._carried is not None else None + scene_state = current_sim.scene.get_scene_state(reachability_fn=reachability_fn, carried_object=carried_name) + state_text = json.dumps(scene_state, indent=2) + + try: + with pybullet_lock: + plan = current_sim.agent.plan(user_prompt, state_text) + log(f"✅ [1] Đã tạo kế hoạch: {len(plan)} bước.") + except Exception as e: + log(f"❌ [1] Lập kế hoạch thất bại: {e}") + return + # Send steps to client + plan_steps = [] + for idx, step in enumerate(plan, 1): + func = step.get("function") + args = step.get("args", {}) + obj = args.get("object_id") or args.get("location_id") or "" + plan_steps.append({ + "step": idx, + "skill": func, + "object": obj, + "args": args + }) + + asyncio.run_coroutine_threadsafe( + websocket.send_json({"type": "plan", "plan": plan_steps}), + loop + ) + if not plan: + log("⚠️ [1] Kế hoạch rỗng.") + log("⏳ [5/5] Đang tính toán điểm sắp xếp...") + score_val, score_md = compute_and_format_score(current_sim, [], True) + asyncio.run_coroutine_threadsafe( + websocket.send_json({ + "type": "result", + "score_display": score_md, + "score_value": score_val + }), + loop + ) + state_payload = get_simulation_state_payload(current_sim) + if state_payload: + asyncio.run_coroutine_threadsafe(websocket.send_json(state_payload), loop) + return + # Step 2: Validation + log("⏳ [2/5] Đang kiểm tra kế hoạch (Validator)...") + try: + with pybullet_lock: + warnings = PlanVerifier.check(plan, scene_state) + if not warnings: + log("✅ [2] Kế hoạch hợp lệ.") + else: + log(f"⚠️ [2] Validator phát hiện {len(warnings)} cảnh báo.") + for w in warnings: + log(f" - {w}") + except Exception as e: + log(f"❌ [2] Lỗi kiểm tra kế hoạch: {e}") + return + # Step 3: PyBullet Execution (Live!) + log("⏳ [3/5] Đang thực thi hành động của robot...") + + # Hook pb.stepSimulation to capture states during movements + original_step = pb.stepSimulation + last_stream_time = [0.0] + throttle_interval = 0.033 if current_sim.gui else 0.066 + + def wrapped_step(): + original_step() + if not current_sim.gui: + # Sleep slightly in headless mode to simulate arm speed and avoid freezing + time.sleep(0.001) + curr_time = time.time() + if curr_time - last_stream_time[0] >= throttle_interval: + last_stream_time[0] = curr_time + state_payload = get_simulation_state_payload(current_sim) + if state_payload: + asyncio.run_coroutine_threadsafe( + websocket.send_json(state_payload), + loop + ) + + with pybullet_lock: + pb.stepSimulation = wrapped_step + + executed_successfully = True + try: + # Trigger an initial simulation state transmission + state_payload = get_simulation_state_payload(current_sim) + if state_payload: + asyncio.run_coroutine_threadsafe(websocket.send_json(state_payload), loop) + + for i, step in enumerate(plan, 1): + log(f"🚀 [3/5] Đang chạy bước {i}/{len(plan)}: {step['function']}") + with pybullet_lock: + current_sim._execute(step, verbose=True) + + log("✅ [3] Thực thi thành công toàn bộ kế hoạch.") + except Exception as e: + log(f"❌ Lỗi trong lúc thực thi mô phỏng: {e}") + executed_successfully = False + finally: + with pybullet_lock: + pb.stepSimulation = original_step + + # Send a final state to ensure visual sync + state_payload = get_simulation_state_payload(current_sim) + if state_payload: + asyncio.run_coroutine_threadsafe(websocket.send_json(state_payload), loop) + # Step 5: Scoring + log("⏳ [5/5] Đang tính toán điểm sắp xếp...") + score_val, score_md = compute_and_format_score(current_sim, plan, executed_successfully) + + asyncio.run_coroutine_threadsafe( + websocket.send_json({ + "type": "result", + "score_display": score_md, + "score_value": score_val + }), + loop + ) +@app.websocket("/ws") +async def websocket_endpoint(websocket: WebSocket): + global current_sim + await websocket.accept() + loop = asyncio.get_running_loop() + + # Retrieve user's desktop display preference from client query params + client_wants_gui = websocket.query_params.get("gui", "false").lower() == "true" + + # Force gui = False to run PyBullet completely headless (DIRECT mode) + gui = False + + camera_state = { + "target": [0.5, 0.0, 0.3], + "dist": 1.3, + "yaw": 45.0, + "pitch": -35.0 + } + + async with executor_lock: + def init_sim(): + global current_sim + with pybullet_lock: + is_connected = False + if current_sim is not None and current_sim.client is not None: + try: + is_connected = pb.isConnected(current_sim.client) + except Exception: + is_connected = False + + if is_connected and current_sim.gui == gui: + current_sim.reset_objects(seed=0) + current_sim.controller.reset_to_home() + for _ in range(5): + pb.stepSimulation(physicsClientId=current_sim.client) + else: + if is_connected: + try: + current_sim.disconnect() + except Exception as e: + print(f"[Teardown Error] {e}") + current_sim = PandaSimulation(gui=gui, seed=0) + + await asyncio.to_thread(init_sim) + # Apply the client's visibility preference to show/hide the PyBullet GUI window on the desktop + await asyncio.to_thread(set_pybullet_window_visibility, client_wants_gui) + + # Send static scene configuration + init_payload = await asyncio.to_thread(get_init_payload, current_sim) + await websocket.send_json(init_payload) + # Send the first simulation state to sync objects and joints + state_payload = await asyncio.to_thread(get_simulation_state_payload, current_sim) + if state_payload: + await websocket.send_json(state_payload) + + try: + while True: + data = await websocket.receive_text() + payload = json.loads(data) + + p_type = payload.get("type") + if p_type == "run": + prompt = payload.get("prompt", "") + use_mock = payload.get("mock", False) + asyncio.create_task( + asyncio.to_thread( + run_pipeline_threadsafe, + websocket, + prompt, + loop, + use_mock + ) + ) + + elif p_type == "reset": + async with executor_lock: + def reset_sim(): + with pybullet_lock: + current_sim.reset_objects(seed=0) + current_sim.controller.reset_to_home() + await asyncio.to_thread(reset_sim) + + state_payload = await asyncio.to_thread(get_simulation_state_payload, current_sim) + if state_payload: + await websocket.send_json(state_payload) + await websocket.send_json({"type": "log", "message": "🔄 Đã reset môi trường mô phỏng."}) + + elif p_type in ("camera_rotate", "camera_pan", "camera_zoom"): + pass + + except WebSocketDisconnect: + print("Client disconnected") + except Exception as e: + print(f"WS Exception: {e}") +if __name__ == "__main__": + uvicorn.run("interactive_server:app", host="0.0.0.0", port=8000, reload=False) diff --git a/.history/frontend/app_20260627231430.js b/.history/frontend/app_20260627231430.js new file mode 100644 index 0000000000000000000000000000000000000000..3ea8a587be3c8ce800194b555f800770b831259d --- /dev/null +++ b/.history/frontend/app_20260627231430.js @@ -0,0 +1,511 @@ +import sys +import os +import json +import asyncio +import math +import time +import threading +from typing import Optional +from fastapi import FastAPI, WebSocket, WebSocketDisconnect +from fastapi.staticfiles import StaticFiles +from fastapi.responses import HTMLResponse +import uvicorn +import cv2 +import numpy as np +import pybullet as pb +# Ensure project source root is in path +PROJECT_SRC = os.path.abspath(os.path.join(os.path.dirname(__file__), "..")) +if PROJECT_SRC not in sys.path: + sys.path.insert(0, PROJECT_SRC) +from dotenv import load_dotenv +load_dotenv() +from main import PandaSimulation, _YCB_CATALOG +from llm_panda.llm_agent import LLMAgent, RemoteLLMPlanner, RuleBasedPlanner +from llm_panda.plan_verifier import PlanVerifier +from llm_panda import config +import pybullet_data +from pybullet_object_models import ycb_objects +app = FastAPI(title="LLM-Panda Web-Embedded PyBullet Simulation") +# Serve static files from the frontend directory itself +static_dir = os.path.dirname(__file__) +app.mount("/static", StaticFiles(directory=static_dir), name="static") +# Mount robot meshes and YCB object assets +panda_data_path = os.path.join(pybullet_data.getDataPath(), "franka_panda") +ycb_data_path = ycb_objects.getDataPath() +app.mount("/assets/panda", StaticFiles(directory=panda_data_path), name="panda") +app.mount("/assets/ycb", StaticFiles(directory=ycb_data_path), name="ycb") +@app.get("/") +async def get(): + html_file = os.path.join(static_dir, "index.html") + if os.path.exists(html_file): + with open(html_file, "r", encoding="utf-8") as f: + return HTMLResponse(content=f.read(), status_code=200) + return HTMLResponse(content="

    index.html not found!

    ", status_code=404) +# Global variables to track the current active simulation, lock, and thread lock +current_sim: Optional[PandaSimulation] = None +executor_lock = asyncio.Lock() +pybullet_lock = threading.RLock() +def get_init_payload(sim: PandaSimulation) -> dict: + """Gathers the initial static geometry and YCB object definitions.""" + with pybullet_lock: + objects_info = {} + if sim and sim.scene: + for oid in sim.scene.object_ids: + name = sim.scene.get_name(oid) + cls = sim.scene.get_class(oid) + folder = "" + for cat_name, cat_cls, cat_folder in _YCB_CATALOG: + if cat_name == name: + folder = cat_folder + break + pos, ori = pb.getBasePositionAndOrientation(oid, physicsClientId=sim.client) + + # Query visual shape data for exact dimensions/scales and offsets + visual_data = pb.getVisualShapeData(oid, physicsClientId=sim.client) + vis_scale = [1.0, 1.0, 1.0] + vis_local_pos = [0.0, 0.0, 0.0] + vis_local_ori = [0.0, 0.0, 0.0, 1.0] + if visual_data: + vd = visual_data[0] + vis_scale = list(vd[3]) + vis_local_pos = list(vd[5]) + vis_local_ori = list(vd[6]) + # Query collision shape data for offsets and scale + # Query collision shape data for CoM-to-link offset + collision_data = pb.getCollisionShapeData(oid, -1, physicsClientId=sim.client) + coll_scale = [1.0, 1.0, 1.0] + coll_local_pos = [0.0, 0.0, 0.0] + coll_local_ori = [0.0, 0.0, 0.0, 1.0] + if collision_data: + cd = collision_data[0] + coll_scale = list(cd[3]) + coll_local_pos = list(cd[5]) + coll_local_ori = list(cd[6]) + # Query visual shape data for exact dimensions/scales and offsets relative to link + visual_data = pb.getVisualShapeData(oid, physicsClientId=sim.client) + vis_scale = [1.0, 1.0, 1.0] + vis_local_pos = [0.0, 0.0, 0.0] + vis_local_ori = [0.0, 0.0, 0.0, 1.0] + if visual_data: + vd = visual_data[0] + vis_scale = list(vd[3]) + # Transform visual frame to be relative to CoM: CoM_to_visual = CoM_to_link * link_to_visual + vis_pos_com, vis_ori_com = pb.multiplyTransforms( + coll_local_pos, coll_local_ori, + list(vd[5]), list(vd[6]) + ) + vis_local_pos = list(vis_pos_com) + vis_local_ori = list(vis_ori_com) + + objects_info[name] = { + "class": cls, + "folder": folder, + "initial_pos": list(pos), + "initial_ori": list(ori), + "vis_scale": vis_scale, + "vis_local_pos": vis_local_pos, + "vis_local_ori": vis_local_ori, + "coll_scale": coll_scale, + "coll_local_pos": coll_local_pos, + "coll_local_ori": coll_local_ori + } + return { + "type": "init", + "table": { + "center": [config.TABLE_CENTER[0], config.TABLE_CENTER[1], config.TABLE_BASE_Z], + "half_extents": list(config.TABLE_HALF_EXTENTS), + "color": list(config.TABLE_COLOR), + "top_z": config.TABLE_TOP_Z + }, + "tray": { + "position": list(config.TRAY_POSITION), + "half_extents": list(config.TRAY_HALF_EXTENTS), + "color": list(config.TRAY_COLOR) + }, + "slots": {name: list(pos) for name, pos in config.SLOTS.items()}, + "objects": objects_info + } +def get_simulation_state_payload(sim: PandaSimulation) -> dict: + """Gathers the current robot joint positions and YCB object poses.""" + with pybullet_lock: + if sim is None or sim.client is None or not pb.isConnected(sim.client): + return {} + + # Read all joints (12 joints including arm joints and gripper fingers) + num_joints = pb.getNumJoints(sim.robot_id, physicsClientId=sim.client) + joints_state = [] + for i in range(num_joints): + pos, _, _, _ = pb.getJointState(sim.robot_id, i, physicsClientId=sim.client) + joints_state.append(pos) + + # Read objects pos/ori + objects_state = {} + for oid in sim.scene.object_ids: + name = sim.scene.get_name(oid) + pos, ori = pb.getBasePositionAndOrientation(oid, physicsClientId=sim.client) + objects_state[name] = { + "pos": list(pos), + "ori": list(ori) + } + + return { + "type": "state", + "joints": joints_state, + "objects": objects_state + } +def set_pybullet_window_visibility(visible: bool): + """Finds the PyBullet GUI window on Windows and sets its visibility by moving it on/off-screen.""" + import sys + if sys.platform != "win32": + return False + import ctypes + import time + + EnumWindowsProc = ctypes.WINFUNCTYPE(ctypes.c_bool, ctypes.c_void_p, ctypes.c_void_p) + + for _ in range(30): + found_hwnd = [] + + def foreach_window(hwnd, lParam): + length = ctypes.windll.user32.GetWindowTextLengthW(hwnd) + buff = ctypes.create_unicode_buffer(length + 1) + ctypes.windll.user32.GetWindowTextW(hwnd, buff, length + 1) + title = buff.value + if "bullet physics examplebrowser" in title.lower(): + found_hwnd.append(hwnd) + return False + return True + + ctypes.windll.user32.EnumWindows(EnumWindowsProc(foreach_window), 0) + if found_hwnd: + hwnd = found_hwnd[0] + # Ensure the window is shown/restored from minimized state first (SW_SHOW = 5) + ctypes.windll.user32.ShowWindow(hwnd, 5) + + # SWP_NOSIZE = 0x0001, SWP_NOZORDER = 0x0004 + if visible: + # Move window to visible region + ctypes.windll.user32.SetWindowPos(hwnd, 0, 100, 100, 0, 0, 0x0001 | 0x0004) + else: + # Move window far off-screen to hide it without destroying OpenGL context + ctypes.windll.user32.SetWindowPos(hwnd, 0, -10000, -10000, 0, 0, 0x0001 | 0x0004) + print(f"[Window Visibility] Set PyBullet window (HWND: {hwnd}) visibility to: {visible}", flush=True) + return True + time.sleep(0.1) + return False +def compute_and_format_score(sim: PandaSimulation, plan: list, executed_successfully: bool): + """Calculates rearrangement score based on final object locations and collisions.""" + with pybullet_lock: + score = 100 + details = [] + + # Check target placement if we had a plan + target_location = None + target_object = None + for step in plan: + if step.get("function") in ("place_at", "place_down", "move_to"): + args = step.get("args", {}) + if "location_id" in args: + target_location = args["location_id"] + if step.get("function") == "pick_up": + target_object = step.get("args", {}).get("object_id") + + if target_object and target_location: + obj_id = sim.scene.name_to_id(target_object) + if obj_id is not None: + pos, _ = pb.getBasePositionAndOrientation(obj_id) + current_loc = sim.scene.classify_location(pos) + if current_loc == target_location: + details.append(f"✅ **Đã đặt {target_object} đúng vị trí {target_location}**: +50 điểm") + else: + details.append(f"❌ **{target_object} chưa đến đúng vị trí {target_location} (đang ở {current_loc})**: -50 điểm") + score -= 50 + else: + details.append(f"❌ **Không tìm thấy vật thể {target_object}**: -50 điểm") + score -= 50 + else: + details.append("ℹ️ Không có yêu cầu di chuyển vật thể cụ thể nào được phát hiện.") + + # Knock detection + knocked_count = 0 + for oid in sim.scene.object_ids: + if oid == sim.scene.name_to_id(target_object): + continue + pos, _ = pb.getBasePositionAndOrientation(oid) + loc = sim.scene.classify_location(pos) + if loc == "elsewhere": + name = sim.scene.get_name(oid) + details.append(f"⚠️ **Vật thể '{name}' bị lệch khỏi vị trí quy định**: -15 điểm") + score -= 15 + knocked_count += 1 + + if knocked_count == 0: + details.append("✅ **Không có vật thể nào khác bị va chạm hay xê dịch**: +30 điểm") + else: + score = max(0, score) + + # Execution success + if executed_successfully: + details.append("✅ **Thực thi toàn bộ kế hoạch thành công**: +20 điểm") + else: + details.append("❌ **Thực thi gặp lỗi gián đoạn**: -30 điểm") + score -= 30 + + score = max(0, min(100, score)) + + md = f"### 🏆 Rearrangement Evaluation Report\n\n**Tổng điểm: {score}/100**\n\n**Chi tiết:**\n" + "\n".join([f"- {d}" for d in details]) + return score, md +def run_pipeline_threadsafe(websocket: WebSocket, user_prompt: str, loop, use_mock: bool, camera_state: Optional[dict] = None): + """Runs the planning, validation, execution with image streaming, and scoring.""" + global current_sim + + def log(message: str, step: Optional[int] = None): + try: + print(f"[WS Log] {message}", flush=True) + except Exception: + pass + asyncio.run_coroutine_threadsafe( + websocket.send_json({"type": "log", "message": message, "step": step}), + loop + ) + # Step 1: Planning + log("⏳ [1/5] Đang lập kế hoạch (LLM Planner)...") + + if use_mock: + planner = RuleBasedPlanner() + log("✅ [1] Đang sử dụng RuleBasedPlanner (Offline)") + else: + api_key = os.environ.get("OPENAI_API_KEY") or os.environ.get("LLM_API_KEY") + if not api_key: + log("❌ [1] Lỗi: Không tìm thấy OPENAI_API_KEY / LLM_API_KEY. Vui lòng chọn Mock.") + return + planner = RemoteLLMPlanner() + log(f"✅ [1] Đang sử dụng RemoteLLMPlanner (Model: {planner.model})") + + with pybullet_lock: + current_sim.agent = LLMAgent(planner=planner) + + # Define reachability check for scene state + def reachability_fn(oid): + cls = current_sim.scene.get_class(oid) + try: + grasp_pos, grasp_ori = current_sim.grasp_planner.compute_grasp_pose(oid, cls) + return current_sim.controller.is_reachable(grasp_pos, grasp_ori) + except Exception: + return False + carried_name = current_sim.scene.get_name(current_sim._carried) if current_sim._carried is not None else None + scene_state = current_sim.scene.get_scene_state(reachability_fn=reachability_fn, carried_object=carried_name) + state_text = json.dumps(scene_state, indent=2) + + try: + with pybullet_lock: + plan = current_sim.agent.plan(user_prompt, state_text) + log(f"✅ [1] Đã tạo kế hoạch: {len(plan)} bước.") + except Exception as e: + log(f"❌ [1] Lập kế hoạch thất bại: {e}") + return + # Send steps to client + plan_steps = [] + for idx, step in enumerate(plan, 1): + func = step.get("function") + args = step.get("args", {}) + obj = args.get("object_id") or args.get("location_id") or "" + plan_steps.append({ + "step": idx, + "skill": func, + "object": obj, + "args": args + }) + + asyncio.run_coroutine_threadsafe( + websocket.send_json({"type": "plan", "plan": plan_steps}), + loop + ) + if not plan: + log("⚠️ [1] Kế hoạch rỗng.") + log("⏳ [5/5] Đang tính toán điểm sắp xếp...") + score_val, score_md = compute_and_format_score(current_sim, [], True) + asyncio.run_coroutine_threadsafe( + websocket.send_json({ + "type": "result", + "score_display": score_md, + "score_value": score_val + }), + loop + ) + state_payload = get_simulation_state_payload(current_sim) + if state_payload: + asyncio.run_coroutine_threadsafe(websocket.send_json(state_payload), loop) + return + # Step 2: Validation + log("⏳ [2/5] Đang kiểm tra kế hoạch (Validator)...") + try: + with pybullet_lock: + warnings = PlanVerifier.check(plan, scene_state) + if not warnings: + log("✅ [2] Kế hoạch hợp lệ.") + else: + log(f"⚠️ [2] Validator phát hiện {len(warnings)} cảnh báo.") + for w in warnings: + log(f" - {w}") + except Exception as e: + log(f"❌ [2] Lỗi kiểm tra kế hoạch: {e}") + return + # Step 3: PyBullet Execution (Live!) + log("⏳ [3/5] Đang thực thi hành động của robot...") + + # Hook pb.stepSimulation to capture states during movements + original_step = pb.stepSimulation + last_stream_time = [0.0] + throttle_interval = 0.033 if current_sim.gui else 0.066 + + def wrapped_step(): + original_step() + if not current_sim.gui: + # Sleep slightly in headless mode to simulate arm speed and avoid freezing + time.sleep(0.001) + curr_time = time.time() + if curr_time - last_stream_time[0] >= throttle_interval: + last_stream_time[0] = curr_time + state_payload = get_simulation_state_payload(current_sim) + if state_payload: + asyncio.run_coroutine_threadsafe( + websocket.send_json(state_payload), + loop + ) + + with pybullet_lock: + pb.stepSimulation = wrapped_step + + executed_successfully = True + try: + # Trigger an initial simulation state transmission + state_payload = get_simulation_state_payload(current_sim) + if state_payload: + asyncio.run_coroutine_threadsafe(websocket.send_json(state_payload), loop) + + for i, step in enumerate(plan, 1): + log(f"🚀 [3/5] Đang chạy bước {i}/{len(plan)}: {step['function']}") + with pybullet_lock: + current_sim._execute(step, verbose=True) + + log("✅ [3] Thực thi thành công toàn bộ kế hoạch.") + except Exception as e: + log(f"❌ Lỗi trong lúc thực thi mô phỏng: {e}") + executed_successfully = False + finally: + with pybullet_lock: + pb.stepSimulation = original_step + + # Send a final state to ensure visual sync + state_payload = get_simulation_state_payload(current_sim) + if state_payload: + asyncio.run_coroutine_threadsafe(websocket.send_json(state_payload), loop) + # Step 5: Scoring + log("⏳ [5/5] Đang tính toán điểm sắp xếp...") + score_val, score_md = compute_and_format_score(current_sim, plan, executed_successfully) + + asyncio.run_coroutine_threadsafe( + websocket.send_json({ + "type": "result", + "score_display": score_md, + "score_value": score_val + }), + loop + ) +@app.websocket("/ws") +async def websocket_endpoint(websocket: WebSocket): + global current_sim + await websocket.accept() + loop = asyncio.get_running_loop() + + # Retrieve user's desktop display preference from client query params + client_wants_gui = websocket.query_params.get("gui", "false").lower() == "true" + + # Force gui = False to run PyBullet completely headless (DIRECT mode) + gui = False + + camera_state = { + "target": [0.5, 0.0, 0.3], + "dist": 1.3, + "yaw": 45.0, + "pitch": -35.0 + } + + async with executor_lock: + def init_sim(): + global current_sim + with pybullet_lock: + is_connected = False + if current_sim is not None and current_sim.client is not None: + try: + is_connected = pb.isConnected(current_sim.client) + except Exception: + is_connected = False + + if is_connected and current_sim.gui == gui: + current_sim.reset_objects(seed=0) + current_sim.controller.reset_to_home() + for _ in range(5): + pb.stepSimulation(physicsClientId=current_sim.client) + else: + if is_connected: + try: + current_sim.disconnect() + except Exception as e: + print(f"[Teardown Error] {e}") + current_sim = PandaSimulation(gui=gui, seed=0) + + await asyncio.to_thread(init_sim) + # Apply the client's visibility preference to show/hide the PyBullet GUI window on the desktop + await asyncio.to_thread(set_pybullet_window_visibility, client_wants_gui) + + # Send static scene configuration + init_payload = await asyncio.to_thread(get_init_payload, current_sim) + await websocket.send_json(init_payload) + # Send the first simulation state to sync objects and joints + state_payload = await asyncio.to_thread(get_simulation_state_payload, current_sim) + if state_payload: + await websocket.send_json(state_payload) + + try: + while True: + data = await websocket.receive_text() + payload = json.loads(data) + + p_type = payload.get("type") + if p_type == "run": + prompt = payload.get("prompt", "") + use_mock = payload.get("mock", False) + asyncio.create_task( + asyncio.to_thread( + run_pipeline_threadsafe, + websocket, + prompt, + loop, + use_mock + ) + ) + + elif p_type == "reset": + async with executor_lock: + def reset_sim(): + with pybullet_lock: + current_sim.reset_objects(seed=0) + current_sim.controller.reset_to_home() + await asyncio.to_thread(reset_sim) + + state_payload = await asyncio.to_thread(get_simulation_state_payload, current_sim) + if state_payload: + await websocket.send_json(state_payload) + await websocket.send_json({"type": "log", "message": "🔄 Đã reset môi trường mô phỏng."}) + + elif p_type in ("camera_rotate", "camera_pan", "camera_zoom"): + pass + + except WebSocketDisconnect: + print("Client disconnected") + except Exception as e: + print(f"WS Exception: {e}") +if __name__ == "__main__": + uvicorn.run("interactive_server:app", host="0.0.0.0", port=8000, reload=False) diff --git a/.history/frontend/app_20260627231706.js b/.history/frontend/app_20260627231706.js new file mode 100644 index 0000000000000000000000000000000000000000..52d201ca7f9b23617281509f8cb319754add4ec1 --- /dev/null +++ b/.history/frontend/app_20260627231706.js @@ -0,0 +1,1177 @@ +// ─── WebSocket and Visualizer Setup ──────────────────────────────────────── +const canvas = document.getElementById('pybullet-viewport'); +// Three.js Core Variables +let renderer, scene, camera, controls; +let robotGroup, tableMesh, trayMesh; +const slotHelpers = []; +const joints = {}; +const ycbMeshes = {}; +let transformControls = null; +let eeDummy = null; +const OBJ_LOADER = new THREE.OBJLoader(); +const MTL_LOADER = new THREE.MTLLoader(); +let socket = null; +let currentPrompt = ''; +function initVisualizer() { + // Set default coordinate system to Z-up + THREE.Object3D.DefaultUp.set(0, 0, 1); + // Renderer + renderer = new THREE.WebGLRenderer({ canvas: canvas, antialias: true }); + const width = canvas.clientWidth || window.innerWidth; + const height = canvas.clientHeight || window.innerHeight; + renderer.setSize(width, height, false); + renderer.setPixelRatio(window.devicePixelRatio); + renderer.shadowMap.enabled = true; + // Scene + scene = new THREE.Scene(); + scene.background = new THREE.Color('#f1f5f9'); // Light smoke gray background + // Camera + camera = new THREE.PerspectiveCamera(50, width / height, 0.1, 100); + // Position camera to look down at the table, matching PyBullet default view + camera.position.set(1.2, -1.2, 1.2); + // Controls + controls = new THREE.OrbitControls(camera, renderer.domElement); + controls.target.set(0.5, 0.0, 0.2); + controls.enableDamping = true; + controls.dampingFactor = 0.05; + controls.maxPolarAngle = Math.PI / 2 - 0.02; // do not go below table plane + controls.update(); + // Lights + const ambientLight = new THREE.AmbientLight(0xffffff, 0.7); + scene.add(ambientLight); + const dirLight = new THREE.DirectionalLight(0xffffff, 0.85); + dirLight.position.set(2, -2, 4); + dirLight.castShadow = true; + dirLight.shadow.mapSize.width = 1024; + dirLight.shadow.mapSize.height = 1024; + dirLight.shadow.camera.near = 0.5; + dirLight.shadow.camera.far = 15; + scene.add(dirLight); + const dirLight2 = new THREE.DirectionalLight(0xaaccff, 0.35); + dirLight2.position.set(-2, 2, 2); + scene.add(dirLight2); + // Floor plane + const planeGeo = new THREE.PlaneGeometry(10, 10); + const planeMat = new THREE.MeshStandardMaterial({ color: 0xe2e8f0, roughness: 0.85 }); + const plane = new THREE.Mesh(planeGeo, planeMat); + plane.receiveShadow = true; + scene.add(plane); + // Caro background / Grid Helper + const gridHelper = new THREE.GridHelper(10, 100, 0x94a3b8, 0xcbd5e1); + gridHelper.rotation.x = Math.PI / 2; + gridHelper.position.z = 0.001; + scene.add(gridHelper); + // Axes helper (X: Red, Y: Green, Z: Blue) + const axesHelper = new THREE.AxesHelper(0.5); + axesHelper.position.z = 0.002; + scene.add(axesHelper); + // Initialize Transform Controls + transformControls = new THREE.TransformControls(camera, renderer.domElement); + transformControls.addEventListener('dragging-changed', function (event) { + controls.enabled = !event.value; + if (!event.value && transformControls.object && transformControls.object !== eeDummy) { + const obj = transformControls.object; + if (socket && socket.readyState === WebSocket.OPEN) { + const pos = [obj.position.x, obj.position.y, obj.position.z]; + const ori = [obj.quaternion.x, obj.quaternion.y, obj.quaternion.z, obj.quaternion.w]; + socket.send(JSON.stringify({ + type: "update_object_pose", + name: obj.name, + pos: pos, + ori: ori + })); + writeLog(`Đã đặt vật thể ${obj.name} xuống vị trí mới.`, "success"); + } + } + }); + transformControls.addEventListener('change', function () { + if (transformControls.object) { + const obj = transformControls.object; + if (obj === eeDummy) { + if (socket && socket.readyState === WebSocket.OPEN) { + socket.send(JSON.stringify({ + type: "update_robot_ee", + pos: [eeDummy.position.x, eeDummy.position.y, eeDummy.position.z] + })); + } + } else { + obj.position.x = Math.max(0.15, Math.min(0.85, obj.position.x)); + obj.position.y = Math.max(-0.65, Math.min(0.65, obj.position.y)); + obj.position.z = Math.max(0.02, Math.min(0.85, obj.position.z)); + if (targetObjects[obj.name]) { + targetObjects[obj.name].pos.copy(obj.position); + } + } + } + }); + scene.add(transformControls); + // Start animation loop + animate(); +} +let targetJoints = null; +const targetObjects = {}; +let isInitialStateSynced = false; +function animate() { + requestAnimationFrame(animate); + if (controls) controls.update(); + + // Smooth interpolation (Lerp / Slerp) to eliminate visual stutter + if (targetJoints && targetJoints.length >= 11) { + if (!isInitialStateSynced) { + // First tick or after reset: snap immediately to avoid sliding from rest position + joints.joint1.rotation.z = targetJoints[0]; + joints.joint2.rotation.z = targetJoints[1]; + joints.joint3.rotation.z = targetJoints[2]; + joints.joint4.rotation.z = targetJoints[3]; + joints.joint5.rotation.z = targetJoints[4]; + joints.joint6.rotation.z = targetJoints[5]; + joints.joint7.rotation.z = targetJoints[6]; + joints.fingerJoint1.position.y = targetJoints[9]; + joints.fingerJoint2.position.y = -targetJoints[10]; + + Object.entries(targetObjects).forEach(([name, target]) => { + if (transformControls && transformControls.object && transformControls.object.name === name) return; + const group = ycbMeshes[name]; + if (group) { + group.position.copy(target.pos); + group.quaternion.copy(target.ori); + } + }); + isInitialStateSynced = true; + } else { + // Incremental interpolation towards target poses at client framerate (60+ FPS) + const lerpFactor = 0.15; // Balanced tracking speed vs smoothness + joints.joint1.rotation.z = THREE.MathUtils.lerp(joints.joint1.rotation.z, targetJoints[0], lerpFactor); + joints.joint2.rotation.z = THREE.MathUtils.lerp(joints.joint2.rotation.z, targetJoints[1], lerpFactor); + joints.joint3.rotation.z = THREE.MathUtils.lerp(joints.joint3.rotation.z, targetJoints[2], lerpFactor); + joints.joint4.rotation.z = THREE.MathUtils.lerp(joints.joint4.rotation.z, targetJoints[3], lerpFactor); + joints.joint5.rotation.z = THREE.MathUtils.lerp(joints.joint5.rotation.z, targetJoints[4], lerpFactor); + joints.joint6.rotation.z = THREE.MathUtils.lerp(joints.joint6.rotation.z, targetJoints[5], lerpFactor); + joints.joint7.rotation.z = THREE.MathUtils.lerp(joints.joint7.rotation.z, targetJoints[6], lerpFactor); + + joints.fingerJoint1.position.y = THREE.MathUtils.lerp(joints.fingerJoint1.position.y, targetJoints[9], lerpFactor); + joints.fingerJoint2.position.y = THREE.MathUtils.lerp(joints.fingerJoint2.position.y, -targetJoints[10], lerpFactor); + + Object.entries(targetObjects).forEach(([name, target]) => { + if (transformControls && transformControls.object && transformControls.object.name === name) return; + const group = ycbMeshes[name]; + if (group) { + group.position.lerp(target.pos, lerpFactor); + group.quaternion.slerp(target.ori, lerpFactor); + } + }); + } + } + // Update joint sliders to match current animation if user is not actively dragging them + const activeEl = document.activeElement; + const isEditingSliders = activeEl && activeEl.id && activeEl.id.startsWith('slider-'); + if (!isEditingSliders && targetJoints) { + const j1 = document.getElementById('slider-j1'); + if (j1) j1.value = joints.joint1.rotation.z.toFixed(2); + const v1 = document.getElementById('val-j1'); + if (v1) v1.textContent = joints.joint1.rotation.z.toFixed(2); + + const j2 = document.getElementById('slider-j2'); + if (j2) j2.value = joints.joint2.rotation.z.toFixed(2); + const v2 = document.getElementById('val-j2'); + if (v2) v2.textContent = joints.joint2.rotation.z.toFixed(2); + + const j3 = document.getElementById('slider-j3'); + if (j3) j3.value = joints.joint3.rotation.z.toFixed(2); + const v3 = document.getElementById('val-j3'); + if (v3) v3.textContent = joints.joint3.rotation.z.toFixed(2); + + const j4 = document.getElementById('slider-j4'); + if (j4) j4.value = joints.joint4.rotation.z.toFixed(2); + const v4 = document.getElementById('val-j4'); + if (v4) v4.textContent = joints.joint4.rotation.z.toFixed(2); + + const j5 = document.getElementById('slider-j5'); + if (j5) j5.value = joints.joint5.rotation.z.toFixed(2); + const v5 = document.getElementById('val-j5'); + if (v5) v5.textContent = joints.joint5.rotation.z.toFixed(2); + + const j6 = document.getElementById('slider-j6'); + if (j6) j6.value = joints.joint6.rotation.z.toFixed(2); + const v6 = document.getElementById('val-j6'); + if (v6) v6.textContent = joints.joint6.rotation.z.toFixed(2); + + const j7 = document.getElementById('slider-j7'); + if (j7) j7.value = joints.joint7.rotation.z.toFixed(2); + const v7 = document.getElementById('val-j7'); + if (v7) v7.textContent = joints.joint7.rotation.z.toFixed(2); + + const jg = document.getElementById('slider-jg'); + if (jg) jg.value = joints.fingerJoint1.position.y.toFixed(3); + const vg = document.getElementById('val-jg'); + if (vg) vg.textContent = joints.fingerJoint1.position.y.toFixed(3); + } + + // Align eeDummy position to handJoint if not being dragged + if (eeDummy && joints.handJoint && (!transformControls || !transformControls.object || transformControls.object !== eeDummy)) { + const handWorldPos = new THREE.Vector3(); + joints.handJoint.getWorldPosition(handWorldPos); + eeDummy.position.copy(handWorldPos); + } + + renderer.render(scene, camera); +} +// Window resizing +window.addEventListener('resize', () => { + const width = canvas.clientWidth; + const height = canvas.clientHeight; + if (canvas.width !== width || canvas.height !== height) { + renderer.setSize(width, height, false); + camera.aspect = width / height; + camera.updateProjectionMatrix(); + } +}); +// ─── Three.js Scene Construction ──────────────────────────────────────────── +function createTable(tableConfig) { + if (tableMesh) scene.remove(tableMesh); + const ext = tableConfig.half_extents; + const geo = new THREE.BoxGeometry(ext[0] * 2, ext[1] * 2, ext[2] * 2); + const color = new THREE.Color().fromArray(tableConfig.color.slice(0, 3)); + const mat = new THREE.MeshStandardMaterial({ color: color, roughness: 0.6, metalness: 0.1 }); + tableMesh = new THREE.Mesh(geo, mat); + tableMesh.position.set(tableConfig.center[0], tableConfig.center[1], tableConfig.center[2]); + tableMesh.castShadow = true; + tableMesh.receiveShadow = true; + scene.add(tableMesh); +} +function createTray(trayConfig) { + if (trayMesh) scene.remove(trayMesh); + const ext = trayConfig.half_extents; + const geo = new THREE.BoxGeometry(ext[0] * 2, ext[1] * 2, ext[2] * 2); + const color = new THREE.Color().fromArray(trayConfig.color.slice(0, 3)); + const mat = new THREE.MeshStandardMaterial({ color: color, roughness: 0.7 }); + trayMesh = new THREE.Mesh(geo, mat); + trayMesh.position.set(trayConfig.position[0], trayConfig.position[1], trayConfig.position[2] - ext[2]); + trayMesh.castShadow = true; + trayMesh.receiveShadow = true; + scene.add(trayMesh); +} +function createSlotHelpers(slots) { + slotHelpers.forEach(mesh => scene.remove(mesh)); + slotHelpers.length = 0; + + const geom = new THREE.RingGeometry(0.045, 0.05, 32); + const mat = new THREE.MeshBasicMaterial({ color: 0x3b82f6, side: THREE.DoubleSide, transparent: true, opacity: 0.45 }); + + Object.entries(slots).forEach(([name, pos]) => { + const ring = new THREE.Mesh(geom, mat); + ring.position.set(pos[0], pos[1], pos[2] + 0.001); // slightly above table + scene.add(ring); + slotHelpers.push(ring); + }); +} +function initRobotStructure() { + if (robotGroup) scene.remove(robotGroup); + robotGroup = new THREE.Group(); + scene.add(robotGroup); + + joints.joint1 = new THREE.Group(); + joints.joint2 = new THREE.Group(); + joints.joint3 = new THREE.Group(); + joints.joint4 = new THREE.Group(); + joints.joint5 = new THREE.Group(); + joints.joint6 = new THREE.Group(); + joints.joint7 = new THREE.Group(); + joints.joint8 = new THREE.Group(); + joints.handJoint = new THREE.Group(); + joints.fingerJoint1 = new THREE.Group(); + joints.fingerJoint2 = new THREE.Group(); + + const link0 = new THREE.Group(); + const link1 = new THREE.Group(); + const link2 = new THREE.Group(); + const link3 = new THREE.Group(); + const link4 = new THREE.Group(); + const link5 = new THREE.Group(); + const link6 = new THREE.Group(); + const link7 = new THREE.Group(); + const link8 = new THREE.Group(); + const hand = new THREE.Group(); + const leftFinger = new THREE.Group(); + const rightFinger = new THREE.Group(); + + robotGroup.add(link0); + + link0.add(joints.joint1); + joints.joint1.position.set(0, 0, 0.333); + joints.joint1.add(link1); + + link1.add(joints.joint2); + joints.joint2.position.set(0, 0, 0); + joints.joint2.rotation.set(-1.57079632679, 0, 0); + joints.joint2.add(link2); + + link2.add(joints.joint3); + joints.joint3.position.set(0, -0.316, 0); + joints.joint3.rotation.set(1.57079632679, 0, 0); + joints.joint3.add(link3); + + link3.add(joints.joint4); + joints.joint4.position.set(0.0825, 0, 0); + joints.joint4.rotation.set(1.57079632679, 0, 0); + joints.joint4.add(link4); + + link4.add(joints.joint5); + joints.joint5.position.set(-0.0825, 0.384, 0); + joints.joint5.rotation.set(-1.57079632679, 0, 0); + joints.joint5.add(link5); + + link5.add(joints.joint6); + joints.joint6.position.set(0, 0, 0); + joints.joint6.rotation.set(1.57079632679, 0, 0); + joints.joint6.add(link6); + + link6.add(joints.joint7); + joints.joint7.position.set(0.088, 0, 0); + joints.joint7.rotation.set(1.57079632679, 0, 0); + joints.joint7.add(link7); + + link7.add(joints.joint8); + joints.joint8.position.set(0, 0, 0.107); + joints.joint8.add(link8); + + link8.add(joints.handJoint); + joints.handJoint.position.set(0, 0, 0); + joints.handJoint.rotation.set(0, 0, -0.785398163397); + joints.handJoint.add(hand); + + hand.add(joints.fingerJoint1); + joints.fingerJoint1.position.set(0, 0, 0.0584); + joints.fingerJoint1.add(leftFinger); + + hand.add(joints.fingerJoint2); + joints.fingerJoint2.position.set(0, 0, 0.0584); + joints.fingerJoint2.add(rightFinger); + + const defaultPandaMaterial = new THREE.MeshStandardMaterial({ + color: 0xdddddd, + roughness: 0.35, + metalness: 0.15 + }); + const loadModel = (parent, objPath, mtlPath = null, rotateRightFinger = false) => { + const applyRotation = (obj) => { + if (rotateRightFinger) { + obj.rotation.z = Math.PI; + } + parent.add(obj); + }; + if (mtlPath) { + MTL_LOADER.load(mtlPath, (materials) => { + materials.preload(); + + const objLoader = new THREE.OBJLoader(); + objLoader.setMaterials(materials); + objLoader.load(objPath, (obj) => { + obj.traverse(child => { + if (child.isMesh) { + child.castShadow = true; + child.receiveShadow = true; + } + }); + applyRotation(obj); + }); + }); + } else { + const objLoader = new THREE.OBJLoader(); + objLoader.load(objPath, (obj) => { + obj.traverse(child => { + if (child.isMesh) { + child.material = defaultPandaMaterial; + child.castShadow = true; + child.receiveShadow = true; + } + }); + applyRotation(obj); + }); + } + }; + loadModel(link0, '/assets/panda/meshes/collision/link0.obj'); + loadModel(link1, '/assets/panda/meshes/visual/link1.obj', '/assets/panda/meshes/visual/link1.mtl'); + loadModel(link2, '/assets/panda/meshes/visual/link2.obj', '/assets/panda/meshes/visual/link2.mtl'); + loadModel(link3, '/assets/panda/meshes/visual/link3.obj', '/assets/panda/meshes/visual/link3.mtl'); + loadModel(link4, '/assets/panda/meshes/visual/link4.obj', '/assets/panda/meshes/visual/link4.mtl'); + loadModel(link5, '/assets/panda/meshes/visual/link5.obj', '/assets/panda/meshes/visual/link5.mtl'); + loadModel(link6, '/assets/panda/meshes/visual/link6.obj', '/assets/panda/meshes/visual/link6.mtl'); + loadModel(link7, '/assets/panda/meshes/collision/link7.obj'); + loadModel(hand, '/assets/panda/meshes/visual/hand.obj', '/assets/panda/meshes/visual/hand.mtl'); + loadModel(leftFinger, '/assets/panda/meshes/visual/finger.obj', '/assets/panda/meshes/visual/finger.mtl'); + loadModel(rightFinger, '/assets/panda/meshes/visual/finger.obj', '/assets/panda/meshes/visual/finger.mtl', true); + // Create eeDummy sphere representing the end-effector target + if (eeDummy) scene.remove(eeDummy); + const dummyGeo = new THREE.SphereGeometry(0.035, 16, 16); + const dummyMat = new THREE.MeshStandardMaterial({ + color: 0x3b82f6, + transparent: true, + opacity: 0.65, + roughness: 0.1, + metalness: 0.9 + }); + eeDummy = new THREE.Mesh(dummyGeo, dummyMat); + eeDummy.name = 'robot'; + eeDummy.visible = false; + scene.add(eeDummy); +} +function loadYcbObjects(objectsConfig) { + // Clear old meshes/groups from scene + Object.values(ycbMeshes).forEach(group => scene.remove(group)); + for (const key in ycbMeshes) delete ycbMeshes[key]; + + Object.entries(objectsConfig).forEach(([name, config]) => { + const folder = config.folder; + let objFile = ""; + let mtlFile = ""; + + if (folder === "YcbBanana" || folder === "YcbTomatoSoupCan" || folder === "YcbCrackerBox" || folder === "YcbMustardBottle" || folder === "YcbPottedMeatCan") { + objFile = `/assets/ycb/${folder}/textured_simple_reoriented.obj`; + mtlFile = `/assets/ycb/${folder}/textured_simple_reoriented.mtl`; + } else if (folder === "YcbChipsCan") { + objFile = `/assets/ycb/${folder}/textured.obj`; + mtlFile = `/assets/ycb/${folder}/textured.mtl`; + } + + if (!objFile) return; + // Create a parent group to represent the object's body link pose + const objectGroup = new THREE.Group(); + objectGroup.name = name; + objectGroup.position.fromArray(config.initial_pos); + objectGroup.quaternion.fromArray(config.initial_ori); + scene.add(objectGroup); + ycbMeshes[name] = objectGroup; + // 1. Load Visual Mesh + MTL_LOADER.load(mtlFile, (materials) => { + materials.preload(); + + const objLoader = new THREE.OBJLoader(); + objLoader.setMaterials(materials); + objLoader.load(objFile, (visObj) => { + visObj.traverse(child => { + if (child.isMesh) { + child.castShadow = true; + child.receiveShadow = true; + } + }); + + // Position, rotate and scale relative to parent group + if (config.vis_local_pos) visObj.position.fromArray(config.vis_local_pos); + if (config.vis_local_ori) visObj.quaternion.fromArray(config.vis_local_ori); + if (config.vis_scale) visObj.scale.fromArray(config.vis_scale); + + objectGroup.add(visObj); + }); + }); + // 2. Load Collision Mesh (Semi-transparent Blue) + const collObjFile = `/assets/ycb/${folder}/collision_vhacd.obj`; + const collLoader = new THREE.OBJLoader(); + collLoader.load(collObjFile, (collObj) => { + collObj.traverse(child => { + if (child.isMesh) { + child.material = new THREE.MeshStandardMaterial({ + color: 0x0000ff, // blue + transparent: true, + opacity: 0.5, // semi-transparent + roughness: 0.4, + metalness: 0.1 + }); + child.castShadow = true; + child.receiveShadow = true; + } + }); + + // Position, rotate and scale relative to parent group + if (config.coll_local_pos) collObj.position.fromArray(config.coll_local_pos); + if (config.coll_local_ori) collObj.quaternion.fromArray(config.coll_local_ori); + if (config.coll_scale) collObj.scale.fromArray(config.coll_scale); + + objectGroup.add(collObj); + }); + }); +} +function updateSimulationState(jointsData, objectsData) { + if (jointsData && jointsData.length >= 11) { + targetJoints = jointsData; + } + + if (objectsData) { + Object.entries(objectsData).forEach(([name, data]) => { + targetObjects[name] = { + pos: new THREE.Vector3().fromArray(data.pos), + ori: new THREE.Quaternion().fromArray(data.ori) + }; + }); + } +} +let reconnectTimeout = null; +function connectWebSocket() { + if (reconnectTimeout) { + clearTimeout(reconnectTimeout); + reconnectTimeout = null; + } + const guiToggle = document.getElementById('gui-toggle'); + const showGui = guiToggle ? guiToggle.checked : false; + const wsProtocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:'; + const wsUrl = `${wsProtocol}//${window.location.host}/ws?gui=${showGui}`; + + updateBadgeStatus('disconnected'); + + socket = new WebSocket(wsUrl); + socket.onopen = () => { + console.log("WebSocket connected."); + updateBadgeStatus('connected'); + writeLog("Kết nối thành công đến Backend server.", "success"); + }; + socket.onmessage = (event) => { + const msg = JSON.parse(event.data); + handleSocketMessage(msg); + }; + socket.onclose = () => { + console.log("WebSocket disconnected."); + updateBadgeStatus('disconnected'); + writeLog("Mất kết nối đến Backend server. Đang thử kết nối lại...", "error"); + reconnectTimeout = setTimeout(connectWebSocket, 3000); + }; + socket.onerror = (err) => { + console.error("WebSocket Error: ", err); + }; +} +function handleSocketMessage(msg) { + switch(msg.type) { + case 'init': + createTable(msg.table); + createTray(msg.tray); + createSlotHelpers(msg.slots); + loadYcbObjects(msg.objects); + initRobotStructure(); + isInitialStateSynced = false; // Reset sync state for new simulations + break; + + case 'state': + updateSimulationState(msg.joints, msg.objects); + break; + + case 'log': + writeLog(msg.message, getLogClass(msg.message)); + updatePipelineUI(msg.message); + break; + + case 'plan': + displayPlan(msg.plan); + break; + + case 'result': + showRearrangementScore(msg.score_display); + unlockInput(); + + // Add new run record to history log dynamically + const now = new Date(); + const timeStr = now.toTimeString().split(' ')[0]; + const scoreVal = msg.score_value !== undefined ? msg.score_value : 100; + const scoreClass = scoreVal >= 90 ? "high" : (scoreVal >= 60 ? "medium" : "low"); + + historyData.unshift({ + time: timeStr, + operator: "Operator", + prompt: currentPrompt || "Câu lệnh nhanh", + score: scoreVal, + class: scoreClass + }); + renderHistory(); + + // Speak speech feedback + speakFeedback(`Đã hoàn thành vận hành. Điểm rearrangement đạt ${scoreVal} điểm.`); + break; + } +} +// ─── UI Updates and Interactions ──────────────────────────────────────────── +const badge = document.getElementById('connection-badge'); +const logConsole = document.getElementById('log-console'); +const planList = document.getElementById('plan-list'); +const chatInput = document.getElementById('chat-input'); +const submitBtn = document.getElementById('submit-btn'); +const mockToggle = document.getElementById('mock-toggle'); +const guiToggle = document.getElementById('gui-toggle'); +const resetBtn = document.getElementById('reset-btn'); +const scoreModal = document.getElementById('score-modal'); +const scoreContent = document.getElementById('score-md-content'); +const closeModalBtn = document.getElementById('close-modal-btn'); +const ttsToggle = document.getElementById('tts-toggle'); +const autocompletePanel = document.getElementById('autocomplete-panel'); +// 1. Tab switching logic +document.querySelectorAll('.tab-btn').forEach(btn => { + btn.addEventListener('click', () => { + document.querySelectorAll('.tab-btn').forEach(b => b.classList.remove('active')); + document.querySelectorAll('.tab-panel').forEach(p => p.classList.remove('active')); + btn.classList.add('active'); + const tabId = btn.dataset.tab; + document.getElementById(`panel-${tabId}`).classList.add('active'); + }); +}); +// 2. Scenario template click events +document.querySelectorAll('.scenario-card').forEach(card => { + card.addEventListener('click', () => { + const prompt = card.dataset.prompt; + chatInput.value = prompt; + chatInput.focus(); + }); +}); +document.querySelectorAll('.preset-command-item').forEach(item => { + item.addEventListener('click', () => { + const prompt = item.dataset.prompt; + chatInput.value = prompt; + chatInput.focus(); + }); +}); +// 3. Object Catalog Data & Render +const activeObjects = [ + { id: "banana", name: "Quả chuối (YCB)", mass: 0.066, friction: 0.8, trait: "Safe" }, + { id: "soup_can", name: "Lon súp cà chua", mass: 0.349, friction: 0.8, trait: "Safe" }, + { id: "chips_can", name: "Lon snack khoai tây", mass: 0.205, friction: 0.5, trait: "Safe" } +]; +function renderObjectsTable() { + const objectsTableBody = document.getElementById('objects-table-body'); + if (!objectsTableBody) return; + objectsTableBody.innerHTML = activeObjects.map(obj => ` + + ${obj.name}
    ${obj.id} + ${obj.mass} + ${obj.friction} + ${obj.trait} + + `).join(''); +} +// 4. History Logs Data & Render +const historyData = [ + { time: "14:20:15", operator: "Operator", prompt: "gắp lon snack đặt vào khay", score: 100, class: "high" }, + { time: "14:15:32", operator: "Operator", prompt: "dọn dẹp chướng ngại vật ở khay", score: 85, class: "medium" }, + { time: "14:02:10", operator: "Operator", prompt: "gắp quả chuối đặt vào Slot_2", score: 100, class: "high" } +]; +function renderHistory() { + const historyList = document.getElementById('history-list'); + if (!historyList) return; + historyList.innerHTML = historyData.map((item, index) => ` +
    +
    + 🕒 ${item.time} - ${item.operator} + ${item.score}/100 +
    +

    "${item.prompt}"

    + +
    + `).join(''); +} +window.runHistoryPrompt = function(index) { + const item = historyData[index]; + if (item) { + chatInput.value = item.prompt; + chatInput.focus(); + document.getElementById('chat-form').dispatchEvent(new Event('submit')); + } +}; +// 5. Speech Synthesis (Text-to-Speech) +function speakFeedback(text) { + if (!ttsToggle || !ttsToggle.checked) return; + + // Determine language based on text content (Vietnamese by default, English if it contains mostly technical terms) + let lang = 'vi'; + const textLower = text.toLowerCase(); + if (textLower.includes('evaluation') || textLower.includes('score') || textLower.includes('report') || textLower.includes('step') || textLower.includes('verification')) { + lang = 'en'; + } + + // Call Google Translate TTS (free API) for high-quality English & Vietnamese voices + const encodedText = encodeURIComponent(text); + const ttsUrl = `https://translate.google.com/translate_tts?ie=UTF-8&tl=${lang}&client=tw-ob&q=${encodedText}`; + + const audio = new Audio(ttsUrl); + audio.play().catch(err => { + console.warn("Google Translate TTS failed, falling back to local speech synthesis:", err); + if ('speechSynthesis' in window) { + window.speechSynthesis.cancel(); + const utterance = new SpeechSynthesisUtterance(text); + utterance.lang = lang === 'vi' ? 'vi-VN' : 'en-US'; + utterance.rate = 1.0; + utterance.pitch = 1.0; + + const voices = window.speechSynthesis.getVoices(); + const matchingVoice = voices.find(voice => voice.lang.includes(lang)); + if (matchingVoice) utterance.voice = matchingVoice; + + window.speechSynthesis.speak(utterance); + } + }); +} +// 6. Voice Recognition (Speech-to-Text) +const micBtn = document.getElementById('mic-btn'); +let recognition = null; +let isRecording = false; +if ('webkitSpeechRecognition' in window || 'SpeechRecognition' in window) { + const SpeechRecognition = window.SpeechRecognition || window.webkitSpeechRecognition; + recognition = new SpeechRecognition(); + recognition.continuous = false; + recognition.interimResults = false; + recognition.lang = 'vi-VN'; + recognition.onstart = () => { + isRecording = true; + micBtn.classList.add('recording'); + writeLog("Đang nghe giọng nói của bạn... Hãy nói đi.", "info"); + speakFeedback("Tôi đang nghe."); + }; + recognition.onresult = (event) => { + const resultText = event.results[0][0].transcript; + chatInput.value = resultText; + writeLog(`Nhận dạng giọng nói: "${resultText}"`, "success"); + speakFeedback(`Đã nhận diện: ${resultText}`); + }; + recognition.onerror = (event) => { + console.error("Speech Recognition Error: ", event.error); + writeLog("Nhận diện giọng nói gặp lỗi: " + event.error, "warn"); + isRecording = false; + micBtn.classList.remove('recording'); + }; + recognition.onend = () => { + isRecording = false; + micBtn.classList.remove('recording'); + }; + micBtn.addEventListener('click', () => { + if (isRecording) { + recognition.stop(); + } else { + recognition.start(); + } + }); +} else { + micBtn.style.display = 'none'; +} +// 7. Smart Autocomplete suggestions +const autocompleteVocabulary = [ + "gắp quả chuối đặt vào khay", + "gắp quả chuối đặt vào Slot_2", + "gắp quả chuối đặt vào Slot_4", + "gắp lon súp cà chua đặt vào khay", + "gắp lon súp cà chua đặt vào Slot_3", + "gắp lon snack đặt vào khay", + "gắp lon snack đặt vào Slot_6", + "dọn dẹp chướng ngại vật trên bàn", + "sắp xếp lại bàn học tập", + "cất dọn đồ vật nguy hiểm" +]; +if (chatInput && autocompletePanel) { + chatInput.addEventListener('input', (e) => { + const query = e.target.value.toLowerCase().trim(); + if (!query || query.length < 2) { + autocompletePanel.classList.add('hidden'); + return; + } + + const matches = autocompleteVocabulary.filter(item => item.includes(query)).slice(0, 4); + if (matches.length === 0) { + autocompletePanel.classList.add('hidden'); + return; + } + + autocompletePanel.innerHTML = matches.map(match => ` +
    ${match}
    + `).join(''); + autocompletePanel.classList.remove('hidden'); + + document.querySelectorAll('.autocomplete-item').forEach(item => { + item.addEventListener('click', () => { + chatInput.value = item.dataset.value; + autocompletePanel.classList.add('hidden'); + chatInput.focus(); + }); + }); + }); + + document.addEventListener('click', (e) => { + if (!e.target.closest('#chat-form')) { + autocompletePanel.classList.add('hidden'); + } + }); +} +// 8. Log and Pipeline functions +function updateBadgeStatus(status) { + if (status === 'connected') { + badge.className = 'badge online'; + badge.textContent = 'Connected'; + } else { + badge.className = 'badge offline'; + badge.textContent = 'Disconnected'; + } +} +function writeLog(text, className = 'info') { + const entry = document.createElement('div'); + entry.className = `log-entry ${className}`; + entry.textContent = `> ${text}`; + + const placeholder = logConsole.querySelector('.placeholder-text'); + if (placeholder) placeholder.remove(); + logConsole.appendChild(entry); + logConsole.scrollTop = logConsole.scrollHeight; +} +function getLogClass(message) { + if (message.includes('✅')) return 'success'; + if (message.includes('❌')) return 'error'; + if (message.includes('⚠️')) return 'warn'; + if (message.includes('🚀') || message.includes('⏳')) return 'info'; + return ''; +} +function updatePipelineUI(message) { + const stepLlm = document.getElementById('step-llm'); + const stepVal = document.getElementById('step-val'); + const stepExec = document.getElementById('step-exec'); + const stepScore = document.getElementById('step-score'); + if (message.includes('[1/5]')) { + setActiveStep(stepLlm); + } else if (message.includes('✅ [1]')) { + setCompletedStep(stepLlm); + } else if (message.includes('❌ [1]')) { + setErrorStep(stepLlm); + unlockInput(); + speakFeedback("Lập kế hoạch thất bại. Vui lòng kiểm tra lại câu lệnh."); + } + else if (message.includes('[2/5]')) { + setActiveStep(stepVal); + } else if (message.includes('✅ [2]')) { + setCompletedStep(stepVal); + } else if (message.includes('❌ [2]') || message.includes('⚠️ [2]')) { + if (message.includes('❌')) { + setErrorStep(stepVal); + unlockInput(); + speakFeedback("Kế hoạch không hợp lệ. Vi phạm các quy tắc an toàn."); + } else { + stepVal.className = 'status-step active warn'; + } + } + else if (message.includes('[3/5]')) { + setActiveStep(stepExec); + } else if (message.includes('Thực thi thành công')) { + setCompletedStep(stepExec); + } else if (message.includes('Thực thi kết thúc có bước lỗi')) { + setErrorStep(stepExec); + speakFeedback("Quá trình thực thi gặp sự cố va chạm."); + } + else if (message.includes('[5/5]')) { + setActiveStep(stepScore); + } else if (message.includes('Rearrangement Evaluation Report') || message.includes('result')) { + setCompletedStep(stepScore); + unlockInput(); + } +} +function setActiveStep(el) { + el.className = 'status-step active'; +} +function setCompletedStep(el) { + el.className = 'status-step completed'; +} +function setErrorStep(el) { + el.className = 'status-step error'; +} +function displayPlan(plan) { + planList.innerHTML = ''; + plan.forEach(step => { + const item = document.createElement('div'); + item.className = 'plan-item'; + item.id = `plan-step-${step.step}`; + + const argsStr = Object.entries(step.args) + .map(([k, v]) => `${k}:${v}`) + .join(', '); + + item.innerHTML = ` + Step ${step.step}: ${step.skill}(${step.object}) + ${argsStr} + `; + planList.appendChild(item); + }); +} +function showRearrangementScore(markdownText) { + let html = markdownText + .replace(/### (.*)/g, '

    $1

    ') + .replace(/\*\*(.*?)\*\*/g, '$1') + .replace(/- (.*)/g, '
  • $1
  • ') + .replace(/\n\n/g, '
    ') + .replace(/✅/g, '✅') + .replace(/⚠️/g, '⚠️') + .replace(/❌/g, '❌'); + + scoreContent.innerHTML = html; + scoreModal.classList.remove('hidden'); +} +function lockInput() { + chatInput.disabled = true; + submitBtn.disabled = true; + resetBtn.disabled = true; + mockToggle.disabled = true; + if (guiToggle) guiToggle.disabled = true; +} +document.getElementById('chat-form').addEventListener('submit', (e) => { + e.preventDefault(); + const prompt = chatInput.value.trim(); + if (!prompt || !socket || socket.readyState !== WebSocket.OPEN) return; + currentPrompt = prompt; + chatInput.value = ''; + + logConsole.innerHTML = ''; + planList.innerHTML = '

    Đang tải kế hoạch...

    '; + + ['step-llm', 'step-val', 'step-exec', 'step-score'].forEach(id => { + document.getElementById(id).className = 'status-step'; + }); + writeLog(`Gửi yêu cầu: "${prompt}"`, "info"); + lockInput(); + + speakFeedback("Bắt đầu xử lý câu lệnh điều khiển của bạn."); + socket.send(JSON.stringify({ + type: 'run', + prompt: prompt, + mock: mockToggle.checked + })); +}); +function unlockInput() { + chatInput.disabled = false; + submitBtn.disabled = false; + resetBtn.disabled = false; + mockToggle.disabled = false; + if (guiToggle) guiToggle.disabled = false; +} +resetBtn.addEventListener('click', () => { + if (!socket || socket.readyState !== WebSocket.OPEN) return; + + logConsole.innerHTML = ''; + planList.innerHTML = '

    Chưa có kế hoạch...

    '; + + ['step-llm', 'step-val', 'step-exec', 'step-score'].forEach(id => { + document.getElementById(id).className = 'status-step'; + }); + socket.send(JSON.stringify({ + type: 'reset' + })); +}); +closeModalBtn.addEventListener('click', () => { + scoreModal.classList.add('hidden'); + unlockInput(); +}); +if (guiToggle) { + guiToggle.addEventListener('change', () => { + writeLog("Thay đổi thiết lập hiển thị cửa sổ PyBullet. Đang kết nối lại...", "info"); + if (socket) { + socket.onclose = null; + socket.close(); + } + connectWebSocket(); + }); +} +// 10. Manual joint controls sending +function sendManualJoints() { + if (!socket || socket.readyState !== WebSocket.OPEN) return; + const q0 = parseFloat(document.getElementById('slider-j1').value); + const q1 = parseFloat(document.getElementById('slider-j2').value); + const q2 = parseFloat(document.getElementById('slider-j3').value); + const q3 = parseFloat(document.getElementById('slider-j4').value); + const q4 = parseFloat(document.getElementById('slider-j5').value); + const q5 = parseFloat(document.getElementById('slider-j6').value); + const q6 = parseFloat(document.getElementById('slider-j7').value); + const qg = parseFloat(document.getElementById('slider-jg').value); + + socket.send(JSON.stringify({ + type: "update_joints", + joints: [q0, q1, q2, q3, q4, q5, q6, 0.0, 0.0, qg, qg] + })); +} +const slidersList = ['j1', 'j2', 'j3', 'j4', 'j5', 'j6', 'j7', 'jg']; +slidersList.forEach(id => { + const slider = document.getElementById(`slider-${id}`); + const label = document.getElementById(`val-${id}`); + if (slider && label) { + slider.addEventListener('input', (e) => { + const val = parseFloat(e.target.value); + label.textContent = id === 'jg' ? val.toFixed(3) : val.toFixed(2); + sendManualJoints(); + }); + } +}); +// 11. Interactive Drag and Drop for YCB objects and Robot End Effector using THREE.TransformControls +const raycaster = new THREE.Raycaster(); +const mouse = new THREE.Vector2(); +// State variables for Hover Highlight +const originalEmissives = new Map(); +let hoveredGroup = null; +canvas.addEventListener('mousedown', onMouseDown); +canvas.addEventListener('mousemove', onMouseMove); +// Helper to determine if an intersected object belongs to a draggable group (YCB or Robot) +function findDraggableTarget(hitObject) { + let curr = hitObject; + while (curr && curr !== scene) { + if (curr === robotGroup) { + return { type: 'robot', group: robotGroup, name: 'robot' }; + } + const ycbEntry = Object.entries(ycbMeshes).find(([name, group]) => group === curr); + if (ycbEntry) { + return { type: 'ycb', group: ycbEntry[1], name: ycbEntry[0] }; + } + curr = curr.parent; + } + return null; +} +// Helper to set/restore emissive highlight glow on all child meshes of a group +function highlightGroup(group, highlightColor = null) { + if (!group) return; + group.traverse(child => { + if (child.isMesh) { + if (highlightColor) { + if (!originalEmissives.has(child.uuid)) { + if (child.material && child.material.emissive) { + originalEmissives.set(child.uuid, { + color: child.material.emissive.clone(), + material: child.material + }); + } + } + if (child.material && child.material.emissive) { + child.material.emissive.copy(highlightColor); + } + } else { + const orig = originalEmissives.get(child.uuid); + if (orig && orig.material && orig.material.emissive) { + orig.material.emissive.copy(orig.color); + } + } + } + }); +} +function onMouseDown(event) { + if (event.button !== 0 || chatInput.disabled) return; + + // Ignore clicks if we are already dragging the transform controls handles + if (transformControls && transformControls.dragging) return; + const rect = canvas.getBoundingClientRect(); + mouse.x = ((event.clientX - rect.left) / rect.width) * 2 - 1; + mouse.y = -((event.clientY - rect.top) / rect.height) * 2 + 1; + raycaster.setFromCamera(mouse, camera); + const hits = raycaster.intersectObjects(scene.children, true); + let target = null; + + // Check if the click hit the Gizmo itself + for (let i = 0; i < hits.length; i++) { + // Exclude the gizmo meshes themselves + let isGizmo = false; + let p = hits[i].object; + while (p) { + if (p === transformControls) { + isGizmo = true; + break; + // Click is on the gizmo handles; let TransformControls handle it + return; + } + p = p.parent; + } + if (isGizmo) continue; + } + let target = null; + for (let i = 0; i < hits.length; i++) { + const found = findDraggableTarget(hits[i].object); + if (found) { + target = found; + break; + } + } + if (target) { + if (target.type === 'robot') { + if (eeDummy && joints.handJoint) { + const handWorldPos = new THREE.Vector3(); + joints.handJoint.getWorldPosition(handWorldPos); + eeDummy.position.copy(handWorldPos); + eeDummy.visible = true; + + transformControls.attach(eeDummy); + writeLog("Đã kích hoạt Gizmo điều khiển cánh tay robot. Kéo các trục mũi tên để dịch chuyển.", "info"); + } + } else { + if (transformControls.object === eeDummy) { + eeDummy.visible = false; + } + transformControls.attach(target.group); + writeLog(`Đã chọn vật thể: ${target.name}. Kéo các trục mũi tên để dịch chuyển.`, "info"); + } + } else { + if (transformControls && !transformControls.dragging) { + if (transformControls.object === eeDummy) { + eeDummy.visible = false; + } + transformControls.detach(); + } + } +} +function onMouseMove(event) { + if (transformControls && transformControls.dragging) { + return; + } + const rect = canvas.getBoundingClientRect(); + mouse.x = ((event.clientX - rect.left) / rect.width) * 2 - 1; + mouse.y = -((event.clientY - rect.top) / rect.height) * 2 + 1; + raycaster.setFromCamera(mouse, camera); + const hits = raycaster.intersectObjects(scene.children, true); + let hoverTarget = null; + + // Check if the mouse is hovering over the Gizmo itself + for (let i = 0; i < hits.length; i++) { + let isGizmo = false; + let p = hits[i].object; + while (p) { + if (p === transformControls) { + isGizmo = true; + break; + // Let Gizmo handle cursors and mouse interaction + return; + } + p = p.parent; + } + if (isGizmo) continue; + } + let hoverTarget = null; + for (let i = 0; i < hits.length; i++) { + const found = findDraggableTarget(hits[i].object); + if (found) { + hoverTarget = found; + break; + } + } + if (hoverTarget) { + if (hoveredGroup !== hoverTarget.group) { + if (hoveredGroup) { + highlightGroup(hoveredGroup, null); + } + originalEmissives.clear(); + + hoveredGroup = hoverTarget.group; + const glowColor = new THREE.Color(hoverTarget.type === 'robot' ? '#1e40af' : '#2563eb'); + highlightGroup(hoveredGroup, glowColor); + + canvas.style.cursor = 'pointer'; + } + } else { + if (hoveredGroup) { + highlightGroup(hoveredGroup, null); + hoveredGroup = null; + originalEmissives.clear(); + canvas.style.cursor = ''; + } + } +} +// 12. Initial runs +initVisualizer(); +connectWebSocket(); +renderObjectsTable(); +renderHistory(); diff --git a/.history/frontend/index_20260627225036.css b/.history/frontend/index_20260627225036.css new file mode 100644 index 0000000000000000000000000000000000000000..94f966ec9d655c6801248cea892d09cdfc1cc4d5 --- /dev/null +++ b/.history/frontend/index_20260627225036.css @@ -0,0 +1,595 @@ +:root { + --primary-color: #1e3a8a; /* Dark Navy Blue */ + --primary-glow: rgba(30, 58, 138, 0.3); + --accent-success: #064e3b; /* Very Dark Green */ + --accent-warning: #78350f; /* Dark Amber/Brown */ + --accent-error: #7f1d1d; /* Dark Red */ + --bg-dark: #f8fafc; + --text-main: #000000; /* Pure Black for maximum contrast */ + --text-muted: #1e293b; /* Dark Slate */ + --hud-text-shadow: 0 1px 3px rgba(255, 255, 255, 0.95), 0 0 6px rgba(255, 255, 255, 0.85); +} + +* { + box-sizing: border-box; + margin: 0; + padding: 0; +} + +body { + font-family: 'Outfit', -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif; + background-color: #f1f5f9; + color: var(--text-main); + overflow: hidden; + width: 100vw; + height: 100vh; +} + +/* Fullscreen Viewport Container */ +#viewport-container { + position: absolute; + top: 0; + left: 0; + width: 100vw; + height: 100vh; + background-color: #f1f5f9; + z-index: 1; + overflow: hidden; +} + +#pybullet-viewport { + width: 100%; + height: 100%; + object-fit: cover; /* Stretches to fill widescreen displays without borders */ + border: none; + border-radius: 0; + box-shadow: none; + cursor: grab; +} + +#pybullet-viewport:active { + cursor: grabbing; +} + +/* Transparent HUD Panels with Premium Glassmorphism */ +.glass { + background: rgba(255, 255, 255, 0.75); + backdrop-filter: blur(12px); + -webkit-backdrop-filter: blur(12px); + border: 1px solid rgba(255, 255, 255, 0.4); + box-shadow: 0 8px 32px 0 rgba(31, 38, 135, 0.08); + border-radius: 16px; +} + +/* Sidebar Styling (Light-HUD layout) */ +.sidebar { + position: absolute; + top: 20px; + left: 20px; + width: 360px; + height: calc(100vh - 40px); + z-index: 10; + padding: 24px; + display: flex; + flex-direction: column; + gap: 22px; + pointer-events: auto; +} + +.sidebar-header { + display: flex; + justify-content: space-between; + align-items: center; + border-bottom: 2px solid rgba(37, 99, 235, 0.3); + padding-bottom: 12px; +} + +.sidebar-header h2 { + font-family: 'Space Grotesk', sans-serif; + font-size: 1.6rem; + font-weight: 700; + letter-spacing: -0.025em; + color: #1e3a8a; /* Navy Blue */ + text-shadow: var(--hud-text-shadow); +} + +.badge { + font-size: 0.75rem; + font-weight: 700; + padding: 4px 12px; + border-radius: 12px; + text-transform: uppercase; + letter-spacing: 0.05em; + display: inline-flex; + align-items: center; + gap: 6px; + text-shadow: var(--hud-text-shadow); + border: 1px solid currentColor; +} + +.badge::before { + content: ''; + display: inline-block; + width: 6px; + height: 6px; + border-radius: 50%; +} + +.badge.online { + background: rgba(16, 185, 129, 0.15); + color: var(--accent-success); +} +.badge.online::before { + background: var(--accent-success); + box-shadow: 0 0 8px var(--accent-success); +} + +.badge.offline { + background: rgba(239, 68, 68, 0.15); + color: var(--accent-error); +} +.badge.offline::before { + background: var(--accent-error); +} + +.sidebar-section { + display: flex; + flex-direction: column; + gap: 10px; +} + +.sidebar-section.flex-grow { + flex-grow: 1; + min-height: 0; +} + +.sidebar-section h3 { + font-size: 0.85rem; + font-weight: 700; + text-transform: uppercase; + color: var(--primary-color); /* Darker blue header */ + letter-spacing: 0.05em; + text-shadow: var(--hud-text-shadow); +} + +/* Status Steps */ +.status-steps { + display: flex; + flex-direction: column; + gap: 10px; + background: transparent; + padding: 0; +} + +.status-step { + display: flex; + align-items: center; + gap: 12px; + font-size: 0.95rem; + color: var(--text-muted); + font-weight: 600; + text-shadow: var(--hud-text-shadow); + transition: all 0.3s ease; +} + +.status-step .dot { + width: 8px; + height: 8px; + border-radius: 50%; + background: rgba(15, 23, 42, 0.3); + border: 1px solid rgba(15, 23, 42, 0.5); + transition: all 0.3s ease; +} + +.status-step.active { + color: var(--primary-color); +} +.status-step.active .dot { + background: var(--primary-color); + box-shadow: 0 0 8px var(--primary-color); + border-color: var(--primary-color); +} + +.status-step.completed { + color: var(--accent-success); +} +.status-step.completed .dot { + background: var(--accent-success); + border-color: var(--accent-success); +} + +.status-step.error { + color: var(--accent-error); +} +.status-step.error .dot { + background: var(--accent-error); + border-color: var(--accent-error); +} + +/* Plan steps list (translucent backdrop for readability) */ +.plan-list { + background: rgba(255, 255, 255, 0.65); + backdrop-filter: blur(8px); + border: 1px solid rgba(0, 0, 0, 0.08); + border-radius: 10px; + max-height: 160px; + overflow-y: auto; + padding: 10px; + display: flex; + flex-direction: column; + gap: 6px; + box-shadow: 0 4px 20px rgba(0,0,0,0.05); +} + +.plan-item { + font-size: 0.85rem; + padding: 8px 10px; + background: rgba(255, 255, 255, 0.4); + border-radius: 6px; + border-left: 3px solid rgba(0, 0, 0, 0.1); + color: var(--text-main); + font-weight: 500; + display: flex; + justify-content: space-between; +} + +.plan-item.active { + background: rgba(37, 99, 235, 0.08); + border-left-color: var(--primary-color); + color: var(--primary-color); + font-weight: 600; +} + +.plan-item.completed { + border-left-color: var(--accent-success); + color: rgba(15, 23, 42, 0.4); + text-decoration: line-through; + opacity: 0.6; +} + +/* Scrollable Log Console (translucent backdrop for readability) */ +.log-console { + background: rgba(255, 255, 255, 0.65); + backdrop-filter: blur(8px); + border: 1px solid rgba(0, 0, 0, 0.08); + font-family: 'Space Grotesk', monospace; + font-size: 0.85rem; + line-height: 1.4; + border-radius: 10px; + padding: 12px; + overflow-y: auto; + flex-grow: 1; + display: flex; + flex-direction: column; + gap: 6px; + box-shadow: 0 4px 20px rgba(0,0,0,0.05); +} + +.log-entry { + color: var(--text-main); + font-weight: 600; +} +.log-entry.info { color: #1e3a8a; } +.log-entry.success { color: #064e3b; } +.log-entry.warn { color: #78350f; } +.log-entry.error { color: #7f1d1d; } + +.placeholder-text { + color: var(--text-muted); + font-style: italic; + text-align: center; + margin: auto; +} + +/* Floating Chat Input Box */ +.chat-container { + position: absolute; + bottom: 30px; + left: calc(50% + 185px); + transform: translateX(-50%); + width: 650px; + z-index: 10; + padding: 12px; + display: flex; + flex-direction: column; + gap: 12px; + pointer-events: auto; +} + +#chat-form { + display: flex; + gap: 12px; + align-items: center; +} + +#chat-input { + flex-grow: 1; + background: rgba(255, 255, 255, 0.75); /* Highly readable text entry */ + backdrop-filter: blur(10px); + border: 2px solid var(--primary-color); + box-shadow: 0 4px 20px rgba(0,0,0,0.08); + padding: 14px 20px; + border-radius: 12px; + color: #0f172a; + font-size: 1rem; + font-weight: 600; + outline: none; + transition: all 0.3s ease; +} + +#chat-input:focus { + border-color: #1d4ed8; + background: rgba(255, 255, 255, 0.9); + box-shadow: 0 0 15px rgba(37, 99, 235, 0.3); +} + +#submit-btn { + background: var(--primary-color); + color: white; + border: none; + width: 50px; + height: 50px; + border-radius: 12px; + cursor: pointer; + display: flex; + justify-content: center; + align-items: center; + transition: all 0.3s ease; + box-shadow: 0 4px 12px var(--primary-glow); +} + +#submit-btn:hover { + background: #1d4ed8; + box-shadow: 0 4px 20px rgba(29, 78, 216, 0.5); + transform: translateY(-1px); +} + +#submit-btn:active { + transform: translateY(1px); +} + +#submit-btn:disabled, #chat-input:disabled { + opacity: 0.4; + cursor: not-allowed; + box-shadow: none; +} + +.chat-options { + display: flex; + justify-content: space-between; + align-items: center; + font-size: 0.85rem; + color: #0f172a; + font-weight: 600; + text-shadow: var(--hud-text-shadow); +} + +/* Toggle Switch */ +.toggle-switch { + display: flex; + align-items: center; + gap: 8px; + cursor: pointer; +} + +.toggle-switch input { + display: none; +} + +.slider { + position: relative; + display: inline-block; + width: 36px; + height: 20px; + background-color: rgba(15, 23, 42, 0.2); + border-radius: 20px; + transition: .4s; + border: 1px solid rgba(0, 0, 0, 0.2); +} + +.slider:before { + position: absolute; + content: ""; + height: 12px; + width: 12px; + left: 3px; + bottom: 3px; + background-color: #0f172a; + border-radius: 50%; + transition: .4s; +} + +.toggle-switch input:checked + .slider { + background-color: var(--primary-color); + border-color: #1d4ed8; +} + +.toggle-switch input:checked + .slider:before { + background-color: white; + transform: translateX(16px); +} + +.toggle-label { + user-select: none; +} + +/* Buttons */ +.text-btn { + background: none; + border: none; + color: #1d4ed8; + cursor: pointer; + font-weight: 700; + transition: color 0.2s; + font-size: 0.85rem; + text-shadow: var(--hud-text-shadow); +} + +.text-btn:hover { + color: #0f172a; +} + +.primary-btn { + background: var(--primary-color); + color: white; + border: none; + padding: 10px 24px; + border-radius: 8px; + font-weight: 600; + cursor: pointer; + transition: all 0.3s; + box-shadow: 0 4px 12px var(--primary-glow); +} + +.primary-btn:hover { + background: #1d4ed8; + box-shadow: 0 4px 20px rgba(29, 78, 216, 0.4); +} + +/* Header overlays */ +.header-overlay { + position: absolute; + top: 20px; + left: 390px; + right: 20px; + z-index: 10; + pointer-events: none; +} + +.header-overlay h1 { + font-family: 'Space Grotesk', sans-serif; + font-size: 1.4rem; + font-weight: 700; + letter-spacing: -0.015em; + color: #0f172a; + text-shadow: var(--hud-text-shadow); + margin-bottom: 4px; +} + +.header-overlay p { + font-size: 0.85rem; + color: var(--text-muted); + text-shadow: var(--hud-text-shadow); + margin-bottom: 12px; +} + +.preset-badges { + pointer-events: auto; + display: flex; + gap: 8px; + flex-wrap: wrap; +} + +.preset-badge { + background: rgba(255, 255, 255, 0.75); + border: 1.5px solid var(--primary-color); + color: var(--text-main); + font-family: inherit; + font-size: 0.8rem; + font-weight: 600; + padding: 6px 14px; + border-radius: 8px; + cursor: pointer; + transition: all 0.2s; + box-shadow: 0 2px 10px rgba(0,0,0,0.05); +} + +.preset-badge:hover { + background: rgba(255, 255, 255, 0.95); + border-color: #1d4ed8; + box-shadow: 0 4px 15px rgba(37, 99, 235, 0.2); + transform: translateY(-1px); +} + +/* Modal Overlay for Score Card */ +.modal-overlay { + position: fixed; + top: 0; + left: 0; + width: 100vw; + height: 100vh; + background: rgba(15, 23, 42, 0.45); + backdrop-filter: blur(10px); + z-index: 1000; + display: flex; + justify-content: center; + align-items: center; + opacity: 1; + transition: opacity 0.3s ease; +} + +.modal-overlay.hidden { + opacity: 0; + pointer-events: none; +} + +.modal-content { + width: 500px; + max-width: 90%; + padding: 30px; + display: flex; + flex-direction: column; + gap: 20px; + background: rgba(255, 255, 255, 0.9) !important; + border: 2px solid var(--primary-color) !important; + box-shadow: 0 10px 40px rgba(0, 0, 0, 0.2) !important; + border-radius: 16px; + animation: scaleUp 0.3s cubic-bezier(0.34, 1.56, 0.64, 1); +} + +@keyframes scaleUp { + from { transform: scale(0.9); opacity: 0; } + to { transform: scale(1); opacity: 1; } +} + +.modal-content h2 { + font-family: 'Space Grotesk', sans-serif; + font-size: 1.5rem; + text-align: center; + border-bottom: 2px solid rgba(37, 99, 235, 0.2); + padding-bottom: 12px; + color: #0f172a; +} + +.score-md-content { + font-size: 0.95rem; + line-height: 1.6; + color: #334155; +} + +.score-md-content h3 { + margin: 14px 0 6px 0; + font-size: 1.15rem; + color: #1d4ed8; +} + +.score-md-content ul { + padding-left: 20px; + margin-bottom: 10px; +} + +.score-md-content li { + margin-bottom: 4px; +} + +.score-md-content strong { + color: #0f172a; +} + +/* Scrollbars styling */ +::-webkit-scrollbar { + width: 6px; +} + +::-webkit-scrollbar-track { + background: transparent; +} + +::-webkit-scrollbar-thumb { + background: rgba(37, 99, 235, 0.25); + border-radius: 3px; +} + +::-webkit-scrollbar-thumb:hover { + background: rgba(37, 99, 235, 0.45); +} diff --git a/.history/frontend/index_20260627225036.html b/.history/frontend/index_20260627225036.html new file mode 100644 index 0000000000000000000000000000000000000000..d5fe8403a8548620a7392d2d2f3274f7cc5259c4 --- /dev/null +++ b/.history/frontend/index_20260627225036.html @@ -0,0 +1,125 @@ + + + + + + LLM-Panda Web-Embedded PyBullet Simulation + + + + + + + + + + + + + + +
    + +
    + + + + + +
    +
    + + +
    +
    + + + +
    +
    + + +
    +

    Web-Embedded PyBullet Interface

    +

    Tương tác trực tiếp: Kéo chuột trái để xoay camera, Kéo chuột phải để di chuyển camera, Cuộn chuột để Zoom

    +
    + + + +
    +
    + + + + + + + + diff --git a/.history/frontend/index_20260627231836.html b/.history/frontend/index_20260627231836.html new file mode 100644 index 0000000000000000000000000000000000000000..52d201ca7f9b23617281509f8cb319754add4ec1 --- /dev/null +++ b/.history/frontend/index_20260627231836.html @@ -0,0 +1,1177 @@ +// ─── WebSocket and Visualizer Setup ──────────────────────────────────────── +const canvas = document.getElementById('pybullet-viewport'); +// Three.js Core Variables +let renderer, scene, camera, controls; +let robotGroup, tableMesh, trayMesh; +const slotHelpers = []; +const joints = {}; +const ycbMeshes = {}; +let transformControls = null; +let eeDummy = null; +const OBJ_LOADER = new THREE.OBJLoader(); +const MTL_LOADER = new THREE.MTLLoader(); +let socket = null; +let currentPrompt = ''; +function initVisualizer() { + // Set default coordinate system to Z-up + THREE.Object3D.DefaultUp.set(0, 0, 1); + // Renderer + renderer = new THREE.WebGLRenderer({ canvas: canvas, antialias: true }); + const width = canvas.clientWidth || window.innerWidth; + const height = canvas.clientHeight || window.innerHeight; + renderer.setSize(width, height, false); + renderer.setPixelRatio(window.devicePixelRatio); + renderer.shadowMap.enabled = true; + // Scene + scene = new THREE.Scene(); + scene.background = new THREE.Color('#f1f5f9'); // Light smoke gray background + // Camera + camera = new THREE.PerspectiveCamera(50, width / height, 0.1, 100); + // Position camera to look down at the table, matching PyBullet default view + camera.position.set(1.2, -1.2, 1.2); + // Controls + controls = new THREE.OrbitControls(camera, renderer.domElement); + controls.target.set(0.5, 0.0, 0.2); + controls.enableDamping = true; + controls.dampingFactor = 0.05; + controls.maxPolarAngle = Math.PI / 2 - 0.02; // do not go below table plane + controls.update(); + // Lights + const ambientLight = new THREE.AmbientLight(0xffffff, 0.7); + scene.add(ambientLight); + const dirLight = new THREE.DirectionalLight(0xffffff, 0.85); + dirLight.position.set(2, -2, 4); + dirLight.castShadow = true; + dirLight.shadow.mapSize.width = 1024; + dirLight.shadow.mapSize.height = 1024; + dirLight.shadow.camera.near = 0.5; + dirLight.shadow.camera.far = 15; + scene.add(dirLight); + const dirLight2 = new THREE.DirectionalLight(0xaaccff, 0.35); + dirLight2.position.set(-2, 2, 2); + scene.add(dirLight2); + // Floor plane + const planeGeo = new THREE.PlaneGeometry(10, 10); + const planeMat = new THREE.MeshStandardMaterial({ color: 0xe2e8f0, roughness: 0.85 }); + const plane = new THREE.Mesh(planeGeo, planeMat); + plane.receiveShadow = true; + scene.add(plane); + // Caro background / Grid Helper + const gridHelper = new THREE.GridHelper(10, 100, 0x94a3b8, 0xcbd5e1); + gridHelper.rotation.x = Math.PI / 2; + gridHelper.position.z = 0.001; + scene.add(gridHelper); + // Axes helper (X: Red, Y: Green, Z: Blue) + const axesHelper = new THREE.AxesHelper(0.5); + axesHelper.position.z = 0.002; + scene.add(axesHelper); + // Initialize Transform Controls + transformControls = new THREE.TransformControls(camera, renderer.domElement); + transformControls.addEventListener('dragging-changed', function (event) { + controls.enabled = !event.value; + if (!event.value && transformControls.object && transformControls.object !== eeDummy) { + const obj = transformControls.object; + if (socket && socket.readyState === WebSocket.OPEN) { + const pos = [obj.position.x, obj.position.y, obj.position.z]; + const ori = [obj.quaternion.x, obj.quaternion.y, obj.quaternion.z, obj.quaternion.w]; + socket.send(JSON.stringify({ + type: "update_object_pose", + name: obj.name, + pos: pos, + ori: ori + })); + writeLog(`Đã đặt vật thể ${obj.name} xuống vị trí mới.`, "success"); + } + } + }); + transformControls.addEventListener('change', function () { + if (transformControls.object) { + const obj = transformControls.object; + if (obj === eeDummy) { + if (socket && socket.readyState === WebSocket.OPEN) { + socket.send(JSON.stringify({ + type: "update_robot_ee", + pos: [eeDummy.position.x, eeDummy.position.y, eeDummy.position.z] + })); + } + } else { + obj.position.x = Math.max(0.15, Math.min(0.85, obj.position.x)); + obj.position.y = Math.max(-0.65, Math.min(0.65, obj.position.y)); + obj.position.z = Math.max(0.02, Math.min(0.85, obj.position.z)); + if (targetObjects[obj.name]) { + targetObjects[obj.name].pos.copy(obj.position); + } + } + } + }); + scene.add(transformControls); + // Start animation loop + animate(); +} +let targetJoints = null; +const targetObjects = {}; +let isInitialStateSynced = false; +function animate() { + requestAnimationFrame(animate); + if (controls) controls.update(); + + // Smooth interpolation (Lerp / Slerp) to eliminate visual stutter + if (targetJoints && targetJoints.length >= 11) { + if (!isInitialStateSynced) { + // First tick or after reset: snap immediately to avoid sliding from rest position + joints.joint1.rotation.z = targetJoints[0]; + joints.joint2.rotation.z = targetJoints[1]; + joints.joint3.rotation.z = targetJoints[2]; + joints.joint4.rotation.z = targetJoints[3]; + joints.joint5.rotation.z = targetJoints[4]; + joints.joint6.rotation.z = targetJoints[5]; + joints.joint7.rotation.z = targetJoints[6]; + joints.fingerJoint1.position.y = targetJoints[9]; + joints.fingerJoint2.position.y = -targetJoints[10]; + + Object.entries(targetObjects).forEach(([name, target]) => { + if (transformControls && transformControls.object && transformControls.object.name === name) return; + const group = ycbMeshes[name]; + if (group) { + group.position.copy(target.pos); + group.quaternion.copy(target.ori); + } + }); + isInitialStateSynced = true; + } else { + // Incremental interpolation towards target poses at client framerate (60+ FPS) + const lerpFactor = 0.15; // Balanced tracking speed vs smoothness + joints.joint1.rotation.z = THREE.MathUtils.lerp(joints.joint1.rotation.z, targetJoints[0], lerpFactor); + joints.joint2.rotation.z = THREE.MathUtils.lerp(joints.joint2.rotation.z, targetJoints[1], lerpFactor); + joints.joint3.rotation.z = THREE.MathUtils.lerp(joints.joint3.rotation.z, targetJoints[2], lerpFactor); + joints.joint4.rotation.z = THREE.MathUtils.lerp(joints.joint4.rotation.z, targetJoints[3], lerpFactor); + joints.joint5.rotation.z = THREE.MathUtils.lerp(joints.joint5.rotation.z, targetJoints[4], lerpFactor); + joints.joint6.rotation.z = THREE.MathUtils.lerp(joints.joint6.rotation.z, targetJoints[5], lerpFactor); + joints.joint7.rotation.z = THREE.MathUtils.lerp(joints.joint7.rotation.z, targetJoints[6], lerpFactor); + + joints.fingerJoint1.position.y = THREE.MathUtils.lerp(joints.fingerJoint1.position.y, targetJoints[9], lerpFactor); + joints.fingerJoint2.position.y = THREE.MathUtils.lerp(joints.fingerJoint2.position.y, -targetJoints[10], lerpFactor); + + Object.entries(targetObjects).forEach(([name, target]) => { + if (transformControls && transformControls.object && transformControls.object.name === name) return; + const group = ycbMeshes[name]; + if (group) { + group.position.lerp(target.pos, lerpFactor); + group.quaternion.slerp(target.ori, lerpFactor); + } + }); + } + } + // Update joint sliders to match current animation if user is not actively dragging them + const activeEl = document.activeElement; + const isEditingSliders = activeEl && activeEl.id && activeEl.id.startsWith('slider-'); + if (!isEditingSliders && targetJoints) { + const j1 = document.getElementById('slider-j1'); + if (j1) j1.value = joints.joint1.rotation.z.toFixed(2); + const v1 = document.getElementById('val-j1'); + if (v1) v1.textContent = joints.joint1.rotation.z.toFixed(2); + + const j2 = document.getElementById('slider-j2'); + if (j2) j2.value = joints.joint2.rotation.z.toFixed(2); + const v2 = document.getElementById('val-j2'); + if (v2) v2.textContent = joints.joint2.rotation.z.toFixed(2); + + const j3 = document.getElementById('slider-j3'); + if (j3) j3.value = joints.joint3.rotation.z.toFixed(2); + const v3 = document.getElementById('val-j3'); + if (v3) v3.textContent = joints.joint3.rotation.z.toFixed(2); + + const j4 = document.getElementById('slider-j4'); + if (j4) j4.value = joints.joint4.rotation.z.toFixed(2); + const v4 = document.getElementById('val-j4'); + if (v4) v4.textContent = joints.joint4.rotation.z.toFixed(2); + + const j5 = document.getElementById('slider-j5'); + if (j5) j5.value = joints.joint5.rotation.z.toFixed(2); + const v5 = document.getElementById('val-j5'); + if (v5) v5.textContent = joints.joint5.rotation.z.toFixed(2); + + const j6 = document.getElementById('slider-j6'); + if (j6) j6.value = joints.joint6.rotation.z.toFixed(2); + const v6 = document.getElementById('val-j6'); + if (v6) v6.textContent = joints.joint6.rotation.z.toFixed(2); + + const j7 = document.getElementById('slider-j7'); + if (j7) j7.value = joints.joint7.rotation.z.toFixed(2); + const v7 = document.getElementById('val-j7'); + if (v7) v7.textContent = joints.joint7.rotation.z.toFixed(2); + + const jg = document.getElementById('slider-jg'); + if (jg) jg.value = joints.fingerJoint1.position.y.toFixed(3); + const vg = document.getElementById('val-jg'); + if (vg) vg.textContent = joints.fingerJoint1.position.y.toFixed(3); + } + + // Align eeDummy position to handJoint if not being dragged + if (eeDummy && joints.handJoint && (!transformControls || !transformControls.object || transformControls.object !== eeDummy)) { + const handWorldPos = new THREE.Vector3(); + joints.handJoint.getWorldPosition(handWorldPos); + eeDummy.position.copy(handWorldPos); + } + + renderer.render(scene, camera); +} +// Window resizing +window.addEventListener('resize', () => { + const width = canvas.clientWidth; + const height = canvas.clientHeight; + if (canvas.width !== width || canvas.height !== height) { + renderer.setSize(width, height, false); + camera.aspect = width / height; + camera.updateProjectionMatrix(); + } +}); +// ─── Three.js Scene Construction ──────────────────────────────────────────── +function createTable(tableConfig) { + if (tableMesh) scene.remove(tableMesh); + const ext = tableConfig.half_extents; + const geo = new THREE.BoxGeometry(ext[0] * 2, ext[1] * 2, ext[2] * 2); + const color = new THREE.Color().fromArray(tableConfig.color.slice(0, 3)); + const mat = new THREE.MeshStandardMaterial({ color: color, roughness: 0.6, metalness: 0.1 }); + tableMesh = new THREE.Mesh(geo, mat); + tableMesh.position.set(tableConfig.center[0], tableConfig.center[1], tableConfig.center[2]); + tableMesh.castShadow = true; + tableMesh.receiveShadow = true; + scene.add(tableMesh); +} +function createTray(trayConfig) { + if (trayMesh) scene.remove(trayMesh); + const ext = trayConfig.half_extents; + const geo = new THREE.BoxGeometry(ext[0] * 2, ext[1] * 2, ext[2] * 2); + const color = new THREE.Color().fromArray(trayConfig.color.slice(0, 3)); + const mat = new THREE.MeshStandardMaterial({ color: color, roughness: 0.7 }); + trayMesh = new THREE.Mesh(geo, mat); + trayMesh.position.set(trayConfig.position[0], trayConfig.position[1], trayConfig.position[2] - ext[2]); + trayMesh.castShadow = true; + trayMesh.receiveShadow = true; + scene.add(trayMesh); +} +function createSlotHelpers(slots) { + slotHelpers.forEach(mesh => scene.remove(mesh)); + slotHelpers.length = 0; + + const geom = new THREE.RingGeometry(0.045, 0.05, 32); + const mat = new THREE.MeshBasicMaterial({ color: 0x3b82f6, side: THREE.DoubleSide, transparent: true, opacity: 0.45 }); + + Object.entries(slots).forEach(([name, pos]) => { + const ring = new THREE.Mesh(geom, mat); + ring.position.set(pos[0], pos[1], pos[2] + 0.001); // slightly above table + scene.add(ring); + slotHelpers.push(ring); + }); +} +function initRobotStructure() { + if (robotGroup) scene.remove(robotGroup); + robotGroup = new THREE.Group(); + scene.add(robotGroup); + + joints.joint1 = new THREE.Group(); + joints.joint2 = new THREE.Group(); + joints.joint3 = new THREE.Group(); + joints.joint4 = new THREE.Group(); + joints.joint5 = new THREE.Group(); + joints.joint6 = new THREE.Group(); + joints.joint7 = new THREE.Group(); + joints.joint8 = new THREE.Group(); + joints.handJoint = new THREE.Group(); + joints.fingerJoint1 = new THREE.Group(); + joints.fingerJoint2 = new THREE.Group(); + + const link0 = new THREE.Group(); + const link1 = new THREE.Group(); + const link2 = new THREE.Group(); + const link3 = new THREE.Group(); + const link4 = new THREE.Group(); + const link5 = new THREE.Group(); + const link6 = new THREE.Group(); + const link7 = new THREE.Group(); + const link8 = new THREE.Group(); + const hand = new THREE.Group(); + const leftFinger = new THREE.Group(); + const rightFinger = new THREE.Group(); + + robotGroup.add(link0); + + link0.add(joints.joint1); + joints.joint1.position.set(0, 0, 0.333); + joints.joint1.add(link1); + + link1.add(joints.joint2); + joints.joint2.position.set(0, 0, 0); + joints.joint2.rotation.set(-1.57079632679, 0, 0); + joints.joint2.add(link2); + + link2.add(joints.joint3); + joints.joint3.position.set(0, -0.316, 0); + joints.joint3.rotation.set(1.57079632679, 0, 0); + joints.joint3.add(link3); + + link3.add(joints.joint4); + joints.joint4.position.set(0.0825, 0, 0); + joints.joint4.rotation.set(1.57079632679, 0, 0); + joints.joint4.add(link4); + + link4.add(joints.joint5); + joints.joint5.position.set(-0.0825, 0.384, 0); + joints.joint5.rotation.set(-1.57079632679, 0, 0); + joints.joint5.add(link5); + + link5.add(joints.joint6); + joints.joint6.position.set(0, 0, 0); + joints.joint6.rotation.set(1.57079632679, 0, 0); + joints.joint6.add(link6); + + link6.add(joints.joint7); + joints.joint7.position.set(0.088, 0, 0); + joints.joint7.rotation.set(1.57079632679, 0, 0); + joints.joint7.add(link7); + + link7.add(joints.joint8); + joints.joint8.position.set(0, 0, 0.107); + joints.joint8.add(link8); + + link8.add(joints.handJoint); + joints.handJoint.position.set(0, 0, 0); + joints.handJoint.rotation.set(0, 0, -0.785398163397); + joints.handJoint.add(hand); + + hand.add(joints.fingerJoint1); + joints.fingerJoint1.position.set(0, 0, 0.0584); + joints.fingerJoint1.add(leftFinger); + + hand.add(joints.fingerJoint2); + joints.fingerJoint2.position.set(0, 0, 0.0584); + joints.fingerJoint2.add(rightFinger); + + const defaultPandaMaterial = new THREE.MeshStandardMaterial({ + color: 0xdddddd, + roughness: 0.35, + metalness: 0.15 + }); + const loadModel = (parent, objPath, mtlPath = null, rotateRightFinger = false) => { + const applyRotation = (obj) => { + if (rotateRightFinger) { + obj.rotation.z = Math.PI; + } + parent.add(obj); + }; + if (mtlPath) { + MTL_LOADER.load(mtlPath, (materials) => { + materials.preload(); + + const objLoader = new THREE.OBJLoader(); + objLoader.setMaterials(materials); + objLoader.load(objPath, (obj) => { + obj.traverse(child => { + if (child.isMesh) { + child.castShadow = true; + child.receiveShadow = true; + } + }); + applyRotation(obj); + }); + }); + } else { + const objLoader = new THREE.OBJLoader(); + objLoader.load(objPath, (obj) => { + obj.traverse(child => { + if (child.isMesh) { + child.material = defaultPandaMaterial; + child.castShadow = true; + child.receiveShadow = true; + } + }); + applyRotation(obj); + }); + } + }; + loadModel(link0, '/assets/panda/meshes/collision/link0.obj'); + loadModel(link1, '/assets/panda/meshes/visual/link1.obj', '/assets/panda/meshes/visual/link1.mtl'); + loadModel(link2, '/assets/panda/meshes/visual/link2.obj', '/assets/panda/meshes/visual/link2.mtl'); + loadModel(link3, '/assets/panda/meshes/visual/link3.obj', '/assets/panda/meshes/visual/link3.mtl'); + loadModel(link4, '/assets/panda/meshes/visual/link4.obj', '/assets/panda/meshes/visual/link4.mtl'); + loadModel(link5, '/assets/panda/meshes/visual/link5.obj', '/assets/panda/meshes/visual/link5.mtl'); + loadModel(link6, '/assets/panda/meshes/visual/link6.obj', '/assets/panda/meshes/visual/link6.mtl'); + loadModel(link7, '/assets/panda/meshes/collision/link7.obj'); + loadModel(hand, '/assets/panda/meshes/visual/hand.obj', '/assets/panda/meshes/visual/hand.mtl'); + loadModel(leftFinger, '/assets/panda/meshes/visual/finger.obj', '/assets/panda/meshes/visual/finger.mtl'); + loadModel(rightFinger, '/assets/panda/meshes/visual/finger.obj', '/assets/panda/meshes/visual/finger.mtl', true); + // Create eeDummy sphere representing the end-effector target + if (eeDummy) scene.remove(eeDummy); + const dummyGeo = new THREE.SphereGeometry(0.035, 16, 16); + const dummyMat = new THREE.MeshStandardMaterial({ + color: 0x3b82f6, + transparent: true, + opacity: 0.65, + roughness: 0.1, + metalness: 0.9 + }); + eeDummy = new THREE.Mesh(dummyGeo, dummyMat); + eeDummy.name = 'robot'; + eeDummy.visible = false; + scene.add(eeDummy); +} +function loadYcbObjects(objectsConfig) { + // Clear old meshes/groups from scene + Object.values(ycbMeshes).forEach(group => scene.remove(group)); + for (const key in ycbMeshes) delete ycbMeshes[key]; + + Object.entries(objectsConfig).forEach(([name, config]) => { + const folder = config.folder; + let objFile = ""; + let mtlFile = ""; + + if (folder === "YcbBanana" || folder === "YcbTomatoSoupCan" || folder === "YcbCrackerBox" || folder === "YcbMustardBottle" || folder === "YcbPottedMeatCan") { + objFile = `/assets/ycb/${folder}/textured_simple_reoriented.obj`; + mtlFile = `/assets/ycb/${folder}/textured_simple_reoriented.mtl`; + } else if (folder === "YcbChipsCan") { + objFile = `/assets/ycb/${folder}/textured.obj`; + mtlFile = `/assets/ycb/${folder}/textured.mtl`; + } + + if (!objFile) return; + // Create a parent group to represent the object's body link pose + const objectGroup = new THREE.Group(); + objectGroup.name = name; + objectGroup.position.fromArray(config.initial_pos); + objectGroup.quaternion.fromArray(config.initial_ori); + scene.add(objectGroup); + ycbMeshes[name] = objectGroup; + // 1. Load Visual Mesh + MTL_LOADER.load(mtlFile, (materials) => { + materials.preload(); + + const objLoader = new THREE.OBJLoader(); + objLoader.setMaterials(materials); + objLoader.load(objFile, (visObj) => { + visObj.traverse(child => { + if (child.isMesh) { + child.castShadow = true; + child.receiveShadow = true; + } + }); + + // Position, rotate and scale relative to parent group + if (config.vis_local_pos) visObj.position.fromArray(config.vis_local_pos); + if (config.vis_local_ori) visObj.quaternion.fromArray(config.vis_local_ori); + if (config.vis_scale) visObj.scale.fromArray(config.vis_scale); + + objectGroup.add(visObj); + }); + }); + // 2. Load Collision Mesh (Semi-transparent Blue) + const collObjFile = `/assets/ycb/${folder}/collision_vhacd.obj`; + const collLoader = new THREE.OBJLoader(); + collLoader.load(collObjFile, (collObj) => { + collObj.traverse(child => { + if (child.isMesh) { + child.material = new THREE.MeshStandardMaterial({ + color: 0x0000ff, // blue + transparent: true, + opacity: 0.5, // semi-transparent + roughness: 0.4, + metalness: 0.1 + }); + child.castShadow = true; + child.receiveShadow = true; + } + }); + + // Position, rotate and scale relative to parent group + if (config.coll_local_pos) collObj.position.fromArray(config.coll_local_pos); + if (config.coll_local_ori) collObj.quaternion.fromArray(config.coll_local_ori); + if (config.coll_scale) collObj.scale.fromArray(config.coll_scale); + + objectGroup.add(collObj); + }); + }); +} +function updateSimulationState(jointsData, objectsData) { + if (jointsData && jointsData.length >= 11) { + targetJoints = jointsData; + } + + if (objectsData) { + Object.entries(objectsData).forEach(([name, data]) => { + targetObjects[name] = { + pos: new THREE.Vector3().fromArray(data.pos), + ori: new THREE.Quaternion().fromArray(data.ori) + }; + }); + } +} +let reconnectTimeout = null; +function connectWebSocket() { + if (reconnectTimeout) { + clearTimeout(reconnectTimeout); + reconnectTimeout = null; + } + const guiToggle = document.getElementById('gui-toggle'); + const showGui = guiToggle ? guiToggle.checked : false; + const wsProtocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:'; + const wsUrl = `${wsProtocol}//${window.location.host}/ws?gui=${showGui}`; + + updateBadgeStatus('disconnected'); + + socket = new WebSocket(wsUrl); + socket.onopen = () => { + console.log("WebSocket connected."); + updateBadgeStatus('connected'); + writeLog("Kết nối thành công đến Backend server.", "success"); + }; + socket.onmessage = (event) => { + const msg = JSON.parse(event.data); + handleSocketMessage(msg); + }; + socket.onclose = () => { + console.log("WebSocket disconnected."); + updateBadgeStatus('disconnected'); + writeLog("Mất kết nối đến Backend server. Đang thử kết nối lại...", "error"); + reconnectTimeout = setTimeout(connectWebSocket, 3000); + }; + socket.onerror = (err) => { + console.error("WebSocket Error: ", err); + }; +} +function handleSocketMessage(msg) { + switch(msg.type) { + case 'init': + createTable(msg.table); + createTray(msg.tray); + createSlotHelpers(msg.slots); + loadYcbObjects(msg.objects); + initRobotStructure(); + isInitialStateSynced = false; // Reset sync state for new simulations + break; + + case 'state': + updateSimulationState(msg.joints, msg.objects); + break; + + case 'log': + writeLog(msg.message, getLogClass(msg.message)); + updatePipelineUI(msg.message); + break; + + case 'plan': + displayPlan(msg.plan); + break; + + case 'result': + showRearrangementScore(msg.score_display); + unlockInput(); + + // Add new run record to history log dynamically + const now = new Date(); + const timeStr = now.toTimeString().split(' ')[0]; + const scoreVal = msg.score_value !== undefined ? msg.score_value : 100; + const scoreClass = scoreVal >= 90 ? "high" : (scoreVal >= 60 ? "medium" : "low"); + + historyData.unshift({ + time: timeStr, + operator: "Operator", + prompt: currentPrompt || "Câu lệnh nhanh", + score: scoreVal, + class: scoreClass + }); + renderHistory(); + + // Speak speech feedback + speakFeedback(`Đã hoàn thành vận hành. Điểm rearrangement đạt ${scoreVal} điểm.`); + break; + } +} +// ─── UI Updates and Interactions ──────────────────────────────────────────── +const badge = document.getElementById('connection-badge'); +const logConsole = document.getElementById('log-console'); +const planList = document.getElementById('plan-list'); +const chatInput = document.getElementById('chat-input'); +const submitBtn = document.getElementById('submit-btn'); +const mockToggle = document.getElementById('mock-toggle'); +const guiToggle = document.getElementById('gui-toggle'); +const resetBtn = document.getElementById('reset-btn'); +const scoreModal = document.getElementById('score-modal'); +const scoreContent = document.getElementById('score-md-content'); +const closeModalBtn = document.getElementById('close-modal-btn'); +const ttsToggle = document.getElementById('tts-toggle'); +const autocompletePanel = document.getElementById('autocomplete-panel'); +// 1. Tab switching logic +document.querySelectorAll('.tab-btn').forEach(btn => { + btn.addEventListener('click', () => { + document.querySelectorAll('.tab-btn').forEach(b => b.classList.remove('active')); + document.querySelectorAll('.tab-panel').forEach(p => p.classList.remove('active')); + btn.classList.add('active'); + const tabId = btn.dataset.tab; + document.getElementById(`panel-${tabId}`).classList.add('active'); + }); +}); +// 2. Scenario template click events +document.querySelectorAll('.scenario-card').forEach(card => { + card.addEventListener('click', () => { + const prompt = card.dataset.prompt; + chatInput.value = prompt; + chatInput.focus(); + }); +}); +document.querySelectorAll('.preset-command-item').forEach(item => { + item.addEventListener('click', () => { + const prompt = item.dataset.prompt; + chatInput.value = prompt; + chatInput.focus(); + }); +}); +// 3. Object Catalog Data & Render +const activeObjects = [ + { id: "banana", name: "Quả chuối (YCB)", mass: 0.066, friction: 0.8, trait: "Safe" }, + { id: "soup_can", name: "Lon súp cà chua", mass: 0.349, friction: 0.8, trait: "Safe" }, + { id: "chips_can", name: "Lon snack khoai tây", mass: 0.205, friction: 0.5, trait: "Safe" } +]; +function renderObjectsTable() { + const objectsTableBody = document.getElementById('objects-table-body'); + if (!objectsTableBody) return; + objectsTableBody.innerHTML = activeObjects.map(obj => ` + + ${obj.name}
    ${obj.id} + ${obj.mass} + ${obj.friction} + ${obj.trait} + + `).join(''); +} +// 4. History Logs Data & Render +const historyData = [ + { time: "14:20:15", operator: "Operator", prompt: "gắp lon snack đặt vào khay", score: 100, class: "high" }, + { time: "14:15:32", operator: "Operator", prompt: "dọn dẹp chướng ngại vật ở khay", score: 85, class: "medium" }, + { time: "14:02:10", operator: "Operator", prompt: "gắp quả chuối đặt vào Slot_2", score: 100, class: "high" } +]; +function renderHistory() { + const historyList = document.getElementById('history-list'); + if (!historyList) return; + historyList.innerHTML = historyData.map((item, index) => ` +
    +
    + 🕒 ${item.time} - ${item.operator} + ${item.score}/100 +
    +

    "${item.prompt}"

    + +
    + `).join(''); +} +window.runHistoryPrompt = function(index) { + const item = historyData[index]; + if (item) { + chatInput.value = item.prompt; + chatInput.focus(); + document.getElementById('chat-form').dispatchEvent(new Event('submit')); + } +}; +// 5. Speech Synthesis (Text-to-Speech) +function speakFeedback(text) { + if (!ttsToggle || !ttsToggle.checked) return; + + // Determine language based on text content (Vietnamese by default, English if it contains mostly technical terms) + let lang = 'vi'; + const textLower = text.toLowerCase(); + if (textLower.includes('evaluation') || textLower.includes('score') || textLower.includes('report') || textLower.includes('step') || textLower.includes('verification')) { + lang = 'en'; + } + + // Call Google Translate TTS (free API) for high-quality English & Vietnamese voices + const encodedText = encodeURIComponent(text); + const ttsUrl = `https://translate.google.com/translate_tts?ie=UTF-8&tl=${lang}&client=tw-ob&q=${encodedText}`; + + const audio = new Audio(ttsUrl); + audio.play().catch(err => { + console.warn("Google Translate TTS failed, falling back to local speech synthesis:", err); + if ('speechSynthesis' in window) { + window.speechSynthesis.cancel(); + const utterance = new SpeechSynthesisUtterance(text); + utterance.lang = lang === 'vi' ? 'vi-VN' : 'en-US'; + utterance.rate = 1.0; + utterance.pitch = 1.0; + + const voices = window.speechSynthesis.getVoices(); + const matchingVoice = voices.find(voice => voice.lang.includes(lang)); + if (matchingVoice) utterance.voice = matchingVoice; + + window.speechSynthesis.speak(utterance); + } + }); +} +// 6. Voice Recognition (Speech-to-Text) +const micBtn = document.getElementById('mic-btn'); +let recognition = null; +let isRecording = false; +if ('webkitSpeechRecognition' in window || 'SpeechRecognition' in window) { + const SpeechRecognition = window.SpeechRecognition || window.webkitSpeechRecognition; + recognition = new SpeechRecognition(); + recognition.continuous = false; + recognition.interimResults = false; + recognition.lang = 'vi-VN'; + recognition.onstart = () => { + isRecording = true; + micBtn.classList.add('recording'); + writeLog("Đang nghe giọng nói của bạn... Hãy nói đi.", "info"); + speakFeedback("Tôi đang nghe."); + }; + recognition.onresult = (event) => { + const resultText = event.results[0][0].transcript; + chatInput.value = resultText; + writeLog(`Nhận dạng giọng nói: "${resultText}"`, "success"); + speakFeedback(`Đã nhận diện: ${resultText}`); + }; + recognition.onerror = (event) => { + console.error("Speech Recognition Error: ", event.error); + writeLog("Nhận diện giọng nói gặp lỗi: " + event.error, "warn"); + isRecording = false; + micBtn.classList.remove('recording'); + }; + recognition.onend = () => { + isRecording = false; + micBtn.classList.remove('recording'); + }; + micBtn.addEventListener('click', () => { + if (isRecording) { + recognition.stop(); + } else { + recognition.start(); + } + }); +} else { + micBtn.style.display = 'none'; +} +// 7. Smart Autocomplete suggestions +const autocompleteVocabulary = [ + "gắp quả chuối đặt vào khay", + "gắp quả chuối đặt vào Slot_2", + "gắp quả chuối đặt vào Slot_4", + "gắp lon súp cà chua đặt vào khay", + "gắp lon súp cà chua đặt vào Slot_3", + "gắp lon snack đặt vào khay", + "gắp lon snack đặt vào Slot_6", + "dọn dẹp chướng ngại vật trên bàn", + "sắp xếp lại bàn học tập", + "cất dọn đồ vật nguy hiểm" +]; +if (chatInput && autocompletePanel) { + chatInput.addEventListener('input', (e) => { + const query = e.target.value.toLowerCase().trim(); + if (!query || query.length < 2) { + autocompletePanel.classList.add('hidden'); + return; + } + + const matches = autocompleteVocabulary.filter(item => item.includes(query)).slice(0, 4); + if (matches.length === 0) { + autocompletePanel.classList.add('hidden'); + return; + } + + autocompletePanel.innerHTML = matches.map(match => ` +
    ${match}
    + `).join(''); + autocompletePanel.classList.remove('hidden'); + + document.querySelectorAll('.autocomplete-item').forEach(item => { + item.addEventListener('click', () => { + chatInput.value = item.dataset.value; + autocompletePanel.classList.add('hidden'); + chatInput.focus(); + }); + }); + }); + + document.addEventListener('click', (e) => { + if (!e.target.closest('#chat-form')) { + autocompletePanel.classList.add('hidden'); + } + }); +} +// 8. Log and Pipeline functions +function updateBadgeStatus(status) { + if (status === 'connected') { + badge.className = 'badge online'; + badge.textContent = 'Connected'; + } else { + badge.className = 'badge offline'; + badge.textContent = 'Disconnected'; + } +} +function writeLog(text, className = 'info') { + const entry = document.createElement('div'); + entry.className = `log-entry ${className}`; + entry.textContent = `> ${text}`; + + const placeholder = logConsole.querySelector('.placeholder-text'); + if (placeholder) placeholder.remove(); + logConsole.appendChild(entry); + logConsole.scrollTop = logConsole.scrollHeight; +} +function getLogClass(message) { + if (message.includes('✅')) return 'success'; + if (message.includes('❌')) return 'error'; + if (message.includes('⚠️')) return 'warn'; + if (message.includes('🚀') || message.includes('⏳')) return 'info'; + return ''; +} +function updatePipelineUI(message) { + const stepLlm = document.getElementById('step-llm'); + const stepVal = document.getElementById('step-val'); + const stepExec = document.getElementById('step-exec'); + const stepScore = document.getElementById('step-score'); + if (message.includes('[1/5]')) { + setActiveStep(stepLlm); + } else if (message.includes('✅ [1]')) { + setCompletedStep(stepLlm); + } else if (message.includes('❌ [1]')) { + setErrorStep(stepLlm); + unlockInput(); + speakFeedback("Lập kế hoạch thất bại. Vui lòng kiểm tra lại câu lệnh."); + } + else if (message.includes('[2/5]')) { + setActiveStep(stepVal); + } else if (message.includes('✅ [2]')) { + setCompletedStep(stepVal); + } else if (message.includes('❌ [2]') || message.includes('⚠️ [2]')) { + if (message.includes('❌')) { + setErrorStep(stepVal); + unlockInput(); + speakFeedback("Kế hoạch không hợp lệ. Vi phạm các quy tắc an toàn."); + } else { + stepVal.className = 'status-step active warn'; + } + } + else if (message.includes('[3/5]')) { + setActiveStep(stepExec); + } else if (message.includes('Thực thi thành công')) { + setCompletedStep(stepExec); + } else if (message.includes('Thực thi kết thúc có bước lỗi')) { + setErrorStep(stepExec); + speakFeedback("Quá trình thực thi gặp sự cố va chạm."); + } + else if (message.includes('[5/5]')) { + setActiveStep(stepScore); + } else if (message.includes('Rearrangement Evaluation Report') || message.includes('result')) { + setCompletedStep(stepScore); + unlockInput(); + } +} +function setActiveStep(el) { + el.className = 'status-step active'; +} +function setCompletedStep(el) { + el.className = 'status-step completed'; +} +function setErrorStep(el) { + el.className = 'status-step error'; +} +function displayPlan(plan) { + planList.innerHTML = ''; + plan.forEach(step => { + const item = document.createElement('div'); + item.className = 'plan-item'; + item.id = `plan-step-${step.step}`; + + const argsStr = Object.entries(step.args) + .map(([k, v]) => `${k}:${v}`) + .join(', '); + + item.innerHTML = ` + Step ${step.step}: ${step.skill}(${step.object}) + ${argsStr} + `; + planList.appendChild(item); + }); +} +function showRearrangementScore(markdownText) { + let html = markdownText + .replace(/### (.*)/g, '

    $1

    ') + .replace(/\*\*(.*?)\*\*/g, '$1') + .replace(/- (.*)/g, '
  • $1
  • ') + .replace(/\n\n/g, '
    ') + .replace(/✅/g, '✅') + .replace(/⚠️/g, '⚠️') + .replace(/❌/g, '❌'); + + scoreContent.innerHTML = html; + scoreModal.classList.remove('hidden'); +} +function lockInput() { + chatInput.disabled = true; + submitBtn.disabled = true; + resetBtn.disabled = true; + mockToggle.disabled = true; + if (guiToggle) guiToggle.disabled = true; +} +document.getElementById('chat-form').addEventListener('submit', (e) => { + e.preventDefault(); + const prompt = chatInput.value.trim(); + if (!prompt || !socket || socket.readyState !== WebSocket.OPEN) return; + currentPrompt = prompt; + chatInput.value = ''; + + logConsole.innerHTML = ''; + planList.innerHTML = '

    Đang tải kế hoạch...

    '; + + ['step-llm', 'step-val', 'step-exec', 'step-score'].forEach(id => { + document.getElementById(id).className = 'status-step'; + }); + writeLog(`Gửi yêu cầu: "${prompt}"`, "info"); + lockInput(); + + speakFeedback("Bắt đầu xử lý câu lệnh điều khiển của bạn."); + socket.send(JSON.stringify({ + type: 'run', + prompt: prompt, + mock: mockToggle.checked + })); +}); +function unlockInput() { + chatInput.disabled = false; + submitBtn.disabled = false; + resetBtn.disabled = false; + mockToggle.disabled = false; + if (guiToggle) guiToggle.disabled = false; +} +resetBtn.addEventListener('click', () => { + if (!socket || socket.readyState !== WebSocket.OPEN) return; + + logConsole.innerHTML = ''; + planList.innerHTML = '

    Chưa có kế hoạch...

    '; + + ['step-llm', 'step-val', 'step-exec', 'step-score'].forEach(id => { + document.getElementById(id).className = 'status-step'; + }); + socket.send(JSON.stringify({ + type: 'reset' + })); +}); +closeModalBtn.addEventListener('click', () => { + scoreModal.classList.add('hidden'); + unlockInput(); +}); +if (guiToggle) { + guiToggle.addEventListener('change', () => { + writeLog("Thay đổi thiết lập hiển thị cửa sổ PyBullet. Đang kết nối lại...", "info"); + if (socket) { + socket.onclose = null; + socket.close(); + } + connectWebSocket(); + }); +} +// 10. Manual joint controls sending +function sendManualJoints() { + if (!socket || socket.readyState !== WebSocket.OPEN) return; + const q0 = parseFloat(document.getElementById('slider-j1').value); + const q1 = parseFloat(document.getElementById('slider-j2').value); + const q2 = parseFloat(document.getElementById('slider-j3').value); + const q3 = parseFloat(document.getElementById('slider-j4').value); + const q4 = parseFloat(document.getElementById('slider-j5').value); + const q5 = parseFloat(document.getElementById('slider-j6').value); + const q6 = parseFloat(document.getElementById('slider-j7').value); + const qg = parseFloat(document.getElementById('slider-jg').value); + + socket.send(JSON.stringify({ + type: "update_joints", + joints: [q0, q1, q2, q3, q4, q5, q6, 0.0, 0.0, qg, qg] + })); +} +const slidersList = ['j1', 'j2', 'j3', 'j4', 'j5', 'j6', 'j7', 'jg']; +slidersList.forEach(id => { + const slider = document.getElementById(`slider-${id}`); + const label = document.getElementById(`val-${id}`); + if (slider && label) { + slider.addEventListener('input', (e) => { + const val = parseFloat(e.target.value); + label.textContent = id === 'jg' ? val.toFixed(3) : val.toFixed(2); + sendManualJoints(); + }); + } +}); +// 11. Interactive Drag and Drop for YCB objects and Robot End Effector using THREE.TransformControls +const raycaster = new THREE.Raycaster(); +const mouse = new THREE.Vector2(); +// State variables for Hover Highlight +const originalEmissives = new Map(); +let hoveredGroup = null; +canvas.addEventListener('mousedown', onMouseDown); +canvas.addEventListener('mousemove', onMouseMove); +// Helper to determine if an intersected object belongs to a draggable group (YCB or Robot) +function findDraggableTarget(hitObject) { + let curr = hitObject; + while (curr && curr !== scene) { + if (curr === robotGroup) { + return { type: 'robot', group: robotGroup, name: 'robot' }; + } + const ycbEntry = Object.entries(ycbMeshes).find(([name, group]) => group === curr); + if (ycbEntry) { + return { type: 'ycb', group: ycbEntry[1], name: ycbEntry[0] }; + } + curr = curr.parent; + } + return null; +} +// Helper to set/restore emissive highlight glow on all child meshes of a group +function highlightGroup(group, highlightColor = null) { + if (!group) return; + group.traverse(child => { + if (child.isMesh) { + if (highlightColor) { + if (!originalEmissives.has(child.uuid)) { + if (child.material && child.material.emissive) { + originalEmissives.set(child.uuid, { + color: child.material.emissive.clone(), + material: child.material + }); + } + } + if (child.material && child.material.emissive) { + child.material.emissive.copy(highlightColor); + } + } else { + const orig = originalEmissives.get(child.uuid); + if (orig && orig.material && orig.material.emissive) { + orig.material.emissive.copy(orig.color); + } + } + } + }); +} +function onMouseDown(event) { + if (event.button !== 0 || chatInput.disabled) return; + + // Ignore clicks if we are already dragging the transform controls handles + if (transformControls && transformControls.dragging) return; + const rect = canvas.getBoundingClientRect(); + mouse.x = ((event.clientX - rect.left) / rect.width) * 2 - 1; + mouse.y = -((event.clientY - rect.top) / rect.height) * 2 + 1; + raycaster.setFromCamera(mouse, camera); + const hits = raycaster.intersectObjects(scene.children, true); + let target = null; + + // Check if the click hit the Gizmo itself + for (let i = 0; i < hits.length; i++) { + // Exclude the gizmo meshes themselves + let isGizmo = false; + let p = hits[i].object; + while (p) { + if (p === transformControls) { + isGizmo = true; + break; + // Click is on the gizmo handles; let TransformControls handle it + return; + } + p = p.parent; + } + if (isGizmo) continue; + } + let target = null; + for (let i = 0; i < hits.length; i++) { + const found = findDraggableTarget(hits[i].object); + if (found) { + target = found; + break; + } + } + if (target) { + if (target.type === 'robot') { + if (eeDummy && joints.handJoint) { + const handWorldPos = new THREE.Vector3(); + joints.handJoint.getWorldPosition(handWorldPos); + eeDummy.position.copy(handWorldPos); + eeDummy.visible = true; + + transformControls.attach(eeDummy); + writeLog("Đã kích hoạt Gizmo điều khiển cánh tay robot. Kéo các trục mũi tên để dịch chuyển.", "info"); + } + } else { + if (transformControls.object === eeDummy) { + eeDummy.visible = false; + } + transformControls.attach(target.group); + writeLog(`Đã chọn vật thể: ${target.name}. Kéo các trục mũi tên để dịch chuyển.`, "info"); + } + } else { + if (transformControls && !transformControls.dragging) { + if (transformControls.object === eeDummy) { + eeDummy.visible = false; + } + transformControls.detach(); + } + } +} +function onMouseMove(event) { + if (transformControls && transformControls.dragging) { + return; + } + const rect = canvas.getBoundingClientRect(); + mouse.x = ((event.clientX - rect.left) / rect.width) * 2 - 1; + mouse.y = -((event.clientY - rect.top) / rect.height) * 2 + 1; + raycaster.setFromCamera(mouse, camera); + const hits = raycaster.intersectObjects(scene.children, true); + let hoverTarget = null; + + // Check if the mouse is hovering over the Gizmo itself + for (let i = 0; i < hits.length; i++) { + let isGizmo = false; + let p = hits[i].object; + while (p) { + if (p === transformControls) { + isGizmo = true; + break; + // Let Gizmo handle cursors and mouse interaction + return; + } + p = p.parent; + } + if (isGizmo) continue; + } + let hoverTarget = null; + for (let i = 0; i < hits.length; i++) { + const found = findDraggableTarget(hits[i].object); + if (found) { + hoverTarget = found; + break; + } + } + if (hoverTarget) { + if (hoveredGroup !== hoverTarget.group) { + if (hoveredGroup) { + highlightGroup(hoveredGroup, null); + } + originalEmissives.clear(); + + hoveredGroup = hoverTarget.group; + const glowColor = new THREE.Color(hoverTarget.type === 'robot' ? '#1e40af' : '#2563eb'); + highlightGroup(hoveredGroup, glowColor); + + canvas.style.cursor = 'pointer'; + } + } else { + if (hoveredGroup) { + highlightGroup(hoveredGroup, null); + hoveredGroup = null; + originalEmissives.clear(); + canvas.style.cursor = ''; + } + } +} +// 12. Initial runs +initVisualizer(); +connectWebSocket(); +renderObjectsTable(); +renderHistory(); diff --git a/.history/frontend/index_20260627231838.html b/.history/frontend/index_20260627231838.html new file mode 100644 index 0000000000000000000000000000000000000000..d5fe8403a8548620a7392d2d2f3274f7cc5259c4 --- /dev/null +++ b/.history/frontend/index_20260627231838.html @@ -0,0 +1,125 @@ + + + + + + LLM-Panda Web-Embedded PyBullet Simulation + + + + + + + + + + + + + + +
    + +
    + + + + + +
    +
    + + +
    +
    + + + +
    +
    + + +
    +

    Web-Embedded PyBullet Interface

    +

    Tương tác trực tiếp: Kéo chuột trái để xoay camera, Kéo chuột phải để di chuyển camera, Cuộn chuột để Zoom

    +
    + + + +
    +
    + + + + + + + + diff --git a/.history/frontend/index_20260627231852.html b/.history/frontend/index_20260627231852.html new file mode 100644 index 0000000000000000000000000000000000000000..0f991f6131ca55ca407406b922b75298bb91bb48 --- /dev/null +++ b/.history/frontend/index_20260627231852.html @@ -0,0 +1,388 @@ + + + + + + LLM-Panda Web-Embedded PyBullet Simulation + + + + + + + + + + + + + + + +
    + +
    + + + +
    +
    + + + + + +
    +
    + + + +
    +
    + +
    +

    Mô phỏng điều khiển Franka Panda

    +

    Thao tác: Kéo chuột trái để xoay camera, Kéo chuột phải để di chuyển camera, Cuộn chuột để Zoom

    +
    + + + + + + \ No newline at end of file diff --git a/.history/frontend/index_20260627232058.css b/.history/frontend/index_20260627232058.css new file mode 100644 index 0000000000000000000000000000000000000000..977217e5c93c60f24b3473bfebf6a385d938547b --- /dev/null +++ b/.history/frontend/index_20260627232058.css @@ -0,0 +1,569 @@ +import sys +import os +import json +import asyncio +import math +import time +import threading +from typing import Optional +from fastapi import FastAPI, WebSocket, WebSocketDisconnect +from fastapi.staticfiles import StaticFiles +from fastapi.responses import HTMLResponse +import uvicorn +import cv2 +import numpy as np +import pybullet as pb +# Ensure project source root is in path +PROJECT_SRC = os.path.abspath(os.path.join(os.path.dirname(__file__), "..")) +if PROJECT_SRC not in sys.path: + sys.path.insert(0, PROJECT_SRC) +from dotenv import load_dotenv +load_dotenv() +from main import PandaSimulation, _YCB_CATALOG +from llm_panda.llm_agent import LLMAgent, RemoteLLMPlanner, RuleBasedPlanner +from llm_panda.plan_verifier import PlanVerifier +from llm_panda import config +import pybullet_data +from pybullet_object_models import ycb_objects +app = FastAPI(title="LLM-Panda Web-Embedded PyBullet Simulation") +# Serve static files from the frontend directory itself +static_dir = os.path.dirname(__file__) +app.mount("/static", StaticFiles(directory=static_dir), name="static") +# Mount robot meshes and YCB object assets +panda_data_path = os.path.join(pybullet_data.getDataPath(), "franka_panda") +ycb_data_path = ycb_objects.getDataPath() +app.mount("/assets/panda", StaticFiles(directory=panda_data_path), name="panda") +app.mount("/assets/ycb", StaticFiles(directory=ycb_data_path), name="ycb") +@app.get("/") +async def get(): + html_file = os.path.join(static_dir, "index.html") + if os.path.exists(html_file): + with open(html_file, "r", encoding="utf-8") as f: + return HTMLResponse(content=f.read(), status_code=200) + return HTMLResponse(content="

    index.html not found!

    ", status_code=404) +# Global variables to track the current active simulation, lock, and thread lock +current_sim: Optional[PandaSimulation] = None +executor_lock = asyncio.Lock() +pybullet_lock = threading.RLock() +def get_init_payload(sim: PandaSimulation) -> dict: + """Gathers the initial static geometry and YCB object definitions.""" + with pybullet_lock: + objects_info = {} + if sim and sim.scene: + for oid in sim.scene.object_ids: + name = sim.scene.get_name(oid) + cls = sim.scene.get_class(oid) + folder = "" + for cat_name, cat_cls, cat_folder in _YCB_CATALOG: + if cat_name == name: + folder = cat_folder + break + pos, ori = pb.getBasePositionAndOrientation(oid, physicsClientId=sim.client) + + # Query collision shape data for CoM-to-link offset + collision_data = pb.getCollisionShapeData(oid, -1, physicsClientId=sim.client) + coll_scale = [1.0, 1.0, 1.0] + coll_local_pos = [0.0, 0.0, 0.0] + coll_local_ori = [0.0, 0.0, 0.0, 1.0] + if collision_data: + cd = collision_data[0] + coll_scale = list(cd[3]) + coll_local_pos = list(cd[5]) + coll_local_ori = list(cd[6]) + # Query visual shape data for exact dimensions/scales and offsets relative to link + visual_data = pb.getVisualShapeData(oid, physicsClientId=sim.client) + vis_scale = [1.0, 1.0, 1.0] + vis_local_pos = [0.0, 0.0, 0.0] + vis_local_ori = [0.0, 0.0, 0.0, 1.0] + if visual_data: + vd = visual_data[0] + vis_scale = list(vd[3]) + # Transform visual frame to be relative to CoM: CoM_to_visual = CoM_to_link * link_to_visual + vis_pos_com, vis_ori_com = pb.multiplyTransforms( + coll_local_pos, coll_local_ori, + list(vd[5]), list(vd[6]) + ) + vis_local_pos = list(vis_pos_com) + vis_local_ori = list(vis_ori_com) + + objects_info[name] = { + "class": cls, + "folder": folder, + "initial_pos": list(pos), + "initial_ori": list(ori), + "vis_scale": vis_scale, + "vis_local_pos": vis_local_pos, + "vis_local_ori": vis_local_ori, + "coll_scale": coll_scale, + "coll_local_pos": coll_local_pos, + "coll_local_ori": coll_local_ori + } + return { + "type": "init", + "table": { + "center": [config.TABLE_CENTER[0], config.TABLE_CENTER[1], config.TABLE_BASE_Z], + "half_extents": list(config.TABLE_HALF_EXTENTS), + "color": list(config.TABLE_COLOR), + "top_z": config.TABLE_TOP_Z + }, + "tray": { + "position": list(config.TRAY_POSITION), + "half_extents": list(config.TRAY_HALF_EXTENTS), + "color": list(config.TRAY_COLOR) + }, + "slots": {name: list(pos) for name, pos in config.SLOTS.items()}, + "objects": objects_info + } +def get_simulation_state_payload(sim: PandaSimulation) -> dict: + """Gathers the current robot joint positions and YCB object poses.""" + with pybullet_lock: + if sim is None or sim.client is None or not pb.isConnected(sim.client): + return {} + + # Read all joints (12 joints including arm joints and gripper fingers) + num_joints = pb.getNumJoints(sim.robot_id, physicsClientId=sim.client) + joints_state = [] + for i in range(num_joints): + pos, _, _, _ = pb.getJointState(sim.robot_id, i, physicsClientId=sim.client) + joints_state.append(pos) + + # Read objects pos/ori + objects_state = {} + for oid in sim.scene.object_ids: + name = sim.scene.get_name(oid) + pos, ori = pb.getBasePositionAndOrientation(oid, physicsClientId=sim.client) + objects_state[name] = { + "pos": list(pos), + "ori": list(ori) + } + + return { + "type": "state", + "joints": joints_state, + "objects": objects_state + } +def set_pybullet_window_visibility(visible: bool): + """Finds the PyBullet GUI window on Windows and sets its visibility by moving it on/off-screen.""" + import sys + if sys.platform != "win32": + return False + import ctypes + import time + + EnumWindowsProc = ctypes.WINFUNCTYPE(ctypes.c_bool, ctypes.c_void_p, ctypes.c_void_p) + + for _ in range(30): + found_hwnd = [] + + def foreach_window(hwnd, lParam): + length = ctypes.windll.user32.GetWindowTextLengthW(hwnd) + buff = ctypes.create_unicode_buffer(length + 1) + ctypes.windll.user32.GetWindowTextW(hwnd, buff, length + 1) + title = buff.value + if "bullet physics examplebrowser" in title.lower(): + found_hwnd.append(hwnd) + return False + return True + + ctypes.windll.user32.EnumWindows(EnumWindowsProc(foreach_window), 0) + if found_hwnd: + hwnd = found_hwnd[0] + # Ensure the window is shown/restored from minimized state first (SW_SHOW = 5) + ctypes.windll.user32.ShowWindow(hwnd, 5) + + # SWP_NOSIZE = 0x0001, SWP_NOZORDER = 0x0004 + if visible: + # Move window to visible region + ctypes.windll.user32.SetWindowPos(hwnd, 0, 100, 100, 0, 0, 0x0001 | 0x0004) + else: + # Move window far off-screen to hide it without destroying OpenGL context + ctypes.windll.user32.SetWindowPos(hwnd, 0, -10000, -10000, 0, 0, 0x0001 | 0x0004) + print(f"[Window Visibility] Set PyBullet window (HWND: {hwnd}) visibility to: {visible}", flush=True) + return True + time.sleep(0.1) + return False +def compute_and_format_score(sim: PandaSimulation, plan: list, executed_successfully: bool): + """Calculates rearrangement score based on final object locations and collisions.""" + with pybullet_lock: + score = 100 + details = [] + + # Check target placement if we had a plan + target_location = None + target_object = None + for step in plan: + if step.get("function") in ("place_at", "place_down", "move_to"): + args = step.get("args", {}) + if "location_id" in args: + target_location = args["location_id"] + if step.get("function") == "pick_up": + target_object = step.get("args", {}).get("object_id") + + if target_object and target_location: + obj_id = sim.scene.name_to_id(target_object) + if obj_id is not None: + pos, _ = pb.getBasePositionAndOrientation(obj_id) + current_loc = sim.scene.classify_location(pos) + if current_loc == target_location: + details.append(f"✅ **Đã đặt {target_object} đúng vị trí {target_location}**: +50 điểm") + else: + details.append(f"❌ **{target_object} chưa đến đúng vị trí {target_location} (đang ở {current_loc})**: -50 điểm") + score -= 50 + else: + details.append(f"❌ **Không tìm thấy vật thể {target_object}**: -50 điểm") + score -= 50 + else: + details.append("ℹ️ Không có yêu cầu di chuyển vật thể cụ thể nào được phát hiện.") + + # Knock detection + knocked_count = 0 + for oid in sim.scene.object_ids: + if oid == sim.scene.name_to_id(target_object): + continue + pos, _ = pb.getBasePositionAndOrientation(oid) + loc = sim.scene.classify_location(pos) + if loc == "elsewhere": + name = sim.scene.get_name(oid) + details.append(f"⚠️ **Vật thể '{name}' bị lệch khỏi vị trí quy định**: -15 điểm") + score -= 15 + knocked_count += 1 + + if knocked_count == 0: + details.append("✅ **Không có vật thể nào khác bị va chạm hay xê dịch**: +30 điểm") + else: + score = max(0, score) + + # Execution success + if executed_successfully: + details.append("✅ **Thực thi toàn bộ kế hoạch thành công**: +20 điểm") + else: + details.append("❌ **Thực thi gặp lỗi gián đoạn**: -30 điểm") + score -= 30 + + score = max(0, min(100, score)) + + md = f"### 🏆 Rearrangement Evaluation Report\n\n**Tổng điểm: {score}/100**\n\n**Chi tiết:**\n" + "\n".join([f"- {d}" for d in details]) + return score, md +def run_pipeline_threadsafe(websocket: WebSocket, user_prompt: str, loop, use_mock: bool, camera_state: Optional[dict] = None): + """Runs the planning, validation, execution with image streaming, and scoring.""" + global current_sim + + def log(message: str, step: Optional[int] = None): + try: + print(f"[WS Log] {message}", flush=True) + except Exception: + pass + asyncio.run_coroutine_threadsafe( + websocket.send_json({"type": "log", "message": message, "step": step}), + loop + ) + # Step 1: Planning + log("⏳ [1/5] Đang lập kế hoạch (LLM Planner)...") + + if use_mock: + planner = RuleBasedPlanner() + log("✅ [1] Đang sử dụng RuleBasedPlanner (Offline)") + else: + api_key = os.environ.get("OPENAI_API_KEY") or os.environ.get("LLM_API_KEY") + if not api_key: + log("❌ [1] Lỗi: Không tìm thấy OPENAI_API_KEY / LLM_API_KEY. Vui lòng chọn Mock.") + return + planner = RemoteLLMPlanner() + log(f"✅ [1] Đang sử dụng RemoteLLMPlanner (Model: {planner.model})") + + with pybullet_lock: + current_sim.agent = LLMAgent(planner=planner) + + # Define reachability check for scene state + def reachability_fn(oid): + cls = current_sim.scene.get_class(oid) + try: + grasp_pos, grasp_ori = current_sim.grasp_planner.compute_grasp_pose(oid, cls) + return current_sim.controller.is_reachable(grasp_pos, grasp_ori) + except Exception: + return False + carried_name = current_sim.scene.get_name(current_sim._carried) if current_sim._carried is not None else None + scene_state = current_sim.scene.get_scene_state(reachability_fn=reachability_fn, carried_object=carried_name) + state_text = json.dumps(scene_state, indent=2) + + try: + with pybullet_lock: + plan = current_sim.agent.plan(user_prompt, state_text) + log(f"✅ [1] Đã tạo kế hoạch: {len(plan)} bước.") + except Exception as e: + log(f"❌ [1] Lập kế hoạch thất bại: {e}") + return + # Send steps to client + plan_steps = [] + for idx, step in enumerate(plan, 1): + func = step.get("function") + args = step.get("args", {}) + obj = args.get("object_id") or args.get("location_id") or "" + plan_steps.append({ + "step": idx, + "skill": func, + "object": obj, + "args": args + }) + + asyncio.run_coroutine_threadsafe( + websocket.send_json({"type": "plan", "plan": plan_steps}), + loop + ) + if not plan: + log("⚠️ [1] Kế hoạch rỗng.") + log("⏳ [5/5] Đang tính toán điểm sắp xếp...") + score_val, score_md = compute_and_format_score(current_sim, [], True) + asyncio.run_coroutine_threadsafe( + websocket.send_json({ + "type": "result", + "score_display": score_md, + "score_value": score_val + }), + loop + ) + state_payload = get_simulation_state_payload(current_sim) + if state_payload: + asyncio.run_coroutine_threadsafe(websocket.send_json(state_payload), loop) + return + # Step 2: Validation + log("⏳ [2/5] Đang kiểm tra kế hoạch (Validator)...") + try: + with pybullet_lock: + warnings = PlanVerifier.check(plan, scene_state) + if not warnings: + log("✅ [2] Kế hoạch hợp lệ.") + else: + log(f"⚠️ [2] Validator phát hiện {len(warnings)} cảnh báo.") + for w in warnings: + log(f" - {w}") + except Exception as e: + log(f"❌ [2] Lỗi kiểm tra kế hoạch: {e}") + return + # Step 3: PyBullet Execution (Live!) + log("⏳ [3/5] Đang thực thi hành động của robot...") + + # Hook pb.stepSimulation to capture states during movements + original_step = pb.stepSimulation + last_stream_time = [0.0] + throttle_interval = 0.033 + + def wrapped_step(): + original_step() + if not current_sim.gui: + # Sleep slightly in headless mode to simulate arm speed and avoid freezing + time.sleep(0.001) + curr_time = time.time() + if curr_time - last_stream_time[0] >= throttle_interval: + last_stream_time[0] = curr_time + state_payload = get_simulation_state_payload(current_sim) + if state_payload: + asyncio.run_coroutine_threadsafe( + websocket.send_json(state_payload), + loop + ) + + with pybullet_lock: + pb.stepSimulation = wrapped_step + + executed_successfully = True + try: + # Trigger an initial simulation state transmission + state_payload = get_simulation_state_payload(current_sim) + if state_payload: + asyncio.run_coroutine_threadsafe(websocket.send_json(state_payload), loop) + + for i, step in enumerate(plan, 1): + log(f"🚀 [3/5] Đang chạy bước {i}/{len(plan)}: {step['function']}") + with pybullet_lock: + current_sim._execute(step, verbose=True) + + log("✅ [3] Thực thi thành công toàn bộ kế hoạch.") + except Exception as e: + log(f"❌ Lỗi trong lúc thực thi mô phỏng: {e}") + executed_successfully = False + finally: + with pybullet_lock: + pb.stepSimulation = original_step + + # Send a final state to ensure visual sync + state_payload = get_simulation_state_payload(current_sim) + if state_payload: + asyncio.run_coroutine_threadsafe(websocket.send_json(state_payload), loop) + # Step 5: Scoring + log("⏳ [5/5] Đang tính toán điểm sắp xếp...") + score_val, score_md = compute_and_format_score(current_sim, plan, executed_successfully) + + asyncio.run_coroutine_threadsafe( + websocket.send_json({ + "type": "result", + "score_display": score_md, + "score_value": score_val + }), + loop + ) +@app.websocket("/ws") +async def websocket_endpoint(websocket: WebSocket): + global current_sim + await websocket.accept() + loop = asyncio.get_running_loop() + + # Retrieve user's desktop display preference from client query params + client_wants_gui = websocket.query_params.get("gui", "false").lower() == "true" + + # Force gui = False to run PyBullet completely headless (DIRECT mode) + gui = False + + camera_state = { + "target": [0.5, 0.0, 0.3], + "dist": 1.3, + "yaw": 45.0, + "pitch": -35.0 + } + + async with executor_lock: + def init_sim(): + global current_sim + with pybullet_lock: + is_connected = False + if current_sim is not None and current_sim.client is not None: + try: + is_connected = pb.isConnected(current_sim.client) + except Exception: + is_connected = False + + if is_connected and current_sim.gui == gui: + current_sim.reset_objects(seed=0) + current_sim.controller.reset_to_home() + for _ in range(5): + pb.stepSimulation(physicsClientId=current_sim.client) + else: + if is_connected: + try: + current_sim.disconnect() + except Exception as e: + print(f"[Teardown Error] {e}") + current_sim = PandaSimulation(gui=gui, seed=0) + + await asyncio.to_thread(init_sim) + # Apply the client's visibility preference to show/hide the PyBullet GUI window on the desktop + await asyncio.to_thread(set_pybullet_window_visibility, client_wants_gui) + + # Send static scene configuration + init_payload = await asyncio.to_thread(get_init_payload, current_sim) + await websocket.send_json(init_payload) + # Send the first simulation state to sync objects and joints + state_payload = await asyncio.to_thread(get_simulation_state_payload, current_sim) + if state_payload: + await websocket.send_json(state_payload) + + try: + while True: + data = await websocket.receive_text() + payload = json.loads(data) + + p_type = payload.get("type") + if p_type == "run": + prompt = payload.get("prompt", "") + use_mock = payload.get("mock", False) + asyncio.create_task( + asyncio.to_thread( + run_pipeline_threadsafe, + websocket, + prompt, + loop, + use_mock + ) + ) + + elif p_type == "reset": + async with executor_lock: + def reset_sim(): + with pybullet_lock: + current_sim.reset_objects(seed=0) + current_sim.controller.reset_to_home() + await asyncio.to_thread(reset_sim) + + state_payload = await asyncio.to_thread(get_simulation_state_payload, current_sim) + if state_payload: + await websocket.send_json(state_payload) + await websocket.send_json({"type": "log", "message": "🔄 Đã reset môi trường mô phỏng."}) + + elif p_type == "update_object_pose": + name = payload.get("name") + pos = payload.get("pos") + ori = payload.get("ori") + async with executor_lock: + def move_obj(): + with pybullet_lock: + oid = current_sim.scene.name_to_id(name) + if oid is not None: + pb.resetBasePositionAndOrientation(oid, pos, ori) + await asyncio.to_thread(move_obj) + + state_payload = await asyncio.to_thread(get_simulation_state_payload, current_sim) + if state_payload: + await websocket.send_json(state_payload) + + elif p_type == "update_joints": + joints_data = payload.get("joints") + async with executor_lock: + def move_joints(): + with pybullet_lock: + for idx, q in enumerate(joints_data[:7]): + pb.resetJointState(current_sim.robot_id, idx, q) + if len(joints_data) >= 11: + pb.resetJointState(current_sim.robot_id, 9, joints_data[9]) + pb.resetJointState(current_sim.robot_id, 10, joints_data[10]) + await asyncio.to_thread(move_joints) + + state_payload = await asyncio.to_thread(get_simulation_state_payload, current_sim) + if state_payload: + await websocket.send_json(state_payload) + elif p_type == "update_robot_ee": + pos = payload.get("pos") + async with executor_lock: + def move_robot_ee(): + with pybullet_lock: + link_state = pb.getLinkState( + current_sim.robot_id, + current_sim.controller.ee_index, + physicsClientId=current_sim.client + ) + ee_ori = link_state[1] + + solution = pb.calculateInverseKinematics( + current_sim.robot_id, + current_sim.controller.ee_index, + pos, + ee_ori, + lowerLimits=current_sim.controller._lower_limits, + upperLimits=current_sim.controller._upper_limits, + jointRanges=current_sim.controller._joint_ranges, + restPoses=current_sim.controller._rest_poses, + maxNumIterations=300, + residualThreshold=1e-5, + physicsClientId=current_sim.client + ) + + for idx, q in enumerate(solution[:7]): + pb.resetJointState( + current_sim.robot_id, + idx, + q, + physicsClientId=current_sim.client + ) + await asyncio.to_thread(move_robot_ee) + + state_payload = await asyncio.to_thread(get_simulation_state_payload, current_sim) + if state_payload: + await websocket.send_json(state_payload) + elif p_type in ("camera_rotate", "camera_pan", "camera_zoom"): + pass + + except WebSocketDisconnect: + print("Client disconnected") + except Exception as e: + print(f"WS Exception: {e}") +if __name__ == "__main__": + uvicorn.run("interactive_server:app", host="0.0.0.0", port=8000, reload=False) \ No newline at end of file diff --git a/.history/frontend/index_20260627232102.css b/.history/frontend/index_20260627232102.css new file mode 100644 index 0000000000000000000000000000000000000000..977217e5c93c60f24b3473bfebf6a385d938547b --- /dev/null +++ b/.history/frontend/index_20260627232102.css @@ -0,0 +1,569 @@ +import sys +import os +import json +import asyncio +import math +import time +import threading +from typing import Optional +from fastapi import FastAPI, WebSocket, WebSocketDisconnect +from fastapi.staticfiles import StaticFiles +from fastapi.responses import HTMLResponse +import uvicorn +import cv2 +import numpy as np +import pybullet as pb +# Ensure project source root is in path +PROJECT_SRC = os.path.abspath(os.path.join(os.path.dirname(__file__), "..")) +if PROJECT_SRC not in sys.path: + sys.path.insert(0, PROJECT_SRC) +from dotenv import load_dotenv +load_dotenv() +from main import PandaSimulation, _YCB_CATALOG +from llm_panda.llm_agent import LLMAgent, RemoteLLMPlanner, RuleBasedPlanner +from llm_panda.plan_verifier import PlanVerifier +from llm_panda import config +import pybullet_data +from pybullet_object_models import ycb_objects +app = FastAPI(title="LLM-Panda Web-Embedded PyBullet Simulation") +# Serve static files from the frontend directory itself +static_dir = os.path.dirname(__file__) +app.mount("/static", StaticFiles(directory=static_dir), name="static") +# Mount robot meshes and YCB object assets +panda_data_path = os.path.join(pybullet_data.getDataPath(), "franka_panda") +ycb_data_path = ycb_objects.getDataPath() +app.mount("/assets/panda", StaticFiles(directory=panda_data_path), name="panda") +app.mount("/assets/ycb", StaticFiles(directory=ycb_data_path), name="ycb") +@app.get("/") +async def get(): + html_file = os.path.join(static_dir, "index.html") + if os.path.exists(html_file): + with open(html_file, "r", encoding="utf-8") as f: + return HTMLResponse(content=f.read(), status_code=200) + return HTMLResponse(content="

    index.html not found!

    ", status_code=404) +# Global variables to track the current active simulation, lock, and thread lock +current_sim: Optional[PandaSimulation] = None +executor_lock = asyncio.Lock() +pybullet_lock = threading.RLock() +def get_init_payload(sim: PandaSimulation) -> dict: + """Gathers the initial static geometry and YCB object definitions.""" + with pybullet_lock: + objects_info = {} + if sim and sim.scene: + for oid in sim.scene.object_ids: + name = sim.scene.get_name(oid) + cls = sim.scene.get_class(oid) + folder = "" + for cat_name, cat_cls, cat_folder in _YCB_CATALOG: + if cat_name == name: + folder = cat_folder + break + pos, ori = pb.getBasePositionAndOrientation(oid, physicsClientId=sim.client) + + # Query collision shape data for CoM-to-link offset + collision_data = pb.getCollisionShapeData(oid, -1, physicsClientId=sim.client) + coll_scale = [1.0, 1.0, 1.0] + coll_local_pos = [0.0, 0.0, 0.0] + coll_local_ori = [0.0, 0.0, 0.0, 1.0] + if collision_data: + cd = collision_data[0] + coll_scale = list(cd[3]) + coll_local_pos = list(cd[5]) + coll_local_ori = list(cd[6]) + # Query visual shape data for exact dimensions/scales and offsets relative to link + visual_data = pb.getVisualShapeData(oid, physicsClientId=sim.client) + vis_scale = [1.0, 1.0, 1.0] + vis_local_pos = [0.0, 0.0, 0.0] + vis_local_ori = [0.0, 0.0, 0.0, 1.0] + if visual_data: + vd = visual_data[0] + vis_scale = list(vd[3]) + # Transform visual frame to be relative to CoM: CoM_to_visual = CoM_to_link * link_to_visual + vis_pos_com, vis_ori_com = pb.multiplyTransforms( + coll_local_pos, coll_local_ori, + list(vd[5]), list(vd[6]) + ) + vis_local_pos = list(vis_pos_com) + vis_local_ori = list(vis_ori_com) + + objects_info[name] = { + "class": cls, + "folder": folder, + "initial_pos": list(pos), + "initial_ori": list(ori), + "vis_scale": vis_scale, + "vis_local_pos": vis_local_pos, + "vis_local_ori": vis_local_ori, + "coll_scale": coll_scale, + "coll_local_pos": coll_local_pos, + "coll_local_ori": coll_local_ori + } + return { + "type": "init", + "table": { + "center": [config.TABLE_CENTER[0], config.TABLE_CENTER[1], config.TABLE_BASE_Z], + "half_extents": list(config.TABLE_HALF_EXTENTS), + "color": list(config.TABLE_COLOR), + "top_z": config.TABLE_TOP_Z + }, + "tray": { + "position": list(config.TRAY_POSITION), + "half_extents": list(config.TRAY_HALF_EXTENTS), + "color": list(config.TRAY_COLOR) + }, + "slots": {name: list(pos) for name, pos in config.SLOTS.items()}, + "objects": objects_info + } +def get_simulation_state_payload(sim: PandaSimulation) -> dict: + """Gathers the current robot joint positions and YCB object poses.""" + with pybullet_lock: + if sim is None or sim.client is None or not pb.isConnected(sim.client): + return {} + + # Read all joints (12 joints including arm joints and gripper fingers) + num_joints = pb.getNumJoints(sim.robot_id, physicsClientId=sim.client) + joints_state = [] + for i in range(num_joints): + pos, _, _, _ = pb.getJointState(sim.robot_id, i, physicsClientId=sim.client) + joints_state.append(pos) + + # Read objects pos/ori + objects_state = {} + for oid in sim.scene.object_ids: + name = sim.scene.get_name(oid) + pos, ori = pb.getBasePositionAndOrientation(oid, physicsClientId=sim.client) + objects_state[name] = { + "pos": list(pos), + "ori": list(ori) + } + + return { + "type": "state", + "joints": joints_state, + "objects": objects_state + } +def set_pybullet_window_visibility(visible: bool): + """Finds the PyBullet GUI window on Windows and sets its visibility by moving it on/off-screen.""" + import sys + if sys.platform != "win32": + return False + import ctypes + import time + + EnumWindowsProc = ctypes.WINFUNCTYPE(ctypes.c_bool, ctypes.c_void_p, ctypes.c_void_p) + + for _ in range(30): + found_hwnd = [] + + def foreach_window(hwnd, lParam): + length = ctypes.windll.user32.GetWindowTextLengthW(hwnd) + buff = ctypes.create_unicode_buffer(length + 1) + ctypes.windll.user32.GetWindowTextW(hwnd, buff, length + 1) + title = buff.value + if "bullet physics examplebrowser" in title.lower(): + found_hwnd.append(hwnd) + return False + return True + + ctypes.windll.user32.EnumWindows(EnumWindowsProc(foreach_window), 0) + if found_hwnd: + hwnd = found_hwnd[0] + # Ensure the window is shown/restored from minimized state first (SW_SHOW = 5) + ctypes.windll.user32.ShowWindow(hwnd, 5) + + # SWP_NOSIZE = 0x0001, SWP_NOZORDER = 0x0004 + if visible: + # Move window to visible region + ctypes.windll.user32.SetWindowPos(hwnd, 0, 100, 100, 0, 0, 0x0001 | 0x0004) + else: + # Move window far off-screen to hide it without destroying OpenGL context + ctypes.windll.user32.SetWindowPos(hwnd, 0, -10000, -10000, 0, 0, 0x0001 | 0x0004) + print(f"[Window Visibility] Set PyBullet window (HWND: {hwnd}) visibility to: {visible}", flush=True) + return True + time.sleep(0.1) + return False +def compute_and_format_score(sim: PandaSimulation, plan: list, executed_successfully: bool): + """Calculates rearrangement score based on final object locations and collisions.""" + with pybullet_lock: + score = 100 + details = [] + + # Check target placement if we had a plan + target_location = None + target_object = None + for step in plan: + if step.get("function") in ("place_at", "place_down", "move_to"): + args = step.get("args", {}) + if "location_id" in args: + target_location = args["location_id"] + if step.get("function") == "pick_up": + target_object = step.get("args", {}).get("object_id") + + if target_object and target_location: + obj_id = sim.scene.name_to_id(target_object) + if obj_id is not None: + pos, _ = pb.getBasePositionAndOrientation(obj_id) + current_loc = sim.scene.classify_location(pos) + if current_loc == target_location: + details.append(f"✅ **Đã đặt {target_object} đúng vị trí {target_location}**: +50 điểm") + else: + details.append(f"❌ **{target_object} chưa đến đúng vị trí {target_location} (đang ở {current_loc})**: -50 điểm") + score -= 50 + else: + details.append(f"❌ **Không tìm thấy vật thể {target_object}**: -50 điểm") + score -= 50 + else: + details.append("ℹ️ Không có yêu cầu di chuyển vật thể cụ thể nào được phát hiện.") + + # Knock detection + knocked_count = 0 + for oid in sim.scene.object_ids: + if oid == sim.scene.name_to_id(target_object): + continue + pos, _ = pb.getBasePositionAndOrientation(oid) + loc = sim.scene.classify_location(pos) + if loc == "elsewhere": + name = sim.scene.get_name(oid) + details.append(f"⚠️ **Vật thể '{name}' bị lệch khỏi vị trí quy định**: -15 điểm") + score -= 15 + knocked_count += 1 + + if knocked_count == 0: + details.append("✅ **Không có vật thể nào khác bị va chạm hay xê dịch**: +30 điểm") + else: + score = max(0, score) + + # Execution success + if executed_successfully: + details.append("✅ **Thực thi toàn bộ kế hoạch thành công**: +20 điểm") + else: + details.append("❌ **Thực thi gặp lỗi gián đoạn**: -30 điểm") + score -= 30 + + score = max(0, min(100, score)) + + md = f"### 🏆 Rearrangement Evaluation Report\n\n**Tổng điểm: {score}/100**\n\n**Chi tiết:**\n" + "\n".join([f"- {d}" for d in details]) + return score, md +def run_pipeline_threadsafe(websocket: WebSocket, user_prompt: str, loop, use_mock: bool, camera_state: Optional[dict] = None): + """Runs the planning, validation, execution with image streaming, and scoring.""" + global current_sim + + def log(message: str, step: Optional[int] = None): + try: + print(f"[WS Log] {message}", flush=True) + except Exception: + pass + asyncio.run_coroutine_threadsafe( + websocket.send_json({"type": "log", "message": message, "step": step}), + loop + ) + # Step 1: Planning + log("⏳ [1/5] Đang lập kế hoạch (LLM Planner)...") + + if use_mock: + planner = RuleBasedPlanner() + log("✅ [1] Đang sử dụng RuleBasedPlanner (Offline)") + else: + api_key = os.environ.get("OPENAI_API_KEY") or os.environ.get("LLM_API_KEY") + if not api_key: + log("❌ [1] Lỗi: Không tìm thấy OPENAI_API_KEY / LLM_API_KEY. Vui lòng chọn Mock.") + return + planner = RemoteLLMPlanner() + log(f"✅ [1] Đang sử dụng RemoteLLMPlanner (Model: {planner.model})") + + with pybullet_lock: + current_sim.agent = LLMAgent(planner=planner) + + # Define reachability check for scene state + def reachability_fn(oid): + cls = current_sim.scene.get_class(oid) + try: + grasp_pos, grasp_ori = current_sim.grasp_planner.compute_grasp_pose(oid, cls) + return current_sim.controller.is_reachable(grasp_pos, grasp_ori) + except Exception: + return False + carried_name = current_sim.scene.get_name(current_sim._carried) if current_sim._carried is not None else None + scene_state = current_sim.scene.get_scene_state(reachability_fn=reachability_fn, carried_object=carried_name) + state_text = json.dumps(scene_state, indent=2) + + try: + with pybullet_lock: + plan = current_sim.agent.plan(user_prompt, state_text) + log(f"✅ [1] Đã tạo kế hoạch: {len(plan)} bước.") + except Exception as e: + log(f"❌ [1] Lập kế hoạch thất bại: {e}") + return + # Send steps to client + plan_steps = [] + for idx, step in enumerate(plan, 1): + func = step.get("function") + args = step.get("args", {}) + obj = args.get("object_id") or args.get("location_id") or "" + plan_steps.append({ + "step": idx, + "skill": func, + "object": obj, + "args": args + }) + + asyncio.run_coroutine_threadsafe( + websocket.send_json({"type": "plan", "plan": plan_steps}), + loop + ) + if not plan: + log("⚠️ [1] Kế hoạch rỗng.") + log("⏳ [5/5] Đang tính toán điểm sắp xếp...") + score_val, score_md = compute_and_format_score(current_sim, [], True) + asyncio.run_coroutine_threadsafe( + websocket.send_json({ + "type": "result", + "score_display": score_md, + "score_value": score_val + }), + loop + ) + state_payload = get_simulation_state_payload(current_sim) + if state_payload: + asyncio.run_coroutine_threadsafe(websocket.send_json(state_payload), loop) + return + # Step 2: Validation + log("⏳ [2/5] Đang kiểm tra kế hoạch (Validator)...") + try: + with pybullet_lock: + warnings = PlanVerifier.check(plan, scene_state) + if not warnings: + log("✅ [2] Kế hoạch hợp lệ.") + else: + log(f"⚠️ [2] Validator phát hiện {len(warnings)} cảnh báo.") + for w in warnings: + log(f" - {w}") + except Exception as e: + log(f"❌ [2] Lỗi kiểm tra kế hoạch: {e}") + return + # Step 3: PyBullet Execution (Live!) + log("⏳ [3/5] Đang thực thi hành động của robot...") + + # Hook pb.stepSimulation to capture states during movements + original_step = pb.stepSimulation + last_stream_time = [0.0] + throttle_interval = 0.033 + + def wrapped_step(): + original_step() + if not current_sim.gui: + # Sleep slightly in headless mode to simulate arm speed and avoid freezing + time.sleep(0.001) + curr_time = time.time() + if curr_time - last_stream_time[0] >= throttle_interval: + last_stream_time[0] = curr_time + state_payload = get_simulation_state_payload(current_sim) + if state_payload: + asyncio.run_coroutine_threadsafe( + websocket.send_json(state_payload), + loop + ) + + with pybullet_lock: + pb.stepSimulation = wrapped_step + + executed_successfully = True + try: + # Trigger an initial simulation state transmission + state_payload = get_simulation_state_payload(current_sim) + if state_payload: + asyncio.run_coroutine_threadsafe(websocket.send_json(state_payload), loop) + + for i, step in enumerate(plan, 1): + log(f"🚀 [3/5] Đang chạy bước {i}/{len(plan)}: {step['function']}") + with pybullet_lock: + current_sim._execute(step, verbose=True) + + log("✅ [3] Thực thi thành công toàn bộ kế hoạch.") + except Exception as e: + log(f"❌ Lỗi trong lúc thực thi mô phỏng: {e}") + executed_successfully = False + finally: + with pybullet_lock: + pb.stepSimulation = original_step + + # Send a final state to ensure visual sync + state_payload = get_simulation_state_payload(current_sim) + if state_payload: + asyncio.run_coroutine_threadsafe(websocket.send_json(state_payload), loop) + # Step 5: Scoring + log("⏳ [5/5] Đang tính toán điểm sắp xếp...") + score_val, score_md = compute_and_format_score(current_sim, plan, executed_successfully) + + asyncio.run_coroutine_threadsafe( + websocket.send_json({ + "type": "result", + "score_display": score_md, + "score_value": score_val + }), + loop + ) +@app.websocket("/ws") +async def websocket_endpoint(websocket: WebSocket): + global current_sim + await websocket.accept() + loop = asyncio.get_running_loop() + + # Retrieve user's desktop display preference from client query params + client_wants_gui = websocket.query_params.get("gui", "false").lower() == "true" + + # Force gui = False to run PyBullet completely headless (DIRECT mode) + gui = False + + camera_state = { + "target": [0.5, 0.0, 0.3], + "dist": 1.3, + "yaw": 45.0, + "pitch": -35.0 + } + + async with executor_lock: + def init_sim(): + global current_sim + with pybullet_lock: + is_connected = False + if current_sim is not None and current_sim.client is not None: + try: + is_connected = pb.isConnected(current_sim.client) + except Exception: + is_connected = False + + if is_connected and current_sim.gui == gui: + current_sim.reset_objects(seed=0) + current_sim.controller.reset_to_home() + for _ in range(5): + pb.stepSimulation(physicsClientId=current_sim.client) + else: + if is_connected: + try: + current_sim.disconnect() + except Exception as e: + print(f"[Teardown Error] {e}") + current_sim = PandaSimulation(gui=gui, seed=0) + + await asyncio.to_thread(init_sim) + # Apply the client's visibility preference to show/hide the PyBullet GUI window on the desktop + await asyncio.to_thread(set_pybullet_window_visibility, client_wants_gui) + + # Send static scene configuration + init_payload = await asyncio.to_thread(get_init_payload, current_sim) + await websocket.send_json(init_payload) + # Send the first simulation state to sync objects and joints + state_payload = await asyncio.to_thread(get_simulation_state_payload, current_sim) + if state_payload: + await websocket.send_json(state_payload) + + try: + while True: + data = await websocket.receive_text() + payload = json.loads(data) + + p_type = payload.get("type") + if p_type == "run": + prompt = payload.get("prompt", "") + use_mock = payload.get("mock", False) + asyncio.create_task( + asyncio.to_thread( + run_pipeline_threadsafe, + websocket, + prompt, + loop, + use_mock + ) + ) + + elif p_type == "reset": + async with executor_lock: + def reset_sim(): + with pybullet_lock: + current_sim.reset_objects(seed=0) + current_sim.controller.reset_to_home() + await asyncio.to_thread(reset_sim) + + state_payload = await asyncio.to_thread(get_simulation_state_payload, current_sim) + if state_payload: + await websocket.send_json(state_payload) + await websocket.send_json({"type": "log", "message": "🔄 Đã reset môi trường mô phỏng."}) + + elif p_type == "update_object_pose": + name = payload.get("name") + pos = payload.get("pos") + ori = payload.get("ori") + async with executor_lock: + def move_obj(): + with pybullet_lock: + oid = current_sim.scene.name_to_id(name) + if oid is not None: + pb.resetBasePositionAndOrientation(oid, pos, ori) + await asyncio.to_thread(move_obj) + + state_payload = await asyncio.to_thread(get_simulation_state_payload, current_sim) + if state_payload: + await websocket.send_json(state_payload) + + elif p_type == "update_joints": + joints_data = payload.get("joints") + async with executor_lock: + def move_joints(): + with pybullet_lock: + for idx, q in enumerate(joints_data[:7]): + pb.resetJointState(current_sim.robot_id, idx, q) + if len(joints_data) >= 11: + pb.resetJointState(current_sim.robot_id, 9, joints_data[9]) + pb.resetJointState(current_sim.robot_id, 10, joints_data[10]) + await asyncio.to_thread(move_joints) + + state_payload = await asyncio.to_thread(get_simulation_state_payload, current_sim) + if state_payload: + await websocket.send_json(state_payload) + elif p_type == "update_robot_ee": + pos = payload.get("pos") + async with executor_lock: + def move_robot_ee(): + with pybullet_lock: + link_state = pb.getLinkState( + current_sim.robot_id, + current_sim.controller.ee_index, + physicsClientId=current_sim.client + ) + ee_ori = link_state[1] + + solution = pb.calculateInverseKinematics( + current_sim.robot_id, + current_sim.controller.ee_index, + pos, + ee_ori, + lowerLimits=current_sim.controller._lower_limits, + upperLimits=current_sim.controller._upper_limits, + jointRanges=current_sim.controller._joint_ranges, + restPoses=current_sim.controller._rest_poses, + maxNumIterations=300, + residualThreshold=1e-5, + physicsClientId=current_sim.client + ) + + for idx, q in enumerate(solution[:7]): + pb.resetJointState( + current_sim.robot_id, + idx, + q, + physicsClientId=current_sim.client + ) + await asyncio.to_thread(move_robot_ee) + + state_payload = await asyncio.to_thread(get_simulation_state_payload, current_sim) + if state_payload: + await websocket.send_json(state_payload) + elif p_type in ("camera_rotate", "camera_pan", "camera_zoom"): + pass + + except WebSocketDisconnect: + print("Client disconnected") + except Exception as e: + print(f"WS Exception: {e}") +if __name__ == "__main__": + uvicorn.run("interactive_server:app", host="0.0.0.0", port=8000, reload=False) \ No newline at end of file diff --git a/.history/frontend/index_20260627232122.css b/.history/frontend/index_20260627232122.css new file mode 100644 index 0000000000000000000000000000000000000000..2369dc7253a216f4a5363e7c69bea379843ff831 --- /dev/null +++ b/.history/frontend/index_20260627232122.css @@ -0,0 +1,937 @@ +:root { + --primary-color: #1e3a8a; /* Dark Navy Blue */ + --primary-glow: rgba(30, 58, 138, 0.3); + --accent-success: #064e3b; /* Very Dark Green */ + --accent-warning: #78350f; /* Dark Amber/Brown */ + --accent-error: #7f1d1d; /* Dark Red */ + --bg-dark: #f8fafc; + --text-main: #000000; /* Pure Black for maximum contrast */ + --text-muted: #1e293b; /* Dark Slate */ + --hud-text-shadow: 0 1px 3px rgba(255, 255, 255, 0.95), 0 0 6px rgba(255, 255, 255, 0.85); +} +* { + box-sizing: border-box; + margin: 0; + padding: 0; +} +body { + font-family: 'Outfit', -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif; + background-color: #f1f5f9; + color: var(--text-main); + overflow: hidden; + width: 100vw; + height: 100vh; +} +button, input, select, table { + font-family: inherit; +} +/* Fullscreen Viewport Container */ +#viewport-container { + position: absolute; + top: 0; + left: 0; + width: 100vw; + height: 100vh; + background-color: #f1f5f9; + z-index: 1; + overflow: hidden; +} +#pybullet-viewport { + width: 100%; + height: 100%; + object-fit: cover; + border: none; + border-radius: 0; + box-shadow: none; + cursor: grab; +} +#pybullet-viewport:active { + cursor: grabbing; +} +/* Transparent HUD Panels with Premium Glassmorphism */ +.glass { + background: rgba(255, 255, 255, 0.75); + backdrop-filter: blur(12px); + -webkit-backdrop-filter: blur(12px); + border: 1px solid rgba(255, 255, 255, 0.4); + box-shadow: 0 8px 32px 0 rgba(31, 38, 135, 0.08); + border-radius: 16px; +} +/* Sidebar Styling (Light-HUD layout) */ +.sidebar { + position: absolute; + top: 20px; + left: 20px; + width: 360px; + height: calc(100vh - 40px); + z-index: 10; + padding: 20px; + display: flex; + flex-direction: column; + gap: 16px; + pointer-events: auto; +} +.sidebar-header { + display: flex; + justify-content: space-between; + align-items: center; + border-bottom: 2px solid rgba(37, 99, 235, 0.2); + padding-bottom: 10px; +} +.sidebar-header .brand { + display: flex; + align-items: center; + gap: 8px; + color: #1e3a8a; +} +.sidebar-header h2 { + font-size: 1.4rem; + font-weight: 700; + letter-spacing: -0.025em; + text-shadow: var(--hud-text-shadow); +} +.brand-icon { + filter: drop-shadow(0 1px 2px rgba(255,255,255,0.8)); +} +.badge { + font-size: 0.7rem; + font-weight: 700; + padding: 4px 10px; + border-radius: 10px; + text-transform: uppercase; + letter-spacing: 0.05em; + display: inline-flex; + align-items: center; + gap: 6px; + text-shadow: var(--hud-text-shadow); + border: 1px solid currentColor; +} +.badge::before { + content: ''; + display: inline-block; + width: 6px; + height: 6px; + border-radius: 50%; +} +.badge.online { + background: rgba(16, 185, 129, 0.15); + color: var(--accent-success); +} +.badge.online::before { + background: var(--accent-success); + box-shadow: 0 0 8px var(--accent-success); +} +.badge.offline { + background: rgba(239, 68, 68, 0.15); + color: var(--accent-error); +} +.badge.offline::before { + background: var(--accent-error); +} +/* Tab Bar Navigation inside Sidebar */ +.sidebar-tabs { + display: flex; + gap: 4px; + background: rgba(15, 23, 42, 0.05); + border: 1px solid rgba(0, 0, 0, 0.05); + border-radius: 10px; + padding: 3px; + justify-content: space-between; +} +.tab-btn { + flex-grow: 1; + display: flex; + justify-content: center; + align-items: center; + padding: 8px 4px; + background: transparent; + border: none; + border-radius: 6px; + color: var(--text-muted); + cursor: pointer; + transition: all 0.2s ease; + outline: none; +} +.tab-btn:hover { + background: rgba(255, 255, 255, 0.5); + color: var(--primary-color); +} +.tab-btn.active { + background: white; + color: var(--primary-color); + box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06); +} +/* Tab Panel Transitions */ +.tab-panel { + display: none; + opacity: 0; + transition: opacity 0.3s ease; +} +.tab-panel.active { + display: flex; + flex-direction: column; + gap: 16px; + opacity: 1; + flex-grow: 1; + min-height: 0; +} +.sidebar-section { + display: flex; + flex-direction: column; + gap: 8px; +} +.sidebar-section.flex-grow { + flex-grow: 1; + min-height: 0; +} +.sidebar-section h3 { + font-size: 0.8rem; + font-weight: 700; + text-transform: uppercase; + color: var(--primary-color); + letter-spacing: 0.05em; + text-shadow: var(--hud-text-shadow); +} +/* Operations Steps */ +.status-steps { + display: flex; + flex-direction: column; + gap: 8px; +} +.status-step { + display: flex; + align-items: center; + gap: 10px; + font-size: 0.9rem; + color: var(--text-muted); + font-weight: 600; + text-shadow: var(--hud-text-shadow); + transition: all 0.2s ease; +} +.status-step .dot { + width: 8px; + height: 8px; + border-radius: 50%; + background: rgba(15, 23, 42, 0.3); + border: 1px solid rgba(15, 23, 42, 0.5); + transition: all 0.2s ease; +} +.status-step.active { + color: var(--primary-color); +} +.status-step.active .dot { + background: var(--primary-color); + box-shadow: 0 0 8px var(--primary-color); + border-color: var(--primary-color); +} +.status-step.completed { + color: var(--accent-success); +} +.status-step.completed .dot { + background: var(--accent-success); + border-color: var(--accent-success); +} +.status-step.error { + color: var(--accent-error); +} +.status-step.error .dot { + background: var(--accent-error); + border-color: var(--accent-error); +} +/* Task Plan List */ +.plan-list { + background: rgba(255, 255, 255, 0.65); + backdrop-filter: blur(8px); + border: 1px solid rgba(0, 0, 0, 0.08); + border-radius: 10px; + max-height: 120px; + overflow-y: auto; + padding: 8px; + display: flex; + flex-direction: column; + gap: 5px; + box-shadow: 0 4px 20px rgba(0,0,0,0.03); +} +.plan-item { + font-size: 0.8rem; + padding: 6px 10px; + background: rgba(255, 255, 255, 0.4); + border-radius: 6px; + border-left: 3px solid rgba(0, 0, 0, 0.1); + color: var(--text-main); + font-weight: 500; + display: flex; + justify-content: space-between; +} +.plan-item.active { + background: rgba(37, 99, 235, 0.08); + border-left-color: var(--primary-color); + color: var(--primary-color); + font-weight: 600; +} +.plan-item.completed { + border-left-color: var(--accent-success); + color: rgba(15, 23, 42, 0.4); + text-decoration: line-through; + opacity: 0.6; +} +/* Monospace Log Console */ +.log-console { + background: rgba(255, 255, 255, 0.65); + backdrop-filter: blur(8px); + border: 1px solid rgba(0, 0, 0, 0.08); + font-family: 'Consolas', 'Fira Code', monospace; + font-size: 0.8rem; + line-height: 1.4; + border-radius: 10px; + padding: 10px; + overflow-y: auto; + flex-grow: 1; + display: flex; + flex-direction: column; + gap: 5px; + box-shadow: 0 4px 20px rgba(0,0,0,0.03); +} +.log-entry { + color: var(--text-main); + font-weight: 600; +} +.log-entry.info { color: #1e3a8a; } +.log-entry.success { color: #064e3b; } +.log-entry.warn { color: #78350f; } +.log-entry.error { color: #7f1d1d; } +.placeholder-text { + color: var(--text-muted); + font-style: italic; + text-align: center; + margin: auto; + font-size: 0.85rem; +} +/* Scenarios Tab styling */ +.scenarios-grid { + display: grid; + grid-template-columns: repeat(3, 1fr); + gap: 8px; +} +.scenario-card { + background: rgba(255, 255, 255, 0.6); + border: 1px solid rgba(0, 0, 0, 0.08); + border-radius: 10px; + padding: 10px 6px; + display: flex; + flex-direction: column; + align-items: center; + gap: 6px; + text-align: center; + cursor: pointer; + transition: all 0.2s ease; + user-select: none; +} +.scenario-card:hover { + background: rgba(255, 255, 255, 0.95); + border-color: var(--primary-color); + box-shadow: 0 4px 12px rgba(30, 58, 138, 0.08); + transform: translateY(-1.5px); +} +.scenario-icon { + color: var(--primary-color); + background: rgba(30, 58, 138, 0.06); + padding: 6px; + border-radius: 8px; + display: flex; + align-items: center; + justify-content: center; +} +.scenario-card h4 { + font-size: 0.7rem; + font-weight: 700; + color: var(--text-muted); + line-height: 1.2; +} +.preset-commands-list { + display: flex; + flex-direction: column; + gap: 6px; +} +.preset-command-item { + background: rgba(255, 255, 255, 0.55); + border: 1px solid rgba(0, 0, 0, 0.06); + border-radius: 8px; + padding: 8px 12px; + font-size: 0.8rem; + font-weight: 600; + color: var(--text-muted); + text-align: left; + cursor: pointer; + transition: all 0.2s ease; +} +.preset-command-item:hover { + background: rgba(255, 255, 255, 0.85); + border-color: var(--primary-color); + color: var(--primary-color); +} +/* Objects Tab Table */ +.table-container { + background: rgba(255, 255, 255, 0.65); + border: 1px solid rgba(0, 0, 0, 0.06); + border-radius: 10px; + overflow: hidden; + box-shadow: 0 4px 20px rgba(0,0,0,0.03); +} +.objects-table { + width: 100%; + border-collapse: collapse; + font-size: 0.8rem; + text-align: left; +} +.objects-table th, .objects-table td { + padding: 10px 10px; + border-bottom: 1px solid rgba(0, 0, 0, 0.05); +} +.objects-table th { + background: rgba(15, 23, 42, 0.03); + color: var(--primary-color); + font-weight: 700; + text-transform: uppercase; + font-size: 0.7rem; + letter-spacing: 0.05em; +} +.objects-table tr:last-child td { + border-bottom: none; +} +.objects-table td { + color: var(--text-main); + font-weight: 600; +} +.tag-badge { + display: inline-block; + padding: 2px 6px; + border-radius: 4px; + font-size: 0.65rem; + font-weight: 700; + text-transform: uppercase; +} +.tag-badge.safe { + background: rgba(16, 185, 129, 0.1); + color: #047857; +} +/* History Tab list */ +.history-list { + display: flex; + flex-direction: column; + gap: 8px; + max-height: calc(100vh - 120px); + overflow-y: auto; + padding-right: 2px; +} +.history-card { + background: rgba(255, 255, 255, 0.6); + border: 1px solid rgba(0, 0, 0, 0.06); + border-radius: 10px; + padding: 10px 12px; + display: flex; + flex-direction: column; + gap: 6px; + transition: all 0.2s ease; +} +.history-card:hover { + background: rgba(255, 255, 255, 0.85); + border-color: var(--primary-color); +} +.history-card-header { + display: flex; + justify-content: space-between; + font-size: 0.7rem; + color: var(--text-muted); + font-weight: 600; +} +.history-card-prompt { + font-size: 0.8rem; + font-style: italic; + color: var(--text-main); + font-weight: 600; + line-height: 1.3; +} +.history-card-footer { + display: flex; + justify-content: space-between; + align-items: center; + border-top: 1px solid rgba(0, 0, 0, 0.04); + padding-top: 6px; + margin-top: 2px; +} +.history-score { + font-size: 0.85rem; + font-weight: 700; +} +.history-score.high { color: #047857; } +.history-score.medium { color: #b45309; } +.history-score.low { color: #b91c1c; } +.history-actions { + display: flex; + gap: 4px; +} +.history-action-btn { + background: transparent; + border: 1px solid rgba(37, 99, 235, 0.2); + color: var(--primary-color); + padding: 3px 6px; + border-radius: 4px; + font-size: 0.7rem; + font-weight: 600; + cursor: pointer; + display: flex; + align-items: center; + gap: 3px; + transition: all 0.2s ease; +} +.history-action-btn:hover { + background: rgba(37, 99, 235, 0.08); + border-color: var(--primary-color); +} +/* Analytics Tab KPIs & Charts */ +.kpi-grid { + display: grid; + grid-template-columns: repeat(3, 1fr); + gap: 8px; +} +.kpi-card { + background: rgba(255, 255, 255, 0.65); + border: 1px solid rgba(0, 0, 0, 0.06); + border-radius: 10px; + padding: 10px 4px; + display: flex; + flex-direction: column; + align-items: center; + text-align: center; + box-shadow: 0 2px 8px rgba(0,0,0,0.02); +} +.kpi-value { + font-size: 1.15rem; + font-weight: 700; + color: var(--primary-color); +} +.kpi-label { + font-size: 0.65rem; + font-weight: 700; + color: var(--text-muted); + text-transform: uppercase; + margin-top: 2px; + letter-spacing: 0.02em; +} +.analytics-chart { + display: flex; + flex-direction: column; + gap: 10px; + background: rgba(255, 255, 255, 0.5); + border: 1px solid rgba(0, 0, 0, 0.06); + border-radius: 10px; + padding: 12px; +} +.chart-bar-group { + display: flex; + flex-direction: column; + gap: 4px; +} +.chart-label-row { + display: flex; + justify-content: space-between; + font-size: 0.75rem; + font-weight: 600; + color: var(--text-muted); +} +.chart-track { + width: 100%; + height: 8px; + background: rgba(0, 0, 0, 0.05); + border-radius: 4px; + overflow: hidden; +} +.chart-bar { + height: 100%; + border-radius: 4px; + transition: width 0.6s cubic-bezier(0.16, 1, 0.3, 1); +} +/* System settings form controls */ +.form-group { + display: flex; + flex-direction: column; + gap: 4px; +} +.form-label { + font-size: 0.8rem; + font-weight: 600; + color: var(--text-muted); +} +.select-wrapper { + position: relative; + width: 100%; +} +.glass-select { + width: 100%; + background: rgba(255, 255, 255, 0.7); + border: 1px solid rgba(0, 0, 0, 0.1); + border-radius: 8px; + padding: 8px 24px 8px 10px; + font-size: 0.8rem; + font-weight: 600; + color: var(--text-main); + outline: none; + cursor: pointer; + transition: all 0.2s ease; + appearance: none; +} +.glass-select:focus { + border-color: var(--primary-color); + box-shadow: 0 0 10px rgba(37, 99, 235, 0.1); +} +.select-wrapper::after { + content: ''; + position: absolute; + right: 10px; + top: 50%; + transform: translateY(-50%); + width: 0; + height: 0; + border-left: 4px solid transparent; + border-right: 4px solid transparent; + border-top: 4px solid var(--text-muted); + pointer-events: none; +} +/* Floating Chat Input Box & Buttons */ +.chat-container { + position: absolute; + bottom: 30px; + left: calc(50% + 180px); + transform: translateX(-50%); + width: 650px; + z-index: 10; + padding: 12px; + display: flex; + flex-direction: column; + gap: 8px; + pointer-events: auto; +} +#chat-form { + display: flex; + gap: 8px; + align-items: center; + position: relative; +} +#chat-input { + flex-grow: 1; + background: rgba(255, 255, 255, 0.75); + backdrop-filter: blur(10px); + border: 2px solid var(--primary-color); + box-shadow: 0 4px 20px rgba(0,0,0,0.05); + padding: 12px 18px; + border-radius: 12px; + color: #0f172a; + font-size: 0.95rem; + font-weight: 600; + outline: none; + transition: all 0.2s ease; +} +#chat-input:focus { + border-color: #1d4ed8; + background: rgba(255, 255, 255, 0.9); + box-shadow: 0 0 15px rgba(37, 99, 235, 0.2); +} +.chat-action-btn { + background: rgba(255, 255, 255, 0.85); + border: 2px solid var(--primary-color); + color: var(--primary-color); + width: 46px; + height: 46px; + border-radius: 12px; + cursor: pointer; + display: flex; + justify-content: center; + align-items: center; + transition: all 0.2s ease; + box-shadow: 0 4px 12px rgba(0, 0, 0, 0.03); + outline: none; +} +.chat-action-btn:hover { + background: rgba(255, 255, 255, 0.95); + transform: translateY(-1px); + box-shadow: 0 4px 16px rgba(30, 58, 138, 0.12); +} +.chat-action-btn:active { + transform: translateY(0); +} +#submit-btn { + background: var(--primary-color); + color: white; +} +#submit-btn:hover { + background: #1d4ed8; +} +#submit-btn:disabled, #chat-input:disabled, #mic-btn:disabled { + opacity: 0.4; + cursor: not-allowed; + box-shadow: none; +} +/* Pulsing voice recorder active glow */ +#mic-btn.recording { + border-color: var(--accent-error); + color: var(--accent-error); + background: rgba(239, 68, 68, 0.08); + animation: pulseMic 1.5s infinite alternate; +} +@keyframes pulseMic { + 0% { + box-shadow: 0 0 4px rgba(239, 68, 68, 0.2); + } + 100% { + box-shadow: 0 0 16px rgba(239, 68, 68, 0.5); + } +} +.chat-options { + display: flex; + justify-content: space-between; + align-items: center; + font-size: 0.8rem; + color: #0f172a; + font-weight: 600; + text-shadow: var(--hud-text-shadow); +} +/* Toggle Switch styling */ +.toggle-switch { + display: flex; + align-items: center; + gap: 6px; + cursor: pointer; +} +.toggle-switch input { + display: none; +} +.slider { + position: relative; + display: inline-block; + width: 32px; + height: 18px; + background-color: rgba(15, 23, 42, 0.2); + border-radius: 18px; + transition: .3s; + border: 1px solid rgba(0, 0, 0, 0.15); +} +.slider:before { + position: absolute; + content: ""; + height: 12px; + width: 12px; + left: 2px; + bottom: 2px; + background-color: #0f172a; + border-radius: 50%; + transition: .3s; +} +.toggle-switch input:checked + .slider { + background-color: var(--primary-color); + border-color: #1d4ed8; +} +.toggle-switch input:checked + .slider:before { + background-color: white; + transform: translateX(14px); +} +.toggle-label { + user-select: none; +} +/* Custom Text and Primary Buttons */ +.text-btn { + background: none; + border: none; + color: #1d4ed8; + cursor: pointer; + font-weight: 700; + transition: color 0.2s; + font-size: 0.8rem; + text-shadow: var(--hud-text-shadow); +} +.text-btn:hover { + color: #0f172a; +} +.primary-btn { + background: var(--primary-color); + color: white; + border: none; + padding: 10px 24px; + border-radius: 8px; + font-weight: 600; + cursor: pointer; + transition: all 0.3s; + box-shadow: 0 4px 12px var(--primary-glow); +} +.primary-btn:hover { + background: #1d4ed8; + box-shadow: 0 4px 20px rgba(29, 78, 216, 0.4); +} +/* Header overlays */ +.header-overlay { + position: absolute; + top: 20px; + left: 390px; + right: 20px; + z-index: 10; + pointer-events: none; +} +.header-overlay h1 { + font-size: 1.3rem; + font-weight: 700; + letter-spacing: -0.015em; + color: #0f172a; + text-shadow: var(--hud-text-shadow); + margin-bottom: 2px; +} +.header-overlay p { + font-size: 0.8rem; + color: var(--text-muted); + text-shadow: var(--hud-text-shadow); +} +/* Autocomplete Suggestion Panel styling */ +.autocomplete-panel { + position: absolute; + bottom: calc(100% + 10px); + left: 0; + width: 100%; + background: rgba(255, 255, 255, 0.9); + backdrop-filter: blur(12px); + border: 1px solid rgba(30, 58, 138, 0.15); + border-radius: 12px; + box-shadow: 0 -8px 32px rgba(0, 0, 0, 0.08); + padding: 6px; + display: flex; + flex-direction: column; + gap: 3px; + z-index: 100; + max-height: 150px; + overflow-y: auto; +} +.autocomplete-panel.hidden { + display: none; +} +.autocomplete-item { + padding: 8px 12px; + font-size: 0.8rem; + font-weight: 600; + color: var(--text-muted); + border-radius: 6px; + cursor: pointer; + transition: all 0.2s ease; + text-align: left; +} +.autocomplete-item:hover { + background: rgba(30, 58, 138, 0.06); + color: var(--primary-color); +} +/* Modal Overlay for Score Card */ +.modal-overlay { + position: fixed; + top: 0; + left: 0; + width: 100vw; + height: 100vh; + background: rgba(15, 23, 42, 0.45); + backdrop-filter: blur(10px); + z-index: 1000; + display: flex; + justify-content: center; + align-items: center; + opacity: 1; + transition: opacity 0.3s ease; +} +.modal-overlay.hidden { + opacity: 0; + pointer-events: none; +} +.modal-content { + width: 500px; + max-width: 90%; + padding: 24px; + display: flex; + flex-direction: column; + gap: 16px; + background: rgba(255, 255, 255, 0.9) !important; + border: 2px solid var(--primary-color) !important; + box-shadow: 0 10px 40px rgba(0, 0, 0, 0.2) !important; + border-radius: 16px; + animation: scaleUp 0.3s cubic-bezier(0.34, 1.56, 0.64, 1); +} +@keyframes scaleUp { + from { transform: scale(0.9); opacity: 0; } + to { transform: scale(1); opacity: 1; } +} +.modal-content h2 { + font-size: 1.35rem; + text-align: center; + border-bottom: 2px solid rgba(37, 99, 235, 0.2); + padding-bottom: 10px; + color: #0f172a; +} +.score-md-content { + font-size: 0.9rem; + line-height: 1.5; + color: #334155; +} +.score-md-content h3 { + margin: 10px 0 4px 0; + font-size: 1rem; + color: #1d4ed8; +} +.score-md-content ul { + padding-left: 18px; + margin-bottom: 8px; +} +.score-md-content li { + margin-bottom: 2px; +} +.score-md-content strong { + color: #0f172a; +} +/* Scrollbars styling */ +::-webkit-scrollbar { + width: 6px; +} +::-webkit-scrollbar-track { + background: transparent; +} +::-webkit-scrollbar-thumb { + background: rgba(37, 99, 235, 0.25); + border-radius: 3px; +} +::-webkit-scrollbar-thumb:hover { + background: rgba(37, 99, 235, 0.45); +} +/* Manual controls range sliders styling */ +.manual-controls { + display: flex; + flex-direction: column; + gap: 8px; + background: rgba(255, 255, 255, 0.5); + border: 1px solid rgba(0, 0, 0, 0.06); + border-radius: 10px; + padding: 12px; + max-height: 240px; + overflow-y: auto; +} +.slider-group { + display: flex; + flex-direction: column; + gap: 2px; +} +.slider-group label { + font-size: 0.75rem; + font-weight: 600; + color: var(--text-muted); + display: flex; + justify-content: space-between; +} +.slider-group input[type="range"] { + width: 100%; + height: 4px; + background: rgba(15, 23, 42, 0.1); + border-radius: 2px; + outline: none; + accent-color: var(--primary-color); +} \ No newline at end of file diff --git a/.history/frontend/interactive_server_20260627225036.py b/.history/frontend/interactive_server_20260627225036.py new file mode 100644 index 0000000000000000000000000000000000000000..b68a9f36bd7ddbf0bc51accc48a7420b712a7bbd --- /dev/null +++ b/.history/frontend/interactive_server_20260627225036.py @@ -0,0 +1,524 @@ +import sys +import os +import json +import asyncio +import math +import time +import threading +from typing import Optional +from fastapi import FastAPI, WebSocket, WebSocketDisconnect +from fastapi.staticfiles import StaticFiles +from fastapi.responses import HTMLResponse +import uvicorn +import cv2 +import numpy as np +import pybullet as pb + +# Ensure project source root is in path +PROJECT_SRC = os.path.abspath(os.path.join(os.path.dirname(__file__), "..")) +if PROJECT_SRC not in sys.path: + sys.path.insert(0, PROJECT_SRC) + +from dotenv import load_dotenv +load_dotenv() + +from main import PandaSimulation, _YCB_CATALOG +from llm_panda.llm_agent import LLMAgent, RemoteLLMPlanner, RuleBasedPlanner +from llm_panda.plan_verifier import PlanVerifier +from llm_panda import config +import pybullet_data +from pybullet_object_models import ycb_objects + +app = FastAPI(title="LLM-Panda Web-Embedded PyBullet Simulation") + +# Serve static files from the frontend directory itself +static_dir = os.path.dirname(__file__) +app.mount("/static", StaticFiles(directory=static_dir), name="static") + +# Mount robot meshes and YCB object assets +panda_data_path = os.path.join(pybullet_data.getDataPath(), "franka_panda") +ycb_data_path = ycb_objects.getDataPath() +app.mount("/assets/panda", StaticFiles(directory=panda_data_path), name="panda") +app.mount("/assets/ycb", StaticFiles(directory=ycb_data_path), name="ycb") + +@app.get("/") +async def get(): + html_file = os.path.join(static_dir, "index.html") + if os.path.exists(html_file): + with open(html_file, "r", encoding="utf-8") as f: + return HTMLResponse(content=f.read(), status_code=200) + return HTMLResponse(content="

    index.html not found!

    ", status_code=404) + +# Global variables to track the current active simulation, lock, and thread lock +current_sim: Optional[PandaSimulation] = None +executor_lock = asyncio.Lock() +pybullet_lock = threading.RLock() + +def get_init_payload(sim: PandaSimulation) -> dict: + """Gathers the initial static geometry and YCB object definitions.""" + with pybullet_lock: + objects_info = {} + if sim and sim.scene: + for oid in sim.scene.object_ids: + name = sim.scene.get_name(oid) + cls = sim.scene.get_class(oid) + folder = "" + for cat_name, cat_cls, cat_folder in _YCB_CATALOG: + if cat_name == name: + folder = cat_folder + break + pos, ori = pb.getBasePositionAndOrientation(oid, physicsClientId=sim.client) + + # Query collision shape data for CoM-to-link offset + collision_data = pb.getCollisionShapeData(oid, -1, physicsClientId=sim.client) + coll_scale = [1.0, 1.0, 1.0] + coll_local_pos = [0.0, 0.0, 0.0] + coll_local_ori = [0.0, 0.0, 0.0, 1.0] + if collision_data: + cd = collision_data[0] + coll_scale = list(cd[3]) + coll_local_pos = list(cd[5]) + coll_local_ori = list(cd[6]) + + # Query visual shape data for exact dimensions/scales and offsets relative to link + visual_data = pb.getVisualShapeData(oid, physicsClientId=sim.client) + vis_scale = [1.0, 1.0, 1.0] + vis_local_pos = [0.0, 0.0, 0.0] + vis_local_ori = [0.0, 0.0, 0.0, 1.0] + if visual_data: + vd = visual_data[0] + vis_scale = list(vd[3]) + # Transform visual frame to be relative to CoM: CoM_to_visual = CoM_to_link * link_to_visual + vis_pos_com, vis_ori_com = pb.multiplyTransforms( + coll_local_pos, coll_local_ori, + list(vd[5]), list(vd[6]) + ) + vis_local_pos = list(vis_pos_com) + vis_local_ori = list(vis_ori_com) + + objects_info[name] = { + "class": cls, + "folder": folder, + "initial_pos": list(pos), + "initial_ori": list(ori), + "vis_scale": vis_scale, + "vis_local_pos": vis_local_pos, + "vis_local_ori": vis_local_ori, + "coll_scale": coll_scale, + "coll_local_pos": coll_local_pos, + "coll_local_ori": coll_local_ori + } + return { + "type": "init", + "table": { + "center": [config.TABLE_CENTER[0], config.TABLE_CENTER[1], config.TABLE_BASE_Z], + "half_extents": list(config.TABLE_HALF_EXTENTS), + "color": list(config.TABLE_COLOR), + "top_z": config.TABLE_TOP_Z + }, + "tray": { + "position": list(config.TRAY_POSITION), + "half_extents": list(config.TRAY_HALF_EXTENTS), + "color": list(config.TRAY_COLOR) + }, + "slots": {name: list(pos) for name, pos in config.SLOTS.items()}, + "objects": objects_info + } + +def get_simulation_state_payload(sim: PandaSimulation) -> dict: + """Gathers the current robot joint positions and YCB object poses.""" + with pybullet_lock: + if sim is None or sim.client is None or not pb.isConnected(sim.client): + return {} + + # Read all joints (12 joints including arm joints and gripper fingers) + num_joints = pb.getNumJoints(sim.robot_id, physicsClientId=sim.client) + joints_state = [] + for i in range(num_joints): + pos, _, _, _ = pb.getJointState(sim.robot_id, i, physicsClientId=sim.client) + joints_state.append(pos) + + # Read objects pos/ori + objects_state = {} + for oid in sim.scene.object_ids: + name = sim.scene.get_name(oid) + pos, ori = pb.getBasePositionAndOrientation(oid, physicsClientId=sim.client) + objects_state[name] = { + "pos": list(pos), + "ori": list(ori) + } + + return { + "type": "state", + "joints": joints_state, + "objects": objects_state + } + +def set_pybullet_window_visibility(visible: bool): + """Finds the PyBullet GUI window on Windows and sets its visibility by moving it on/off-screen.""" + import sys + if sys.platform != "win32": + return False + import ctypes + import time + + EnumWindowsProc = ctypes.WINFUNCTYPE(ctypes.c_bool, ctypes.c_void_p, ctypes.c_void_p) + + for _ in range(30): + found_hwnd = [] + + def foreach_window(hwnd, lParam): + length = ctypes.windll.user32.GetWindowTextLengthW(hwnd) + buff = ctypes.create_unicode_buffer(length + 1) + ctypes.windll.user32.GetWindowTextW(hwnd, buff, length + 1) + title = buff.value + if "bullet physics examplebrowser" in title.lower(): + found_hwnd.append(hwnd) + return False + return True + + ctypes.windll.user32.EnumWindows(EnumWindowsProc(foreach_window), 0) + if found_hwnd: + hwnd = found_hwnd[0] + # Ensure the window is shown/restored from minimized state first (SW_SHOW = 5) + ctypes.windll.user32.ShowWindow(hwnd, 5) + + # SWP_NOSIZE = 0x0001, SWP_NOZORDER = 0x0004 + if visible: + # Move window to visible region + ctypes.windll.user32.SetWindowPos(hwnd, 0, 100, 100, 0, 0, 0x0001 | 0x0004) + else: + # Move window far off-screen to hide it without destroying OpenGL context + ctypes.windll.user32.SetWindowPos(hwnd, 0, -10000, -10000, 0, 0, 0x0001 | 0x0004) + print(f"[Window Visibility] Set PyBullet window (HWND: {hwnd}) visibility to: {visible}", flush=True) + return True + time.sleep(0.1) + return False + +def compute_and_format_score(sim: PandaSimulation, plan: list, executed_successfully: bool): + """Calculates rearrangement score based on final object locations and collisions.""" + with pybullet_lock: + score = 100 + details = [] + + # Check target placement if we had a plan + target_location = None + target_object = None + for step in plan: + if step.get("function") in ("place_at", "place_down", "move_to"): + args = step.get("args", {}) + if "location_id" in args: + target_location = args["location_id"] + if step.get("function") == "pick_up": + target_object = step.get("args", {}).get("object_id") + + if target_object and target_location: + obj_id = sim.scene.name_to_id(target_object) + if obj_id is not None: + pos, _ = pb.getBasePositionAndOrientation(obj_id) + current_loc = sim.scene.classify_location(pos) + if current_loc == target_location: + details.append(f"✅ **Đã đặt {target_object} đúng vị trí {target_location}**: +50 điểm") + else: + details.append(f"❌ **{target_object} chưa đến đúng vị trí {target_location} (đang ở {current_loc})**: -50 điểm") + score -= 50 + else: + details.append(f"❌ **Không tìm thấy vật thể {target_object}**: -50 điểm") + score -= 50 + else: + details.append("ℹ️ Không có yêu cầu di chuyển vật thể cụ thể nào được phát hiện.") + + # Knock detection + knocked_count = 0 + for oid in sim.scene.object_ids: + if oid == sim.scene.name_to_id(target_object): + continue + pos, _ = pb.getBasePositionAndOrientation(oid) + loc = sim.scene.classify_location(pos) + if loc == "elsewhere": + name = sim.scene.get_name(oid) + details.append(f"⚠️ **Vật thể '{name}' bị lệch khỏi vị trí quy định**: -15 điểm") + score -= 15 + knocked_count += 1 + + if knocked_count == 0: + details.append("✅ **Không có vật thể nào khác bị va chạm hay xê dịch**: +30 điểm") + else: + score = max(0, score) + + # Execution success + if executed_successfully: + details.append("✅ **Thực thi toàn bộ kế hoạch thành công**: +20 điểm") + else: + details.append("❌ **Thực thi gặp lỗi gián đoạn**: -30 điểm") + score -= 30 + + score = max(0, min(100, score)) + + md = f"### 🏆 Rearrangement Evaluation Report\n\n**Tổng điểm: {score}/100**\n\n**Chi tiết:**\n" + "\n".join([f"- {d}" for d in details]) + return score, md + +def run_pipeline_threadsafe(websocket: WebSocket, user_prompt: str, loop, use_mock: bool, camera_state: Optional[dict] = None): + """Runs the planning, validation, execution with image streaming, and scoring.""" + global current_sim + + def log(message: str, step: Optional[int] = None): + try: + print(f"[WS Log] {message}", flush=True) + except Exception: + pass + asyncio.run_coroutine_threadsafe( + websocket.send_json({"type": "log", "message": message, "step": step}), + loop + ) + + # Step 1: Planning + log("⏳ [1/5] Đang lập kế hoạch (LLM Planner)...") + + if use_mock: + planner = RuleBasedPlanner() + log("✅ [1] Đang sử dụng RuleBasedPlanner (Offline)") + else: + api_key = os.environ.get("OPENAI_API_KEY") or os.environ.get("LLM_API_KEY") + if not api_key: + log("❌ [1] Lỗi: Không tìm thấy OPENAI_API_KEY / LLM_API_KEY. Vui lòng chọn Mock.") + return + planner = RemoteLLMPlanner() + log(f"✅ [1] Đang sử dụng RemoteLLMPlanner (Model: {planner.model})") + + with pybullet_lock: + current_sim.agent = LLMAgent(planner=planner) + + # Define reachability check for scene state + def reachability_fn(oid): + cls = current_sim.scene.get_class(oid) + try: + grasp_pos, grasp_ori = current_sim.grasp_planner.compute_grasp_pose(oid, cls) + return current_sim.controller.is_reachable(grasp_pos, grasp_ori) + except Exception: + return False + + carried_name = current_sim.scene.get_name(current_sim._carried) if current_sim._carried is not None else None + scene_state = current_sim.scene.get_scene_state(reachability_fn=reachability_fn, carried_object=carried_name) + state_text = json.dumps(scene_state, indent=2) + + try: + with pybullet_lock: + plan = current_sim.agent.plan(user_prompt, state_text) + log(f"✅ [1] Đã tạo kế hoạch: {len(plan)} bước.") + except Exception as e: + log(f"❌ [1] Lập kế hoạch thất bại: {e}") + return + + # Send steps to client + plan_steps = [] + for idx, step in enumerate(plan, 1): + func = step.get("function") + args = step.get("args", {}) + obj = args.get("object_id") or args.get("location_id") or "" + plan_steps.append({ + "step": idx, + "skill": func, + "object": obj, + "args": args + }) + + asyncio.run_coroutine_threadsafe( + websocket.send_json({"type": "plan", "plan": plan_steps}), + loop + ) + + if not plan: + log("⚠️ [1] Kế hoạch rỗng.") + log("⏳ [5/5] Đang tính toán điểm sắp xếp...") + score_val, score_md = compute_and_format_score(current_sim, [], True) + asyncio.run_coroutine_threadsafe( + websocket.send_json({ + "type": "result", + "score_display": score_md, + "score_value": score_val + }), + loop + ) + state_payload = get_simulation_state_payload(current_sim) + if state_payload: + asyncio.run_coroutine_threadsafe(websocket.send_json(state_payload), loop) + return + + # Step 2: Validation + log("⏳ [2/5] Đang kiểm tra kế hoạch (Validator)...") + try: + with pybullet_lock: + warnings = PlanVerifier.check(plan, scene_state) + if not warnings: + log("✅ [2] Kế hoạch hợp lệ.") + else: + log(f"⚠️ [2] Validator phát hiện {len(warnings)} cảnh báo.") + for w in warnings: + log(f" - {w}") + except Exception as e: + log(f"❌ [2] Lỗi kiểm tra kế hoạch: {e}") + return + + # Step 3: PyBullet Execution (Live!) + log("⏳ [3/5] Đang thực thi hành động của robot...") + + # Hook pb.stepSimulation to capture states during movements + original_step = pb.stepSimulation + last_stream_time = [0.0] + throttle_interval = 0.033 if current_sim.gui else 0.066 + + def wrapped_step(): + original_step() + if not current_sim.gui: + # Sleep slightly in headless mode to simulate arm speed and avoid freezing + time.sleep(0.001) + curr_time = time.time() + if curr_time - last_stream_time[0] >= throttle_interval: + last_stream_time[0] = curr_time + state_payload = get_simulation_state_payload(current_sim) + if state_payload: + asyncio.run_coroutine_threadsafe( + websocket.send_json(state_payload), + loop + ) + + with pybullet_lock: + pb.stepSimulation = wrapped_step + + executed_successfully = True + try: + # Trigger an initial simulation state transmission + state_payload = get_simulation_state_payload(current_sim) + if state_payload: + asyncio.run_coroutine_threadsafe(websocket.send_json(state_payload), loop) + + for i, step in enumerate(plan, 1): + log(f"🚀 [3/5] Đang chạy bước {i}/{len(plan)}: {step['function']}") + with pybullet_lock: + current_sim._execute(step, verbose=True) + + log("✅ [3] Thực thi thành công toàn bộ kế hoạch.") + except Exception as e: + log(f"❌ Lỗi trong lúc thực thi mô phỏng: {e}") + executed_successfully = False + finally: + with pybullet_lock: + pb.stepSimulation = original_step + + # Send a final state to ensure visual sync + state_payload = get_simulation_state_payload(current_sim) + if state_payload: + asyncio.run_coroutine_threadsafe(websocket.send_json(state_payload), loop) + + # Step 5: Scoring + log("⏳ [5/5] Đang tính toán điểm sắp xếp...") + score_val, score_md = compute_and_format_score(current_sim, plan, executed_successfully) + + asyncio.run_coroutine_threadsafe( + websocket.send_json({ + "type": "result", + "score_display": score_md, + "score_value": score_val + }), + loop + ) + +@app.websocket("/ws") +async def websocket_endpoint(websocket: WebSocket): + global current_sim + await websocket.accept() + loop = asyncio.get_running_loop() + + # Retrieve user's desktop display preference from client query params + client_wants_gui = websocket.query_params.get("gui", "false").lower() == "true" + + # Force gui = False to run PyBullet completely headless (DIRECT mode) + gui = False + + camera_state = { + "target": [0.5, 0.0, 0.3], + "dist": 1.3, + "yaw": 45.0, + "pitch": -35.0 + } + + async with executor_lock: + def init_sim(): + global current_sim + with pybullet_lock: + is_connected = False + if current_sim is not None and current_sim.client is not None: + try: + is_connected = pb.isConnected(current_sim.client) + except Exception: + is_connected = False + + if is_connected and current_sim.gui == gui: + current_sim.reset_objects(seed=0) + current_sim.controller.reset_to_home() + for _ in range(5): + pb.stepSimulation(physicsClientId=current_sim.client) + else: + if is_connected: + try: + current_sim.disconnect() + except Exception as e: + print(f"[Teardown Error] {e}") + current_sim = PandaSimulation(gui=gui, seed=0) + + await asyncio.to_thread(init_sim) + # Apply the client's visibility preference to show/hide the PyBullet GUI window on the desktop + await asyncio.to_thread(set_pybullet_window_visibility, client_wants_gui) + + # Send static scene configuration + init_payload = await asyncio.to_thread(get_init_payload, current_sim) + await websocket.send_json(init_payload) + + # Send the first simulation state to sync objects and joints + state_payload = await asyncio.to_thread(get_simulation_state_payload, current_sim) + if state_payload: + await websocket.send_json(state_payload) + + try: + while True: + data = await websocket.receive_text() + payload = json.loads(data) + + p_type = payload.get("type") + if p_type == "run": + prompt = payload.get("prompt", "") + use_mock = payload.get("mock", False) + asyncio.create_task( + asyncio.to_thread( + run_pipeline_threadsafe, + websocket, + prompt, + loop, + use_mock + ) + ) + + elif p_type == "reset": + async with executor_lock: + def reset_sim(): + with pybullet_lock: + current_sim.reset_objects(seed=0) + current_sim.controller.reset_to_home() + await asyncio.to_thread(reset_sim) + + state_payload = await asyncio.to_thread(get_simulation_state_payload, current_sim) + if state_payload: + await websocket.send_json(state_payload) + await websocket.send_json({"type": "log", "message": "🔄 Đã reset môi trường mô phỏng."}) + + elif p_type in ("camera_rotate", "camera_pan", "camera_zoom"): + pass + + except WebSocketDisconnect: + print("Client disconnected") + except Exception as e: + print(f"WS Exception: {e}") + +if __name__ == "__main__": + uvicorn.run("interactive_server:app", host="0.0.0.0", port=8000, reload=False) diff --git a/.history/frontend/interactive_server_20260627232008.py b/.history/frontend/interactive_server_20260627232008.py new file mode 100644 index 0000000000000000000000000000000000000000..977217e5c93c60f24b3473bfebf6a385d938547b --- /dev/null +++ b/.history/frontend/interactive_server_20260627232008.py @@ -0,0 +1,569 @@ +import sys +import os +import json +import asyncio +import math +import time +import threading +from typing import Optional +from fastapi import FastAPI, WebSocket, WebSocketDisconnect +from fastapi.staticfiles import StaticFiles +from fastapi.responses import HTMLResponse +import uvicorn +import cv2 +import numpy as np +import pybullet as pb +# Ensure project source root is in path +PROJECT_SRC = os.path.abspath(os.path.join(os.path.dirname(__file__), "..")) +if PROJECT_SRC not in sys.path: + sys.path.insert(0, PROJECT_SRC) +from dotenv import load_dotenv +load_dotenv() +from main import PandaSimulation, _YCB_CATALOG +from llm_panda.llm_agent import LLMAgent, RemoteLLMPlanner, RuleBasedPlanner +from llm_panda.plan_verifier import PlanVerifier +from llm_panda import config +import pybullet_data +from pybullet_object_models import ycb_objects +app = FastAPI(title="LLM-Panda Web-Embedded PyBullet Simulation") +# Serve static files from the frontend directory itself +static_dir = os.path.dirname(__file__) +app.mount("/static", StaticFiles(directory=static_dir), name="static") +# Mount robot meshes and YCB object assets +panda_data_path = os.path.join(pybullet_data.getDataPath(), "franka_panda") +ycb_data_path = ycb_objects.getDataPath() +app.mount("/assets/panda", StaticFiles(directory=panda_data_path), name="panda") +app.mount("/assets/ycb", StaticFiles(directory=ycb_data_path), name="ycb") +@app.get("/") +async def get(): + html_file = os.path.join(static_dir, "index.html") + if os.path.exists(html_file): + with open(html_file, "r", encoding="utf-8") as f: + return HTMLResponse(content=f.read(), status_code=200) + return HTMLResponse(content="

    index.html not found!

    ", status_code=404) +# Global variables to track the current active simulation, lock, and thread lock +current_sim: Optional[PandaSimulation] = None +executor_lock = asyncio.Lock() +pybullet_lock = threading.RLock() +def get_init_payload(sim: PandaSimulation) -> dict: + """Gathers the initial static geometry and YCB object definitions.""" + with pybullet_lock: + objects_info = {} + if sim and sim.scene: + for oid in sim.scene.object_ids: + name = sim.scene.get_name(oid) + cls = sim.scene.get_class(oid) + folder = "" + for cat_name, cat_cls, cat_folder in _YCB_CATALOG: + if cat_name == name: + folder = cat_folder + break + pos, ori = pb.getBasePositionAndOrientation(oid, physicsClientId=sim.client) + + # Query collision shape data for CoM-to-link offset + collision_data = pb.getCollisionShapeData(oid, -1, physicsClientId=sim.client) + coll_scale = [1.0, 1.0, 1.0] + coll_local_pos = [0.0, 0.0, 0.0] + coll_local_ori = [0.0, 0.0, 0.0, 1.0] + if collision_data: + cd = collision_data[0] + coll_scale = list(cd[3]) + coll_local_pos = list(cd[5]) + coll_local_ori = list(cd[6]) + # Query visual shape data for exact dimensions/scales and offsets relative to link + visual_data = pb.getVisualShapeData(oid, physicsClientId=sim.client) + vis_scale = [1.0, 1.0, 1.0] + vis_local_pos = [0.0, 0.0, 0.0] + vis_local_ori = [0.0, 0.0, 0.0, 1.0] + if visual_data: + vd = visual_data[0] + vis_scale = list(vd[3]) + # Transform visual frame to be relative to CoM: CoM_to_visual = CoM_to_link * link_to_visual + vis_pos_com, vis_ori_com = pb.multiplyTransforms( + coll_local_pos, coll_local_ori, + list(vd[5]), list(vd[6]) + ) + vis_local_pos = list(vis_pos_com) + vis_local_ori = list(vis_ori_com) + + objects_info[name] = { + "class": cls, + "folder": folder, + "initial_pos": list(pos), + "initial_ori": list(ori), + "vis_scale": vis_scale, + "vis_local_pos": vis_local_pos, + "vis_local_ori": vis_local_ori, + "coll_scale": coll_scale, + "coll_local_pos": coll_local_pos, + "coll_local_ori": coll_local_ori + } + return { + "type": "init", + "table": { + "center": [config.TABLE_CENTER[0], config.TABLE_CENTER[1], config.TABLE_BASE_Z], + "half_extents": list(config.TABLE_HALF_EXTENTS), + "color": list(config.TABLE_COLOR), + "top_z": config.TABLE_TOP_Z + }, + "tray": { + "position": list(config.TRAY_POSITION), + "half_extents": list(config.TRAY_HALF_EXTENTS), + "color": list(config.TRAY_COLOR) + }, + "slots": {name: list(pos) for name, pos in config.SLOTS.items()}, + "objects": objects_info + } +def get_simulation_state_payload(sim: PandaSimulation) -> dict: + """Gathers the current robot joint positions and YCB object poses.""" + with pybullet_lock: + if sim is None or sim.client is None or not pb.isConnected(sim.client): + return {} + + # Read all joints (12 joints including arm joints and gripper fingers) + num_joints = pb.getNumJoints(sim.robot_id, physicsClientId=sim.client) + joints_state = [] + for i in range(num_joints): + pos, _, _, _ = pb.getJointState(sim.robot_id, i, physicsClientId=sim.client) + joints_state.append(pos) + + # Read objects pos/ori + objects_state = {} + for oid in sim.scene.object_ids: + name = sim.scene.get_name(oid) + pos, ori = pb.getBasePositionAndOrientation(oid, physicsClientId=sim.client) + objects_state[name] = { + "pos": list(pos), + "ori": list(ori) + } + + return { + "type": "state", + "joints": joints_state, + "objects": objects_state + } +def set_pybullet_window_visibility(visible: bool): + """Finds the PyBullet GUI window on Windows and sets its visibility by moving it on/off-screen.""" + import sys + if sys.platform != "win32": + return False + import ctypes + import time + + EnumWindowsProc = ctypes.WINFUNCTYPE(ctypes.c_bool, ctypes.c_void_p, ctypes.c_void_p) + + for _ in range(30): + found_hwnd = [] + + def foreach_window(hwnd, lParam): + length = ctypes.windll.user32.GetWindowTextLengthW(hwnd) + buff = ctypes.create_unicode_buffer(length + 1) + ctypes.windll.user32.GetWindowTextW(hwnd, buff, length + 1) + title = buff.value + if "bullet physics examplebrowser" in title.lower(): + found_hwnd.append(hwnd) + return False + return True + + ctypes.windll.user32.EnumWindows(EnumWindowsProc(foreach_window), 0) + if found_hwnd: + hwnd = found_hwnd[0] + # Ensure the window is shown/restored from minimized state first (SW_SHOW = 5) + ctypes.windll.user32.ShowWindow(hwnd, 5) + + # SWP_NOSIZE = 0x0001, SWP_NOZORDER = 0x0004 + if visible: + # Move window to visible region + ctypes.windll.user32.SetWindowPos(hwnd, 0, 100, 100, 0, 0, 0x0001 | 0x0004) + else: + # Move window far off-screen to hide it without destroying OpenGL context + ctypes.windll.user32.SetWindowPos(hwnd, 0, -10000, -10000, 0, 0, 0x0001 | 0x0004) + print(f"[Window Visibility] Set PyBullet window (HWND: {hwnd}) visibility to: {visible}", flush=True) + return True + time.sleep(0.1) + return False +def compute_and_format_score(sim: PandaSimulation, plan: list, executed_successfully: bool): + """Calculates rearrangement score based on final object locations and collisions.""" + with pybullet_lock: + score = 100 + details = [] + + # Check target placement if we had a plan + target_location = None + target_object = None + for step in plan: + if step.get("function") in ("place_at", "place_down", "move_to"): + args = step.get("args", {}) + if "location_id" in args: + target_location = args["location_id"] + if step.get("function") == "pick_up": + target_object = step.get("args", {}).get("object_id") + + if target_object and target_location: + obj_id = sim.scene.name_to_id(target_object) + if obj_id is not None: + pos, _ = pb.getBasePositionAndOrientation(obj_id) + current_loc = sim.scene.classify_location(pos) + if current_loc == target_location: + details.append(f"✅ **Đã đặt {target_object} đúng vị trí {target_location}**: +50 điểm") + else: + details.append(f"❌ **{target_object} chưa đến đúng vị trí {target_location} (đang ở {current_loc})**: -50 điểm") + score -= 50 + else: + details.append(f"❌ **Không tìm thấy vật thể {target_object}**: -50 điểm") + score -= 50 + else: + details.append("ℹ️ Không có yêu cầu di chuyển vật thể cụ thể nào được phát hiện.") + + # Knock detection + knocked_count = 0 + for oid in sim.scene.object_ids: + if oid == sim.scene.name_to_id(target_object): + continue + pos, _ = pb.getBasePositionAndOrientation(oid) + loc = sim.scene.classify_location(pos) + if loc == "elsewhere": + name = sim.scene.get_name(oid) + details.append(f"⚠️ **Vật thể '{name}' bị lệch khỏi vị trí quy định**: -15 điểm") + score -= 15 + knocked_count += 1 + + if knocked_count == 0: + details.append("✅ **Không có vật thể nào khác bị va chạm hay xê dịch**: +30 điểm") + else: + score = max(0, score) + + # Execution success + if executed_successfully: + details.append("✅ **Thực thi toàn bộ kế hoạch thành công**: +20 điểm") + else: + details.append("❌ **Thực thi gặp lỗi gián đoạn**: -30 điểm") + score -= 30 + + score = max(0, min(100, score)) + + md = f"### 🏆 Rearrangement Evaluation Report\n\n**Tổng điểm: {score}/100**\n\n**Chi tiết:**\n" + "\n".join([f"- {d}" for d in details]) + return score, md +def run_pipeline_threadsafe(websocket: WebSocket, user_prompt: str, loop, use_mock: bool, camera_state: Optional[dict] = None): + """Runs the planning, validation, execution with image streaming, and scoring.""" + global current_sim + + def log(message: str, step: Optional[int] = None): + try: + print(f"[WS Log] {message}", flush=True) + except Exception: + pass + asyncio.run_coroutine_threadsafe( + websocket.send_json({"type": "log", "message": message, "step": step}), + loop + ) + # Step 1: Planning + log("⏳ [1/5] Đang lập kế hoạch (LLM Planner)...") + + if use_mock: + planner = RuleBasedPlanner() + log("✅ [1] Đang sử dụng RuleBasedPlanner (Offline)") + else: + api_key = os.environ.get("OPENAI_API_KEY") or os.environ.get("LLM_API_KEY") + if not api_key: + log("❌ [1] Lỗi: Không tìm thấy OPENAI_API_KEY / LLM_API_KEY. Vui lòng chọn Mock.") + return + planner = RemoteLLMPlanner() + log(f"✅ [1] Đang sử dụng RemoteLLMPlanner (Model: {planner.model})") + + with pybullet_lock: + current_sim.agent = LLMAgent(planner=planner) + + # Define reachability check for scene state + def reachability_fn(oid): + cls = current_sim.scene.get_class(oid) + try: + grasp_pos, grasp_ori = current_sim.grasp_planner.compute_grasp_pose(oid, cls) + return current_sim.controller.is_reachable(grasp_pos, grasp_ori) + except Exception: + return False + carried_name = current_sim.scene.get_name(current_sim._carried) if current_sim._carried is not None else None + scene_state = current_sim.scene.get_scene_state(reachability_fn=reachability_fn, carried_object=carried_name) + state_text = json.dumps(scene_state, indent=2) + + try: + with pybullet_lock: + plan = current_sim.agent.plan(user_prompt, state_text) + log(f"✅ [1] Đã tạo kế hoạch: {len(plan)} bước.") + except Exception as e: + log(f"❌ [1] Lập kế hoạch thất bại: {e}") + return + # Send steps to client + plan_steps = [] + for idx, step in enumerate(plan, 1): + func = step.get("function") + args = step.get("args", {}) + obj = args.get("object_id") or args.get("location_id") or "" + plan_steps.append({ + "step": idx, + "skill": func, + "object": obj, + "args": args + }) + + asyncio.run_coroutine_threadsafe( + websocket.send_json({"type": "plan", "plan": plan_steps}), + loop + ) + if not plan: + log("⚠️ [1] Kế hoạch rỗng.") + log("⏳ [5/5] Đang tính toán điểm sắp xếp...") + score_val, score_md = compute_and_format_score(current_sim, [], True) + asyncio.run_coroutine_threadsafe( + websocket.send_json({ + "type": "result", + "score_display": score_md, + "score_value": score_val + }), + loop + ) + state_payload = get_simulation_state_payload(current_sim) + if state_payload: + asyncio.run_coroutine_threadsafe(websocket.send_json(state_payload), loop) + return + # Step 2: Validation + log("⏳ [2/5] Đang kiểm tra kế hoạch (Validator)...") + try: + with pybullet_lock: + warnings = PlanVerifier.check(plan, scene_state) + if not warnings: + log("✅ [2] Kế hoạch hợp lệ.") + else: + log(f"⚠️ [2] Validator phát hiện {len(warnings)} cảnh báo.") + for w in warnings: + log(f" - {w}") + except Exception as e: + log(f"❌ [2] Lỗi kiểm tra kế hoạch: {e}") + return + # Step 3: PyBullet Execution (Live!) + log("⏳ [3/5] Đang thực thi hành động của robot...") + + # Hook pb.stepSimulation to capture states during movements + original_step = pb.stepSimulation + last_stream_time = [0.0] + throttle_interval = 0.033 + + def wrapped_step(): + original_step() + if not current_sim.gui: + # Sleep slightly in headless mode to simulate arm speed and avoid freezing + time.sleep(0.001) + curr_time = time.time() + if curr_time - last_stream_time[0] >= throttle_interval: + last_stream_time[0] = curr_time + state_payload = get_simulation_state_payload(current_sim) + if state_payload: + asyncio.run_coroutine_threadsafe( + websocket.send_json(state_payload), + loop + ) + + with pybullet_lock: + pb.stepSimulation = wrapped_step + + executed_successfully = True + try: + # Trigger an initial simulation state transmission + state_payload = get_simulation_state_payload(current_sim) + if state_payload: + asyncio.run_coroutine_threadsafe(websocket.send_json(state_payload), loop) + + for i, step in enumerate(plan, 1): + log(f"🚀 [3/5] Đang chạy bước {i}/{len(plan)}: {step['function']}") + with pybullet_lock: + current_sim._execute(step, verbose=True) + + log("✅ [3] Thực thi thành công toàn bộ kế hoạch.") + except Exception as e: + log(f"❌ Lỗi trong lúc thực thi mô phỏng: {e}") + executed_successfully = False + finally: + with pybullet_lock: + pb.stepSimulation = original_step + + # Send a final state to ensure visual sync + state_payload = get_simulation_state_payload(current_sim) + if state_payload: + asyncio.run_coroutine_threadsafe(websocket.send_json(state_payload), loop) + # Step 5: Scoring + log("⏳ [5/5] Đang tính toán điểm sắp xếp...") + score_val, score_md = compute_and_format_score(current_sim, plan, executed_successfully) + + asyncio.run_coroutine_threadsafe( + websocket.send_json({ + "type": "result", + "score_display": score_md, + "score_value": score_val + }), + loop + ) +@app.websocket("/ws") +async def websocket_endpoint(websocket: WebSocket): + global current_sim + await websocket.accept() + loop = asyncio.get_running_loop() + + # Retrieve user's desktop display preference from client query params + client_wants_gui = websocket.query_params.get("gui", "false").lower() == "true" + + # Force gui = False to run PyBullet completely headless (DIRECT mode) + gui = False + + camera_state = { + "target": [0.5, 0.0, 0.3], + "dist": 1.3, + "yaw": 45.0, + "pitch": -35.0 + } + + async with executor_lock: + def init_sim(): + global current_sim + with pybullet_lock: + is_connected = False + if current_sim is not None and current_sim.client is not None: + try: + is_connected = pb.isConnected(current_sim.client) + except Exception: + is_connected = False + + if is_connected and current_sim.gui == gui: + current_sim.reset_objects(seed=0) + current_sim.controller.reset_to_home() + for _ in range(5): + pb.stepSimulation(physicsClientId=current_sim.client) + else: + if is_connected: + try: + current_sim.disconnect() + except Exception as e: + print(f"[Teardown Error] {e}") + current_sim = PandaSimulation(gui=gui, seed=0) + + await asyncio.to_thread(init_sim) + # Apply the client's visibility preference to show/hide the PyBullet GUI window on the desktop + await asyncio.to_thread(set_pybullet_window_visibility, client_wants_gui) + + # Send static scene configuration + init_payload = await asyncio.to_thread(get_init_payload, current_sim) + await websocket.send_json(init_payload) + # Send the first simulation state to sync objects and joints + state_payload = await asyncio.to_thread(get_simulation_state_payload, current_sim) + if state_payload: + await websocket.send_json(state_payload) + + try: + while True: + data = await websocket.receive_text() + payload = json.loads(data) + + p_type = payload.get("type") + if p_type == "run": + prompt = payload.get("prompt", "") + use_mock = payload.get("mock", False) + asyncio.create_task( + asyncio.to_thread( + run_pipeline_threadsafe, + websocket, + prompt, + loop, + use_mock + ) + ) + + elif p_type == "reset": + async with executor_lock: + def reset_sim(): + with pybullet_lock: + current_sim.reset_objects(seed=0) + current_sim.controller.reset_to_home() + await asyncio.to_thread(reset_sim) + + state_payload = await asyncio.to_thread(get_simulation_state_payload, current_sim) + if state_payload: + await websocket.send_json(state_payload) + await websocket.send_json({"type": "log", "message": "🔄 Đã reset môi trường mô phỏng."}) + + elif p_type == "update_object_pose": + name = payload.get("name") + pos = payload.get("pos") + ori = payload.get("ori") + async with executor_lock: + def move_obj(): + with pybullet_lock: + oid = current_sim.scene.name_to_id(name) + if oid is not None: + pb.resetBasePositionAndOrientation(oid, pos, ori) + await asyncio.to_thread(move_obj) + + state_payload = await asyncio.to_thread(get_simulation_state_payload, current_sim) + if state_payload: + await websocket.send_json(state_payload) + + elif p_type == "update_joints": + joints_data = payload.get("joints") + async with executor_lock: + def move_joints(): + with pybullet_lock: + for idx, q in enumerate(joints_data[:7]): + pb.resetJointState(current_sim.robot_id, idx, q) + if len(joints_data) >= 11: + pb.resetJointState(current_sim.robot_id, 9, joints_data[9]) + pb.resetJointState(current_sim.robot_id, 10, joints_data[10]) + await asyncio.to_thread(move_joints) + + state_payload = await asyncio.to_thread(get_simulation_state_payload, current_sim) + if state_payload: + await websocket.send_json(state_payload) + elif p_type == "update_robot_ee": + pos = payload.get("pos") + async with executor_lock: + def move_robot_ee(): + with pybullet_lock: + link_state = pb.getLinkState( + current_sim.robot_id, + current_sim.controller.ee_index, + physicsClientId=current_sim.client + ) + ee_ori = link_state[1] + + solution = pb.calculateInverseKinematics( + current_sim.robot_id, + current_sim.controller.ee_index, + pos, + ee_ori, + lowerLimits=current_sim.controller._lower_limits, + upperLimits=current_sim.controller._upper_limits, + jointRanges=current_sim.controller._joint_ranges, + restPoses=current_sim.controller._rest_poses, + maxNumIterations=300, + residualThreshold=1e-5, + physicsClientId=current_sim.client + ) + + for idx, q in enumerate(solution[:7]): + pb.resetJointState( + current_sim.robot_id, + idx, + q, + physicsClientId=current_sim.client + ) + await asyncio.to_thread(move_robot_ee) + + state_payload = await asyncio.to_thread(get_simulation_state_payload, current_sim) + if state_payload: + await websocket.send_json(state_payload) + elif p_type in ("camera_rotate", "camera_pan", "camera_zoom"): + pass + + except WebSocketDisconnect: + print("Client disconnected") + except Exception as e: + print(f"WS Exception: {e}") +if __name__ == "__main__": + uvicorn.run("interactive_server:app", host="0.0.0.0", port=8000, reload=False) \ No newline at end of file diff --git a/.pytest_cache/.gitignore b/.pytest_cache/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..08a7f458f1f002823bc794c47ca1996a57e72c86 --- /dev/null +++ b/.pytest_cache/.gitignore @@ -0,0 +1,2 @@ +# Created by pytest automatically. +* diff --git a/.pytest_cache/CACHEDIR.TAG b/.pytest_cache/CACHEDIR.TAG new file mode 100644 index 0000000000000000000000000000000000000000..fce15ad7eaa74e5682b644c84efb75334c112f95 --- /dev/null +++ b/.pytest_cache/CACHEDIR.TAG @@ -0,0 +1,4 @@ +Signature: 8a477f597d28d172789f06886806bc55 +# This file is a cache directory tag created by pytest. +# For information about cache directory tags, see: +# https://bford.info/cachedir/spec.html diff --git a/.pytest_cache/README.md b/.pytest_cache/README.md new file mode 100644 index 0000000000000000000000000000000000000000..c7526af2448672de4537dfed042ed74daadb17bf --- /dev/null +++ b/.pytest_cache/README.md @@ -0,0 +1,8 @@ +# pytest cache directory # + +This directory contains data from the pytest's cache plugin, +which provides the `--lf` and `--ff` options, as well as the `cache` fixture. + +**Do not** commit this to version control. + +See [the docs](https://docs.pytest.org/en/stable/how-to/cache.html) for more information. diff --git a/.pytest_cache/v/cache/lastfailed b/.pytest_cache/v/cache/lastfailed new file mode 100644 index 0000000000000000000000000000000000000000..1833cc694cbd7cd95f388874f4cdf4a9ff4e8ff3 --- /dev/null +++ b/.pytest_cache/v/cache/lastfailed @@ -0,0 +1,3 @@ +{ + "tests/test_new_pipeline.py::test_pipeline_executor_completes_pick_and_place": true +} \ No newline at end of file diff --git a/.pytest_cache/v/cache/nodeids b/.pytest_cache/v/cache/nodeids new file mode 100644 index 0000000000000000000000000000000000000000..cd52c507b0c6865c7ba144efec9315ac296c2bae --- /dev/null +++ b/.pytest_cache/v/cache/nodeids @@ -0,0 +1,53 @@ +[ + "tests/test_geofik.py::test_clamp_acos_input", + "tests/test_geofik.py::test_franka_geometry", + "tests/test_geofik.py::test_rotations", + "tests/test_geofik.py::test_wrap_angle", + "tests/test_llm_plan.py::test_remote_llm_planner_expected[Case_1_g\\u1eafp qu\\u1ea3 chu\\u1ed1i l\\xean]", + "tests/test_llm_plan.py::test_remote_llm_planner_expected[Case_2_di chuy\\u1ec3n lon s\\xfap v\\xe0o Slot_3]", + "tests/test_llm_plan.py::test_remote_llm_planner_expected[Case_3_\\u0111\\u1ec3 v\\xe0o khay]", + "tests/test_llm_plan.py::test_remote_llm_planner_expected[Case_4_\\u0111\\u1eb7t qu\\u1ea3 chu\\u1ed1i l\\xean b\\xe0n]", + "tests/test_llm_plan.py::test_remote_llm_planner_expected[Case_5_\\u0111\\u1eb7t l\\xean b\\xe0n]", + "tests/test_llm_plan.py::test_rule_based_planner_expected[Case_1_g\\u1eafp qu\\u1ea3 chu\\u1ed1i l\\xean]", + "tests/test_llm_plan.py::test_rule_based_planner_expected[Case_2_di chuy\\u1ec3n lon s\\xfap v\\xe0o Slot_3]", + "tests/test_llm_plan.py::test_rule_based_planner_expected[Case_3_\\u0111\\u1ec3 v\\xe0o khay]", + "tests/test_llm_plan.py::test_rule_based_planner_expected[Case_4_\\u0111\\u1eb7t qu\\u1ea3 chu\\u1ed1i l\\xean b\\xe0n]", + "tests/test_llm_plan.py::test_rule_based_planner_expected[Case_5_\\u0111\\u1eb7t l\\xean b\\xe0n]", + "tests/test_new_pipeline.py::test_contact_sampler_antipodal_constraints", + "tests/test_new_pipeline.py::test_grasp_candidate_generator", + "tests/test_new_pipeline.py::test_mesh_parser_loads_obj", + "tests/test_new_pipeline.py::test_pipeline_executor_completes_pick_and_place", + "tests/test_new_pipeline.py::test_rrt_connect_planner_finds_path", + "tests/test_occupancy.py::test_carried_object_is_excluded", + "tests/test_occupancy.py::test_carried_object_location_is_elsewhere", + "tests/test_occupancy.py::test_empty_table_is_fully_free", + "tests/test_occupancy.py::test_find_free_placements_avoids_occupied_region", + "tests/test_occupancy.py::test_object_larger_than_table_has_no_placement", + "tests/test_occupancy.py::test_occupied_area_tracks_object_footprint", + "tests/test_occupancy.py::test_reachable_filter_is_applied", + "tests/test_occupancy.py::test_tray_object_does_not_count_against_the_table", + "tests/test_pipeline.py::test_corridor_obstacle_detected", + "tests/test_pipeline.py::test_corridor_obstacle_not_detected_beyond_target", + "tests/test_pipeline.py::test_force_frictionless_is_finite_and_clamped", + "tests/test_pipeline.py::test_force_saturates_high_and_low", + "tests/test_pipeline.py::test_force_within_envelope_for_extreme_mass[-100.0]", + "tests/test_pipeline.py::test_force_within_envelope_for_extreme_mass[0.05]", + "tests/test_pipeline.py::test_force_within_envelope_for_extreme_mass[0.0]", + "tests/test_pipeline.py::test_force_within_envelope_for_extreme_mass[1.0]", + "tests/test_pipeline.py::test_force_within_envelope_for_extreme_mass[1000000.0]", + "tests/test_pipeline.py::test_force_within_envelope_for_extreme_mass[1000000000000.0]", + "tests/test_pipeline.py::test_force_within_envelope_for_extreme_mass[1e-09]", + "tests/test_pipeline.py::test_force_within_envelope_for_extreme_mass[50.0]", + "tests/test_pipeline.py::test_free_slot_prefers_reachable_order", + "tests/test_pipeline.py::test_grasp_offset_is_rotation_invariant[0.0]", + "tests/test_pipeline.py::test_grasp_offset_is_rotation_invariant[135.0]", + "tests/test_pipeline.py::test_grasp_offset_is_rotation_invariant[180.0]", + "tests/test_pipeline.py::test_grasp_offset_is_rotation_invariant[45.0]", + "tests/test_pipeline.py::test_grasp_offset_is_rotation_invariant[90.0]", + "tests/test_pipeline.py::test_grasp_rotation_actually_moves_world_point", + "tests/test_pipeline.py::test_grasp_survives_fast_translation", + "tests/test_pipeline.py::test_plan_verifier_detects_out_of_reach", + "tests/test_pipeline.py::test_rule_based_planner_two_step_pick_place", + "tests/test_task_nullspace.py::test_box_manifold_jacobian", + "tests/test_task_nullspace.py::test_cylinder_manifold_jacobian" +] \ No newline at end of file diff --git a/.pytest_cache/v/cache/stepwise b/.pytest_cache/v/cache/stepwise new file mode 100644 index 0000000000000000000000000000000000000000..0637a088a01e8ddab3bf3fa98dbe804cbde1a0dc --- /dev/null +++ b/.pytest_cache/v/cache/stepwise @@ -0,0 +1 @@ +[] \ No newline at end of file diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..7667b88919b8bdfcdd94bf7985f19eec554ec71e --- /dev/null +++ b/Dockerfile @@ -0,0 +1,45 @@ +# Sử dụng image Python 3.10 slim để nhẹ gọn +FROM python:3.10-slim + +# Biến môi trường để không tạo bytecode và log output trực tiếp +ENV PYTHONDONTWRITEBYTECODE=1 +ENV PYTHONUNBUFFERED=1 + +# Thiết lập thư mục làm việc +WORKDIR /app + +# Cài đặt các gói thư viện hệ thống cần thiết cho PyBullet và hệ thống +# libgl1-mesa-glx và libglib2.0-0 là cần thiết cho các thư viện C++ (như OpenCV/PyBullet) +RUN apt-get update && apt-get install -y --no-install-recommends \ + build-essential \ + libgl1-mesa-glx \ + libglib2.0-0 \ + && rm -rf /var/lib/apt/lists/* + +# Copy file requirements.txt trước để tận dụng cache Docker +COPY requirements.txt . + +# Cài đặt các thư viện Python +RUN pip install --no-cache-dir -r requirements.txt + +# Copy toàn bộ mã nguồn vào image +COPY . . + +# Tạo một user không có quyền root theo yêu cầu bảo mật của Hugging Face Spaces (khuyến nghị) +RUN useradd -m -u 1000 user +USER user +ENV HOME=/home/user +ENV PATH=/home/user/.local/bin:$PATH + +# Thiết lập thư mục làm việc của user (Spaces thường map vào home của user) +WORKDIR $HOME/app + +# Copy lại code vào home của user và phân quyền +COPY --chown=user . $HOME/app + +# Mở cổng 7860 (cổng bắt buộc trên Hugging Face Spaces) +EXPOSE 7860 + +# Lệnh khởi chạy server (sử dụng uvicorn chạy FastAPI app) +# Lưu ý: "frontend.interactive_server:app" là tên module và biến chứa ứng dụng FastAPI +CMD ["uvicorn", "frontend.interactive_server:app", "--host", "0.0.0.0", "--port", "7860"] diff --git a/EVAL_EVIDENCES.md b/EVAL_EVIDENCES.md new file mode 100644 index 0000000000000000000000000000000000000000..fbba2243ef69e0c276e6d8a2bdeb4d85141b3000 --- /dev/null +++ b/EVAL_EVIDENCES.md @@ -0,0 +1,163 @@ +# Evaluation Evidences — LLM Planner Test Report + +**Date:** 2026-06-19 +**Environment:** Linux, Python 3.13.13, pytest 9.0.3 +**Command executed:** `pytest -v tests/test_llm_plan.py` +**Test data:** [`tests/test_llm_expected.json`](tests/test_llm_expected.json) — 5 manual test cases + +--- + +## 1. Test design (đúng yêu cầu) + +| Loại | Số case | Case IDs | +|------|---------|----------| +| Happy path | 3 | 1, 2, 3 | +| Edge case | 1 | 4 | +| Error case | 1 | 5 | +| **Tổng** | **5** | | + +Mỗi case ghi rõ **input** (`instruction` + `scene_state`) và **expected output** (`expected_plan`) trong +`tests/test_llm_expected.json`. Ba happy-path được chọn để mỗi case minh hoạ **một cấu trúc kế hoạch khác nhau** +(pick đơn lẻ / pick→slot→place / pick→tray→place), không trùng lặp. + +--- + +## 2. Bằng chứng "không mock / không hardcode" + +Đây là điểm cốt lõi của báo cáo. Mỗi case được kiểm chứng **độc lập bởi HAI bộ lập kế hoạch**, và cả hai +phải cho ra **đúng cùng một `expected_plan`** thì test mới pass: + +1. **`RuleBasedPlanner`** — bộ suy luận xác định, chạy **offline** (không mạng, không API key). + *Test:* `test_rule_based_planner_expected`. +2. **`RemoteLLMPlanner`** — gọi **API LLM thật** qua endpoint OpenAI-compatible. + *Test:* `test_remote_llm_planner_expected`. + - **Model:** `google/gemma-3n-e2b-it` + - **Endpoint:** `https://integrate.api.nvidia.com/v1` + - Nếu **không** có API key trong môi trường, test này tự `skip` (xem `test_llm_plan.py:35`) — + tức là khi nó **PASSED** thì chắc chắn đã có một lệnh gọi mạng thật được thực hiện. + +> Vì sao điều này chứng minh không mock: `expected_plan` **không** được nhúng vào prompt gửi cho LLM +> (xem `RemoteLLMPlanner.SYSTEM_PROMPT` — chỉ gửi scene + instruction). Việc một mô hình ngôn ngữ +> bên ngoài và một bộ luật offline **độc lập** cùng tạo ra y hệt chuỗi function-call cho thấy kết quả +> đến từ suy luận thực, không phải giá trị được hardcode. + +### Lưu ý trung thực về error case + +`RuleBasedPlanner` **không** kiểm tra trường `reachable`, nên "vật ngoài tầm với" **không** được dùng +làm error case (hai planner sẽ bất đồng). Ngoài ra, khi thử case "ra lệnh đặt xuống trong khi tay gắp +trống", LLM thật **không** tuân thủ ràng buộc và vẫn sinh `move_to + place_down` thay vì `[]` — nên case +đó cũng bị loại. Error case được giữ lại (Case 5: vật không tồn tại) là case mà **cả hai** planner +nhất quán trả về kế hoạch rỗng. + +--- + +## 3. Kết quả chạy thực tế (Actual Output) + +```text +============================= test session starts ============================== +platform linux -- Python 3.13.13, pytest-9.0.3, pluggy-1.6.0 +rootdir: /media/minhnht31/data/vinuni/C2-App-151 +configfile: pytest.ini +collected 10 items + +tests/test_llm_plan.py::test_rule_based_planner_expected[Case_1_gắp quả chuối lên] PASSED [ 10%] +tests/test_llm_plan.py::test_rule_based_planner_expected[Case_2_di chuyển lon súp vào Slot_3] PASSED [ 20%] +tests/test_llm_plan.py::test_rule_based_planner_expected[Case_3_gắp bim bim bỏ vào khay] PASSED [ 30%] +tests/test_llm_plan.py::test_rule_based_planner_expected[Case_4_đặt vào khay] PASSED [ 40%] +tests/test_llm_plan.py::test_rule_based_planner_expected[Case_5_gắp con mèo lên] PASSED [ 50%] +tests/test_llm_plan.py::test_remote_llm_planner_expected[Case_1_gắp quả chuối lên] PASSED [ 60%] +tests/test_llm_plan.py::test_remote_llm_planner_expected[Case_2_di chuyển lon súp vào Slot_3] PASSED [ 70%] +tests/test_llm_plan.py::test_remote_llm_planner_expected[Case_3_gắp bim bim bỏ vào khay] PASSED [ 80%] +tests/test_llm_plan.py::test_remote_llm_planner_expected[Case_4_đặt vào khay] PASSED [ 90%] +tests/test_llm_plan.py::test_remote_llm_planner_expected[Case_5_gắp con mèo lên] PASSED [100%] + +============================= 10 passed in 14.95s ============================== +``` + +* **Tests collected:** 10 (5 cases × 2 planners) +* **Passed:** 10 · **Failed:** 0 · **Skipped:** 0 +* **Status:** SUCCESS ✅ — `actual_plan == expected_plan` cho **mọi** case, ở **cả hai** planner. + +--- + +## 4. Phân tích chi tiết từng case + +Mỗi mục dưới đây: **Input** (instruction + trạng thái scene rút gọn) → **Expected = Actual** (kế hoạch +khớp ở cả `RuleBasedPlanner` offline và LLM thật). + +### ✅ Case 1 — Happy path: pick đơn lẻ +* **Instruction:** `"gắp quả chuối lên"` +* **Input scene:** `carried_object = null`; banana@Slot_4, soup_can@Slot_2, chips_can@Slot_3. +* **Lý do:** Có động từ pick (`gắp`) + đối tượng (`quả chuối` → `banana`), **không** có đích đến → + chỉ sinh một bước `pick_up`, không tự thêm `move_to`/`place_down`. +* **Expected = Actual:** + ```json + [ + {"function": "pick_up", "args": {"object_id": "banana"}} + ] + ``` + +### ✅ Case 2 — Happy path: pick → slot → place +* **Instruction:** `"di chuyển lon súp vào Slot_3"` +* **Input scene:** `carried_object = null`; soup_can@Slot_5; `Slot_3` ∈ `free_slots`. +* **Lý do:** Tay gắp trống nên phải `pick_up` trước, rồi `move_to` đích `Slot_3` (đang trống) và + `place_down`. +* **Expected = Actual:** + ```json + [ + {"function": "pick_up", "args": {"object_id": "soup_can"}}, + {"function": "move_to", "args": {"location_id": "Slot_3"}}, + {"function": "place_down", "args": {}} + ] + ``` + +### ✅ Case 3 — Happy path: pick → tray → place +* **Instruction:** `"gắp bim bim bỏ vào khay"` +* **Input scene:** `carried_object = null`; chips_can@Slot_6; tray trống. +* **Lý do:** `bim bim` → `chips_can`; `khay` → `tray`. Tay gắp trống → `pick_up` rồi `move_to tray` + + `place_down`. +* **Expected = Actual:** + ```json + [ + {"function": "pick_up", "args": {"object_id": "chips_can"}}, + {"function": "move_to", "args": {"location_id": "tray"}}, + {"function": "place_down", "args": {}} + ] + ``` + +### ✅ Case 4 — Edge case: tay gắp ĐANG giữ vật (one-gripper state) +* **Instruction:** `"đặt vào khay"` +* **Input scene:** `carried_object = "banana"` (đang cầm chuối); chỉ nêu đích, **không** nêu vật. +* **Lý do (edge):** Vì đã có vật trên tay (ràng buộc 1 gripper giữ tối đa 1 vật), planner **không** + được sinh `pick_up` mới — chỉ `move_to tray` + `place_down`. Đây là case dễ sai nếu planner máy móc + luôn bắt đầu bằng `pick_up`. +* **Expected = Actual:** + ```json + [ + {"function": "move_to", "args": {"location_id": "tray"}}, + {"function": "place_down", "args": {}} + ] + ``` + +### ✅ Case 5 — Error case: vật không tồn tại +* **Instruction:** `"gắp con mèo lên"` +* **Input scene:** `carried_object = null`; scene chỉ có banana / soup_can / chips_can. +* **Lý do (error):** `con mèo` không khớp đối tượng nào trong scene và không có đích đến hợp lệ → + planner phải trả **kế hoạch rỗng** thay vì bịa ra hành động. Cả `RuleBasedPlanner` và LLM thật đều + trả `[]`. +* **Expected = Actual:** + ```json + [] + ``` + +--- + +## 5. Tự kiểm tra lại + +```bash +# Offline (rule-based) — không cần API key: +pytest -v tests/test_llm_plan.py -k rule_based + +# Có gọi LLM thật — cần OPENAI_API_KEY/LLM_API_KEY trong môi trường (hoặc .env): +pytest -v tests/test_llm_plan.py -k remote +``` diff --git a/GeoFIK/README.md b/GeoFIK/README.md new file mode 100644 index 0000000000000000000000000000000000000000..d03117ebd0de34a9cf763e719ed90c13e5cd7257 --- /dev/null +++ b/GeoFIK/README.md @@ -0,0 +1,295 @@ +# GeoFIK: A fast and reliable geometric IK solver for the Franka arm + +**GeoFIK** (**Geo**metric **F**ranka **IK**) is an analytical geometric solver for the inverse kinematics (IK) of the Franka arm. GeoFIK has the following advantages over other solvers: +* GeoFIK is ultra fast! It is an analytical solver, so the computational time is in the order of tens of microseconds on standard laptops. This is much faster than numerical solvers and, according to our experiments, also faster than the algebraic analytical solvers generated by IKFast. +* Unlike other analytical solvers, GeoFIK provides four different ways to resolve the 1-DOF redundancy of the Franka arm. Functions that solve the IK using $$q\_7$$, $$q\_6$$, $$q\_4$$ or the swivel angle as free variables are provided. +* Before computing the joint angles, GeoFIK finds the entire geometry of the arm by calculating the screw axes of the joints. Hence, the Jacobian matrices for each IK solution are returned at no significan extra computational cost. +* Due to its geometric nature, all possible solutions for the IK problem with redundancy solved are found. We proved that the maximum number is 8. Joint limits are checked before returning the solutions. +* All singularities are detected and handled efficiently using screw theory. The user can provide emergency values of joint angles to resolve the singularity. + +For detailed information about the implementation, tests and experiments, see the preprint of our paper [arXiv:2503.03992v1](https://arxiv.org/abs/2503.03992v1). + +## Requirements + +This version has been tested with GCC compiler for C++ 17. The functions use the Eigen library which can be downloaded [here](https://eigen.tuxfamily.org). This version was tested with Eigen 3.4.0. + +## Usage + +### World and end-effector frames + +GeoFIK uses frame $$E$$ as end-effector frame, and frame $$O$$ as world frame, as shown in the picture below. In [franka_ros](https://frankaemika.github.io/docs/franka_ros.html) $$E$$ and $$O$$ are named `panda_hand_tcp` and `panda_link0`, respectively. + +![frames of the franka arm](frames.png) + +Some applications, especially when the gripper is removed, may use the flage frame 8 (`panda_link8`) also called $$F$$ as end-effector frame. The transformation between this frame and frame $$E$$ is shown in the figure above and can be represented by the following transformation matrix $${}^{8}\_{E}$$𝐓: +``` +T8E = [[ 0.70710678 0.70710678 0. 0. ] + [-0.70710678 0.70710678 0. 0. ] + [ 0. 0. 1. 0.1034 ] + [ 0. 0. 0. 1. ]] +``` +Therefore, when working with frame 8, given a desired pose $${}^{O}\_{8}$$𝐓, the solver must be called with $${}^{O}\_{E}$$𝐓 = $${}^{O}\_{8}$$𝐓 $${}^{8}\_{E}$$𝐓. + +### Functions provided + +**Functions that only calculate joint angles** + +All functions return the number of solutions found as an `unsigned int`. 8 solutions for joint angles are stored in an array `qsols` which is passed by reference by the caller. If a solution does not exist `nan` is assigned to all the entries of the corresponding row. If a joint angle is outside the joint limits in a found solution, `nan` is assigned to the joint angle. + +--- + +``` +unsigned int franka_ik_q7(const array& r, + const array& ROE, + const double q7, + array, 8>& qsols, + const double q1_sing = PI / 2) +``` +Solves the IK with $$q\_7$$ as free variable, generates joint angles of solutions. +* `r` position of frame $$E$$ in world frame $$O$$. +* `ROE` rotation matrix of frame $$E$$ with respect to frame $$O$$ (row-first format). +* `q7` joint angle of joint 7 (radians). +* `qsols` array to store 8 solutions. +* `q1_sing` [optional] emergency value of $$q\_1$$ in case of singularity at shoulder joints (type-1 singularity in our [paper](https://arxiv.org/abs/2503.03992v1)) + +--- + +``` +unsigned int franka_ik_q6(const array& r, + const array& ROE, + const double q6, + array, 8>& qsols, + const double q1_sing = PI / 2, + const double q7_sing = 0) +``` +Solves the IK with $$q\_6$$ as free variable, generates joint angles of solutions. +* `r` position of frame $$E$$ in world frame $$O$$. +* `ROE` rotation matrix of frame $$E$$ with respect to frame $$O$$ (row-first format). +* `q6` joint angle of joint 6 (radians). +* `qsols` array to store 8 solutions. +* `q1_sing` [optional] emergency value of $$q\_1$$ in case of singularity at shoulder joints (type-1 singularity in our [paper](https://arxiv.org/abs/2503.03992v1)) +* `q7_sing` [optional] emergency value of q7 in case of type-2 singularity (see our [paper](https://arxiv.org/abs/2503.03992v1)). + +--- + +``` +unsigned int franka_ik_q4(const array& r, + const array& ROE, + const double q4, + array, 8>& qsols, + const double q1_sing = PI / 2, + const double q7_sing = 0) +``` +Solves the IK with $$q\_4$$ as free variable, generates joint angles of solutions. +* `r` position of frame $$E$$ in world frame $$O$$. +* `ROE` rotation matrix of frame $$E$$ with respect to frame $$O$$ (row-first format). +* `q4` joint angle of joint 4 (radians). +* `qsols` array to store 8 solutions. +* `q1_sing` [optional] emergency value of $$q\_1$$ in case of singularity at shoulder joints (type-1 singularity in our [paper](https://arxiv.org/abs/2503.03992v1)) +* `q7_sing` [optional] emergency value of q7 in case of type-2 singularity (see our [paper](https://arxiv.org/abs/2503.03992v1)) + +--- + +``` +unsigned int franka_ik_swivel(const array& r, + const array& ROE, + const double theta, + array, 8>& qsols, + const double q1_sing = PI / 2, + const unsigned int n_points = 600) +``` +Solves the IK with the swivel angle as free variable, generates joint angles of solutions. See our [paper](https://arxiv.org/abs/2503.03992v1) for the geometric definition of swivel angle used here. This is a numerical algorithm as no closed-form solution exists. However, since the solver only uses the strictly necessary geometric information in each iteration, the computational times on standard laptops range in the few hundreds of microseconds. +* `r` position of frame $$E$$ in world frame $$O$$. +* `ROE` rotation matrix of frame $$E$$ with respect to frame $$O$$ (row-first format). +* `theta` swivel angle in radians (see paper for geometric defninition). +* `qsols` array to store 8 solutions. +* `q1_sing` [optional] emergency value of $$q\_1$$ in case of singularity at shoulder joints (type-1 singularity in our [paper](https://arxiv.org/abs/2503.03992v1)) +* `n_points` [optional] number of points to discretise the range of q7. + +--- + +**Functions that calculate joint angles and Jacobian matrices** + +The following functions include the optional parameter `Jacobian_ee` which allows to specify an end-effector frame for the Jacobian. Note that this can be different to the end-effector frame of the IK which is _always_ $$E$$. When working with frames $$F$$, $$8$$ or $$6$$, this parameter allows the user to get the Jacobian in the desired frame without having to transform it manually, saving computational time. + +--- + +``` +unsigned int franka_J_ik_q7(const array& r, + const array& ROE, + const double q7, + array, 7>, 8>& Jsols, + array, 8>& qsols, + const bool joint_angles = false, + const char Jacobian_ee = 'E', + const double q1_sing = PI / 2) +``` +Solves the IK with $$q\_7$$ as free variable, generates the joint angles and the Jacobians of all solutions. +* `r` position of frame $$E$$ in world frame $$O$$. +* `ROE` rotation matrix of frame $$E$$ with respect to frame $$O$$ (row-first format). +* `q7` joint angle of joint 7 (radians). +* `Jsols` array to store 8 Jacobian solutions. +* `qsols` array to store 8 solutions. +* `joint_angles` [optional] if `false` only Jacobians are returned. +* `Jacobian_ee` [optional] end-effector frame of the Jacobian (`'E'`, `'F'`, `'8'` or `'6'`). +* `q1_sing` [optional] emergency value of $$q\_1$$ in case of singularity at shoulder joints (type-1 singularity in our [paper](https://arxiv.org/abs/2503.03992v1)) + +--- + +``` +unsigned int franka_J_ik_q6(const array& r, + const array& ROE, + const double q6, + array, 7>, 8>& Jsols, + array, 8>& qsols, + const bool joint_angles = false, + const char Jacobian_ee = 'E', + const double q1_sing = PI / 2, + const double q7_sing = 0) +``` +Solves the IK with $$q\_6$$ as free variable, generates the joint angles and the Jacobians of all solutions. +* `r` position of frame $$E$$ in world frame $$O$$. +* `ROE` rotation matrix of frame $$E$$ with respect to frame $$O$$ (row-first format). +* `q6` joint angle of joint 6 (radians). +* `Jsols` array to store 8 Jacobian solutions. +* `qsols` array to store 8 solutions. +* `joint_angles` [optional] if `false` only Jacobians are returned. +* `Jacobian_ee` [optional] end-effector frame of the Jacobian (`'E'`, `'F'`, `'8'` or `'6'`). +* `q1_sing` [optional] emergency value of $$q\_1$$ in case of singularity at shoulder joints (type-1 singularity in our [paper](https://arxiv.org/abs/2503.03992v1)) +* `q7_sing` [optional] emergency value of $$q\_7$$ in case of type-2 singularity (see our [paper](https://arxiv.org/abs/2503.03992v1)). + +--- + +``` +unsigned int franka_J_ik_q4(const array& r, + const array& ROE, + const double q4, + array, 7>, 8>& Jsols, + array, 8>& qsols, + const bool joint_angles = false, + const char Jacobian_ee = 'E', + const double q1_sing = PI / 2, + const double q7_sing = 0) +``` +Solves the IK with $$q\_4$$ as free variable, generates the joint angles and the Jacobians of all solutions. +* `r` position of frame $$E$$ in world frame $$O$$. +* `ROE` rotation matrix of frame $$E$$ with respect to frame $$O$$ (row-first format). +* `q4` joint angle of joint 4 (radians). +* `Jsols` array to store 8 Jacobian solutions. +* `qsols` array to store 8 solutions. +* `joint_angles` [optional] if `false` only Jacobians are returned. +* `Jacobian_ee` [optional] end-effector frame of the Jacobian (`'E'`, `'F'`, `'8'` or `'6'`). +* `q1_sing` [optional] emergency value of $$q\_1$$ in case of singularity at shoulder joints (type-1 singularity in our [paper](https://arxiv.org/abs/2503.03992v1)) +* `q7_sing` [optional] emergency value of $$q\_7$$ in case of type-2 singularity (see our [paper](https://arxiv.org/abs/2503.03992v1)). + +--- + +``` +unsigned int franka_J_ik_swivel(const array& r, + const array& ROE, + const double theta, + array, 7>, 8>& Jsols, + array, 8>& qsols, + const bool joint_angles = false, + const char Jacobian_ee = 'E', + const double q1_sing = PI / 2, + const unsigned int n_points = 600) +``` +Solves the IK with the swivel angle as free variable, generates the joint angles and the Jacobians of all solutions. +* `r` position of frame $$E$$ in world frame $$O$$. +* `ROE` rotation matrix of frame $$E$$ with respect to frame $$O$$ (row-first format). +* `theta` swivel angle in radians (see paper for geometric defninition). +* `Jsols` array to store 8 Jacobian solutions. +* `qsols` array to store 8 solutions. +* `joint_angles` [optional] if `false` only Jacobians are returned. +* `Jacobian_ee` [optional] end-effector frame of the Jacobian (`'E'`, `'F'`, `'8'` or `'6'`). +* `q1_sing` [optional] emergency value of $$q\_1$$ in case of singularity at shoulder joints (type-1 singularity in our [paper](https://arxiv.org/abs/2503.03992v1)) +* `n_points` [optional] number of points to discretise the range of $$q\_7$$. + +--- + +**Other handy functions** + +--- + +``` +array J_to_q(const array, 7>& J, + const array, 3>& R, + const char ee = 'E') +``` +Returns the joint angles given a Jacobian matrix and orientation of the end-effector frame. +* `J` transpose of Jacobian matrix. +* `R` the rotation matrix of end-effector frame with respect to frame $O$. +* `ee` [optional] name of end-effector frame (`'E'`, `'F'` or `'8'`). + +--- + +``` +array, 7> J_from_q(const array& q, + const char ee = 'E'); +``` +Computes the Jacobian given the joint angles. +* `q` joint angles, name of ee frame. +* `ee` [optional] Name of end-effector frame (`'E'`, `'F'`, `'8'`, ...,`'1'`). + +--- + +``` +Eigen::Matrix4d franka_fk(const array& q, const char ee = 'E'); +``` +Forward kinematics function. Returns the transformation matrix of the specified end-effector frame with respect to world frame $$O$$. +* `q` joint angles, +* `ee` name of ee frame (`'E'`, `'F'`, `'8'`, ...,`'1'`). + +--- + +## Examples + +The file `example_geofik.cpp` shows how to import GeoFIK, and how to call each of the solvers with case examples. For the fastest results, it is recommended to compile with optimization level 3, using a GCC compiler: +``` +g++ example_geofik.cpp geofik.cpp -O3 -o example_geofik.exe +``` + +### Minimal example: + +Consider the IK problem with end-effector position and orientation given by $${}^{O}\_{E}$$𝐓: + +``` +TOE = [[ 0.3522750000000002 0.8334980991082203 0.4256560000000001 -0.26617644] + [-0.6332361000000003 -0.12262271641620001 0.764183 0.31984145] + [ 0.6891402000000002 -0.5387433117066003 0.48460420000000004 0.76295964] + [ 0. 0. 0. 1. ]] +``` + +and a desired value for the fourth joint angle $$q\_4$$ = -2.3402. Then, the following code calls the solver and saves the solutions in the `qsols` array: + +``` +unsigned int nsols; +array ROE = { 0.3522750000000002, 0.8334980991082203, 0.4256560000000001, + -0.6332361000000003, -0.12262271641620001, 0.764183, + 0.6891402000000002, -0.5387433117066003, 0.48460420000000004 }; +array r = { -0.26617644,0.31984145,0.76295964 }; +double q4 = -2.3402; +array, 8> qsols; +nsols = franka_ik_q4(r, ROE, q4, qsols); +``` + +The result is stored in `qsols`. `nan` is assigned to joint angles that are outside the joint limits, and to entire solutions that cannot be assamblied. + +## Cite this work + +This paper is currently under review. The ArXiv preprint can be found [here](https://arxiv.org/abs/2503.03992v1) and can be cited as: + +* Lopez-Custodio PC, Gong Y, Figueredo LFC, “GeoFIK: A Fast and Reliable Geometric Solver for the IK of the Franka Arm based on Screw Theory Enabling Multiple Redundancy Parameters”, PREPRINT: arXiv:2503.03992v1 (2025) + +``` +@misc{lopezcustodio2025geofikfastreliablegeometric, + title={GeoFIK: A Fast and Reliable Geometric Solver for the IK of the Franka Arm based on Screw Theory Enabling Multiple Redundancy Parameters}, + author={Pablo C. Lopez-Custodio and Yuhe Gong and Luis F. C. Figueredo}, + year={2025}, + eprint={2503.03992}, + archivePrefix={arXiv}, + primaryClass={cs.RO}, + url={https://arxiv.org/abs/2503.03992}, +} +``` diff --git a/GeoFIK/example_geofik.cpp b/GeoFIK/example_geofik.cpp new file mode 100644 index 0000000000000000000000000000000000000000..c2a5984627c56c26051fbd953e1c3489e30c203b --- /dev/null +++ b/GeoFIK/example_geofik.cpp @@ -0,0 +1,273 @@ +#include +#include +#include +#include +#include "Eigen/Dense" +#include +using namespace std; +using namespace std::chrono; + +#include "geofik.h" + +// compile with: g++ example_geofik.cpp geofik.cpp -O3 -o example_geofik.exe + +void print_results(const array, 8>& sols, const bool swivel = false, const double theta = 0.0); +void print_results_J(const array, 7>, 8>& Jsols, const array, 8>& qsols, const bool joint_angles, const bool swivel = false, const double theta = 0.0); + +int main() { + + unsigned int nsols = 0; + array ROE; // rotation matrix of frame E with respect to frame O + array r; // position vector of frame E with respect to frame O + double q7, q6, q4, theta; // free variables + bool joint_angles; + array, 8> qsols; + array, 7>, 8> Jsols; + high_resolution_clock::time_point start = high_resolution_clock::now(); + high_resolution_clock::time_point end = high_resolution_clock::now(); + auto duration = duration_cast(end - start); + + // TEST franka_ik_q7() + cout << endl << "=======================================================" << endl; + cout << "franka_ik_q7()" << endl; + cout << "=======================================================" << endl; + ROE = {0.6688331000000003,0.3170534383478098,0.6724130000000006,-0.6398146000000005,-0.2150772409286401,0.7378204999999999,0.3785492999999998,-0.9236984268883508,0.05900459999999996}; + r = {0.61674948,0.32278029,0.56790512}; + q7 = -0.37218362471412003 ; + start = high_resolution_clock::now(); + nsols = franka_ik_q7(r, ROE, q7, qsols); + end = high_resolution_clock::now(); + duration = duration_cast(end - start); + print_results(qsols); + cout << "number of solutions found:" << nsols; + cout << endl << "duration (only q):" << duration.count() << endl; + // second run + start = high_resolution_clock::now(); + nsols = franka_ik_q7(r, ROE, q7, qsols); + end = high_resolution_clock::now(); + duration = duration_cast(end - start); + cout << endl << "duration in second run:" << duration.count() << endl; + + + // TEST franka_ik_q6() + /* + cout << endl << "=======================================================" << endl; + cout << "franka_ik_q6()" << endl; + cout << "=======================================================" << endl; + //test parallel case: + ROE = {-0.6575819999999999,0.22565347159914026,0.7187951000000004,0.5218621000000001,-0.5516899774048302,0.6506136000000007,0.5433652999999999,0.8029437126709107,0.24502140000000006}; + r = {0.65543571,0.5899264,0.59988412}; + q6 = 3.141592653589793 ; + //test non-parallel case: + //ROE = { -0.1192774000000002,0.8774473359489797,0.4646064,0.47138319999999956,0.4618910375721001,-0.7513018999999999,-0.8738254000000001,0.12939431432541965,-0.4687071000000001 }; + //r = { 0.43749227,-0.73488144,0.4951873 }; + //q6 = 2.6179938779914944; + start = high_resolution_clock::now(); + nsols = franka_ik_q6(r, ROE, q6, qsols); + end = high_resolution_clock::now(); + duration = duration_cast(end - start); + print_results(qsols); + cout << "number of solutions found:" << nsols; + cout << endl << "duration:" << duration.count() << endl; + // second run + start = high_resolution_clock::now(); + nsols = franka_ik_q6(r, ROE, q6, qsols); + end = high_resolution_clock::now(); + duration = duration_cast(end - start); + cout << endl << "duration in second run:" << duration.count() << endl; + */ + + // TEST franka_ik_q4() + /* + cout << endl << "=======================================================" << endl; + cout << "franka_ik_q4()" << endl; + cout << "=======================================================" << endl; + ROE = { 0.3522750000000002,0.8334980991082203,0.4256560000000001,-0.6332361000000003,-0.12262271641620001,0.764183,0.6891402000000002,-0.5387433117066003,0.48460420000000004 }; + r = { -0.26617644,0.31984145,0.76295964 }; + q4 = -2.3401949461109055; + start = high_resolution_clock::now(); + nsols = franka_ik_q4(r, ROE, q4, qsols); + end = high_resolution_clock::now(); + duration = duration_cast(end - start); + print_results(qsols); + cout << "number of solutions found:" << nsols; + cout << endl << "duration:" << duration.count() << endl; + //second run + start = high_resolution_clock::now(); + nsols = franka_ik_q4(r, ROE, q4, qsols); + end = high_resolution_clock::now(); + duration = duration_cast(end - start); + cout << endl << "duration in second run:" << duration.count() << endl; + */ + + // TEST franka_ik_swivel() + /* + cout << endl << "=======================================================" << endl; + cout << "franka_ik_swivel()" << endl; + cout << "=======================================================" << endl; + ROE = { -0.5878745000000002,-0.7990239702980599,-0.12635000000000007,-0.16720689999999983,0.2728366411870001,-0.9474186000000001,0.7914831,-0.5358366439507003,-0.293996 }; + r = { -0.15116089,-0.397596,0.47386124 }; + theta = -0.3490658503988659; + start = high_resolution_clock::now(); + nsols = franka_ik_swivel(r, ROE, theta, qsols); + end = high_resolution_clock::now(); + print_results(qsols, true, theta); + duration = duration_cast(end - start); + cout << "Number of solutions found: " << nsols; + cout << endl << "duration:" << duration.count() << endl; + */ + + // TEST franka_J_ik_q7() + /* + cout << endl << "=======================================================" << endl; + cout << "franka_J_ik_q7()" << endl; + cout << "=======================================================" << endl; + ROE = {0.6688331000000003,0.3170534383478098,0.6724130000000006,-0.6398146000000005,-0.2150772409286401,0.7378204999999999,0.3785492999999998,-0.9236984268883508,0.05900459999999996}; + r = {0.61674948,0.32278029,0.56790512}; + q7 = -0.37218362471412003 ; + ROE = { -0.189536, 0.0420467, -0.980973, + 0.404078, -0.907217, -0.116958, + -0.894873, -0.418557, 0.15496 }; + r = { 0.23189, -0.0815989, 0.607269 }; + q7 = 0.771925; + joint_angles = true; + start = high_resolution_clock::now(); + nsols = franka_J_ik_q7(r, ROE, q7, Jsols, qsols, joint_angles); + end = high_resolution_clock::now(); + duration = duration_cast(end - start); + print_results_J(Jsols, qsols, joint_angles); + cout << "number of solutions found: " << nsols; + cout << endl<<"duration:" << duration.count() << endl; + */ + + // TEST franka_J_ik_q6() + /* + cout << endl << "=======================================================" << endl; + cout << "franka_J_ik_q6()" << endl; + cout << "=======================================================" << endl; + //test parallel case: + //ROE = { -0.6575819999999999,0.22565347159914026,0.7187951000000004,0.5218621000000001,-0.5516899774048302,0.6506136000000007,0.5433652999999999,0.8029437126709107,0.24502140000000006 }; + //r = { 0.65543571,0.5899264,0.59988412 }; + //q6 = 3.141592653589793; + //test non-parallel case: + ROE = {-0.1192774000000002,0.8774473359489797,0.4646064,0.47138319999999956,0.4618910375721001,-0.7513018999999999,-0.8738254000000001,0.12939431432541965,-0.4687071000000001}; + r = {0.43749227,-0.73488144,0.4951873}; + q6 = 2.6179938779914944 ; + joint_angles = true; + start = high_resolution_clock::now(); + nsols = franka_J_ik_q6(r, ROE, q6, Jsols, qsols, joint_angles, '8'); + end = high_resolution_clock::now(); + duration = duration_cast(end - start); + print_results_J(Jsols, qsols, joint_angles); + cout << "number of solutions found: " << nsols; + cout << endl << "duration:" << duration.count() << endl; + */ + + // TEST franka_J_ik_q4() + /* + cout << endl << "=======================================================" << endl; + cout << "franka_J_ik_q4()" << endl; + cout << "=======================================================" << endl; + ROE = { 0.3522750000000002,0.8334980991082203,0.4256560000000001,-0.6332361000000003,-0.12262271641620001,0.764183,0.6891402000000002,-0.5387433117066003,0.48460420000000004 }; + r = { -0.26617644,0.31984145,0.76295964 }; + q4 = -2.3401949461109055; + joint_angles = true; + start = high_resolution_clock::now(); + nsols = franka_J_ik_q4(r, ROE, q4, Jsols, qsols, joint_angles); + end = high_resolution_clock::now(); + duration = duration_cast(end - start); + print_results_J(Jsols, qsols, joint_angles); + cout << "number of solutions found: " << nsols; + cout << endl << "duration:" << duration.count() << endl; + */ + + // TEST franka_J_ik_swivel() + /* + cout << endl << "=======================================================" << endl; + cout << "franka_J_ik_swivel()" << endl; + cout << "=======================================================" << endl; + ROE = { -0.5878745000000002,-0.7990239702980599,-0.12635000000000007,-0.16720689999999983,0.2728366411870001,-0.9474186000000001,0.7914831,-0.5358366439507003,-0.293996 }; + r = { -0.15116089,-0.397596,0.47386124 }; + theta = -0.3490658503988659; + joint_angles = true; + start = high_resolution_clock::now(); + nsols = franka_J_ik_swivel(r, ROE, theta, Jsols, qsols, joint_angles, 'F'); + end = high_resolution_clock::now(); + duration = duration_cast(end - start); + print_results_J(Jsols, qsols, joint_angles); + cout << "number of solutions found: " << nsols; + cout << endl << "duration:" << duration.count() << endl; + */ + + return 0; +} + + +// functions to print results + +void print_results(const array, 8>& sols, const bool swivel, const double theta) { + cout << "SOLUTIONS ...................." << endl; + Eigen::Matrix4d T; + double theta_res; + bool sol_in_lims; + for (int i = 0; i < sols.size(); i++) { + sol_in_lims = true; + cout << endl << "solution " << i + 1 << endl; + for (int j = 0; j < 7; j++) { + cout << "q_" << j + 1 << " = " << sols[i][j] * 180 / PI << endl; + if (isnan(sols[i][j])) + sol_in_lims = false; + } + // only print retrieved T if all joints are within limits: + if (sol_in_lims) { + T = franka_fk(sols[i]); + cout << "Forward kinematics for this solution:" << endl; + cout << T; + cout << endl; + if (swivel) { + theta_res = franka_swivel(sols[i]); + cout << "theta = " << theta_res << "rad or " << theta_res * 180 / PI << "degs" << endl; + cout << "error = " << theta - theta_res << "degs" <, 7>, 8>& Jsols, const array, 8>& qsols, const bool joint_angles, const bool swivel, const double theta) { + cout << "SOLUTIONS ...................." << endl; + double theta_res; + std::cout << std::fixed << std::setprecision(5); + bool sol_in_lims; + Eigen::Matrix4d T; + for (int i = 0; i < 8; i++) { + cout << endl << "solution " << i + 1 << endl; + cout << "Jacobian:" << endl; + for (int j = 0; j < 7; j++) { + for (int k = 0; k < 6; k++) { + cout << std::setw(10) << Jsols[i][j][k]; + } + cout << endl; + } + if (joint_angles) { + sol_in_lims = true; + cout << "joint angles" << endl; + for (int j = 0; j < 7; j++) { + cout << "q_" << j + 1 << " = " << qsols[i][j] * 180 / PI << endl; + if (isnan(qsols[i][j])) + sol_in_lims = false; + } + if (sol_in_lims) { + T = franka_fk(qsols[i]); + cout << "Forward kinematics for this solution:" << endl; + cout << T; + cout << endl; + if (swivel) { + theta_res = franka_swivel(qsols[i]); + cout << "theta = " << theta_res << "rad or " << theta_res * 180 / PI << "degs" << endl; + cout << "error = " << theta - theta_res << endl; + } + } + } + cout << endl; + } +} \ No newline at end of file diff --git a/GeoFIK/frames.png b/GeoFIK/frames.png new file mode 100644 index 0000000000000000000000000000000000000000..2f6295501c884ed2241c6a64692f5a738ba956d7 Binary files /dev/null and b/GeoFIK/frames.png differ diff --git a/GeoFIK/geofik.cpp b/GeoFIK/geofik.cpp new file mode 100644 index 0000000000000000000000000000000000000000..7f628a8c04e39afc763ec1d3b2e1ee926cff349a --- /dev/null +++ b/GeoFIK/geofik.cpp @@ -0,0 +1,2108 @@ +/** + * @file geofik.cpp + * @brief functions for the IK of the Franka arm. + * + * @details notation: + * - `r_PQ_O`: position vector of point P with respect to point Q measured in frame O. + * - `ROF`: Rotation matrix representing the orientation of a frame F with respect to frame O. + * + * @author Pablo Lopez-Custodio + * @date 2025-02-08 + * @version 1.0 + */ + +#include "geofik.h" +#include +#include + + +#define d1 0.333 +#define d3 0.316 +#define a4 0.0825 +#define a5 0.0825 +#define d5 0.384 +#define a7 0.088 +// dE = 0.107 + 0.1034 +#define dE 0.2104 +// b1 = sqrt(d3*d3 + a4*a4) +#define b1 0.3265918706887849 +// b2 = sqrt(d5*d5 + a5*a5) +#define b2 0.39276233271534583 +// beta1 = arctan(a4/d3) +#define beta1 0.25537561488738186 +// beta2 = arctan(a5/d5) +#define beta2 0.21162680876562978 + +// toletance for entering in singularity mode +# define SING_TOL 1e-5 + +// error threshold for swivel angle solver +// # define ERR_THRESH 0.01 // this slightly smaller than 1deg +# define ERR_THRESH 0.002 // this slightly smaller than (3deg)*(3deg) +// max number of points in discretisation for swivel angle solver +const unsigned int MAX_N_POINTS = 1000; + +const array q_low = { -2.8973, -1.7628, -2.8973, -3.0718, -2.8973, -0.0175, -2.8973 }; +const array q_up = { 2.8973, 1.762, 2.8973, -0.0698, 2.8973, 3.7525, 2.8973 }; +const array q_mid = { 0.0, 0.0, 0.0, -1.5708, 0.0, 1.8675, 0.0 }; + +// Jacobian at home configuration (orientation only) +const Eigen::Matrix J0_S({ {0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0}, + {0.0, 1.0, 0.0, -1.0, 0.0, -1.0, 0.0}, + {1.0, 0.0, 1.0, 0.0, 1.0, 0.0, -1.0} }); + +Eigen::Matrix3d tmp_R; +Eigen::Matrix tmp_J; +Eigen::Matrix tmp_J_6d; +Eigen::Matrix J_old; +Eigen::Matrix J_old_low; +Eigen::Vector3d s; + +void R_axis_angle(const Eigen::Vector3d& s, double theta) { + double x = s[0]; + double y = s[1]; + double z = s[2]; + double ct = cos(theta); + double st = sin(theta); + double one_minus_ct = 1 - ct; + tmp_R << ct + x * x * one_minus_ct, x* y* one_minus_ct - z * st, x* z* one_minus_ct + y * st, + y* x* one_minus_ct + z * st, ct + y * y * one_minus_ct, y* z* one_minus_ct - x * st, + z* x* one_minus_ct - y * st, z* y* one_minus_ct + x * st, ct + z * z * one_minus_ct; +} + +void R_axis_angle(const array& s, double theta) { + double x = s[0]; + double y = s[1]; + double z = s[2]; + double ct = cos(theta); + double st = sin(theta); + double one_minus_ct = 1 - ct; + tmp_R << ct + x * x * one_minus_ct, x* y* one_minus_ct - z * st, x* z* one_minus_ct + y * st, + y* x* one_minus_ct + z * st, ct + y * y * one_minus_ct, y* z* one_minus_ct - x * st, + z* x* one_minus_ct - y * st, z* y* one_minus_ct + x * st, ct + z * z * one_minus_ct; +} + +array Cross(const Eigen::Vector3d& u, const Eigen::Vector3d& v) { + return array {u[1] * v[2] - v[1] * u[2], v[0] * u[2] - u[0] * v[2], u[0] * v[1] - v[0] * u[1]}; +} + +array Cross(const array& u, const array& v) { + return array {u[1] * v[2] - v[1] * u[2], v[0] * u[2] - u[0] * v[2], u[0] * v[1] - v[0] * u[1]}; +} + +array Cross(const array& u, const Eigen::Vector3d& v) { + return array {u[1] * v[2] - v[1] * u[2], v[0] * u[2] - u[0] * v[2], u[0] * v[1] - v[0] * u[1]}; +} + +array Cross(const Eigen::Vector3d& u, const array& v) { + return array {u[1] * v[2] - v[1] * u[2], v[0] * u[2] - u[0] * v[2], u[0] * v[1] - v[0] * u[1]}; +} + +void Cross_(const array& u, const Eigen::Vector3d& v, array& w) { + w[0] = u[1] * v[2] - v[1] * u[2]; + w[1] = v[0] * u[2] - u[0] * v[2]; + w[2] = u[0] * v[1] - v[0] * u[1]; +} + +void Cross_(const array& u, const array& v, array& w) { + w[0] = u[1] * v[2] - v[1] * u[2]; + w[1] = v[0] * u[2] - u[0] * v[2]; + w[2] = u[0] * v[1] - v[0] * u[1]; +} + +double Dot(const Eigen::Vector3d& u, const Eigen::Vector3d& v) { + return u[0] * v[0] + u[1] * v[1] + u[2] * v[2]; +} + +double Dot(const array& u, const array& v) { + return u[0] * v[0] + u[1] * v[1] + u[2] * v[2]; +} + +double Dot(const array& u, const Eigen::Vector3d& v) { + return u[0] * v[0] + u[1] * v[1] + u[2] * v[2]; +} + +double Dot(const Eigen::Vector3d& u, const array& v) { + return u[0] * v[0] + u[1] * v[1] + u[2] * v[2]; +} + +double Norm(const Eigen::Vector3d& u) { + return sqrt(u[0] * u[0] + u[1] * u[1] + u[2] * u[2]); +} + +double Norm(const array& u) { + return sqrt(u[0] * u[0] + u[1] * u[1] + u[2] * u[2]); +} + +void J_dir(const array& s2, const array& s3, const array& s4, const array& s5, const array& s6, const array& s7) { + tmp_J << 0, s2[0], s3[0], s4[0], s5[0], s6[0], s7[0], + 0, s2[1], s3[1], s4[1], s5[1], s6[1], s7[1], + 1, s2[2], s3[2], s4[2], s5[2], s6[2], s7[2]; +} + +void save_J_sol(const array& s2, + const array& s3, + const array& s4, + const array& s5, + const array& s6, + const array& s7, + const array& r4, + const array& r5, + const array& r_EO_O, + array, 7>, 8>& Jsols, + const int index, + const char Jacobian_ee) { + // saves the two Jacobian solutions for the given joint axes at Jsols[2*index] and Jsols[2*index+1]. + // Jacobian_ee is the frame of the Jacobian end-effector ('6', '8', 'F' or 'E') + // r4 = r_4S_O + // r5 = r_5S_O + array r_1ee_O, r_4ee_O, r_5ee_O; + if (Jacobian_ee == '6') { + // r_P6_O = r_PS_O + r_S6_O + // r_PS_O - r_6S_O remember r_6S_O = r_5S_O + r_1ee_O = { -r5[0], -r5[1], -r5[2] }; + r_4ee_O = { r4[0] - r5[0], r4[1] - r5[1] , r4[2] - r5[2] }; + r_5ee_O = { 0, 0 , 0 }; + } + else if (Jacobian_ee == '8' || Jacobian_ee == 'F') { + // r_PF_O = r_PE_O + r_EF_O + // = r_PS_O - rEO_O + rSO_O + r_EF_O + // = r_PS_O - rEO_O + (0,0,d1) + 0.1034*s7_O + r_1ee_O = { -r_EO_O[0] + 0.1034 * s7[0], -r_EO_O[1] + 0.1034 * s7[1], d1 - r_EO_O[2] + 0.1034 * s7[2] }; + r_4ee_O = { r4[0] - r_EO_O[0] + 0.1034 * s7[0], r4[1] - r_EO_O[1] + 0.1034 * s7[1], d1 + r4[2] - r_EO_O[2] + 0.1034 * s7[2] }; + r_5ee_O = { r5[0] - r_EO_O[0] + 0.1034 * s7[0], r5[1] - r_EO_O[1] + 0.1034 * s7[1], d1 + r5[2] - r_EO_O[2] + 0.1034 * s7[2] }; + } + else { + // r_PE_O = r_PS_O + r_SE_O + // = r_PS_O - r_ES_O + // = r_PS_O - (r_EO_O + r_OS_O) = r_PS_O - r_EO_O + r_SO_O + r_1ee_O = { -r_EO_O[0], -r_EO_O[1], d1 - r_EO_O[2] }; + r_4ee_O = { r4[0] - r_EO_O[0], r4[1] - r_EO_O[1], d1 + r4[2] - r_EO_O[2] }; + r_5ee_O = { r5[0] - r_EO_O[0], r5[1] - r_EO_O[1], d1 + r5[2] - r_EO_O[2] }; + } + + array m; + Jsols[2 * index][0] = { 0, 0, 1, r_1ee_O[1], -r_1ee_O[0], 0 }; // r_1ee_O x (0,0,1) = (r_1ee_O[1], -r_1ee_O[0], 0) + Jsols[2 * index + 1][0] = { 0, 0, 1, r_1ee_O[1], -r_1ee_O[0], 0 }; + Cross_(r_1ee_O, s2, m); // r_2ee_O = r_1ee_O + Jsols[2 * index][1] = { s2[0], s2[1], s2[2], m[0], m[1], m[2] }; + Jsols[2 * index + 1][1] = { -s2[0], -s2[1], -s2[2], -m[0], -m[1], -m[2] }; // second solution of spherical shoulder + Cross_(r_1ee_O, s3, m); // r3_ee = r1_ee + Jsols[2 * index][2] = { s3[0], s3[1], s3[2], m[0], m[1], m[2] }; + Jsols[2 * index + 1][2] = { s3[0], s3[1], s3[2], m[0], m[1], m[2] }; + Cross_(r_4ee_O, s4, m); + Jsols[2 * index][3] = { s4[0], s4[1], s4[2], m[0], m[1], m[2] }; + Jsols[2 * index + 1][3] = { s4[0], s4[1], s4[2], m[0], m[1], m[2] }; + Cross_(r_5ee_O, s5, m); + Jsols[2 * index][4] = { s5[0], s5[1], s5[2], m[0], m[1], m[2] }; + Jsols[2 * index + 1][4] = { s5[0], s5[1], s5[2], m[0], m[1], m[2] }; + Cross_(r_5ee_O, s6, m); // r6 = r5 + Jsols[2 * index][5] = { s6[0], s6[1], s6[2], m[0], m[1], m[2] }; + Jsols[2 * index + 1][5] = { s6[0], s6[1], s6[2], m[0], m[1], m[2] }; + if (Jacobian_ee == '6') { + Jsols[2 * index][6] = { 0, 0, 0, 0, 0, 0 }; + Jsols[2 * index + 1][6] = { 0, 0, 0, 0, 0, 0 }; + } + else { + Jsols[2 * index][6] = { s7[0], s7[1], s7[2], 0, 0, 0 }; + Jsols[2 * index + 1][6] = { s7[0], s7[1], s7[2], 0, 0, 0 }; + } +} + +double signed_angle(const Eigen::Vector3d& v1, const Eigen::Vector3d& v2, const Eigen::Vector3d& s) { + return atan2(Dot(Cross(v1, v2), s), Dot(v1, v2)); +} + +double signed_angle(const array& v1, const array& v2, const array& s) { + //return atan2(s[2]*(v1[0]*v2[1] - v1[1]*v2[0]) - s[1]*(v1[0]*v2[2] - v1[2]*v2[0]) + s[0]*(v1[1]*v2[2] - v1[2]*v2[1]), v1[0]*v2[0] + v1[1]*v2[1] + v1[2]*v2[2]); + return atan2(Dot(Cross(v1, v2), s), Dot(v1, v2)); +} + +void check_limits(array& q, int n) { + for (int i=0; i < n; i++) { + q[i] = q_mid[i] + atan2(sin(q[i] - q_mid[i]), cos(q[i] - q_mid[i])); + if (q[i] < q_low[i] || q[i] > q_up[i]) q[i] = NAN; + } +} + +// whole rotational part of J +array q_from_J(const Eigen::Matrix& J) { + const int dof = 7; + array q; + J_old = J0_S; // [3,dof] + for (int i = 0; i < dof - 1; i++) { + s = J.col(i); + q[i] = signed_angle(J_old.col(i + 1), J.col(i + 1), s); + if (i == dof - 2) break; + R_axis_angle(s, q[i]); + J_old.block(0, i + 1, 3, dof - (i + 1)) = tmp_R * J_old.block(0, i + 1, 3, dof - (i + 1)); + } + return q; +} + +// lower rotationa part of J +array q_from_low_J(const Eigen::Matrix& J) { + const int dof = 4; + array q; + J_old_low = J0_S.block(0, 0, 3, dof); // [3,dof] + for (int i = 0; i < dof - 1; i++) { + s = J.col(i); + q[i] = signed_angle(J_old_low.col(i + 1), J.col(i + 1), s); + if (i == dof - 2) break; + R_axis_angle(s, q[i]); + J_old_low.block(0, i + 1, 3, dof - (i + 1)) = tmp_R * J_old_low.block(0, i + 1, 3, dof - (i + 1)); + } + return q; +} + +// whole Jacobian and q +array J_to_q(const array, 7>& J, const array, 3>& R, const char ee) { + // J is the transpose of the Jacobian + // R is the rotation matrix of frame ee + // ee must be a frame attached to the gripper: "E", "F" or "8". + Eigen::Matrix Jrot; + Jrot << J[0][0], J[1][0], J[2][0], J[3][0], J[4][0], J[5][0], J[6][0], + J[0][1], J[1][1], J[2][1], J[3][1], J[4][1], J[5][1], J[6][1], + J[0][2], J[1][2], J[2][2], J[3][2], J[4][2], J[5][2], J[6][2]; + const int dof = 7; + array q; + array i7, ie, s6, s7; + s6 = { J[5][0] , J[5][1] , J[5][2] }; + s7 = { J[6][0] , J[6][1] , J[6][2] }; + Cross_(s6, s7, i7); + ie = { R[0][0], R[1][0], R[2][0] }; + q[6] = signed_angle(i7, ie, s7) + (ee == 'E' ? -PI / 4 : 0); + J_old = J0_S; // [3,dof] + for (int i = 0; i < dof - 1; i++) { + s = Jrot.col(i); + q[i] = signed_angle(J_old.col(i + 1), Jrot.col(i + 1), s); + if (i == dof - 2) break; + R_axis_angle(s, q[i]); + J_old.block(0, i + 1, 3, dof - (i + 1)) = tmp_R * J_old.block(0, i + 1, 3, dof - (i + 1)); + } + return q; +} + +void column_1s_times_vec(const array& R, const array& v, array& res) { + res[0] = R[0] * v[0] + R[1] * v[1] + R[2] * v[2]; + res[1] = R[3] * v[0] + R[4] * v[1] + R[5] * v[2]; + res[2] = R[6] * v[0] + R[7] * v[1] + R[8] * v[2]; +} + +void rotate_by_axis_angle(const array& s, const double theta, const array& v, array& res) { + R_axis_angle(s, theta); + res[0] = tmp_R(0, 0) * v[0] + tmp_R(0, 1) * v[1] + tmp_R(0, 2) * v[2]; + res[1] = tmp_R(1, 0) * v[0] + tmp_R(1, 1) * v[1] + tmp_R(1, 2) * v[2]; + res[2] = tmp_R(2, 0) * v[0] + tmp_R(2, 1) * v[1] + tmp_R(2, 2) * v[2]; +} + +Eigen::Matrix4d T_rpy(const double r, const double p, const double y, const double px, const double py, const double pz) { + Eigen::Matrix4d T; + T << cos(p) * cos(y), cos(y)* sin(p)* sin(r) - cos(r) * sin(y), sin(r)* sin(y) + cos(r) * cos(y) * sin(p), px, + cos(p)* sin(y), cos(r)* cos(y) + sin(p) * sin(r) * sin(y), cos(r)* sin(p)* sin(y) - cos(y) * sin(r), py, + -sin(p), cos(p)* sin(r), cos(p)* cos(r), pz, + 0, 0, 0, 1; + return T; +} + +Eigen::Matrix4d T_rot_z(const double theta, const double px = 0.0, const double py = 0.0, const double pz = 0.0) { + Eigen::Matrix4d T; + T << cos(theta), -sin(theta), 0, px, + sin(theta), cos(theta), 0, py, + 0, 0, 1, pz, + 0, 0, 0, 1; + return T; +} + +Eigen::Matrix Adj_trans(const double x, const double y, const double z) { + Eigen::Matrix Adj = Eigen::Matrix::Identity(); + Adj.block<3, 3>(3, 0) << 0, -z, y, + z, 0, -x, + -y, x, 0; + return Adj; +} + +void get_frame_transforms(array& Ti, const array& q) { + // gets all the transformation matrices of adjascent frames for joint angles q + Ti[0] = T_rpy(0, 0, 0, 0, 0, 0.333) * T_rot_z(q[0]); // T01 + Ti[1] = T_rpy(-PI / 2, 0, 0, 0, 0, 0) * T_rot_z(q[1]); // T12 + Ti[2] = T_rpy(PI / 2, 0, 0, 0, -0.316, 0) * T_rot_z(q[2]); // T23 + Ti[3] = T_rpy(PI / 2, 0, 0, 0.0825, 0, 0) * T_rot_z(q[3]); // T34 + Ti[4] = T_rpy(-PI / 2, 0, 0, -0.0825, 0.384, 0) * T_rot_z(q[4]); // T45 + Ti[5] = T_rpy(PI / 2, 0, 0, 0, 0, 0) * T_rot_z(q[5]); // T56 + Ti[6] = T_rpy(PI / 2, 0, 0, 0.088, 0, 0) * T_rot_z(q[6]); // T67 + Ti[7] = T_rpy(0, 0, 0, 0, 0, 0.107); // T78 + Ti[8] = T_rot_z(-PI / 4, 0, 0, 0.1034); // T8E +} + +unsigned int ee_number(const char ee) { + if (ee == 'E') // ask default value first + return 9; + if (ee == 'F' || ee == '8') + return 8; + if (ee == '1' || ee == '2' || ee == '3' || ee == '4' || ee == '5' || ee == '6' || ee == '7') + return ee - '0'; + return 9; +} + +array, 7> J_from_q(const array& q, const char ee) { + // returns J^T for a given vector of joint angles, q. The end-effector frame is ee + // OUTPUT: J^T \in R^(7,6): array,7> + // INPUT: q \in R^7, array + // ee + Eigen::Vector3d s, r, m; + unsigned int een = ee_number(ee); + unsigned int cols = een >= 7 ? 7 : een; + Eigen::Matrix J6d; + array Ti; + get_frame_transforms(Ti, q); + Eigen::Matrix4d T = Ti[0]; // T01 + J6d.col(0) << 0, 0, 1, 0, 0, 0; + for (int i = 1; i < een; i++) { + T = T * Ti[i]; // T0{i+1} = T0{i}*T{i}{i+1} + if (i < 7) { + s = T.block<3, 1>(0, 2); + r = T.block<3, 1>(0, 3); + m = r.cross(s); + J6d.col(i) << s[0], s[1], s[2], m[0], m[1], m[2]; + } + } + J6d = Adj_trans(-T(0, 3), -T(1, 3), -T(2, 3)) * J6d; + array, 7> Jarr; + for (int i = 0; i < cols; i++) + Jarr[i] = { J6d(0,i), J6d(1,i), J6d(2,i), J6d(3,i), J6d(4,i), J6d(5,i) }; + for (int i = cols; i < 7; i++) + Jarr[i] = { 0, 0, 0, 0, 0, 0 }; + return Jarr; +} + +Eigen::Matrix4d franka_fk(const array& q, const char ee) { + // Forward kinematics function + // INPUT: joint angles q, and end effector name ee + // OUTPUT: TOee is the transformation matrix of frame ee w.r.t. frame O + unsigned int een = ee_number(ee); + array Ti; + get_frame_transforms(Ti, q); + Eigen::Matrix4d TOee = Ti[0]; + for (int i = 1; i < een; i++) + TOee = TOee * Ti[i]; + return TOee; +} + +void franka_fk_all_frames(array& Ts, const array& q) { + // Forward kinematics function saving in Ts the transformation matrices of all frames w.r.t. frame O + array Ti; + get_frame_transforms(Ti, q); + Ts[0] = Ti[0]; + for (int i = 1; i < 9; i++) + Ts[i] = Ts[i - 1] * Ti[i]; +} + + +unsigned int franka_ik_q7(const array& r, + const array& ROE, + const double q7, + array, 8>& qsols, + const double q1_sing) { + // IK with q7 as free variable + // INPUT: r = r_EO_O, position of frame E in frame O + // ROE, orientation of frame E in frame O + // q7, joint angle of joint 7 + // qsols, array to store 8 solutions + // q1_sing, emergency value of q1 in case of singularity at shoulder joints. + // OUTPUT: number of solutions found. + // ri = r_iS_O, i = 1,2,3,4,5,6,7 + // si = s_i_O + Eigen::Vector3d i_E_O(ROE[0], ROE[3], ROE[6]); + array k_E_O = { ROE[2], ROE[5], ROE[8] }; + R_axis_angle(k_E_O, -(q7 - PI / 4)); + Eigen::Vector3d i_6_O = tmp_R * i_E_O; + array s6; + Cross_(k_E_O, i_6_O, s6); + array r6 = { r[0] - dE * k_E_O[0] - a7 * i_6_O[0], r[1] - dE * k_E_O[1] - a7 * i_6_O[1], r[2] - d1 - dE * k_E_O[2] - a7 * i_6_O[2] }; + double l = Norm(r6); + double tmp = (b1 * b1 - l * l - b2 * b2) / (-2 * l * b2); + if (tmp > 1) { + if ((tmp - 1) * (tmp - 1) < SING_TOL* SING_TOL) { + tmp = 1; + } + else { + cout << "ERROR: unable to assembly kinematic chain"; + for (int i = 0; i < 8; ++i) { + fill(qsols[i].begin(), qsols[i].end(), NAN); + } + return 0; + } + } + double actmp = acos(tmp); + double alpha2 = beta2 + actmp; + array k_C_O = { -r6[0] / l, -r6[1] / l, -r6[2] / l }; + array i_C_O; + Cross_(k_C_O, s6, i_C_O); + tmp = Norm(i_C_O); + i_C_O = { i_C_O[0] / tmp, i_C_O[1] / tmp, i_C_O[2] / tmp }; + array j_C_O; + Cross_(k_C_O, i_C_O, j_C_O); + double ry = s6[0] * j_C_O[0] + s6[1] * j_C_O[1] + s6[2] * j_C_O[2]; + double rz = s6[0] * k_C_O[0] + s6[1] * k_C_O[1] + s6[2] * k_C_O[2]; + array, 4> s5s; + double sa2, ca2; + int n_alphs = 1; + unsigned int n_sols = 0; + if (d3 + d5 < l && l < b1 + b2) n_alphs = 2; + double v[3]; + for (int i = 0; i < n_alphs; i++) { + sa2 = sin(alpha2); + ca2 = cos(alpha2); + tmp = -rz * ca2 / (ry * sa2); + if (tmp * tmp > 1){ + if (fabs(fabs(tmp) - 1.0) < 0.04) + tmp = tmp > 0.0 ? 1.0 : -1.0; + else + continue; + } + tmp = asin(tmp); + v[0] = -sa2 * cos(tmp); + v[1] = -sa2 * sin(tmp); + v[2] = -ca2; + s5s[n_sols] = { i_C_O[0] * v[0] + j_C_O[0] * v[1] + k_C_O[0] * v[2], + i_C_O[1] * v[0] + j_C_O[1] * v[1] + k_C_O[1] * v[2], + i_C_O[2] * v[0] + j_C_O[2] * v[1] + k_C_O[2] * v[2] }; + tmp = 2 * sa2 * cos(tmp); + //s5[n_sols+1] = s5s[n_sols] + (2*sa2*cos(tmp)*i_C_O); + s5s[n_sols + 1] = { s5s[n_sols][0] + tmp * i_C_O[0], + s5s[n_sols][1] + tmp * i_C_O[1], + s5s[n_sols][2] + tmp * i_C_O[2] }; + n_sols += 2; + alpha2 = beta2 - actmp; + } + array sol1; + array sol2; + array s4, r4, s3, s2, s5; + for (int i = 0; i < n_sols; i++) { + s5 = s5s[i]; + Cross_(s5, r6, s4); + tmp = Norm(s4); + s4 = { s4[0] / tmp, s4[1] / tmp, s4[2] / tmp }; + Cross_(s5, s4, r4); + r4 = { r6[0] - d5 * s5[0] + a5 * r4[0], r6[1] - d5 * s5[1] + a5 * r4[1], r6[2] - d5 * s5[2] + a5 * r4[2] }; + R_axis_angle(s4, beta1); + s3 = { tmp_R(0,0) * r4[0] + tmp_R(0,1) * r4[1] + tmp_R(0,2) * r4[2], + tmp_R(1,0) * r4[0] + tmp_R(1,1) * r4[1] + tmp_R(1,2) * r4[2], + tmp_R(2,0) * r4[0] + tmp_R(2,1) * r4[1] + tmp_R(2,2) * r4[2] }; + tmp = Norm(s3); + s3 = { s3[0] / tmp, s3[1] / tmp, s3[2] / tmp }; + tmp = s3[1] * s3[1] + s3[0] * s3[0]; + if (tmp > SING_TOL*SING_TOL) { + s2 = { -s3[1] / sqrt(tmp), s3[0] / sqrt(tmp), 0 }; + } + else { + s2 = { sin(q1_sing), cos(q1_sing), 0 }; + } + J_dir(s2, s3, s4, s5, s6, k_E_O); + sol1 = q_from_J(tmp_J); + tmp_J.col(1) = -1 * tmp_J.col(1); + sol2 = q_from_low_J(tmp_J); + qsols[2 * i] = { sol1[0], sol1[1], sol1[2], sol1[3], sol1[4], sol1[5], q7 }; + check_limits(qsols[2 * i], 7); + qsols[2 * i + 1] = { sol2[0], sol2[1], sol2[2], qsols[2 * i][3], qsols[2 * i][4], qsols[2 * i][5], qsols[2 * i][6] }; + check_limits(qsols[2 * i + 1], 3); + } + for (int i = 2 * n_sols; i < 8; i++) + fill(qsols[i].begin(), qsols[i].end(), NAN); + return 2 * n_sols; +} + + +unsigned int franka_ik_q4(const array& r, + const array& ROE, + const double q4, + array, 8>& qsols, + const double q1_sing, + const double q7_sing) { + // IK with q4 as free variable + // INPUT: r = r_EO_O, position of frame E in frame O + // ROE, orientation of frame E in frame O (row-first format) + // q4, joint angle of joint 4 + // qsols, array to store 8 solutions + // q1_sing, emergency value of q1 in case of singularity at shoulder joints (type-1 singularity). + // q7_sing, emergency value of q7 in case of singularity of S7 intersecting S (type-2 singularity). + // OUTPUT: number of solutions found. + // ri = r_iS_O, i = 1,2,3,4,5,6,7 + // si = s_i_O + array r_ES_O = { r[0], r[1], r[2] - d1 }; + array tmp_v = { r_ES_O[1] * ROE[8] - r_ES_O[2] * ROE[5], + r_ES_O[2] * ROE[2] - r_ES_O[0] * ROE[8], + r_ES_O[0] * ROE[5] - r_ES_O[1] * ROE[2] }; + if (tmp_v[0] * tmp_v[0] + tmp_v[1] * tmp_v[1] + tmp_v[2] * tmp_v[2] < SING_TOL) + return franka_ik_q7(r, ROE, q7_sing, qsols, q1_sing); + array r_O7S_O = { r_ES_O[0] - dE * ROE[2], r_ES_O[1] - dE * ROE[5], r_ES_O[2] - dE * ROE[8] }; + array r_O7S_E = { ROE[0] * r_O7S_O[0] + ROE[3] * r_O7S_O[1] + ROE[6] * r_O7S_O[2], + ROE[1] * r_O7S_O[0] + ROE[4] * r_O7S_O[1] + ROE[7] * r_O7S_O[2], + ROE[2] * r_O7S_O[0] + ROE[5] * r_O7S_O[1] + ROE[8] * r_O7S_O[2] }; + double alpha = q4 + beta1 + beta2 - PI; + double lo2 = b1 * b1 + b2 * b2 - 2 * b1 * b2 * cos(alpha); + double lp2 = lo2 - r_O7S_E[2] * r_O7S_E[2]; + // fixed triangle condition + if (lp2 < 0) { + if (lp2 * lp2 < SING_TOL * SING_TOL) + lp2 = 0; + else { + cout << "\nERROR: unable to assembly kinematic chain\n"; + for (int i = 0; i < 8; ++i) + fill(qsols[i].begin(), qsols[i].end(), NAN); + return 0; + } + } + double gamma2 = beta2 + asin(b1 * sin(alpha) / sqrt(lo2)); + double cg2 = cos(gamma2), sg2 = sin(gamma2); + double Lp2 = r_O7S_E[0] * r_O7S_E[0] + r_O7S_E[1] * r_O7S_E[1], phi = atan2(-r_O7S_E[1], -r_O7S_E[0]); + double tmp = (Lp2 + a7 * a7 - lp2) / (2 * sqrt(Lp2) * a7); + // fixed condition + if (tmp > 1.0) { + if ((tmp - 1) * (tmp - 1) < SING_TOL * SING_TOL) + tmp = 1.0; + else { + cout << "\nERROR: unable to assembly kinematic chain\n"; + for (int i = 0; i < 8; ++i) { + fill(qsols[i].begin(), qsols[i].end(), NAN); + } + return 0; + } + } + /* + if ((tmp - 1) * (tmp - 1) < SING_TOL*SING_TOL) + tmp = 1.0; + if (tmp > 1.0) { + cout << "\nERROR: unable to assembly kinematic chain\n"; + for (int i = 0; i < 8; ++i) { + fill(qsols[i].begin(), qsols[i].end(), NAN); + } + return 0; + } + */ + double psi = acos(tmp), ry, rz; + double q7s[2] = { -phi - psi - 3 * PI / 4, -phi + psi - 3 * PI / 4 }; + double gammas[2] = { 0,0 }; + unsigned int ind = 0; + array s2, s3, s4, s5, s6, r4, r6, i_C_O, j_C_O, k_C_O; + array sol1; + array sol2; + for (auto q7 : q7s) { + tmp_v = { cos(-q7 + 3 * PI / 4), sin(-q7 + 3 * PI / 4), 0 }; + s6 = { ROE[0] * tmp_v[0] + ROE[1] * tmp_v[1], ROE[3] * tmp_v[0] + ROE[4] * tmp_v[1], ROE[6] * tmp_v[0] + ROE[7] * tmp_v[1] }; + tmp_v = { -a7 * cos(-q7 + PI / 4), -a7 * sin(-q7 + PI / 4), 0 }; + r6 = { ROE[0] * tmp_v[0] + ROE[1] * tmp_v[1], ROE[3] * tmp_v[0] + ROE[4] * tmp_v[1], ROE[6] * tmp_v[0] + ROE[7] * tmp_v[1] }; + r6 = { r6[0] + r_O7S_O[0], r6[1] + r_O7S_O[1], r6[2] + r_O7S_O[2] }; + tmp = Norm(r6); + k_C_O = { -r6[0] / tmp, -r6[1] / tmp, -r6[2] / tmp }; + Cross_(k_C_O, s6, i_C_O); + tmp = Norm(i_C_O); + i_C_O = { i_C_O[0] / tmp, i_C_O[1] / tmp, i_C_O[2] / tmp }; + Cross_(k_C_O, i_C_O, j_C_O); + ry = s6[0] * j_C_O[0] + s6[1] * j_C_O[1] + s6[2] * j_C_O[2]; + rz = s6[0] * k_C_O[0] + s6[1] * k_C_O[1] + s6[2] * k_C_O[2]; + tmp = -rz * cg2 / (ry * sg2); + if (tmp * tmp > 1) continue; + tmp = asin(tmp); + gammas[0] = tmp; + gammas[1] = PI - tmp; + for (auto gamma : gammas) { + tmp_v = { -sg2 * cos(gamma), -sg2 * sin(gamma), -cg2 }; + s5 = { i_C_O[0] * tmp_v[0] + j_C_O[0] * tmp_v[1] + k_C_O[0] * tmp_v[2], + i_C_O[1] * tmp_v[0] + j_C_O[1] * tmp_v[1] + k_C_O[1] * tmp_v[2], + i_C_O[2] * tmp_v[0] + j_C_O[2] * tmp_v[1] + k_C_O[2] * tmp_v[2] }; + Cross_(s5, r6, s4); + tmp = Norm(s4); + s4 = { s4[0] / tmp, s4[1] / tmp, s4[2] / tmp }; + Cross_(s5, s4, r4); + r4 = { r6[0] - d5 * s5[0] + a5 * r4[0], r6[1] - d5 * s5[1] + a5 * r4[1], r6[2] - d5 * s5[2] + a5 * r4[2] }; + R_axis_angle(s4, beta1); + s3 = { tmp_R(0,0) * r4[0] + tmp_R(0,1) * r4[1] + tmp_R(0,2) * r4[2], + tmp_R(1,0) * r4[0] + tmp_R(1,1) * r4[1] + tmp_R(1,2) * r4[2], + tmp_R(2,0) * r4[0] + tmp_R(2,1) * r4[1] + tmp_R(2,2) * r4[2] }; + tmp = Norm(s3); + s3 = { s3[0] / tmp, s3[1] / tmp, s3[2] / tmp }; + tmp = s3[1] * s3[1] + s3[0] * s3[0]; + if (tmp > SING_TOL* SING_TOL) + s2 = { -s3[1] / sqrt(tmp), s3[0] / sqrt(tmp), 0 }; + else + s2 = { sin(q1_sing), cos(q1_sing), 0 }; + J_dir(s2, s3, s4, s5, s6, array{ROE[2], ROE[5], ROE[8]}); + sol1 = q_from_J(tmp_J); + tmp_J.col(1) = -1 * tmp_J.col(1); + sol2 = q_from_low_J(tmp_J); + qsols[2 * ind] = { sol1[0], sol1[1], sol1[2], sol1[3], sol1[4], sol1[5], q7 }; + check_limits(qsols[2 * ind], 7); + qsols[2 * ind + 1] = { sol2[0], sol2[1], sol2[2], qsols[2 * ind][3], qsols[2 * ind][4], qsols[2 * ind][5], qsols[2 * ind][6] }; + check_limits(qsols[2 * ind + 1], 3); + ind++; + } + } + for (int i = 2 * ind; i < 8; ++i) { + fill(qsols[i].begin(), qsols[i].end(), NAN); + } + return 2 * ind; +} + + +unsigned int franka_ik_q6_parallel(const array& r_ES_O, + const array& ROE, + const int sgn, + array, 8>& qsols, + const double q1_sing) { + // Parallel case of the IK with q6 as free variable. Only called by franka_ik_q6(), not by the user. + // INPUT: r_ES_O, ROE, sgn = sign(cos(q6)), qsols, q1_sing. + // OUTPUT: number of solutions found. + // NOTATION: + // ri = r_iS_O, i = 1,2,3,4,5,6,7 + // si = s_i_O + // Q is a frame that is parallel to frame E and has origin at Q + array s7 = { ROE[2],ROE[5],ROE[8] }; + array r_QS_O = { r_ES_O[0] + (-dE + sgn * d5) * s7[0], r_ES_O[1] + (-dE + sgn * d5) * s7[1], r_ES_O[2] + (-dE + sgn * d5) * s7[2] }; + array r_SQ_Q = { -ROE[0] * r_QS_O[0] - ROE[3] * r_QS_O[1] - ROE[6] * r_QS_O[2], + -ROE[1] * r_QS_O[0] - ROE[4] * r_QS_O[1] - ROE[7] * r_QS_O[2], + -ROE[2] * r_QS_O[0] - ROE[5] * r_QS_O[1] - ROE[8] * r_QS_O[2] }; + double tmp = b1 * b1 - r_SQ_Q[2] * r_SQ_Q[2]; + if (tmp * tmp < SING_TOL*SING_TOL) + tmp = 0; + if (tmp < 0) { + cout << "ERROR: unable to assembly kinematic chain"; + for (int i = 0; i < 8; ++i) { + fill(qsols[i].begin(), qsols[i].end(), NAN); + } + return 0; + } + double lp = sqrt(tmp); + array r_SpQ_Q = { r_SQ_Q[0], r_SQ_Q[1], 0 }; + double l_SpQ = sqrt(r_SQ_Q[0] * r_SQ_Q[0] + r_SQ_Q[1] * r_SQ_Q[1]); + double alphas[2], Ls[2]; + double q7; + Ls[0] = a5 + lp; + Ls[1] = a5 - lp; + array tmp_v, r_O6pQ_Q, i_4_Q, r_O4Q_Q, s6_Q, r_O6_Q, s4_Q, s3_Q, s2, s3, s4, s5, s6; + Eigen::Matrix partial_J_Q, partial_J_O; + Eigen::Matrix3d ROQ; + ROQ << ROE[0], ROE[1], ROE[2], + ROE[3], ROE[4], ROE[5], + ROE[6], ROE[7], ROE[8]; + const array k{ {0,0,1} }; + array s5_Q{ {0,0,-1.0 * sgn} }; + int tmp_sgn; + unsigned int ind = 0; + array sol1; + array sol2; + for (auto L : Ls) { + tmp = (-L * L + a7 * a7 + l_SpQ * l_SpQ) / (2 * a7 * l_SpQ); + if ((tmp - 1) * (tmp - 1) < SING_TOL) + tmp = 1; + else if ((tmp + 1) * (tmp + 1) < SING_TOL) + tmp = -1; + if (tmp * tmp > 1) + continue; + alphas[0] = acos(tmp); + alphas[1] = -acos(tmp); + for (auto alpha : alphas) { + rotate_by_axis_angle(k, alpha, r_SpQ_Q, r_O6pQ_Q); + r_O6pQ_Q = { a7 * r_O6pQ_Q[0] / l_SpQ, a7 * r_O6pQ_Q[1] / l_SpQ, a7 * r_O6pQ_Q[2] / l_SpQ }; + i_4_Q = { r_SpQ_Q[0] - r_O6pQ_Q[0], r_SpQ_Q[1] - r_O6pQ_Q[1], r_SpQ_Q[2] - r_O6pQ_Q[2] }; + tmp = Norm(i_4_Q); + tmp_sgn = L < 0 ? -1 : 1; + i_4_Q = { tmp_sgn * i_4_Q[0] / tmp, tmp_sgn * i_4_Q[1] / tmp, tmp_sgn * i_4_Q[2] / tmp }; + r_O4Q_Q = { r_O6pQ_Q[0] + a5 * i_4_Q[0], r_O6pQ_Q[1] + a5 * i_4_Q[1], r_O6pQ_Q[2] + a5 * i_4_Q[2] }; + Cross_(r_O6pQ_Q, k, s6_Q); + r_O6_Q = { r_O6pQ_Q[0], r_O6pQ_Q[1], r_O6pQ_Q[2] - sgn * d5 }; + Cross_(i_4_Q, s5_Q, s4_Q); + tmp_v = { r_O4Q_Q[0] - r_SQ_Q[0], r_O4Q_Q[1] - r_SQ_Q[1], r_O4Q_Q[2] - r_SQ_Q[2] }; + rotate_by_axis_angle(s4_Q, beta1, tmp_v, s3_Q); + tmp = Norm(s3_Q); + partial_J_Q << s3_Q[0] / tmp, s4_Q[0], s5_Q[0], s6_Q[0], + s3_Q[1] / tmp, s4_Q[1], s5_Q[1], s6_Q[1], + s3_Q[2] / tmp, s4_Q[2], s5_Q[2], s6_Q[2]; + partial_J_O = ROQ * partial_J_Q; + s3 = { partial_J_O(0,0), partial_J_O(1,0), partial_J_O(2,0) }; + s4 = { partial_J_O(0,1), partial_J_O(1,1), partial_J_O(2,1) }; + s5 = { partial_J_O(0,2), partial_J_O(1,2), partial_J_O(2,2) }; + s6 = { partial_J_O(0,3), partial_J_O(1,3), partial_J_O(2,3) }; + q7 = atan2(r_O6pQ_Q[1], -r_O6pQ_Q[0]) + PI / 4; + tmp = s3[1] * s3[1] + s3[0] * s3[0]; + if (tmp > SING_TOL* SING_TOL) + s2 = { -s3[1] / sqrt(tmp), s3[0] / sqrt(tmp), 0 }; + else + s2 = { sin(q1_sing), cos(q1_sing), 0 }; + J_dir(s2, s3, s4, s5, s6, s7); + sol1 = q_from_J(tmp_J); + tmp_J.col(1) = -1 * tmp_J.col(1); + sol2 = q_from_low_J(tmp_J); + qsols[2 * ind] = { sol1[0], sol1[1], sol1[2], sol1[3], sol1[4], sol1[5], q7 }; + check_limits(qsols[2 * ind], 7); + qsols[2 * ind + 1] = { sol2[0], sol2[1], sol2[2], qsols[2 * ind][3], qsols[2 * ind][4], qsols[2 * ind][5], qsols[2 * ind][6] }; + check_limits(qsols[2 * ind + 1], 3); + ind++; + } + } + for (int i = 2 * ind; i < 8; ++i) { + fill(qsols[i].begin(), qsols[i].end(), NAN); + } + return 2 * ind; +} + +unsigned int franka_ik_q6(const array& r, + const array& ROE, + const double q6, + array, 8>& qsols, + const double q1_sing, + const double q7_sing) { + // IK with q6 as free variable + // INPUT: r = r_EO_O, position of frame E in frame O + // ROE, orientation of frame E in frame O (row-first format) + // q6, joint angle of joint 6 + // qsols, array to store 8 solutions + // q1_sing, emergency value of q1 in case of singularity at shoulder joints (type-1 singularity). + // q7_sing, emergency value of q7 in case of singularity of S7 intersecting S (type-2 singularity). + // OUTPUT: number of solutions found. + // NOTATION: + // ri = r_iS_O, i = 1,2,3,4,5,6,7 + // si = s_i_O + array r_ES_O = { r[0], r[1], r[2] - d1 }; + array tmp_v = { r_ES_O[1] * ROE[8] - r_ES_O[2] * ROE[5], + r_ES_O[2] * ROE[2] - r_ES_O[0] * ROE[8], + r_ES_O[0] * ROE[5] - r_ES_O[1] * ROE[2] }; + if (tmp_v[0] * tmp_v[0] + tmp_v[1] * tmp_v[1] + tmp_v[2] * tmp_v[2] < SING_TOL) + return franka_ik_q7(r, ROE, q7_sing, qsols, q1_sing); + if (sin(q6) * sin(q6) < SING_TOL* SING_TOL) // PARALLEL CASE: + return franka_ik_q6_parallel(r_ES_O, ROE, cos(q6) >= 0 ? 1 : -1, qsols, q1_sing); + + // NON-PARALLEL CASE: + array s7 = { ROE[2],ROE[5],ROE[8] }; + double gamma1 = PI - q6; + double cg1 = cos(gamma1); + double sg1 = sin(gamma1); + array r_O7S_O = { r_ES_O[0] - dE * ROE[2], r_ES_O[1] - dE * ROE[5], r_ES_O[2] - dE * ROE[8] }; + array r_PS_O = { r_O7S_O[0] + (a7 / tan(gamma1)) * s7[0], r_O7S_O[1] + (a7 / tan(gamma1)) * s7[1], r_O7S_O[2] + (a7 / tan(gamma1)) * s7[2] }; + double lP = Norm(r_PS_O); + double lC = a7 / sg1; + double Cx = -(ROE[0] * r_PS_O[0] + ROE[3] * r_PS_O[1] + ROE[6] * r_PS_O[2]); + double Cy = -(ROE[1] * r_PS_O[0] + ROE[4] * r_PS_O[1] + ROE[7] * r_PS_O[2]); + double Cz = -(ROE[2] * r_PS_O[0] + ROE[5] * r_PS_O[1] + ROE[8] * r_PS_O[2]); + double c = sqrt(a5 * a5 + (lC + d5) * (lC + d5)); + double tmp = (-b1 * b1 + lP * lP + c * c) / (2 * lP * c); + //cout << "tmp at triangle: " << tmp; + if (tmp > 1.0) { + if ((tmp - 1) * (tmp - 1) < SING_TOL * SING_TOL) + tmp = 1.0; + else { + cout << "ERROR: unable to assembly kinematic chain"; + for (int i = 0; i < 8; ++i) { + fill(qsols[i].begin(), qsols[i].end(), NAN); + } + return 0; + } + } + double tau = acos(tmp); + unsigned int n_gamma_sols = 1; + if ((d3 + d5 + lC < lP) && (lP < b1 + c)) n_gamma_sols = 2; + double gamma2s[2]; + if (d5 < -lC) + gamma2s[0] = tau + atan(a5 / (d5 + lC)) + PI; + else + gamma2s[0] = tau + atan(a5 / (d5 + lC)); + if (n_gamma_sols > 1) + gamma2s[1] = gamma2s[0] - 2 * tau; + + array, 4> s5s; + double q7s[4]; + double d, u1, u2; + unsigned int n_sols = 0; + for (int i = 0; i < n_gamma_sols; i++) { + d = lP * cos(gamma2s[i]); + tmp = (d + Cz * cg1) / (sqrt(Cx * Cx * sg1 * sg1 + Cy * Cy * sg1 * sg1)); + //cout << "tmp at cone: " << tmp; + if (tmp > 1) { + if ((tmp - 1) * (tmp - 1) < SING_TOL * SING_TOL) + tmp = 1; + else + continue; + } + else if (tmp < -1) { + if ((tmp + 1) * (tmp + 1) < SING_TOL * SING_TOL) + tmp = -1; + else + continue; + } + u1 = asin(tmp); + u2 = atan2(Cx * sg1, Cy * sg1); + //cout << "u1 = " << u1 << endl; + //cout << "u2 = " << u2 << endl; + q7s[n_sols] = 5*PI/4 - u1 + u2; + tmp_v = { -sg1 * cos(u1 - u2), -sg1 * sin(u1 - u2), cg1 }; + column_1s_times_vec(ROE, tmp_v, s5s[n_sols]); + n_sols++; + q7s[n_sols] = PI/4 + u1 + u2; + tmp_v = { -sg1 * cos(PI - u1 - u2), -sg1 * sin(PI - u1 - u2), cg1 }; + column_1s_times_vec(ROE, tmp_v, s5s[n_sols]); + n_sols++; + } + + array s2, s3, s4, s6, r4, r6; + array sol1; + array sol2; + for (int i=0; i < n_sols; i++) { + r6 = { r_PS_O[0] - lC * s5s[i][0], r_PS_O[1] - lC * s5s[i][1], r_PS_O[2] - lC * s5s[i][2] }; + tmp_v = { r_O7S_O[0] - r6[0], r_O7S_O[1] - r6[1], r_O7S_O[2] - r6[2] }; + Cross_(s7, tmp_v, s6); + tmp = Norm(s6); + s6 = { s6[0] / tmp,s6[1] / tmp,s6[2] / tmp }; + Cross_(s5s[i], r6, s4); + tmp = Norm(s4); + s4 = { s4[0] / tmp,s4[1] / tmp,s4[2] / tmp }; + Cross_(s5s[i], s4, tmp_v); + r4 = { r6[0] - d5 * s5s[i][0] + a5 * tmp_v[0], r6[1] - d5 * s5s[i][1] + a5 * tmp_v[1], r6[2] - d5 * s5s[i][2] + a5 * tmp_v[2] }; + rotate_by_axis_angle(s4, beta1, r4, s3); + tmp = Norm(s3); + s3 = { s3[0] / tmp,s3[1] / tmp,s3[2] / tmp }; + tmp = s3[1] * s3[1] + s3[0] * s3[0]; + if (tmp > SING_TOL*SING_TOL) + s2 = { -s3[1] / sqrt(tmp), s3[0] / sqrt(tmp), 0 }; + else + s2 = { sin(q1_sing), cos(q1_sing), 0 }; + J_dir(s2, s3, s4, s5s[i], s6, s7); + sol1 = q_from_J(tmp_J); + tmp_J.col(1) = -1 * tmp_J.col(1); + sol2 = q_from_low_J(tmp_J); + qsols[2 * i] = { sol1[0], sol1[1], sol1[2], sol1[3], sol1[4], sol1[5], q7s[i] }; + check_limits(qsols[2 * i], 7); + qsols[2 * i + 1] = { sol2[0], sol2[1], sol2[2], qsols[2 * i][3], qsols[2 * i][4], qsols[2 * i][5], qsols[2 * i][6] }; + check_limits(qsols[2 * i + 1], 3); + } + for (int i = 2 * n_sols; i < 8; ++i) { + fill(qsols[i].begin(), qsols[i].end(), NAN); + } + return 2 * n_sols; +} + +// FUNCTIONS FOR SWIVEL ANGLE + +array theta_err_from_q7_explore_around_sing(double& q7m, + const double theta, + const Eigen::Vector3d& i_E_O, + const array& k_E_O, + Eigen::Vector3d& i_6_O, + const array& n1_O, + const array& r_O7S_O, + const array& u_O7S_O, + const double q7step, + const unsigned int n_fine) { + array s6, r6, k_C_O, i_C_O, j_C_O, s4, r4, n2_O, v; + array errs; + array, 2> s5s; + double l, tmp, actmp, alpha2, ry, rz, sa2, ca2; + double best_q7 = q7m; + array min_errs = { 1e15 , 1e15 }; + double min_err = 1e15; + double q7up = q7m + q7step / 2; + double q7j = q7m - q7step / 2; + while (q7j < q7up) { + R_axis_angle(k_E_O, -(q7j - PI / 4)); + i_6_O = tmp_R * i_E_O; + Cross_(k_E_O, i_6_O, s6); + r6 = { r_O7S_O[0] - a7 * i_6_O[0], r_O7S_O[1] - a7 * i_6_O[1], r_O7S_O[2] - a7 * i_6_O[2] }; + l = Norm(r6); + tmp = (b1 * b1 - l * l - b2 * b2) / (-2 * l * b2); + if (tmp > 1) { + if ((tmp - 1) * (tmp - 1) < SING_TOL) + tmp = 1; + else{ + q7j += q7step / (2 * n_fine); + continue; + } + } + actmp = acos(tmp); + alpha2 = beta2 + actmp; + k_C_O = { -r6[0] / l, -r6[1] / l, -r6[2] / l }; + i_C_O = Cross(k_C_O, s6); + tmp = Norm(i_C_O); + i_C_O = { i_C_O[0] / tmp, i_C_O[1] / tmp, i_C_O[2] / tmp }; + Cross_(k_C_O, i_C_O, j_C_O); + ry = s6[0] * j_C_O[0] + s6[1] * j_C_O[1] + s6[2] * j_C_O[2]; + rz = s6[0] * k_C_O[0] + s6[1] * k_C_O[1] + s6[2] * k_C_O[2]; + sa2 = sin(alpha2); + ca2 = cos(alpha2); + tmp = -rz * ca2 / (ry * sa2); + if (tmp * tmp > 1) + { + q7j += q7step / (2 * n_fine); + continue; + } + tmp = asin(tmp); + v = { -sa2 * cos(tmp), -sa2 * sin(tmp), -ca2 }; + s5s[0] = { i_C_O[0] * v[0] + j_C_O[0] * v[1] + k_C_O[0] * v[2], + i_C_O[1] * v[0] + j_C_O[1] * v[1] + k_C_O[1] * v[2], + i_C_O[2] * v[0] + j_C_O[2] * v[1] + k_C_O[2] * v[2] }; + tmp = 2 * sa2 * cos(tmp); + s5s[1] = { s5s[0][0] + tmp * i_C_O[0], + s5s[0][1] + tmp * i_C_O[1], + s5s[0][2] + tmp * i_C_O[2] }; + for (int i = 0; i < 2; i++) { + s4 = Cross(s5s[i], r6); + tmp = Norm(s4); + s4 = { s4[0] / tmp, s4[1] / tmp, s4[2] / tmp }; + Cross_(s5s[i], s4, r4); + r4 = { r6[0] - d5 * s5s[i][0] + a5 * r4[0], + r6[1] - d5 * s5s[i][1] + a5 * r4[1], + r6[2] - d5 * s5s[i][2] + a5 * r4[2] }; + Cross_(r_O7S_O, r4, n2_O); + tmp = Dot(n2_O, s4); + if (tmp < 0) + n2_O = { -n2_O[0], -n2_O[1], -n2_O[2] }; + errs[i] = acos(cos(theta - signed_angle(n1_O, n2_O, u_O7S_O))); + errs[i] *= errs[i]; + } + if (errs[0] < min_err || errs[1] < min_err) { + best_q7 = q7j; + min_errs[0] = errs[0]; + min_errs[1] = errs[1]; + min_err = (errs[0] < errs[1]) ? errs[0] : errs[1]; + } + q7j += q7step / (2 * n_fine); + } + q7m = best_q7; + return min_errs; +} + +array theta_err_from_q7(double& q7, + const double theta, + const Eigen::Vector3d& i_E_O, + const array& k_E_O, + Eigen::Vector3d& i_6_O, + const array& n1_O, + const array& r_O7S_O, + const array& u_O7S_O, + const double q7step, + const unsigned int n_fine) { + // Calculates the error in swivel angle given the necessary geometry, q7, and the desired swivel angle theta + // NOTATION: u_O7S_O = r_O7S_O/norm(r_O7S_O), precalculated to improve speed + array errs; + R_axis_angle(k_E_O, -(q7 - PI / 4)); + i_6_O = tmp_R * i_E_O; + array s6; + Cross_(k_E_O, i_6_O, s6); + //r6 = r_O7S_O - a7 * i_6_O + array r6 = { r_O7S_O[0] - a7 * i_6_O[0], r_O7S_O[1] - a7 * i_6_O[1], r_O7S_O[2] - a7 * i_6_O[2] }; + double l = Norm(r6); + double tmp = (b1 * b1 - l * l - b2 * b2) / (-2 * l * b2); + //cout << "\ttmp at triangle condition = " << tmp << endl; + if (tmp > 1) { + if ((tmp - 1) * (tmp - 1) < SING_TOL) + tmp = 1; + else + return array{1e10, 1e10}; + } + else if (tmp > 0.9 && n_fine > 0) + { + return theta_err_from_q7_explore_around_sing(q7, theta, i_E_O, k_E_O, i_6_O, n1_O, r_O7S_O, u_O7S_O, q7step, n_fine); + } + double actmp = acos(tmp); + double alpha2 = beta2 + actmp; + array k_C_O = { -r6[0] / l, -r6[1] / l, -r6[2] / l }; + array i_C_O = Cross(k_C_O, s6); + tmp = Norm(i_C_O); + i_C_O = { i_C_O[0] / tmp, i_C_O[1] / tmp, i_C_O[2] / tmp }; + array j_C_O; + Cross_(k_C_O, i_C_O, j_C_O); + double ry = s6[0] * j_C_O[0] + s6[1] * j_C_O[1] + s6[2] * j_C_O[2]; + double rz = s6[0] * k_C_O[0] + s6[1] * k_C_O[1] + s6[2] * k_C_O[2]; + double sa2, ca2; + sa2 = sin(alpha2); + ca2 = cos(alpha2); + tmp = -rz * ca2 / (ry * sa2); + //cout << "\ttmp at cone condition: " << tmp << endl; + if (tmp * tmp > 1) { + if (tmp * tmp < 1.2 && n_fine > 0) { + //cout << "\texploring around current value of q7" << endl; + // errs = theta_err_from_q7_explore_around_sing(q7, theta, i_E_O, k_E_O, i_6_O, n1_O, r_O7S_O, u_O7S_O, q7step, n_fine); + //cout << "\tbest q7 found: " << q7 * 180 / PI << " with errs: " << errs[0] << ", " << errs[1] << endl; + // return errs; + return theta_err_from_q7_explore_around_sing(q7, theta, i_E_O, k_E_O, i_6_O, n1_O, r_O7S_O, u_O7S_O, q7step, n_fine); + } + else + return array{1e15, 1e15}; + } + if (tmp * tmp > 0.8 && n_fine > 0) + { + //cout << "\texploring around current value of q7" << endl; + // errs = theta_err_from_q7_explore_around_sing(q7, theta, i_E_O, k_E_O, i_6_O, n1_O, r_O7S_O, u_O7S_O, q7step, n_fine); + //cout << "\tbest q7 found: " << q7 * 180 / PI << " with errs: " << errs[0] << ", " << errs[1] <, 2> s5s; + s5s[0] = { i_C_O[0] * v[0] + j_C_O[0] * v[1] + k_C_O[0] * v[2], + i_C_O[1] * v[0] + j_C_O[1] * v[1] + k_C_O[1] * v[2], + i_C_O[2] * v[0] + j_C_O[2] * v[1] + k_C_O[2] * v[2] }; + tmp = 2 * sa2 * cos(tmp); + s5s[1] = { s5s[0][0] + tmp * i_C_O[0], + s5s[0][1] + tmp * i_C_O[1], + s5s[0][2] + tmp * i_C_O[2] }; + array s4, r4, n2_O; + for (int i = 0; i < 2; i++) { + s4 = Cross(s5s[i], r6); + tmp = Norm(s4); + s4 = { s4[0] / tmp, s4[1] / tmp, s4[2] / tmp }; + Cross_(s5s[i], s4, r4); + r4 = { r6[0] - d5 * s5s[i][0] + a5 * r4[0], + r6[1] - d5 * s5s[i][1] + a5 * r4[1], + r6[2] - d5 * s5s[i][2] + a5 * r4[2] }; + Cross_(r_O7S_O, r4, n2_O); + tmp = Dot(n2_O, s4); + if (tmp < 0) + n2_O = { -n2_O[0], -n2_O[1], -n2_O[2] }; + errs[i] = acos(cos(theta - signed_angle(n1_O, n2_O, u_O7S_O))); + errs[i] *= errs[i]; + } + return errs; +} + +void franka_ik_q7_one_sol(const double q7, + const Eigen::Vector3d& i_E_O, + const array& k_E_O, + Eigen::Vector3d& i_6_O, + const array& r_O7S_O, + const unsigned int branch, + array, 8>& qsols, + unsigned int ind, + const double q1_sing) { + // returns the two solution related to one single branch of the IK with q7 as free variable. The results are stored in qsols[s*ind] and qsols[2*ind+1] + R_axis_angle(k_E_O, -(q7 - PI / 4)); + i_6_O = tmp_R * i_E_O; + array s6 = Cross(k_E_O, i_6_O); + array r6 = { r_O7S_O[0] - a7 * i_6_O[0], r_O7S_O[1] - a7 * i_6_O[1], r_O7S_O[2] - a7 * i_6_O[2] }; + double l = Norm(r6); + double tmp = (b1 * b1 - l * l - b2 * b2) / (-2 * l * b2); + // The exception tmp*tmp>1 was already handled when Errs was generated + //cout << "FINAL tmp triangle: " << tmp << endl; + if (tmp > 1) tmp = 1; + double actmp = acos(tmp); + double alpha2 = beta2 + actmp; + array k_C_O = { -r6[0] / l, -r6[1] / l, -r6[2] / l }; + array i_C_O = Cross(k_C_O, s6); + tmp = Norm(i_C_O); + i_C_O = { i_C_O[0] / tmp, i_C_O[1] / tmp, i_C_O[2] / tmp }; + array j_C_O = Cross(k_C_O, i_C_O); + double ry = s6[0] * j_C_O[0] + s6[1] * j_C_O[1] + s6[2] * j_C_O[2]; + double rz = s6[0] * k_C_O[0] + s6[1] * k_C_O[1] + s6[2] * k_C_O[2]; + array, 4> s5s; + double sa2, ca2; + sa2 = sin(alpha2); + ca2 = cos(alpha2); + tmp = -rz * ca2 / (ry * sa2); + // The exception tmp*tmp>1 was already handled when Errs was generated + //cout << "FINAL tmp cone: " << tmp << endl; + //cout << "cone variables: rz = " << rz << ", ry = " << ry << ", ca2 = " << ca2 << ", sa2 = " << sa2 << "" << endl; + tmp = asin(tmp); + double v[3] = { -sa2 * cos(tmp), -sa2 * sin(tmp), -ca2 }; + array s5; + s5 = { i_C_O[0] * v[0] + j_C_O[0] * v[1] + k_C_O[0] * v[2], + i_C_O[1] * v[0] + j_C_O[1] * v[1] + k_C_O[1] * v[2], + i_C_O[2] * v[0] + j_C_O[2] * v[1] + k_C_O[2] * v[2] }; + if (branch == 1) { + tmp = 2 * sa2 * cos(tmp); + s5 = { s5[0] + tmp * i_C_O[0], + s5[1] + tmp * i_C_O[1], + s5[2] + tmp * i_C_O[2] }; + } + array s4, r4, s3, s2; + array sol1; + array sol2; + s4 = Cross(s5, r6); + tmp = Norm(s4); + s4 = { s4[0] / tmp, s4[1] / tmp, s4[2] / tmp }; + r4 = Cross(s5, s4); + r4 = { r6[0] - d5 * s5[0] + a5 * r4[0], + r6[1] - d5 * s5[1] + a5 * r4[1], + r6[2] - d5 * s5[2] + a5 * r4[2] }; + R_axis_angle(s4, beta1); + s3 = { tmp_R(0,0) * r4[0] + tmp_R(0,1) * r4[1] + tmp_R(0,2) * r4[2], + tmp_R(1,0) * r4[0] + tmp_R(1,1) * r4[1] + tmp_R(1,2) * r4[2], + tmp_R(2,0) * r4[0] + tmp_R(2,1) * r4[1] + tmp_R(2,2) * r4[2] }; + tmp = Norm(s3); + s3 = { s3[0] / tmp, s3[1] / tmp, s3[2] / tmp }; + tmp = s3[1] * s3[1] + s3[0] * s3[0]; + if (tmp > SING_TOL*SING_TOL) + s2 = { -s3[1] / sqrt(tmp), s3[0] / sqrt(tmp), 0 }; + else + s2 = { sin(q1_sing), cos(q1_sing), 0 }; + J_dir(s2, s3, s4, s5, s6, k_E_O); + sol1 = q_from_J(tmp_J); + tmp_J.col(1) = -1 * tmp_J.col(1); + sol2 = q_from_low_J(tmp_J); + qsols[2 * ind] = { sol1[0], sol1[1], sol1[2], sol1[3], sol1[4], sol1[5], q7 }; + check_limits(qsols[2 * ind], 7); + qsols[2 * ind + 1] = { sol2[0], sol2[1], sol2[2], qsols[2 * ind][3], qsols[2 * ind][4], qsols[2 * ind][5], qsols[2 * ind][6] }; + check_limits(qsols[2 * ind + 1], 3); +} + +unsigned int franka_ik_swivel(const array& r, + const array& ROE, + const double theta, + array, 8>& qsols, + const double q1_sing, + const unsigned int n_points, + const unsigned int n_fine_search) { + // IK with swivel angle as free variable (numerical) + // INPUT: r = r_EO_O, position of frame E in frame O + // ROE, orientation of frame E in frame O (row-first format) + // theta, swivel angle (see paper for geometric defninition) + // qsols, array to store 8 solutions + // q1_sing, emergency value of q1 in case of singularity at shoulder joints (type-1 singularity). + // n_points, number of points to discretise the range of q7. + // OUTPUT: number of solutions found. + // NOTATION: + // ri = r_iS_O, + // si - s_i_O + array k_E_O = { ROE[2], ROE[5], ROE[8] }; + array r_O7S_O = { r[0] - dE * k_E_O[0], r[1] - dE * k_E_O[1], r[2] - d1 - dE * k_E_O[2] }; + double tmp = sqrt(r_O7S_O[1] * r_O7S_O[1] + r_O7S_O[0] * r_O7S_O[0]); + if (tmp < SING_TOL) { + cout << "ERROR: n1_O is undefined"; + for (int i = 0; i < 8; i++) + fill(qsols[i].begin(), qsols[i].end(), NAN); + return 0; + } + array n1_O = { r_O7S_O[1] / tmp, -r_O7S_O[0] / tmp, 0 }; + Eigen::Vector3d i_E_O(ROE[0], ROE[3], ROE[6]); + Eigen::Vector3d i_6_O; + tmp = Norm(r_O7S_O); + array u_O7S_O = { r_O7S_O[0] / tmp, r_O7S_O[1] / tmp, r_O7S_O[2] / tmp }; + double q7_step = (q_up[6] - q_low[6]) / (n_points - 1); + double q7; + array, MAX_N_POINTS> Errs; + array close_cases_b0; + array close_cases_b1; + array q7s; + + //cout << "\nn1_O = " << n1_O[0] << ", " << n1_O[1] << ", " << n1_O[2] << endl; + + unsigned int n_close_cases_b0 = 0; + unsigned int n_close_cases_b1 = 0; + for (int i = 0; i < n_points; i++) { + q7s[i] = q_low[6] + i * q7_step; + //cout << "\nq7 = " << q7s[i]*180/PI << endl; + Errs[i] = theta_err_from_q7(q7s[i], theta, i_E_O, k_E_O, i_6_O, n1_O, r_O7S_O, u_O7S_O, q7_step, n_fine_search); + //cout << "errors at q7 = " << q7s[i]*180/PI << " are " << Errs[i][0] << ", " << Errs[i][1] << endl; + if (Errs[i][0] < ERR_THRESH) + { + close_cases_b0[n_close_cases_b0] = i; + n_close_cases_b0 += 1; + //cout << "saved q7 (b0) = " << q7s[i]*180/PI << endl; + } + if (Errs[i][1] < ERR_THRESH) + { + close_cases_b1[n_close_cases_b1] = i; + n_close_cases_b1 += 1; + //cout << "saved q7 (b1) = " << q7s[i] * 180 / PI << endl; + } + } + + if (n_close_cases_b0 + n_close_cases_b1 == 0) { + for (int i = 0; i < 8; i++) + fill(qsols[i].begin(), qsols[i].end(), NAN); + return 0; + } + + // identify repeated cases i.e. cases where several consecutive solutions passed the threshold + unsigned int min; + vector> best(0); + if (n_close_cases_b0 > 0) { + min = close_cases_b0[0]; + for (int i = 1; i < n_close_cases_b0; i++) { + if (close_cases_b0[i] == close_cases_b0[i - 1] + 1) { + if (Errs[close_cases_b0[i]][0] < Errs[min][0]) { + min = close_cases_b0[i]; + } + } + else { + best.push_back({ min, 0 }); + min = close_cases_b0[i]; + } + } + best.push_back({ min, 0 }); + } + if (n_close_cases_b1 > 0) { + min = close_cases_b1[0]; + for (int i = 1; i < n_close_cases_b1; i++) { + if (close_cases_b1[i] == close_cases_b1[i - 1] + 1) { + if (Errs[close_cases_b1[i]][1] < Errs[min][1]) { + min = close_cases_b1[i]; + } + } + else { + best.push_back({ min, 1 }); + min = close_cases_b1[i]; + } + } + best.push_back({ min, 1 }); + } + + unsigned int n_sols = static_cast(best.size()); + if (n_sols > 4) { + //cout << "\nWARNING: Number of solutions is" << 2 * n_sols << "- Only the first 8 solutions found will be returned.\n"; + n_sols = 4; + } + + // interpolation + double e0, e1, e2, e3, q71, q72, q7_opt; + array m; + for (int i = 0; i < n_sols; i++) { + m = best[i]; + q7_opt = q7s[m[0]]; + if (m[0] > 1 && m[0] < n_points - 2) { + if (Errs[m[0] - 2][m[1]] < ERR_THRESH && Errs[m[0] + 2][m[1]] < ERR_THRESH) { + if (Errs[m[0] + 1][m[1]] < Errs[m[0] - 1][m[1]]) { + // 0=i-1, 1=i, 2=i+1, 3=i+2 + e0 = Errs[m[0] - 1][m[1]]; + e1 = Errs[m[0]][m[1]]; + e2 = Errs[m[0] + 1][m[1]]; + e3 = Errs[m[0] + 2][m[1]]; + q71 = q7s[m[0]]; + q72 = q7s[m[0] + 1]; + } + else { + // 0=i-2, 1=i-1, 2=i, 3=i+1 + e0 = Errs[m[0] - 2][m[1]]; + e1 = Errs[m[0] - 1][m[1]]; + e2 = Errs[m[0]][m[1]]; + e3 = Errs[m[0] + 1][m[1]]; + q71 = q7s[m[0] - 1]; + q72 = q7s[m[0]]; + } + tmp = ((e1 - e0) * q71 - (e3 - e2) * q72 + (e2 - e1) * q7_step) / (e1 - e0 - e3 + e2); + if (tmp > q71 && tmp < q72) + q7_opt = tmp; + } + } + franka_ik_q7_one_sol(q7_opt, i_E_O, k_E_O, i_6_O, r_O7S_O, m[1], qsols, i, q1_sing); + } + for (int i = 2 * n_sols; i < 8; ++i) { + fill(qsols[i].begin(), qsols[i].end(), NAN); + } + return 2 * n_sols; +} + +double franka_swivel(const array& q) { + // swivel angle for a configuration q + array Ts; + franka_fk_all_frames(Ts, q); + array r4 = { Ts[3](0,3), Ts[3](1,3), Ts[3](2,3) - d1 }; + array r7 = { Ts[6](0,3), Ts[6](1,3), Ts[6](2,3) - d1 }; + array s4 = { Ts[3](0,2), Ts[3](1,2), Ts[3](2,2) }; + double tmp = sqrt(r7[1] * r7[1] + r7[0] * r7[0]); + if (tmp < SING_TOL) { + cout << "ERROR: n1_O is undefined"; + return NAN; + } + array n1_O = { r7[1] / tmp, -r7[0] / tmp, 0 }; + array n2_O; + Cross_(r7, r4, n2_O); + tmp = Dot(n2_O, s4); + if (tmp < 0) + n2_O = { -n2_O[0], -n2_O[1], -n2_O[2] }; + tmp = Norm(r7); + return signed_angle(n1_O, n2_O, array{r7[0] / tmp, r7[1] / tmp, r7[2] / tmp}); +} + + + + + + + + + + + + + + + + + + + + + + + + + +// FUNCTIONS FOR JACOBIAN MATRIX ========================================================================== + + + + +unsigned int franka_J_ik_q7(const array& r, + const array& ROE, + const double q7, + array, 7>, 8>& Jsols, + array, 8>& qsols, + const bool joint_angles, + const char Jacobian_ee, + const double q1_sing) { + // IK to calculate Jacobian and joint angles with q7 as free variable. + // INPUT: r = r_EO_O, position of frame E in frame O + // ROE, orientation of frame E in frame O (row-first format) + // q7, value of joint angle of joint 7 + // Jsols, array to store 8 Jacobian solutions + // qsols, array to store 8 joint-angle solutions + // joint_angles, if false only Jacobians are returned + // Jacobian_ee, end-effector frame of the Jacobian, not the IK. Only 'E', 'F', '8' and '6' are supported. + // q1_sing, emergency value of q1 in case of singularity at shoulder joints (type-1 singularity). + // OUTPUT: number of solutions found. + // NOTATION: + // ri = r_iS_O, + // si - s_i_O, + Eigen::Vector3d i_E_O(ROE[0], ROE[3], ROE[6]); + array k_E_O = { ROE[2], ROE[5], ROE[8] }; + R_axis_angle(k_E_O, -(q7 - PI / 4)); + Eigen::Vector3d i_6_O = tmp_R * i_E_O; + array s6; + Cross_(k_E_O, i_6_O, s6); + array r6 = { r[0] - dE * k_E_O[0] - a7 * i_6_O[0], r[1] - dE * k_E_O[1] - a7 * i_6_O[1], r[2] - d1 - dE * k_E_O[2] - a7 * i_6_O[2] }; + double l = Norm(r6); + double tmp = (b1 * b1 - l * l - b2 * b2) / (-2 * l * b2); + if (tmp > 1) { + if ((tmp - 1) * (tmp - 1) < SING_TOL) { + tmp = 1; + } + else { + cout << "ERROR: unable to assembly kinematic chain"; + for (int i = 0; i < 8; ++i) { + fill(qsols[i].begin(), qsols[i].end(), NAN); + for (auto& row : Jsols[i]) + fill(row.begin(), row.end(), NAN); + } + return 0; + } + } + double actmp = acos(tmp); + double alpha2 = beta2 + actmp; + array k_C_O = { -r6[0] / l, -r6[1] / l, -r6[2] / l }; + array i_C_O = Cross(k_C_O, s6); + tmp = Norm(i_C_O); + i_C_O = { i_C_O[0] / tmp, i_C_O[1] / tmp, i_C_O[2] / tmp }; + array j_C_O = Cross(k_C_O, i_C_O); + double ry = s6[0] * j_C_O[0] + s6[1] * j_C_O[1] + s6[2] * j_C_O[2]; + double rz = s6[0] * k_C_O[0] + s6[1] * k_C_O[1] + s6[2] * k_C_O[2]; + array, 4> s5s; + double sa2, ca2; + int n_alphs = 1; + unsigned int n_sols = 0; + if (d3 + d5 < l && l < b1 + b2) n_alphs = 2; + double v[3]; + for (int i = 0; i < n_alphs; i++) { + sa2 = sin(alpha2); + ca2 = cos(alpha2); + tmp = -rz * ca2 / (ry * sa2); + if (tmp * tmp > 1) + continue; + tmp = asin(tmp); + v[0] = -sa2 * cos(tmp); + v[1] = -sa2 * sin(tmp); + v[2] = -ca2; + s5s[n_sols] = { i_C_O[0] * v[0] + j_C_O[0] * v[1] + k_C_O[0] * v[2], + i_C_O[1] * v[0] + j_C_O[1] * v[1] + k_C_O[1] * v[2], + i_C_O[2] * v[0] + j_C_O[2] * v[1] + k_C_O[2] * v[2] }; + tmp = 2 * sa2 * cos(tmp); + //s5[n_sols+1] = s5s[n_sols] + (2*sa2*cos(tmp)*i_C_O); + s5s[n_sols + 1] = { s5s[n_sols][0] + tmp * i_C_O[0], + s5s[n_sols][1] + tmp * i_C_O[1], + s5s[n_sols][2] + tmp * i_C_O[2] }; + n_sols += 2; + alpha2 = beta2 - actmp; + } + //Jsols.resize(2 * n_sols); + //vector> sols; + array sol1; + array sol2; + array s4, r4, s3, s2, s5; + for (int i = 0; i < n_sols; i++) { + s5 = s5s[i]; + Cross_(s5, r6, s4); + tmp = Norm(s4); + s4 = { s4[0] / tmp, s4[1] / tmp, s4[2] / tmp }; + //r4 = r6 - d5 * s5 + a5 * Cross(s5, s4); + Cross_(s5, s4, r4); + r4 = { r6[0] - d5 * s5[0] + a5 * r4[0], r6[1] - d5 * s5[1] + a5 * r4[1], r6[2] - d5 * s5[2] + a5 * r4[2] }; + //s3 = R_axis_angle(s4, beta1) * r4; + R_axis_angle(s4, beta1); + s3 = { tmp_R(0,0) * r4[0] + tmp_R(0,1) * r4[1] + tmp_R(0,2) * r4[2], + tmp_R(1,0) * r4[0] + tmp_R(1,1) * r4[1] + tmp_R(1,2) * r4[2], + tmp_R(2,0) * r4[0] + tmp_R(2,1) * r4[1] + tmp_R(2,2) * r4[2] }; + tmp = Norm(s3); + s3 = { s3[0] / tmp, s3[1] / tmp, s3[2] / tmp }; + tmp = s3[1] * s3[1] + s3[0] * s3[0]; + if (tmp > SING_TOL * SING_TOL) { + s2 = { -s3[1] / sqrt(tmp), s3[0] / sqrt(tmp), 0 }; + } + else { + s2 = { sin(q1_sing), cos(q1_sing), 0 }; + } + save_J_sol(s2, s3, s4, s5, s6, k_E_O, r4, r6, r, Jsols, i, Jacobian_ee); + if (joint_angles) { + J_dir(s2, s3, s4, s5, s6, k_E_O); + sol1 = q_from_J(tmp_J); + tmp_J.col(1) = -1 * tmp_J.col(1); + sol2 = q_from_low_J(tmp_J); + qsols[2 * i] = { sol1[0], sol1[1], sol1[2], sol1[3], sol1[4], sol1[5], q7 }; + check_limits(qsols[2 * i], 7); + qsols[2 * i + 1] = { sol2[0], sol2[1], sol2[2], qsols[2 * i][3], qsols[2 * i][4], qsols[2 * i][5], qsols[2 * i][6] }; + check_limits(qsols[2 * i + 1], 3); + } + } + for (int i = 2 * n_sols; i < 8; ++i) { + for (auto& row : Jsols[i]) + fill(row.begin(), row.end(), NAN); + } + for (int i = joint_angles ? 2 * n_sols : 0; i < 8; i++) + fill(qsols[i].begin(), qsols[i].end(), NAN); + return 2 * n_sols; +} + +unsigned int franka_J_ik_q4(const array& r, + const array& ROE, + const double q4, + array, 7>, 8>& Jsols, + array, 8>& qsols, + const bool joint_angles, + const char Jacobian_ee, + const double q1_sing, + const double q7_sing) { + // IK to calculate Jacobian and joint angles with q4 as free variable. + // INPUT: r = r_EO_O, position of frame E in frame O + // ROE, orientation of frame E in frame O (row-first format) + // q4, value of joint angle of joint 4 + // Jsols, array to store 8 Jacobian solutions + // qsols, array to store 8 joint-angle solutions + // joint_angles, if false only Jacobians are returned + // Jacobian_ee, end-effector frame of the Jacobian, not the IK. Only 'E', 'F', '8' and '6' are supported. + // q1_sing, emergency value of q1 in case of singularity at shoulder joints (type-1 singularity). + // q7_sing, emergency value of q7 in case S7 intersects S (type-2 singularity) + // OUTPUT: number of solutions found. + // NOTATION: + // ri = r_iS_O, + // si - s_i_O, + array r_ES_O = { r[0], r[1], r[2] - d1 }; + array tmp_v = { r_ES_O[1] * ROE[8] - r_ES_O[2] * ROE[5], + r_ES_O[2] * ROE[2] - r_ES_O[0] * ROE[8], + r_ES_O[0] * ROE[5] - r_ES_O[1] * ROE[2] }; + if (tmp_v[0] * tmp_v[0] + tmp_v[1] * tmp_v[1] + tmp_v[2] * tmp_v[2] < SING_TOL) + return franka_J_ik_q7(r, ROE, q7_sing, Jsols, qsols, joint_angles, Jacobian_ee, q1_sing); + array r_O7S_O = { r_ES_O[0] - dE * ROE[2], r_ES_O[1] - dE * ROE[5], r_ES_O[2] - dE * ROE[8] }; + array r_O7S_E = { ROE[0] * r_O7S_O[0] + ROE[3] * r_O7S_O[1] + ROE[6] * r_O7S_O[2], + ROE[1] * r_O7S_O[0] + ROE[4] * r_O7S_O[1] + ROE[7] * r_O7S_O[2], + ROE[2] * r_O7S_O[0] + ROE[5] * r_O7S_O[1] + ROE[8] * r_O7S_O[2] }; + double alpha = q4 + beta1 + beta2 - PI; + double lo2 = b1 * b1 + b2 * b2 - 2 * b1 * b2 * cos(alpha); + double lp2 = lo2 - r_O7S_E[2] * r_O7S_E[2]; + if (lp2 < 0) { + if (lp2 * lp2 < SING_TOL * SING_TOL) + lp2 = 0; + else { + cout << "\nERROR: unable to assembly kinematic chain\n"; + for (int i = 0; i < 8; ++i) + fill(qsols[i].begin(), qsols[i].end(), NAN); + return 0; + } + } + double gamma2 = beta2 + asin(b1 * sin(alpha) / sqrt(lo2)); + double cg2 = cos(gamma2), sg2 = sin(gamma2); + double Lp2 = r_O7S_E[0] * r_O7S_E[0] + r_O7S_E[1] * r_O7S_E[1], phi = atan2(-r_O7S_E[1], -r_O7S_E[0]); + double tmp = (Lp2 + a7 * a7 - lp2) / (2 * sqrt(Lp2) * a7); + if (tmp > 1.0) { + if ((tmp - 1) * (tmp - 1) < SING_TOL * SING_TOL) + tmp = 1.0; + else { + cout << "\nERROR: unable to assembly kinematic chain\n"; + for (int i = 0; i < 8; ++i) { + fill(qsols[i].begin(), qsols[i].end(), NAN); + } + return 0; + } + } + double psi = acos(tmp), ry, rz; + double q7s[2] = { -phi - psi - 3 * PI / 4, -phi + psi - 3 * PI / 4 }; + double gammas[2] = { 0,0 }; + size_t ind = 0; + array s2, s3, s4, s5, s6, r4, r6, i_C_O, j_C_O, k_C_O; + array s7 = { ROE[2],ROE[5],ROE[8] }; + array sol1; + array sol2; + for (auto q7 : q7s) { + tmp_v = { cos(-q7 + 3 * PI / 4), sin(-q7 + 3 * PI / 4), 0 }; + s6 = { ROE[0] * tmp_v[0] + ROE[1] * tmp_v[1], ROE[3] * tmp_v[0] + ROE[4] * tmp_v[1], ROE[6] * tmp_v[0] + ROE[7] * tmp_v[1] }; + tmp_v = { -a7 * cos(-q7 + PI / 4), -a7 * sin(-q7 + PI / 4), 0 }; + r6 = { ROE[0] * tmp_v[0] + ROE[1] * tmp_v[1], ROE[3] * tmp_v[0] + ROE[4] * tmp_v[1], ROE[6] * tmp_v[0] + ROE[7] * tmp_v[1] }; + r6 = { r6[0] + r_O7S_O[0], r6[1] + r_O7S_O[1], r6[2] + r_O7S_O[2] }; + tmp = Norm(r6); + k_C_O = { -r6[0] / tmp, -r6[1] / tmp, -r6[2] / tmp }; + Cross_(k_C_O, s6, i_C_O); + tmp = Norm(i_C_O); + i_C_O = { i_C_O[0] / tmp, i_C_O[1] / tmp, i_C_O[2] / tmp }; + Cross_(k_C_O, i_C_O, j_C_O); + ry = s6[0] * j_C_O[0] + s6[1] * j_C_O[1] + s6[2] * j_C_O[2]; + rz = s6[0] * k_C_O[0] + s6[1] * k_C_O[1] + s6[2] * k_C_O[2]; + tmp = -rz * cg2 / (ry * sg2); + if (tmp * tmp > 1) continue; + tmp = asin(tmp); + gammas[0] = tmp; + gammas[1] = PI - tmp; + for (auto gamma : gammas) { + tmp_v = { -sg2 * cos(gamma), -sg2 * sin(gamma), -cg2 }; + s5 = { i_C_O[0] * tmp_v[0] + j_C_O[0] * tmp_v[1] + k_C_O[0] * tmp_v[2], + i_C_O[1] * tmp_v[0] + j_C_O[1] * tmp_v[1] + k_C_O[1] * tmp_v[2], + i_C_O[2] * tmp_v[0] + j_C_O[2] * tmp_v[1] + k_C_O[2] * tmp_v[2] }; + Cross_(s5, r6, s4); + tmp = Norm(s4); + s4 = { s4[0] / tmp, s4[1] / tmp, s4[2] / tmp }; + Cross_(s5, s4, r4); + r4 = { r6[0] - d5 * s5[0] + a5 * r4[0], r6[1] - d5 * s5[1] + a5 * r4[1], r6[2] - d5 * s5[2] + a5 * r4[2] }; + R_axis_angle(s4, beta1); + s3 = { tmp_R(0,0) * r4[0] + tmp_R(0,1) * r4[1] + tmp_R(0,2) * r4[2], + tmp_R(1,0) * r4[0] + tmp_R(1,1) * r4[1] + tmp_R(1,2) * r4[2], + tmp_R(2,0) * r4[0] + tmp_R(2,1) * r4[1] + tmp_R(2,2) * r4[2] }; + tmp = Norm(s3); + s3 = { s3[0] / tmp, s3[1] / tmp, s3[2] / tmp }; + tmp = s3[1] * s3[1] + s3[0] * s3[0]; + if (tmp > SING_TOL*SING_TOL) + s2 = { -s3[1] / sqrt(tmp), s3[0] / sqrt(tmp), 0 }; + else + s2 = { sin(q1_sing), cos(q1_sing), 0 }; + save_J_sol(s2, s3, s4, s5, s6, s7, r4, r6, r, Jsols, ind, Jacobian_ee); + if (joint_angles) { + J_dir(s2, s3, s4, s5, s6, s7); + sol1 = q_from_J(tmp_J); + tmp_J.col(1) = -1 * tmp_J.col(1); + sol2 = q_from_low_J(tmp_J); + qsols[2 * ind] = { sol1[0], sol1[1], sol1[2], sol1[3], sol1[4], sol1[5], q7 }; + check_limits(qsols[2 * ind], 7); + qsols[2 * ind + 1] = { sol2[0], sol2[1], sol2[2], qsols[2 * ind][3], qsols[2 * ind][4], qsols[2 * ind][5], qsols[2 * ind][6] }; + check_limits(qsols[2 * ind + 1], 3); + } + ind++; + } + } + for (int i = 2 * ind; i < 8; ++i) { + for (auto& row : Jsols[i]) + fill(row.begin(), row.end(), NAN); + } + for (int i = joint_angles ? 2 * ind : 0; i < 8; i++) + fill(qsols[i].begin(), qsols[i].end(), NAN); + return 2 * ind; +} + +unsigned int franka_J_ik_q6_parallel(const array& r, + const array& r_ES_O, + const array& ROE, + const int sgn, + array, 7>, 8>& Jsols, + array, 8>& qsols, + const bool joint_angles, + const char Jacobian_ee, + const double q1_sing) { + // Parallel case of the Jacobian IK with q6 as free variable. Only called by franka_J_ik_q6(), not by the user. + // INPUT: r, r_ES_O, ROE, sgn = sign(cos(q6)), Jsols, qsols, joint_angles, Jacobian_ee, q1_sing. + // OUTPUT: number of solutions found. + // NOTATION: + // ri = r_iS_O, i = 1,2,3,4,5,6,7 + // si = s_i_O + // Q is a frame that is parallel to frame E and has origin at Q (Q is called E' in the paper) + array s7 = { ROE[2],ROE[5],ROE[8] }; + array r_QS_O = { r_ES_O[0] + (-dE + sgn * d5) * s7[0], r_ES_O[1] + (-dE + sgn * d5) * s7[1], r_ES_O[2] + (-dE + sgn * d5) * s7[2] }; + array r_SQ_Q = { -ROE[0] * r_QS_O[0] - ROE[3] * r_QS_O[1] - ROE[6] * r_QS_O[2], + -ROE[1] * r_QS_O[0] - ROE[4] * r_QS_O[1] - ROE[7] * r_QS_O[2], + -ROE[2] * r_QS_O[0] - ROE[5] * r_QS_O[1] - ROE[8] * r_QS_O[2] }; + double tmp = b1 * b1 - r_SQ_Q[2] * r_SQ_Q[2]; + if (tmp * tmp < SING_TOL * SING_TOL) + tmp = 0; + if (tmp < 0) { + cout << "ERROR: unable to assembly kinematic chain"; + for (int i = 0; i < 8; ++i) { + fill(qsols[i].begin(), qsols[i].end(), NAN); + for (auto& row : Jsols[i]) + fill(row.begin(), row.end(), NAN); + } + return 0; + } + double lp = sqrt(tmp); + array r_SpQ_Q = { r_SQ_Q[0], r_SQ_Q[1], 0 }; + double l_SpQ = sqrt(r_SQ_Q[0] * r_SQ_Q[0] + r_SQ_Q[1] * r_SQ_Q[1]); + double alphas[2], Ls[2]; + double q7; + Ls[0] = a5 + lp, + Ls[1] = a5 - lp; + array tmp_v, r_O6pQ_Q, i_4_Q, r_O4Q_Q, s6_Q, r_O6Q_Q, s4_Q, s3_Q, s2, s3, s4, s5, s6, r4, r6; + Eigen::Matrix partial_J_Q, partial_J_O; + Eigen::Matrix rs; + Eigen::Matrix3d ROQ; + ROQ << ROE[0], ROE[1], ROE[2], + ROE[3], ROE[4], ROE[5], + ROE[6], ROE[7], ROE[8]; + const array k{ {0,0,1} }; + array s5_Q{ {0,0,-1.0 * sgn} }; + int tmp_sgn; + unsigned int ind = 0; + array sol1; + array sol2; + for (auto L : Ls) { + tmp = (-L * L + a7 * a7 + l_SpQ * l_SpQ) / (2 * a7 * l_SpQ); + if ((tmp - 1) * (tmp - 1) < SING_TOL) + tmp = 1; + else if ((tmp + 1) * (tmp + 1) < SING_TOL) + tmp = -1; + if (tmp * tmp > 1) + continue; + alphas[0] = acos(tmp); + alphas[1] = -acos(tmp); + for (auto alpha : alphas) { + rotate_by_axis_angle(k, alpha, r_SpQ_Q, r_O6pQ_Q); + r_O6pQ_Q = { a7 * r_O6pQ_Q[0] / l_SpQ, a7 * r_O6pQ_Q[1] / l_SpQ, a7 * r_O6pQ_Q[2] / l_SpQ }; + i_4_Q = { r_SpQ_Q[0] - r_O6pQ_Q[0], r_SpQ_Q[1] - r_O6pQ_Q[1], r_SpQ_Q[2] - r_O6pQ_Q[2] }; + tmp = Norm(i_4_Q); + tmp_sgn = L < 0 ? -1 : 1; + i_4_Q = { tmp_sgn * i_4_Q[0] / tmp, tmp_sgn * i_4_Q[1] / tmp, tmp_sgn * i_4_Q[2] / tmp }; + r_O4Q_Q = { r_O6pQ_Q[0] + a5 * i_4_Q[0], r_O6pQ_Q[1] + a5 * i_4_Q[1], r_O6pQ_Q[2] + a5 * i_4_Q[2] }; + Cross_(r_O6pQ_Q, k, s6_Q); + r_O6Q_Q = { r_O6pQ_Q[0], r_O6pQ_Q[1], r_O6pQ_Q[2] - sgn * d5 }; + rs << r_O4Q_Q[0], r_O6Q_Q[0], + r_O4Q_Q[1], r_O6Q_Q[1], + r_O4Q_Q[2], r_O6Q_Q[2]; + rs = ROQ * rs; // r_O4Q_O, r_O6Q_O + r4 = { rs(0,0) + r_QS_O[0], rs(1,0) + r_QS_O[1], rs(2,0) + r_QS_O[2] }; + r6 = { rs(0,1) + r_QS_O[0], rs(1,1) + r_QS_O[1], rs(2,1) + r_QS_O[2] }; + Cross_(i_4_Q, s5_Q, s4_Q); + tmp_v = { r_O4Q_Q[0] - r_SQ_Q[0], r_O4Q_Q[1] - r_SQ_Q[1], r_O4Q_Q[2] - r_SQ_Q[2] }; + rotate_by_axis_angle(s4_Q, beta1, tmp_v, s3_Q); + tmp = Norm(s3_Q); + //s3_Q = {s3_Q[0]/tmp,s3_Q[1]/tmp,s3_Q[2]/tmp}; + partial_J_Q << s3_Q[0] / tmp, s4_Q[0], s5_Q[0], s6_Q[0], + s3_Q[1] / tmp, s4_Q[1], s5_Q[1], s6_Q[1], + s3_Q[2] / tmp, s4_Q[2], s5_Q[2], s6_Q[2]; + partial_J_O = ROQ * partial_J_Q; + s3 = { partial_J_O(0,0), partial_J_O(1,0), partial_J_O(2,0) }; + s4 = { partial_J_O(0,1), partial_J_O(1,1), partial_J_O(2,1) }; + s5 = { partial_J_O(0,2), partial_J_O(1,2), partial_J_O(2,2) }; + s6 = { partial_J_O(0,3), partial_J_O(1,3), partial_J_O(2,3) }; + q7 = atan2(r_O6pQ_Q[1], -r_O6pQ_Q[0]) + PI / 4; + tmp = s3[1] * s3[1] + s3[0] * s3[0]; + if (tmp > SING_TOL*SING_TOL) + s2 = { -s3[1] / sqrt(tmp), s3[0] / sqrt(tmp), 0 }; + else + s2 = { sin(q1_sing), cos(q1_sing), 0 }; + save_J_sol(s2, s3, s4, s5, s6, s7, r4, r6, r, Jsols, ind, Jacobian_ee); + if (joint_angles) { + J_dir(s2, s3, s4, s5, s6, s7); + sol1 = q_from_J(tmp_J); + tmp_J.col(1) = -1 * tmp_J.col(1); + sol2 = q_from_low_J(tmp_J); + qsols[2 * ind] = { sol1[0], sol1[1], sol1[2], sol1[3], sol1[4], sol1[5], q7 }; + check_limits(qsols[2 * ind], 7); + qsols[2 * ind + 1] = { sol2[0], sol2[1], sol2[2], qsols[2 * ind][3], qsols[2 * ind][4], qsols[2 * ind][5], qsols[2 * ind][6] }; + check_limits(qsols[2 * ind + 1], 3); + } + ind++; + } + } + for (int i = 2 * ind; i < 8; ++i) { + for (auto& row : Jsols[i]) + fill(row.begin(), row.end(), NAN); + } + for (int i = joint_angles ? 2 * ind : 0; i < 8; i++) + fill(qsols[i].begin(), qsols[i].end(), NAN); + return 2 * ind; +} + +unsigned int franka_J_ik_q6(const array& r, + const array& ROE, + const double q6, + array, 7>, 8>& Jsols, + array, 8>& qsols, + const bool joint_angles, + const char Jacobian_ee, + const double q1_sing, + const double q7_sing) { + // IK to calculate Jacobian and joint angles with q6 as free variable. + // INPUT: r = r_EO_O, position of frame E in frame O + // ROE, orientation of frame E in frame O (row-first format) + // q6, value of joint angle of joint 6 + // Jsols, array to store 8 Jacobian solutions + // qsols, array to store 8 joint-angle solutions + // joint_angles, if false only Jacobians are returned + // Jacobian_ee, end-effector frame of the Jacobian, not the IK. Only 'E', 'F', '8' and '6' are supported. + // q1_sing, emergency value of q1 in case of singularity at shoulder joints (type-1 singularity). + // q7_sing, emergency value of q7 in case S7 intersects S (type-2 singularity) + // OUTPUT: number of solutions found. + // NOTATION: + // ri = r_iS_O, + // si - s_i_O, + array r_ES_O = { r[0], r[1], r[2] - d1 }; + array tmp_v = { r_ES_O[1] * ROE[8] - r_ES_O[2] * ROE[5], + r_ES_O[2] * ROE[2] - r_ES_O[0] * ROE[8], + r_ES_O[0] * ROE[5] - r_ES_O[1] * ROE[2] }; + if (tmp_v[0] * tmp_v[0] + tmp_v[1] * tmp_v[1] + tmp_v[2] * tmp_v[2] < SING_TOL) + return franka_J_ik_q7(r, ROE, q7_sing, Jsols, qsols, joint_angles, Jacobian_ee, q1_sing); + if (sin(q6) * sin(q6) < SING_TOL* SING_TOL) + // PARALLEL CASE: + return franka_J_ik_q6_parallel(r, r_ES_O, ROE, cos(q6) >= 0 ? 1 : -1, Jsols, qsols, joint_angles, Jacobian_ee, q1_sing); + // NON-PARALLEL CASE: + array s7 = { ROE[2],ROE[5],ROE[8] }; + double gamma1 = PI - q6; + double cg1 = cos(gamma1); + double sg1 = sin(gamma1); + array r_O7S_O = { r_ES_O[0] - dE * ROE[2], r_ES_O[1] - dE * ROE[5], r_ES_O[2] - dE * ROE[8] }; + array r_PS_O = { r_O7S_O[0] + (a7 / tan(gamma1)) * s7[0], r_O7S_O[1] + (a7 / tan(gamma1)) * s7[1], r_O7S_O[2] + (a7 / tan(gamma1)) * s7[2] }; + double lP = Norm(r_PS_O); + double lC = a7 / sg1; + double Cx = -(ROE[0] * r_PS_O[0] + ROE[3] * r_PS_O[1] + ROE[6] * r_PS_O[2]); + double Cy = -(ROE[1] * r_PS_O[0] + ROE[4] * r_PS_O[1] + ROE[7] * r_PS_O[2]); + double Cz = -(ROE[2] * r_PS_O[0] + ROE[5] * r_PS_O[1] + ROE[8] * r_PS_O[2]); + double c = sqrt(a5 * a5 + (lC + d5) * (lC + d5)); + double tmp = (-b1 * b1 + lP * lP + c * c) / (2 * lP * c); + if (tmp > 1.0) { + if ((tmp - 1) * (tmp - 1) < SING_TOL * SING_TOL) + tmp = 1.0; + else { + cout << "ERROR: unable to assembly kinematic chain"; + for (int i = 0; i < 8; ++i) { + fill(qsols[i].begin(), qsols[i].end(), NAN); + for (auto& row : Jsols[i]) + fill(row.begin(), row.end(), NAN); + } + return 0; + } + } + double tau = acos(tmp); + unsigned int n_gamma_sols = 1; + if ((d3 + d5 + lC < lP) && (lP < b1 + c)) n_gamma_sols = 2; + double gamma2s[2]; + if (d5 < -lC) + gamma2s[0] = tau + atan(a5 / (d5 + lC)) + PI; + else + gamma2s[0] = tau + atan(a5 / (d5 + lC)); + if (n_gamma_sols > 1) + gamma2s[1] = gamma2s[0] - 2 * tau; + array, 4> s5s; + double q7s[4]; + double d, u1, u2; + unsigned int n_sols = 0; + for (int i = 0; i < n_gamma_sols; i++) { + d = lP * cos(gamma2s[i]); + tmp = (d + Cz * cg1) / (sqrt(Cx * Cx * sg1 * sg1 + Cy * Cy * sg1 * sg1)); + if (tmp > 1) { + if ((tmp - 1) * (tmp - 1) < SING_TOL * SING_TOL) + tmp = 1; + else + continue; + } + else if (tmp < -1) { + if ((tmp + 1) * (tmp + 1) < SING_TOL * SING_TOL) + tmp = -1; + else + continue; + } + u1 = asin(tmp); + u2 = atan2(Cx * sg1, Cy * sg1); + q7s[n_sols] = 5 * PI / 4 - u1 + u2; + tmp_v = { -sg1 * cos(u1 - u2), -sg1 * sin(u1 - u2), cg1 }; + column_1s_times_vec(ROE, tmp_v, s5s[n_sols]); + n_sols++; + q7s[n_sols] = PI / 4 + u1 + u2; + tmp_v = { -sg1 * cos(PI - u1 - u2), -sg1 * sin(PI - u1 - u2), cg1 }; + column_1s_times_vec(ROE, tmp_v, s5s[n_sols]); + n_sols++; + } + array s2, s3, s4, s6, r4, r6; + array sol1; + array sol2; + for (int i=0; i < n_sols; i++) { + r6 = { r_PS_O[0] - lC * s5s[i][0], r_PS_O[1] - lC * s5s[i][1], r_PS_O[2] - lC * s5s[i][2] }; + tmp_v = { r_O7S_O[0] - r6[0], r_O7S_O[1] - r6[1], r_O7S_O[2] - r6[2] }; + Cross_(s7, tmp_v, s6); + tmp = Norm(s6); + s6 = { s6[0] / tmp,s6[1] / tmp,s6[2] / tmp }; + Cross_(s5s[i], r6, s4); + tmp = Norm(s4); + s4 = { s4[0] / tmp,s4[1] / tmp,s4[2] / tmp }; + Cross_(s5s[i], s4, tmp_v); + r4 = { r6[0] - d5 * s5s[i][0] + a5 * tmp_v[0], r6[1] - d5 * s5s[i][1] + a5 * tmp_v[1], r6[2] - d5 * s5s[i][2] + a5 * tmp_v[2] }; + rotate_by_axis_angle(s4, beta1, r4, s3); + tmp = Norm(s3); + s3 = { s3[0] / tmp,s3[1] / tmp,s3[2] / tmp }; + tmp = s3[1] * s3[1] + s3[0] * s3[0]; + if (tmp > SING_TOL* SING_TOL) + s2 = { -s3[1] / sqrt(tmp), s3[0] / sqrt(tmp), 0 }; + else + s2 = { sin(q1_sing), cos(q1_sing), 0 }; + save_J_sol(s2, s3, s4, s5s[i], s6, s7, r4, r6, r, Jsols, i, Jacobian_ee); + if (joint_angles) { + J_dir(s2, s3, s4, s5s[i], s6, s7); + sol1 = q_from_J(tmp_J); + tmp_J.col(1) = -1 * tmp_J.col(1); + sol2 = q_from_low_J(tmp_J); + qsols[2 * i] = { sol1[0], sol1[1], sol1[2], sol1[3], sol1[4], sol1[5], q7s[i] }; + check_limits(qsols[2 * i], 7); + qsols[2 * i + 1] = { sol2[0], sol2[1], sol2[2], qsols[2 * i][3], qsols[2 * i][4], qsols[2 * i][5], qsols[2 * i][6] }; + check_limits(qsols[2 * i + 1], 3); + } + } + for (int i = 2 * n_sols; i < 8; ++i) { + for (auto& row : Jsols[i]) + fill(row.begin(), row.end(), NAN); + } + for (int i = joint_angles ? 2 * n_sols : 0; i < 8; i++) + fill(qsols[i].begin(), qsols[i].end(), NAN); + return 2 * n_sols; +} + +// FUNCTIONS FOR SWIVEL ANGLE (JACOBIAN) + + +void franka_J_ik_q7_one_sol(const double q7, + const Eigen::Vector3d& i_E_O, + const array& k_E_O, + Eigen::Vector3d& i_6_O, + const array& r_O7S_O, + const array& r, + array, 7>, 8>& Jsols, + array, 8>& qsols, + unsigned int ind, + const bool joint_angles, + const char Jacobian_ee, + const unsigned int branch, + const double q1_sing) { + // returns the two solution related to one single branch of the IK with q7 as free variable. The results are stored in Jsols[2*ind] and Jsols[2*ind+1] + R_axis_angle(k_E_O, -(q7 - PI / 4)); + i_6_O = tmp_R * i_E_O; + array s6 = Cross(k_E_O, i_6_O); + array r6 = { r_O7S_O[0] - a7 * i_6_O[0], r_O7S_O[1] - a7 * i_6_O[1], r_O7S_O[2] - a7 * i_6_O[2] }; + double l = Norm(r6); + double tmp = (b1 * b1 - l * l - b2 * b2) / (-2 * l * b2); + // The exception tmp*tmp>1 was already handled when Errs was generated + if (tmp > 1) tmp = 1; + double actmp = acos(tmp); + double alpha2 = beta2 + actmp; + array k_C_O = { -r6[0] / l, -r6[1] / l, -r6[2] / l }; + array i_C_O = Cross(k_C_O, s6); + tmp = Norm(i_C_O); + i_C_O = { i_C_O[0] / tmp, i_C_O[1] / tmp, i_C_O[2] / tmp }; + array j_C_O = Cross(k_C_O, i_C_O); + double ry = s6[0] * j_C_O[0] + s6[1] * j_C_O[1] + s6[2] * j_C_O[2]; + double rz = s6[0] * k_C_O[0] + s6[1] * k_C_O[1] + s6[2] * k_C_O[2]; + array, 4> s5s; + double sa2, ca2; + sa2 = sin(alpha2); + ca2 = cos(alpha2); + tmp = -rz * ca2 / (ry * sa2); + // The exception tmp*tmp>1 was already handled when Errs was generated + tmp = asin(tmp); + double v[3] = { -sa2 * cos(tmp), -sa2 * sin(tmp), -ca2 }; + array s5; + s5 = { i_C_O[0] * v[0] + j_C_O[0] * v[1] + k_C_O[0] * v[2], + i_C_O[1] * v[0] + j_C_O[1] * v[1] + k_C_O[1] * v[2], + i_C_O[2] * v[0] + j_C_O[2] * v[1] + k_C_O[2] * v[2] }; + if (branch == 1) { + tmp = 2 * sa2 * cos(tmp); + s5 = { s5[0] + tmp * i_C_O[0], + s5[1] + tmp * i_C_O[1], + s5[2] + tmp * i_C_O[2] }; + } + array s4, r4, s3, s2; + array sol1; + array sol2; + s4 = Cross(s5, r6); + tmp = Norm(s4); + s4 = { s4[0] / tmp, s4[1] / tmp, s4[2] / tmp }; + r4 = Cross(s5, s4); + r4 = { r6[0] - d5 * s5[0] + a5 * r4[0], + r6[1] - d5 * s5[1] + a5 * r4[1], + r6[2] - d5 * s5[2] + a5 * r4[2] }; + R_axis_angle(s4, beta1); + s3 = { tmp_R(0,0) * r4[0] + tmp_R(0,1) * r4[1] + tmp_R(0,2) * r4[2], + tmp_R(1,0) * r4[0] + tmp_R(1,1) * r4[1] + tmp_R(1,2) * r4[2], + tmp_R(2,0) * r4[0] + tmp_R(2,1) * r4[1] + tmp_R(2,2) * r4[2] }; + tmp = Norm(s3); + s3 = { s3[0] / tmp, s3[1] / tmp, s3[2] / tmp }; + tmp = s3[1] * s3[1] + s3[0] * s3[0]; + if (tmp > SING_TOL* SING_TOL) + s2 = { -s3[1] / sqrt(tmp), s3[0] / sqrt(tmp), 0 }; + else + s2 = { sin(q1_sing), cos(q1_sing), 0 }; + save_J_sol(s2, s3, s4, s5, s6, k_E_O, r4, r6, r, Jsols, ind, Jacobian_ee); + if (joint_angles) { + J_dir(s2, s3, s4, s5, s6, k_E_O); + sol1 = q_from_J(tmp_J); + tmp_J.col(1) = -1 * tmp_J.col(1); + sol2 = q_from_low_J(tmp_J); + qsols[2 * ind] = { sol1[0], sol1[1], sol1[2], sol1[3], sol1[4], sol1[5], q7 }; + check_limits(qsols[2 * ind], 7); + qsols[2 * ind + 1] = { sol2[0], sol2[1], sol2[2], qsols[2 * ind][3], qsols[2 * ind][4], qsols[2 * ind][5], qsols[2 * ind][6] }; + check_limits(qsols[2 * ind + 1], 3); + } +} + +unsigned int franka_J_ik_swivel(const array& r, + const array& ROE, + const double theta, + array, 7>, 8>& Jsols, + array, 8>& qsols, + const bool joint_angles, + const char Jacobian_ee, + const double q1_sing, + const unsigned int n_points, + const unsigned int n_fine_search) { + // IK to calculate Jacobian and joint angles with swivel angle as free variable (numerical). + // INPUT: r = r_EO_O, position of frame E in frame O + // ROE, orientation of frame E in frame O (row-first format) + // theta, swivel angle (see paper for gemetric definition) + // Jsols, array to store 8 Jacobian solutions + // qsols, array to store 8 joint-angle solutions + // joint_angles, if false only Jacobians are returned + // Jacobian_ee, end-effector frame of the Jacobian, not the IK. Only 'E', 'F', '8' and '6' are supported. + // q1_sing, emergency value of q1 in case of singularity at shoulder joints (type-1 singularity). + // n_points, number of points to descritise the range of q7 + // OUTPUT: number of solutions found. + // NOTATION: + // ri = r_iS_O, + // si - s_i_O, + array k_E_O = { ROE[2], ROE[5], ROE[8] }; + //r_O7S_O = r_EO_O + r_OS_O + r_O7E_O = r_EO_O - (0,0,d1) - dE*k_E_O + array r_O7S_O = { r[0] - dE * k_E_O[0], r[1] - dE * k_E_O[1], r[2] - d1 - dE * k_E_O[2] }; + double tmp = sqrt(r_O7S_O[1] * r_O7S_O[1] + r_O7S_O[0] * r_O7S_O[0]); + if (tmp < SING_TOL) { + cout << "ERROR: n1_O is undefined"; + for (int i = 0; i < 8; ++i) { + fill(qsols[i].begin(), qsols[i].end(), NAN); + for (auto& row : Jsols[i]) + fill(row.begin(), row.end(), NAN); + } + return 0; + } + array n1_O = { r_O7S_O[1] / tmp, -r_O7S_O[0] / tmp, 0 }; + Eigen::Vector3d i_E_O(ROE[0], ROE[3], ROE[6]); + Eigen::Vector3d i_6_O; + tmp = Norm(r_O7S_O); + array u_O7S_O = { r_O7S_O[0] / tmp, r_O7S_O[1] / tmp, r_O7S_O[2] / tmp }; + double q7_step = (q_up[6] - q_low[6]) / (n_points - 1); + double q7; + array, MAX_N_POINTS> Errs; + array close_cases_b0; + array close_cases_b1; + array q7s; + unsigned int n_close_cases_b0 = 0; + unsigned int n_close_cases_b1 = 0; + for (int i = 0; i < n_points; i++) { + q7s[i] = q_low[6] + i * q7_step; + Errs[i] = theta_err_from_q7(q7s[i], theta, i_E_O, k_E_O, i_6_O, n1_O, r_O7S_O, u_O7S_O, q7_step, n_fine_search); + if (Errs[i][0] < ERR_THRESH) + { + close_cases_b0[n_close_cases_b0] = i; + n_close_cases_b0 += 1; + } + if (Errs[i][1] < ERR_THRESH) + { + close_cases_b1[n_close_cases_b1] = i; + n_close_cases_b1 += 1; + } + } + + if (n_close_cases_b0 + n_close_cases_b1 == 0) { + for (int i = 0; i < 8; ++i) { + fill(qsols[i].begin(), qsols[i].end(), NAN); + for (auto& row : Jsols[i]) + fill(row.begin(), row.end(), NAN); + } + return 0; + } + + // identify repeated cases i.e. cases where several consecutive solutions passed the threshold + unsigned int min; + vector> best(0); + if (n_close_cases_b0 > 0) { + min = close_cases_b0[0]; + for (int i = 1; i < n_close_cases_b0; i++) { + if (close_cases_b0[i] == close_cases_b0[i - 1] + 1) { + if (Errs[close_cases_b0[i]][0] < Errs[min][0]) { + min = close_cases_b0[i]; + } + } + else { + best.push_back({ min, 0 }); + min = close_cases_b0[i]; + } + } + best.push_back({ min, 0 }); + } + if (n_close_cases_b1 > 0) { + min = close_cases_b1[0]; + for (int i = 1; i < n_close_cases_b1; i++) { + if (close_cases_b1[i] == close_cases_b1[i - 1] + 1) { + if (Errs[close_cases_b1[i]][1] < Errs[min][1]) { + min = close_cases_b1[i]; + } + } + else { + best.push_back({ min, 1 }); + min = close_cases_b1[i]; + } + } + best.push_back({ min, 1 }); + } + + unsigned int n_sols = static_cast(best.size()); + if (n_sols > 4) { + //cout << "\nWARNING: Number of solutions is" << 2 * n_sols << "- Only the first 8 solutions found will be returned.\n"; + n_sols = 4; + } + + // interpolation + double e0, e1, e2, e3, q71, q72, q7_opt; + array m; + for (int i = 0; i < n_sols; i++) { + m = best[i]; + q7_opt = q7s[m[0]]; + if (m[0] > 1 && m[0] < n_points - 2) { + if (Errs[m[0] - 2][m[1]] < ERR_THRESH && Errs[m[0] + 2][m[1]] < ERR_THRESH) { + if (Errs[m[0] + 1][m[1]] < Errs[m[0] - 1][m[1]]) { + // 0=i-1, 1=i, 2=i+1, 3=i+2 + e0 = Errs[m[0] - 1][m[1]]; + e1 = Errs[m[0]][m[1]]; + e2 = Errs[m[0] + 1][m[1]]; + e3 = Errs[m[0] + 2][m[1]]; + q71 = q7s[m[0]]; + q72 = q7s[m[0] + 1]; + } + else { + // 0=i-2, 1=i-1, 2=i, 3=i+1 + e0 = Errs[m[0] - 2][m[1]]; + e1 = Errs[m[0] - 1][m[1]]; + e2 = Errs[m[0]][m[1]]; + e3 = Errs[m[0] + 1][m[1]]; + q71 = q7s[m[0] - 1]; + q72 = q7s[m[0]]; + } + tmp = ((e1 - e0) * q71 - (e3 - e2) * q72 + (e2 - e1) * q7_step) / (e1 - e0 - e3 + e2); + if (tmp > q71 && tmp < q72) + q7_opt = tmp; + } + } + franka_J_ik_q7_one_sol(q7_opt, i_E_O, k_E_O, i_6_O, r_O7S_O, r, Jsols, qsols, i, joint_angles, Jacobian_ee, m[1], q1_sing); + } + for (int i = 2 * n_sols; i < 8; ++i) { + for (auto& row : Jsols[i]) + fill(row.begin(), row.end(), NAN); + } + for (int i = joint_angles ? 2 * n_sols : 0; i < 8; i++) + fill(qsols[i].begin(), qsols[i].end(), NAN); + return 2 * n_sols; +} diff --git a/GeoFIK/geofik.h b/GeoFIK/geofik.h new file mode 100644 index 0000000000000000000000000000000000000000..7e3e66eadd067ff89457c4a383d2a576c8f4295e --- /dev/null +++ b/GeoFIK/geofik.h @@ -0,0 +1,201 @@ +#ifndef GEOFIK_H +#define GEOFIK_H + +#include +#include +#include +using namespace std; + +constexpr double PI = 3.14159265359; + +/** + * @brief Computes the joint angles given a Jacobian and the rotation matrix of the ee frame. + * @param J transpose of J. + * @param R the rotation matrix of ee frame with respect to frame O. + * @param ee [optional] name of ee frame ('E', 'F' or '8'). + * @return joint angles q. + */ +array J_to_q(const array, 7>& J, const array, 3>& R, const char ee = 'E'); + +/** + * @brief Computes the Jacobian given the joint angles. + * @param q joint angles, name of ee frame. + * @param ee [optional] Name of ee frame ('E', 'F', '8', ...,'1'). + * @return transpose of J. + */ +array, 7> J_from_q(const array& q, const char ee = 'E'); + +/** + * @brief Forward kinematics. + * @param q joint angles, + * @param ee name of ee frame ('E', 'F', '8', ...,'1'). + * @return transformation matrix of ee frame with respect to frame O. + */ +Eigen::Matrix4d franka_fk(const array& q, const char ee = 'E'); + +/** + * @brief IK with q7 as free variable. + * @param r position of frame E with respect to frame O. + * @param ROE rotation matrix of frame E with respect to frame O (row-first format). + * @param q7 joint angle of joint 7 (radians) + * @param qsols array to store 8 solutions + * @param q1_sing [optional] emergency value of q1 in case of singularity at shoulder joints (type-1 singularity). + * @return number of solutions found. + */ +unsigned int franka_ik_q7(const array& r, + const array& ROE, + const double q7, + array, 8>& qsols, + const double q1_sing = PI / 2); + +/** + * @brief IK with q4 as free variable. + * @param r position of frame E with respect to frame O. + * @param ROE rotation matrix of frame E with respect to frame O (row-first format). + * @param q4 joint angle of joint 4 (radians) + * @param qsols array to store 8 solutions + * @param q1_sing [optional] emergency value of q1 in case of singularity at shoulder joints (type-1 singularity). + * @param q7_sing [optional] emergency value of q7 in case of singularity of S7 intersecting S (type-2 singularity). + * @return number of solutions found. + */ +unsigned int franka_ik_q4(const array& r, + const array& ROE, + const double q4, + array, 8>& qsols, + const double q1_sing = PI / 2, + const double q7_sing = 0); + +/** + * @brief IK with q6 as free variable. + * @param r position of frame E with respect to frame O. + * @param ROE rotation matrix of frame E with respect to frame O (row-first format). + * @param q6 joint angle of joint 6 (radians) + * @param qsols array to store 8 solutions + * @param q1_sing [optional] emergency value of q1 in case of singularity at shoulder joints (type-1 singularity). + * @param q7_sing [optional] emergency value of q7 in case of singularity of S7 intersecting S (type-2 singularity). + * @return number of solutions found. + */ +unsigned int franka_ik_q6(const array& r, + const array& ROE, + const double q6, + array, 8>& qsols, + const double q1_sing = PI / 2, + const double q7_sing = 0); + +/** + * @brief IK with swivel angle as free variable (numerical). + * @param r position of frame E with respect to frame O. + * @param ROE rotation matrix of frame E with respect to frame O (row-first format). + * @param theta swivel angle in radians (see paper for geometric defninition) + * @param qsols array to store 8 solutions + * @param q1_sing [optional] emergency value of q1 in case of singularity at shoulder joints (type-1 singularity). + * @param n_points [optional] number of points to discretise the range of q7. + * @return number of solutions found. + */ +unsigned int franka_ik_swivel(const array& r, + const array& ROE, + const double theta, + array, 8>& qsols, + const double q1_sing = PI / 2, + const unsigned int n_points = 500, + const unsigned int n_fine_search = 3); + +/** + * @brief Calculates the swivel angle given the joint angles q. + * @param q joint angles. + * @return swivel angle theta (see paper for geometric defninition). + */ +double franka_swivel(const array& q); + +/** + * @brief IK to calculate Jacobian and joint angles with q7 as free variable. + * @param r position of frame E with respect to frame O. + * @param ROE rotation matrix of frame E with respect to frame O (row-first format). + * @param q7 joint angle of joint 7 (radians). + * @param Jsols array to store 8 solutions for the Jacobians. + * @param qsols array to store 8 solutions for the joint angles. + * @param joint_angles [optional] if false only Jacobians are returned. + * @param Jacobian_ee [optional] ee frame of the Jacobian, not the IK ('E', 'F', '8' or '6'). + * @param q1_sing [optional] emergency value of q1 in case of singularity at shoulder joints (type-1 singularity). + * @return number of solutions found. + */ +unsigned int franka_J_ik_q7(const array& r, + const array& ROE, + const double q7, + array, 7>, 8>& Jsols, + array, 8>& qsols, + const bool joint_angles = false, + const char Jacobian_ee = 'E', + const double q1_sing = PI / 2); + +/** + * @brief IK to calculate Jacobian and joint angles with q4 as free variable. + * @param r position of frame E with respect to frame O. + * @param ROE rotation matrix of frame E with respect to frame O (row-first format). + * @param q4 joint angle of joint 4 (radians). + * @param Jsols array to store 8 solutions for the Jacobians. + * @param qsols array to store 8 solutions for the joint angles. + * @param joint_angles [optional] if false only Jacobians are returned. + * @param Jacobian_ee [optional] ee frame of the Jacobian, not the IK ('E', 'F', '8' or '6'). + * @param q1_sing [optional] emergency value of q1 in case of singularity at shoulder joints (type-1 singularity). + * @param q7_sing [optional] emergency value of q7 in case of singularity of S7 intersecting S (type-2 singularity). + * @return number of solutions found. + */ +unsigned int franka_J_ik_q4(const array& r, + const array& ROE, + const double q4, + array, 7>, 8>& Jsols, + array, 8>& qsols, + const bool joint_angles = false, + const char Jacobian_ee = 'E', + const double q1_sing = PI / 2, + const double q7_sing = 0); + +/** + * @brief IK to calculate Jacobian and joint angles with q6 as free variable. + * @param r position of frame E with respect to frame O. + * @param ROE rotation matrix of frame E with respect to frame O (row-first format). + * @param q6 joint angle of joint 6 (radians). + * @param Jsols array to store 8 solutions for the Jacobians. + * @param qsols array to store 8 solutions for the joint angles. + * @param joint_angles [optional] if false only Jacobians are returned. + * @param Jacobian_ee [optional] ee frame of the Jacobian, not the IK ('E', 'F', '8' or '6'). + * @param q1_sing [optional] emergency value of q1 in case of singularity at shoulder joints (type-1 singularity). + * @param q7_sing [optional] emergency value of q7 in case of singularity of S7 intersecting S (type-2 singularity). + * @return number of solutions found. + */ +unsigned int franka_J_ik_q6(const array& r, + const array& ROE, + const double q6, + array, 7>, 8>& Jsols, + array, 8>& qsols, + const bool joint_angles = false, + const char Jacobian_ee = 'E', + const double q1_sing = PI / 2, + const double q7_sing = 0); + +/** + * @brief IK to calculate Jacobian and joint angles with swivel angle as free variable (numerical). + * @param r position of frame E with respect to frame O. + * @param ROE rotation matrix of frame E with respect to frame O (row-first format). + * @param theta swivel angle in radians (see paper for geometric defninition). + * @param Jsols array to store 8 solutions for the Jacobians. + * @param qsols array to store 8 solutions for the joint angles. + * @param joint_angles [optional] if false only Jacobians are returned. + * @param Jacobian_ee [optional] ee frame of the Jacobian, not the IK ('E', 'F', '8' or '6'). + * @param q1_sing [optional] emergency value of q1 in case of singularity at shoulder joints (type-1 singularity). + * @param n_points [optional] number of points to discretise the range of q7. + * @return number of solutions found. + */ +unsigned int franka_J_ik_swivel(const array& r, + const array& ROE, + const double theta, + array, 7>, 8>& Jsols, + array, 8>& qsols, + const bool joint_angles = false, + const char Jacobian_ee = 'E', + const double q1_sing = PI / 2, + const unsigned int n_points = 600, + const unsigned int n_fine_search = 3); + +#endif \ No newline at end of file diff --git a/JOURNAL.md b/JOURNAL.md new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/README.md b/README.md index 33786a9c7c43e555e454b2ce879bf888cdf06f96..b9116664983681a03349c5ee7c99870548aa84bd 100644 --- a/README.md +++ b/README.md @@ -1,10 +1,117 @@ ---- -title: Robot -emoji: 📉 -colorFrom: pink -colorTo: purple -sdk: docker -pinned: false ---- - -Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference +# LLM-Panda: Robotic Pick-and-Place Simulator + +LLM-Panda is a PyBullet simulation environment where a Franka Emika Panda robot arm follows natural-language commands to pick, move, and place tabletop objects. It uses an LLM-based semantic planner (or an offline rule-based keyword planner) to generate high-level plans, while deterministic Python controllers handle inverse kinematics (IK), reachability checks, collision avoidance, and grasp stability. + +--- + +## 🚀 Setup Instructions + +Follow these steps to set up the simulator on your local machine: + +1. **Clone the Repository:** + ```bash + git clone https://github.com/AI20K-Build-Cohort-2/C2-App-151.git + cd C2-App-151 + ``` + +2. **Create and Activate a Virtual Environment:** + * **Linux/macOS:** + ```bash + python3 -m venv .venv + source .venv/bin/activate + ``` + * **Windows:** + ```powershell + python -m venv .venv + .\.venv\Scripts\Activate.ps1 + ``` + +3. **Install Core Dependencies:** + ```bash + pip install -r requirements.txt + ``` + +4. **Install Local YCB Objects Assets Package:** + The simulator utilizes YCB dataset models for the physical objects. Unzip the assets and install the package locally: + ```bash + unzip pybullet-object-models.zip + pip install -e pybullet-object-models/pybullet-object-models + ``` + +5. **Configure Environment Variables:** + Copy the example environment file and configure your API keys: + ```bash + cp .env.example .env + ``` + +--- + +## ⚙️ Environment Variables + +The application loads environment variables from the `.env` file in the root directory. + +| Variable | Description | Example Value | +| --- | --- | --- | +| `OPENAI_API_KEY` | API Key for the OpenAI model or compatible NVIDIA Integrate endpoints. | `sk-proj-...` or `nvapi-...` | +| `LLM_API_KEY` | Alternate fallback API Key variable name. | `nvapi-...` | +| `OPENAI_MODEL` | The LLM model name used for semantic planning. | `google/gemma-3n-e2b-it` or `gpt-4o` | +| `OPENAI_BASE_URL` | Base endpoint URL for compatible services. | `https://integrate.api.nvidia.com/v1` | +| `LLM_BASE_URL` | Alternate fallback Base URL variable name. | `https://api.deepseek.com` | +| `LOG_LEVEL` | Logging verbosity level. | `INFO` or `DEBUG` | + +--- + +## 💬 Sample Queries + +The planner resolves Vietnamese/English synonyms and spelling typos, mapping them to the correct objects (`banana`, `soup_can`, `chips_can`) and destinations (`tray`, `Slot_1`..`Slot_6`). + +### Level 1: Basic Commands +* `gắp quả chuối lên` (Grasp banana and hold) +* `nhấc lon súp` (Grasp tomato soup can) +* `để vào khay` (Place currently held object in the tray) +* `di chuyển lon snack vào Slot_3` (Pick up chips can and place at Slot_3) + +### Level 2: Synonyms & Typos +* `gắp hộp snák bỏ vô khay` (Handles accents and Vietnamese synonyms like "vô") +* `nhặt lon canh lên` (Recognizes "lon canh" as soup can) +* `gắp bim bim bỏ vào khay` (Maps "bim bim" to chips can) +* `gắp lon sup bỏ vào trây` (Handles spelling typos) + +### Level 3: Sequential Actions +* `di chuyển snack vào slot 3 và di chuyển lon súp vào khay` +* `gắp lon súp đặt vào slot 2 và gắp quả chuối đặt vào khay` +* `di chuyển quả chuối vào slot 5 rồi di chuyển snack vào khay` + +### Level 4: Spatial Adjacency (Relative Placements) +* `đặt lon súp xuống cạnh bim bim` (Calculates neighboring empty slot) +* `đặt quả chuối cạnh lon súp` +* `đặt quả chuối vào slot trống hàng đầu` +* `đặt lon súp vào slot bên trái khay` + +### Level 5: Obstacle Clearing (Collision Avoidance) +* `dọn dẹp đường đi và gắp quả chuối vào khay` (If banana is blocked, picks up obstacle, moves it to a free slot, then picks and places banana) +* `gắp quả chuối đặt vào khay` (Triggers obstacle clearing if neighbor count >= 1) + +### Level 6: Advanced Swap +* `đổi vị trí quả chuối và snack` (Swaps the positions of the two items using a temporary free slot) +* `hoán đổi vị trí giữa bim bim và quả chuối vàng` +* `hãy đổi vị trí lon súp với quả chuối` + +--- + +## 🛠 Running the Application + +* **Run with PyBullet 3D GUI (Offline Rule-Based Planner):** + ```bash + python main.py --llm rule --gui + ``` + +* **Run with PyBullet 3D GUI (Remote LLM Planner - requires API key in `.env`):** + ```bash + python main.py --llm openai --gui + ``` + +* **Run Python Test Suite:** + ```bash + pytest -v + ``` diff --git a/README_LLM_PANDA.md b/README_LLM_PANDA.md new file mode 100644 index 0000000000000000000000000000000000000000..9e1624e02b1a3ce490e0341751b57a6072dddc5d --- /dev/null +++ b/README_LLM_PANDA.md @@ -0,0 +1,265 @@ +# LLM-Panda — Cánh tay Franka Panda điều khiển bằng Text-LLM (PyBullet) + +Mô phỏng pick-and-place theo kiến trúc **"LLM làm Planner + Grasp Database ở tầng thực thi"**. Một LLM *chỉ-văn-bản* đọc mô tả cảnh dạng ký hiệu rồi xuất ra một chuỗi lời gọi hàm (`pick_up` / `place_at`); tầng thực thi xác định (deterministic) biến kế hoạch đó thành chuyển động tránh va chạm. + +> [!NOTE] +> LLM chỉ **lập kế hoạch ở mức ngữ nghĩa** (gắp vật nào, đặt ở đâu). Toàn bộ hình học, IK, lực kẹp, va chạm do code xử lý → an toàn, tái lập được, và không phụ thuộc việc LLM có "biết" tọa độ hay không. + +--- + +## 1. Tổng quan kiến trúc + +``` + ┌─────────────────────────────────────────────────────┐ + câu lệnh NL │ LLMAgent │ + ────────────► │ RuleBasedPlanner (mặc định, offline, EN/VI) │ + │ RemoteLLMPlanner (OpenAI-compatible) │ + └───────────────┬─────────────────────────────────────┘ + │ kế hoạch JSON: [{pick_up}, {place_at}] + ▼ + ┌─────────────────────────────────────────────────────┐ + │ Executor (main.py) │ + └───────┬───────────────┬───────────────┬─────────────┘ + ▼ ▼ ▼ + SceneManager GraspPlanner RobotController + (Module 1) (Module 2) (Module 3) + world→text grasp pose IK + pick 3 pha + │ + ▼ + GripperController + (Module 4) lực kẹp +``` + +Vòng lặp một lệnh: + +1. **SceneManager** quét thế giới (`getBasePositionAndOrientation`, `getAABB`), gắn mỗi vật vào một vị trí ký hiệu (`Slot_1..6` hoặc `tray`) → chuỗi JSON. +2. **LLMAgent** nhận JSON đó + câu lệnh, trả về danh sách lời gọi hàm. +3. **Executor** duyệt từng lời gọi: + - `pick_up` → GraspPlanner tính world grasp pose → RobotController.pick. + - `place_at` → tra tọa độ slot/tray → RobotController.place. + +--- + +## 2. Cài đặt & chạy + +### Bước 1: Cài đặt các thư viện Python cơ bản +```bash +pip install -r requirements.txt # pybullet, numpy, pytest, python-dotenv, openai +``` + +### Bước 2: Cài đặt mô hình vật thể YCB (`pybullet-object-models.zip`) +Dự án sử dụng các mô hình vật thể thực tế từ bộ dữ liệu YCB. Bạn cần giải nén file zip cục bộ và cài đặt gói ở chế độ editable để PyBullet có thể nạp các mô hình này: + +1. **Giải nén file zip:** + ```bash + unzip pybullet-object-models.zip + ``` +2. **Cài đặt thư viện cục bộ:** + ```bash + pip install -e pybullet-object-models/pybullet-object-models + ``` + +> [!TIP] +> Khi tải các mô hình YCB này, hệ thống sẽ tự động truyền cờ `pb.URDF_USE_MATERIAL_COLORS_FROM_MTL` để hiển thị đúng họa tiết hình ảnh (texture) visual thực tế từ các file `.obj` và `.mtl` đi kèm, thay vì chỉ hiển thị hình dạng collision màu trắng đơn sắc. + +--- + +## 3. Cách chạy mô phỏng + +CLI hỗ trợ **2 chế độ**: + +**a) One-shot** — chạy đúng 1 lệnh rồi thoát: +```bash +python main.py --gui -c "Pick up the banana and place it in the tray" +python main.py -c "gắp quả chuối đặt vào Slot_2" # headless (không giao diện) +python main.py --gui --idle 20 -c "..." # giữ cửa sổ 20 giây sau khi chạy +``` + +**b) Interactive (REPL)** — mặc định khi không truyền `-c`, giữ thế giới sống và gõ lệnh liên tục: +```bash +python main.py --gui # mở GUI rồi vào shell tương tác +python main.py -i -c "..." # chạy 1 lệnh trước, sau đó đi vào shell +``` +Trong shell tương tác: +``` +panda> gắp quả chuối đặt vào tray # câu lệnh ngôn ngữ tự nhiên +panda> :scene # in scene state hiện tại (JSON) +panda> :reset 9 # random lại vị trí vật (seed 9) +panda> :home # đưa tay về tư thế nghỉ +panda> :help # trợ giúp +panda> :quit # thoát (hoặc Ctrl-D / Ctrl-C) +``` + +### Các tham số CLI +| Tham số | Mặc định | Ý nghĩa | +| -------------------- | -------- | ------------------------------------------------ | +| `--gui` | tắt | Mở cửa sổ mô phỏng PyBullet 3D | +| `-c`, `--command` | `None` | Câu lệnh NL (EN/VI). Nếu không truyền sẽ vào REPL | +| `-i`, `--interactive`| tắt | Vào shell tương tác (sau khi chạy `-c` nếu có) | +| `--seed` | `0` | Seed ngẫu nhiên để phân bổ vị trí các vật thể | +| `--llm` | `openai` | Chọn planner: `rule` (offline) hoặc `openai` | +| `--idle` | `5.0` | Số giây giữ cửa sổ GUI sau một lần chạy one-shot | + +Log mẫu của một lần chạy thành công: +``` +[SCENE] banana is at Slot_5; soup_can is at Slot_3; chips_can is at Slot_2; tray is empty +[USER ] gắp quả chuối vào khay +[PLAN ] [{'function': 'pick_up', 'args': {'object_id': 'banana'}}, {'function': 'place_at', 'args': {'location_id': 'tray'}}] +[ACT ] pick_up(banana) grasp@[0.522, 0.134, 0.349] +[GRIP ] force=40.0 N holding=True +[ACT ] place_at(tray) -> [0.42, 0.45, 0.3] +[FINAL] banana is at tray; soup_can is at Slot_3; chips_can is at Slot_2; tray holds banana +``` + +--- + +## 4. Mô tả cảnh (Scene) + +- **Robot**: Franka Emika Panda, đế cố định tại gốc `(0,0,0)`. Khớp tay `0–6` (7 DOF), ngón kẹp `9/10` (hành trình 0–0.04 m), TCP = link `11`. +- **Bàn**: hộp chữ nhật, **mặt bàn ở z = 0.30 m** (đã kiểm chứng IK với tới, sai số < 1 mm cho mọi slot/tray). Tâm `(0.50, 0.0)`. +- **Lưới 6 slot** (2 hàng × 3 cột), tọa độ `(x, y, 0.30)`: + + | Cột → | x=0.40 | x=0.50 | x=0.60 | + | ------------ | -------- | -------- | -------- | + | hàng y=−0.15 | `Slot_1` | `Slot_2` | `Slot_3` | + | hàng y=+0.15 | `Slot_4` | `Slot_5` | `Slot_6` | + +- **Tray** (khay cố định) tại `(0.50, 0.45, 0.30)`, ngay ngoài mép +y của bàn. +- **Vật thể** (sinh ngẫu nhiên trên 3 slot khác nhau theo `--seed`): + - `banana` — quả chuối, khối lượng 0.066 kg, ma sát 0.8, class `banana`. + - `soup_can` — lon súp cà chua, khối lượng 0.349 kg, ma sát 0.8, class `can`. + - `chips_can` — lon snack khoai tây chiên, khối lượng 0.205 kg, ma sát 0.5, class `chips`. + +Mọi hằng số hình học và vật lý nằm trong [llm_panda/config.py](file:///media/minhnht31/data/vinuni/C2-App-151/llm_panda/config.py). + +--- + +## 5. Chi tiết các module + +### Module 1 — `scene_manager.py` +Chuyển trạng thái vật lý → văn bản cho LLM. + +| Hàm | Mô tả | +| --- | --- | +| `register_object(id,name,cls)` | Đăng ký một body để xuất hiện trong scene state | +| `get_world_pose(id)` | Bọc `p.getBasePositionAndOrientation` | +| `get_aabb(id)` | Bọc `p.getAABB` | +| `classify_location(pos)` | Gắn tọa độ → `tray` / `Slot_*` / `elsewhere` theo bán kính | +| `get_scene_state()` | Dict có cấu trúc (objects, slots, tray) | +| `get_scene_state_text()` | **Chuỗi JSON sạch** nạp thẳng vào prompt LLM | + +### Module 2 — `grasp_planner.py` +Cơ sở dữ liệu grasp theo từng class + phép biến đổi cứng sang world. + +- `local_to_world(world_pos, world_ori, local_pos, local_euler)`: đổi Euler→Quaternion (`p.getQuaternionFromEuler`) rồi `p.multiplyTransforms(...)` → **world grasp pose chính xác kể cả khi vật xoay**. +- `compute_grasp_pose(object_id, object_class)`: lấy world pose của vật, đọc local pose từ database, biến đổi sang world. +- **Fallback**: vật không có trong DB → grasp top-down ở **trung điểm mặt trên AABB** (`_aabb_fallback_grasp`). + +Định dạng [data/grasp_database.json](file:///media/minhnht31/data/vinuni/C2-App-151/llm_panda/data/grasp_database.json): +```json +{ + "can": { + "local_position": [0.0, 0.0, 0.02], + "local_euler": [3.14159, 0.0, 0.0] + }, + "chips": { + "local_position": [0.0, 0.0, 0.10], + "local_euler": [3.14159, 0.0, 0.0] + }, + "banana": { + "local_position": [0.0, 0.0, 0.01], + "local_euler": [3.14159, 0.0, 0.0] + }, + "default": { + "local_position": [0.0, 0.0, 0.0], + "local_euler": [3.14159, 0.0, 0.0] + } +} +``` +`local_position` = offset TCP so với tâm vật (m); `local_euler` = hướng kẹp trong hệ vật (rad). `[π,0,0]` = kẹp thẳng từ trên xuống. + +### Module 3 — `robot_controller.py` +IK + quỹ đạo pick 3 pha an toàn. + +- `move_to_pose(pos, ori, steps)`: giải IK (`p.calculateInverseKinematics`) rồi **nội suy trong không gian khớp** để chuyển động mượt. +- `pick(object_id, grasp_pos, grasp_ori)`: + 1. Mở kẹp + di tới **pre-grasp** (cao hơn điểm gắp 10 cm). + 2. Hạ thẳng xuống grasp pose, **đóng kẹp với lực và liên kết đã tính** (nhằm đảm bảo không tuột). + 3. Nhấc vật lên (lift 20 cm trên mặt bàn). +- `place(target_pos)`: di lên trên đích → hạ xuống → mở kẹp → rút lên. +- `isolate_object_collisions(id)`: **chỉ má ngón mới va chạm với vật**, vô hiệu hóa va chạm của mọi link tay khác trong lúc tiếp cận → tránh huých lệch vật trước khi kẹp. + +### Module 4 — `gripper_controller.py` +Mô hình lực kẹp dựa trên vật lý thật. + +- `calculate_optimal_force(object_id)`: đọc khối lượng + ma sát qua `p.getDynamicsInfo`, áp công thức **lực kẹp ma sát tối thiểu**: + ``` + F_g = m · (g + a) · Sf / (n_contacts · μ) + ``` + rồi **kẹp vào ngưỡng phần cứng [40 N, 140 N]**. Bền với input suy biến: μ→0 không gây inf/NaN (bão hòa về max), mass âm → về sàn 40 N. +- `open()` / `close(force)` / `grasp(object_id)`: điều khiển ngón qua `setJointMotorControl2` và tạo liên kết vật lý (`pb.createConstraint`) để gắp chắc chắn hơn. +- `is_holding(object_id)`: True nếu má ngón kẹp tiếp xúc và giữ chặt vật thể. + +### LLM Agent — `llm_agent.py` +- **`RuleBasedPlanner`**: khớp từ khóa song ngữ EN/VI (`banana/chuối`, `can/súp`, `chips/bim bim/snack`, `gắp/pick`, `tray/khay`, `Slot_N`...) và xuất kế hoạch — **chạy offline, không cần API key**. +- **`RemoteLLMPlanner`**: gọi LLM thật qua API OpenAI-compatible (OpenAI mặc định), cùng schema kế hoạch JSON. + +**Bật LLM thật** — cần `pip install openai python-dotenv`, rồi đặt key trong `.env` (tự nạp) hoặc biến môi trường: +```dotenv +# .env (đã được .gitignore — KHÔNG commit) +OPENAI_API_KEY=sk-proj-... +# OPENAI_MODEL=gpt-4o-mini # tùy chọn (mặc định gpt-4o-mini) +``` +Chạy bằng cờ CLI: +```bash +python main.py --llm openai -c "gắp quả chuối đặt vào khay" +python main.py --gui --llm openai # shell tương tác, planner OpenAI +``` + +--- + +## 6. Kiểm thử + +```bash +pytest tests/ -v # 17 test, tất cả pass thành công +``` + +| Nhóm test | Nội dung | +| --- | --- | +| **Bất biến phép biến đổi** | Offset grasp **không đổi** khi xoay vật 0/45/90/135/180° | +| **Lực kẹp** | Lực kẹp hợp lệ trong dải [40 N, 140 N] với mọi giá trị mass/ma sát | +| **Grasp stability (tích hợp)** | Gắp lon súp → tịnh tiến nhanh → kiểm tra vật **không tuột/rơi** (sai số < 0.10 m) | + +--- + +## 7. Khắc phục sự cố + +| Hiện tượng | Nguyên nhân / cách xử lý | +| --- | --- | +| `--gui` không mở cửa sổ | Máy headless (không có màn hình). Bỏ `--gui` để chạy DIRECT. | +| Lỗi `Connection ... GUI` | Đang chạy qua SSH không X-forwarding. Dùng `ssh -X` hoặc headless. | +| Robot không với tới đích | Đích ngoài vùng làm việc — giữ slot trong x∈[0.4,0.6], y∈[±0.15]. | +| Vật tuột khi nhấc | Tăng lực kẹp của ngón, hoặc giảm khối lượng/tốc độ của cánh tay. | +| Planner trả kế hoạch rỗng | Câu lệnh không khớp tên/loại vật hoặc thiếu đích (`tray`/`Slot_N`). | + +--- + +## 8. Cấu trúc thư mục + +``` +C2-App-151/ +├── main.py # Executor + entry point (CLI) +├── requirements.txt +├── README_LLM_PANDA.md # (file này) +├── pybullet-object-models.zip # File nén chứa mô hình vật thể YCB thực tế +├── pybullet-object-models/ # Thư mục giải nén chứa package pybullet_object_models cục bộ +├── llm_panda/ +│ ├── __init__.py +│ ├── config.py # hình học + kết nối + hằng số vật lý (đã validate IK) +│ ├── scene_manager.py # Module 1 +│ ├── grasp_planner.py # Module 2 +│ ├── robot_controller.py # Module 3 +│ ├── gripper_controller.py # Module 4 +│ ├── llm_agent.py # NL → function-call plan +│ └── data/grasp_database.json +``` diff --git a/SYSTEM_ANALYSIS.md b/SYSTEM_ANALYSIS.md new file mode 100644 index 0000000000000000000000000000000000000000..1c5a6083f841746aa2455975724a7f5b53e9c504 --- /dev/null +++ b/SYSTEM_ANALYSIS.md @@ -0,0 +1,230 @@ +# Phân Tích Toàn Diện Hệ Thống LLM-Panda + +Tài liệu này cung cấp một cái nhìn chi tiết và toàn diện về kiến trúc hệ thống, luồng dữ liệu, các thuật toán cốt lõi, logic điều khiển và các ràng buộc vật lý/an toàn của kho lưu trữ **LLM-Panda** (ngoại trừ phần frontend). + +--- + +## 1. Tổng Quan Hệ Thống + +Hệ thống **LLM-Panda** là một ứng dụng mô phỏng cánh tay robot công nghiệp **Franka Emika Panda** trong môi trường vật lý **PyBullet**. Mục tiêu chính của hệ thống là nhận các câu lệnh điều khiển bằng ngôn ngữ tự nhiên (tiếng Anh hoặc tiếng Việt), phân tích trạng thái môi trường hiện tại, lập kế hoạch hành động (planning), kiểm tra tính khả thi và an toàn (verification), sau đó thực thi các chuyển động vật lý để thực hiện các tác vụ gắp và thả vật thể (Pick-and-Place) các vật thể thuộc tập dữ liệu YCB (như chuối, lon súp, lon chips) trên một mặt bàn có các ô chứa (slots) hoặc khay (tray). + +--- + +## 2. Kiến Trúc Các Thành Phần (Component Architecture) + +Hệ thống được tổ chức dạng module rõ ràng, phân tách giữa phần lập kế hoạch logic và phần thực thi phần cứng/vật lý: + +```mermaid +flowchart TB + subgraph Planning ["Lập kế hoạch & An toàn"] + Agent["llm_agent.py
    (LLMAgent)"] + Rule["llm_agent.py
    (RuleBasedPlanner)"] + Remote["llm_agent.py
    (RemoteLLMPlanner)"] + Verifier["plan_verifier.py
    (PlanVerifier)"] + end + + subgraph Execution ["Thực thi Mô phỏng & Vật lý"] + Sim["main.py
    (PandaSimulation)"] + Scene["scene_manager.py
    (SceneManager)"] + Grasp["grasp_planner.py
    (GraspPlanner)"] + Robot["robot_controller.py
    (RobotController)"] + Gripper["gripper_controller.py
    (GripperController)"] + end + + subgraph ConfigData ["Cấu hình & Dữ liệu"] + Config["config.py
    (Hình học, Lực, Khớp)"] + GDB["data/grasp_database.json
    (Toạ độ grasp cục bộ)"] + end + + Sim --> Agent + Sim --> Scene + Sim --> Robot + Sim --> Gripper + Sim --> Grasp + + Agent --> Rule + Agent --> Remote + Agent --> Verifier + + Scene --> Config + Robot --> Config + Gripper --> Config + Grasp --> Config + Grasp --> GDB +``` + +### Chi tiết các file trong `llm_panda/`: + +1. **[config.py](file:///c:/Users/admin/C2-App-151/llm_panda/config.py)**: Chứa toàn bộ hằng số hình học và tham số vật lý của hệ thống. + * *Kích thước & Vị trí bàn*: Tâm bàn `(0.5, 0.0)`, chiều cao mặt bàn `TABLE_TOP_Z = 0.30` m. + * *Lưới Slots*: Gồm 6 ô cố định từ `Slot_1` đến `Slot_6` sắp xếp thành 2 hàng, 3 cột trên bàn. + * *Khay chứa (Tray)*: Kích thước $40 \times 28$ cm tại vị trí `(0.5, 0.45, 0.30)`. + * *Giới hạn robot*: Chỉ số các khớp xoay cánh tay (0-6), khớp tịnh tiến ngón tay (9, 10), và điểm kẹp cuối TCP (11). + * *Lực*: Lực kẹp ngón tay tối thiểu `40.0` N, tối đa `140.0` N. Lực dẫn động cánh tay tối đa `200.0` N. + * *Quỹ đạo*: Chiều cao nâng chuẩn khi tiếp cận `PRE_GRASP_HEIGHT = 10` cm, chiều cao nâng di chuyển `LIFT_HEIGHT = 25` cm. (Check) +2. **[scene_manager.py](file:///c:/Users/admin/C2-App-151/llm_panda/scene_manager.py) (Module 1 - Quản lý Cảnh)**: + * Theo dõi danh sách các body ID vật thể trong PyBullet (`banana`, `soup_can`, `chips_can`). + * Ánh xạ toạ độ vật lý $x, y, z$ của vật thể thành các nhãn logic: `Slot_1`..`Slot_6`, `tray`, hoặc `elsewhere` dựa trên khoảng cách planar. + * Quản lý **Occupancy Grid**: Lưới raster 2D mặt bàn (độ phân giải 1cm) để tính toán vùng chiếm dụng và tìm vị trí trống an toàn (`find_free_placements`) bằng thuật toán Summed-Area Table (SAT). +3. **[grasp_planner.py](file:///c:/Users/admin/C2-App-151/llm_panda/grasp_planner.py) (Module 2 - Kế Hoạch Gắp)**: + * Chuyển đổi toạ độ gắp từ hệ toạ độ cục bộ (object frame) trong `grasp_database.json` sang hệ toạ độ thế giới (world frame) dựa trên tư thế hiện tại của vật thể thông qua phép nhân ma trận biến đổi rigid transform (`pb.multiplyTransforms`). Phép toán này giúp điểm gắp bất biến khi vật thể bị xoay (rotation-invariant). + * Cung cấp phương án dự phòng (fallback) gắp từ trên xuống tại tâm AABB nếu vật thể không có trong database. +4. **[robot_controller.py](file:///c:/Users/admin/C2-App-151/llm_panda/robot_controller.py) (Module 3 - Bộ Điều Khiển Robot)**: + * Giải động học nghịch (Inverse Kinematics - IK) cho 7 khớp của robot. + * Kiểm tra khả năng chạm tới (reachability) và phát hiện va chạm tự động của cánh tay với bàn/khay. + * Điều khiển chuyển động nội suy mượt mà qua các khớp. + * Tính toán chiều cao tránh vật cản động dựa trên các vật thể nằm trên hành lang di chuyển (`_get_corridor_max_z`). + * Tự động cách ly va chạm trong quá trình tiếp cận để tránh robot chạm lệch vật trước khi kẹp. +5. **[gripper_controller.py](file:///c:/Users/admin/C2-App-151/llm_panda/gripper_controller.py) (Module 4 - Bộ Điều Khiển Kẹp)**: + * Tính toán lực kẹp tối ưu dựa trên khối lượng và hệ số ma sát của vật thể được đọc từ môi trường mô phỏng. + * Sử dụng cơ chế **Rigid Constraint** (`JOINT_FIXED`) trong PyBullet để cố định vật thể vào tay robot khi gắp thành công, giúp mô phỏng ổn định, không bị rung lắc vật lý hoặc tuột vật. +6. **[llm_agent.py](file:///c:/Users/admin/C2-App-151/llm_panda/llm_agent.py) (Planning Layer)**: + * Đóng vai trò là Manager tiếp nhận lệnh từ người dùng và trạng thái cảnh từ Scene Manager để dịch sang một chuỗi hành động thô gồm: `pick_up`, `move_to`, `place_down`. + * **RuleBasedPlanner**: Lập kế hoạch cục bộ, bilingual (Anh/Việt) dựa trên từ khoá, tính toán khoảng cách để tự động dọn vật cản (obstacle clearing) và tự động cất vật đang cầm trước khi gắp vật mới. Có cơ chế nhận diện từ khoá "lại" để chạy lại plan gần nhất. + * **RemoteLLMPlanner**: Lập kế hoạch bằng LLM thông qua API tương thích OpenAI (như OpenAI, DeepSeek, Gemini). Có prompt hệ thống chi tiết mô tả đầy đủ các ràng buộc vật lý, không gian làm việc và dọn dẹp vật cản. Hỗ trợ cơ chế exponential backoff khi gặp lỗi giới hạn tần suất gọi API (Rate Limit 429). +7. **[plan_verifier.py](file:///c:/Users/admin/C2-App-151/llm_panda/plan_verifier.py) (Safety Layer)**: + * Kiểm tra tĩnh tính khả thi cấu trúc của kế hoạch trước khi thực thi nhằm phát hiện sớm các lỗi nghiêm trọng (ví dụ: gắp vật không tồn tại, gắp vật ngoài tầm với, gắp liên tiếp 2 vật, đặt vật khi tay trống). + +--- + +## 3. Quy Trình Luồng Dữ Liệu & Thực Thi (Data & Control Flow) + +Quy trình xử lý một câu lệnh của hệ thống diễn ra theo các bước tuần tự sau: + +```mermaid +sequenceDiagram + autonumber + actor User as Người dùng + participant Sim as PandaSimulation (main.py) + participant Scene as SceneManager + participant Agent as LLMAgent + participant PV as PlanVerifier + participant GP as GraspPlanner + participant RC as RobotController + participant GC as GripperController + participant PB as PyBullet + + User->>Sim: Nhập lệnh NL (ví dụ: "gắp chuối bỏ vào khay") + Sim->>Scene: get_scene_state(reachability_fn, carried_object) + Scene->>PB: getBasePositionAndOrientation / getAABB + Scene-->>Sim: Trạng thái cảnh JSON (vị trí logic, occupancy, reachability) + Sim->>Agent: plan(nl_command, state_json) + Agent->>PV: check(plan, state) + PV-->>Agent: Trả về danh sách cảnh báo (nếu có) + Agent-->>Sim: Trả về danh sách bước hành động hợp lệ (đã lọc schema) + + loop Với mỗi hành động trong kế hoạch + alt pick_up(object_id) + Sim->>GP: compute_grasp_pose(object_id, class) + GP->>PB: Đọc tư thế vật thể + GP-->>Sim: Trả về grasp_pos, grasp_ori (world frame) + Sim->>RC: pick(object_id, grasp_pos, grasp_ori) + RC->>RC: Tính toán safe_z (tránh các vật cản dọc đường đi) + RC->>PB: Cách ly va chạm (chỉ cho phép finger pads chạm vật) + RC->>RC: Di chuyển 3 bước trực giao đến grasp_pos + RC->>GC: grasp(object_id) + GC->>PB: Tạo khớp liên kết cố định (Fixed Constraint) + RC->>RC: Nâng vật lên chiều cao an toàn (lift_z) + RC-->>Sim: Trả về kết quả gắp (is_holding=True) + else move_to(location_id) + Sim->>RC: move_to_pose(above_z ở trên target_pos) + RC->>RC: Tính toán above_z dựa trên corridor cản và chiều cao vật cầm + RC->>PB: IK + Di chuyển cánh tay + Sim->>Sim: Lưu vị trí đích tạm thời (_pending_target_pos) + else place_down() + Sim->>RC: place(target_pos) + RC->>RC: Hạ thẳng đứng xuống target_pos (có cộng thêm clearance và obj_height) + RC->>GC: open() + GC->>PB: Xoá bỏ Constraint, mở ngón tay kẹp + RC->>PB: Snap Z (và XY nếu IK lệch > 5cm) để vật tiếp đất chính xác + RC->>RC: Rút cánh tay lên thẳng đứng + RC->>PB: Khôi phục va chạm hoàn toàn giữa robot và vật thể + Sim->>Sim: Xoá trạng thái vật thể đang cầm + end + end + Sim->>Scene: describe() + Scene-->>User: Trả về trạng thái cảnh cuối cùng & Điểm số đạt được +``` + +--- + +## 4. Các Thuật Toán & Logic Cốt Lõi + +### A. Phân Loại Vị Trí Logic (Symbolic Localisation) +Nhằm giúp LLM hiểu trạng thái thế giới mà không cần đọc toạ độ float phức tạp, hệ thống chuyển đổi toạ độ 3D thực tế của vật thể về dạng logic: +1. **Tray Check**: Tính khoảng cách Euclid trên mặt phẳng XY (Planar Distance) từ vật thể tới tâm Tray. Nếu khoảng cách $\le$ `TRAY_MATCH_RADIUS` (0.22 m) $\rightarrow$ vật thể nằm ở `tray`. +2. **Slot Check**: Nếu không ở Tray, tính planar distance từ vật thể tới tâm của 6 Slots. Tìm slot gần nhất. Nếu khoảng cách gần nhất $\le$ `SLOT_MATCH_RADIUS` (0.09 m) $\rightarrow$ vật thể nằm ở Slot đó. +3. **Elsewhere**: Nếu cả hai điều kiện trên không thoả mãn $\rightarrow$ vật thể nằm ở `elsewhere` (ví dụ bị rơi khỏi bàn hoặc bị lệch quá xa). + +### B. Quản Lý Không Gian Trống Bằng Lưới Chiếm Dụng (Occupancy Grid) +Hệ thống duy trì một lưới nhị phân (boolean grid) phủ lên mặt bàn: +* **Vùng khảo sát**: Bàn được thu hẹp vào phía trong một khoảng `TABLE_EDGE_MARGIN` (3 cm) để đảm bảo vật đặt không bị chìa ra ngoài mép bàn. +* **Rasterization**: Mỗi ô lưới có kích thước `OCCUPANCY_CELL_SIZE = 1` cm. Với mỗi vật thể trên bàn (trừ vật đang được robot cầm), hệ thống lấy hộp bao AABB của nó, tăng rộng ra một khoảng lề an toàn (`PLACEMENT_SAFETY_MARGIN = 3` cm), rồi chiếu xuống lưới XY và đánh dấu các ô tương ứng là `True` (bị chiếm). Các vật nằm ở khay hoặc ngoài bàn sẽ bị bỏ qua. + +### C. Tìm Điểm Đặt Trống Bằng Summed-Area Table (SAT) +Khi cần tìm vị trí đặt một vật thể có kích thước footprint $(w_x, w_y)$ lên bàn: +1. Hệ thống tính toán **Summed-Area Table (SAT)** trên Occupancy Grid. SAT cho phép tính tổng số ô bị chiếm trong bất kỳ cửa sổ chữ nhật cỡ $w_x \times w_y$ nào chỉ trong độ phức tạp thời gian $O(1)$. +2. Duyệt qua các cửa sổ khả dĩ trên bàn. Cửa sổ nào có tổng ô chiếm bằng 0 $\rightarrow$ là một điểm đặt hợp lệ. +3. Sắp xếp các điểm đặt hợp lệ theo khoảng cách tới tâm bàn (ưu tiên vùng trung tâm dễ với tới hơn). +4. Lọc các điểm đặt quá sát nhau (khoảng cách planar $\le \max(w_x, w_y)/2$) để phân tán các ứng viên đồng đều. + +### D. Dọn Dẹp Chướng Ngại Vật (Obstacle Clearing) +Trong `RuleBasedPlanner` và hướng dẫn prompt của `RemoteLLMPlanner`, khi gắp một vật thể mục tiêu $A$: +1. Hệ thống quét các vật thể lân cận $B$ có khoảng cách planar tới $A < \text{NEIGHBOR\_RADIUS}$ (0.14 m trong planner, 0.18 m trong scene state) hoặc nằm trên **hành lang tiếp cận** (`_CORRIDOR_WIDTH = 0.09` m) nối từ gốc toạ độ robot tới vật thể mục tiêu. +2. Nếu phát hiện có vật cản $B$ chặn đường gắp, planner tự động chèn thêm chuỗi hành động dọn dẹp trước: + $$\text{pick\_up}(B) \rightarrow \text{move\_to}(\text{free\_slot}) \rightarrow \text{place\_down}()$$ +3. Sau khi dọn dẹp các vật cản, robot mới thực hiện chuỗi hành động gắp vật thể chính $A$. + +### E. Tự Động Đổi Hướng Đích Đặt (Redirection) +Trong `main.py`, khi robot thực thi lệnh đặt vật xuống một ô chứa (hoặc khay) mà ô đó đã bị chiếm dụng: +1. Hệ thống tự động kích hoạt bộ lọc occupancy tại ô đích đó. +2. Tìm kiếm các ô chứa trống trong danh sách `reachable_slots` (ưu tiên các ô gần đích đến ban đầu nhất). +3. Nếu không có ô chứa trống nào có tên logic, hệ thống gọi `find_free_placements` để tìm một toạ độ trống liên tục trên bàn. +4. Nếu tìm thấy điểm trống mới, hệ thống tự động đổi hướng di chuyển (Redirect) sang vị trí đó và ghi nhận cảnh báo lên log (ví dụ: `[REDIR] place_at(Slot_3): footprint blocked → Slot_5`). + +### F. Quy Trình Di Chuyển Trực Giao An Toàn (Orthogonal Motion) +Để tránh va chạm trong quá trình vận hành, robot không di chuyển theo đường chéo thẳng từ điểm này sang điểm khác mà di chuyển theo các trục trực giao: +* **Khi Pick**: + 1. Nâng thẳng tay kẹp từ vị trí hiện tại lên độ cao an toàn (`safe_z`). + 2. Di chuyển ngang ở độ cao `safe_z` đến điểm phía trên vật thể mục tiêu (`pre-grasp`). + 3. Hạ thẳng đứng xuống vị trí gắp (`grasp_pos`). +* **Khi Place**: + 1. Nâng thẳng tay kẹp đang giữ vật lên độ cao an toàn (`above_z`). + 2. Di chuyển ngang đến điểm phía trên vị trí đặt mục tiêu ở độ cao `above_z`. + 3. Hạ thẳng đứng xuống vị trí đặt (`place_pos`). + +Độ cao an toàn `safe_z` và `above_z` được tính toán động bằng cách quét chiều cao Z lớn nhất của toàn bộ vật thể khác dọc theo hành lang di chuyển XY (`_get_corridor_max_z`), cộng thêm chiều cao vật thể đang giữ và biên độ an toàn 5cm. Giá trị này sau đó được giới hạn bởi chiều cao reachable tối đa của robot tại toạ độ đó để tránh lỗi IK vượt ngưỡng. + +### G. Tính Toán Lực Kẹp Vật Lý & Ràng Buộc Cố Định (Grasp Force & Constraint) +1. **Lực kẹp**: Hệ thống tính toán lực kẹp cần thiết để nâng vật không bị trượt dựa trên định luật ma sát: + $$F_g = \frac{m \cdot (g + a) \cdot S_f}{2 \cdot \mu}$$ + Lực này được ép vào khoảng $[40.0, 140.0]$ N. +2. **Khớp cố định**: Do mô phỏng PyBullet có thể gặp lỗi trượt ngón tay vật lý khi cánh tay di chuyển nhanh, sau khi ngón tay gripper đóng lại chạm vật, hệ thống tạo ra một liên kết cứng cố định dạng khớp `pb.JOINT_FIXED` giữ chặt vật thể vào tay robot tại toạ độ tương đối lúc đó. Khi đặt vật xuống, liên kết này sẽ được giải phóng hoàn toàn. + +--- + +## 5. Ràng Buộc Hệ Thống & Các Điểm Kiểm Tra An An Toàn (Constraints & Safety) + +Hệ thống thiết lập nhiều lớp kiểm tra ràng buộc nghiêm ngặt nhằm tránh các hư hỏng hoặc hành động phi lý trong mô phỏng: + +| Loại ràng buộc | Chi tiết ràng buộc | Cách hệ thống xử lý | +| :--- | :--- | :--- | +| **Ràng buộc kẹp** | Robot chỉ có 1 tay kẹp, giữ tối đa 1 vật thể tại một thời điểm. | `PlanVerifier` cảnh báo lỗi gắp liên tiếp. `RuleBasedPlanner` tự động chèn lệnh đặt vật hiện tại xuống slot trống trước khi đi gắp vật mới. | +| **Giới hạn Reachability** | Cánh tay có giới hạn tầm với vật lý và góc khớp. | `RobotController.is_reachable()` kiểm tra trước bằng cách giải IK thử và đo độ lệch TCP thực tế (phải < 2cm). `PlanVerifier` gắn cảnh báo `OUT OF REACH` nếu vật thể ở ngoài tầm với. | +| **Tránh va chạm bàn/khay** | Cánh tay (các link từ -1 đến 8) không được va quẹt vào bàn hoặc khay trong quá trình di chuyển. | Kiểm tra va chạm cơ học trong hàm `is_reachable` thông qua `pb.getContactPoints()`. Nếu phát hiện va chạm $\rightarrow$ báo vị trí không reachable. | +| **Cách ly va chạm tiếp cận** | Tránh gripper gạt lệch vật thể trước khi ngón tay kẹp kịp đóng lại. | `RobotController.isolate_object_collisions()` tạm thời tắt va chạm giữa tất cả các khớp robot với vật thể (chỉ mở va chạm ở 2 ngón tay kẹp) trong suốt pha tiếp cận. Va chạm được khôi phục sau khi đặt vật. | +| **Khắc phục sai lệch IK** | Khi giải IK đến vị trí đặt ở rìa bàn, khớp robot có thể bị lệch XY hoặc Z khiến vật đặt lơ lửng hoặc trôi lệch ô. | Sau khi nhả Constraint gắp, hệ thống thực hiện **Snapping**: thiết lập cứng toạ độ Z của vật thể về đúng mặt tiếp xúc (`target_z + half_height`). Nếu độ lệch XY thực tế so với mục tiêu $> 5$ cm, hệ thống cũng tự động snap toạ độ XY về đúng tâm ô chứa để tránh vật bị rơi ra ngoài bàn. | + +--- + +## 6. Chiến Lược Kiểm Thử (Testing Strategy) + +Hệ thống đi kèm một bộ kiểm thử tự động phong phú trong thư mục `tests/`: + +1. **Unit Tests Hình Học & Vật Lý (`test_pipeline.py`, `test_occupancy.py`)**: + * *Bất biến xoay*: Đảm bảo rằng việc xoay vật thể trên bàn ở góc 45 hay 90 độ không làm thay đổi độ lớn khoảng cách từ điểm gắp thế giới tới tâm vật thể (độ lệch kiểm tra đạt độ chính xác $10^{-6}$ m). + * *Giới hạn lực*: Xác minh hàm tính lực kẹp tối ưu luôn nằm trong dải $[40, 140]$ N kể cả với khối lượng cực đoan ($10^{-9}$ kg đến $10^9$ kg) hoặc khi hệ số ma sát bằng 0. + * *Mô phỏng chiếm dụng*: Kiểm tra logic tính diện tích bàn bị chiếm, loại trừ vật đang cầm, và thuật toán SAT tránh vùng bị chiếm khi tìm điểm đặt mới. +2. **Integration Tests Quy Trình Thực Thi (`test_pipeline.py`, `test_llm_plan.py`)**: + * *Độ ổn định khi di chuyển*: Gắp một vật thể thực tế trong PyBullet headless và thực hiện di chuyển cực nhanh (qua 3 waypoints lớn chỉ trong 50 bước mô phỏng). Xác minh vật thể không bị rơi và vẫn duy trì khoảng cách sát tay kẹp ($< 10$ cm). + * *Kiểm tra Lập kế hoạch*: Chạy kiểm tra ngoại tuyến `RuleBasedPlanner` và `RemoteLLMPlanner` với các kịch bản thực tế trong `test_llm_expected.json` để đối chiếu kết quả đầu ra khớp 100% với kế hoạch mong đợi. diff --git a/SYSTEM_DESIGN.md b/SYSTEM_DESIGN.md new file mode 100644 index 0000000000000000000000000000000000000000..5ff14219ca8ca41275f94c6a7e4a6194b3858181 --- /dev/null +++ b/SYSTEM_DESIGN.md @@ -0,0 +1,337 @@ +# Thiết Kế Hệ Thống Điều Khiển Cánh Tay Robot Bằng Ngôn Ngữ Tự Nhiên (Text & Speech) +## Mã dự án: AI20K-161 — AI Điều Khiển Robot Bằng Ngôn Ngữ Tự Nhiên + +Tài liệu này trình bày thiết kế hệ thống chi tiết cho ứng dụng mô phỏng và điều khiển cánh tay robot **Franka Emika Panda** bằng ngôn ngữ tự nhiên (Văn bản và Giọng nói). Hệ thống tích hợp khả năng lập kế hoạch của Mô hình ngôn ngữ lớn (LLM), lớp kiểm tra an toàn vật lý, mô phỏng động lực học thời gian thực, và giao diện Web SPA hiện đại được triển khai trên môi trường trực tuyến hoàn chỉnh. + +--- + +## 1. Tổng Quan Kiến Trúc Hệ Thống (System Architecture) + +Hệ thống được thiết kế theo kiến trúc hướng dịch vụ (Service-Oriented Architecture), chia nhỏ thành các dịch vụ độc lập giao tiếp qua REST API, WebSockets và RPC để đảm bảo tính sẵn sàng cao, dễ mở rộng và tách biệt trách nhiệm: + +```mermaid +flowchart TB + subgraph Client ["Thiết bị Người Dùng (Client App)"] + UI["Web SPA (Three.js + HTML5 Speech)"] + end + + subgraph API_Gateway ["Cổng API & Quản Lý Người Dùng"] + AuthService["Dịch vụ Xác thực & Phân quyền (JWT)"] + UserDB[("Cơ sở dữ liệu (PostgreSQL)
    Users, Roles, Logs")] + end + + subgraph Execution_Engine ["Tầng Thực Thi Mô Phỏng & Vật Lý"] + FastAPI_WS["FastAPI WebSockets Server"] + PyBulletSim["Mô phỏng PyBullet (Headless Instance)"] + SceneMgr["SceneManager (Module 1)"] + GraspPlan["GraspPlanner (Module 2)"] + RobotCtrl["RobotController (Module 3)"] + GripperCtrl["GripperController (Module 4)"] + end + + subgraph Cognitive_Layer ["Tầng Nhận Thức & Lập Kế Hoạch"] + STT_Service["Dịch vụ Nhận dạng Giọng nói (STT - Whisper/Web Speech API)"] + LLM_Planner["LLMAgent (RuleBased / OpenAI/Claude API)"] + Plan_Verifier["PlanVerifier (Static Validation)"] + end + + %% Giao tiếp + UI <-->|WebSockets: Joints, Objects state| FastAPI_WS + UI -->|REST API: Login, Manage Users| AuthService + UI -->|Speech Input| STT_Service + STT_Service -->|Text Command| UI + + AuthService <--> UserDB + FastAPI_WS <--> PyBulletSim + + PyBulletSim --> SceneMgr + PyBulletSim --> GraspPlan + PyBulletSim --> RobotCtrl + PyBulletSim --> GripperCtrl + + FastAPI_WS <-->|Prompt & State JSON| LLM_Planner + LLM_Planner <-->|Verify Plan| Plan_Verifier +``` + +### Các Dịch Vụ Cốt Lõi (Core Services): + +1. **Dịch vụ Frontend Web SPA**: + * Xây dựng giao diện web phản hồi nhanh (Responsive SPA). + * Tích hợp thư viện **Three.js** để hiển thị mô phỏng 3D thời gian thực thông qua dữ liệu khớp (joint states) và vật thể (object poses) nhận được từ WebSocket. + * Tích hợp API nhận diện giọng nói (Web Speech API hoặc Whisper API) để chuyển khẩu lệnh của người dùng thành văn bản ngay trên trình duyệt. +2. **Dịch vụ Backend API (FastAPI)**: + * Cung cấp các cổng REST API phục vụ đăng nhập, quản lý người dùng, cấp quyền hạn (Roles). + * Cung cấp kết nối WebSocket song công (`/ws`) để truyền trạng thái mô phỏng liên tục ở tần số 30 FPS và nhận các câu lệnh thực thi. + * Quản lý các tiểu trình mô phỏng (Simulation thread pool) để chạy PyBullet headless trên máy chủ. +3. **Dịch vụ Mô phỏng Vật lý (PyBullet Service)**: + * Chạy mô phỏng vật lý 3D Franka Panda và các vật thể YCB cục bộ trên máy chủ trong chế độ không giao diện (`pb.DIRECT` mode). + * Gửi trạng thái góc khớp (11 khớp) và tư thế 3D của các vật thể qua WebSocket về Client. +4. **Dịch vụ Lập kế hoạch LLM (LLMAgent Service)**: + * **RuleBasedPlanner**: Lớp lập kế hoạch ngoại tuyến (Offline) dựa trên luật ánh xạ từ khóa song ngữ Anh/Việt. Dành cho chế độ chạy nhanh và không phụ thuộc mạng. + * **RemoteLLMPlanner**: Lớp lập kế hoạch trực tuyến kết nối đến các API tương thích OpenAI (GPT-4o-mini, Gemini, DeepSeek). Nhận trạng thái cảnh dạng JSON và trả về chuỗi hành động JSON có cấu trúc. +5. **Dịch vụ Kiểm tra Kế hoạch & An toàn (Verification & Safety Service)**: + * **PlanVerifier**: Chạy phân tích tĩnh kế hoạch để phát hiện các hành động bất hợp lý trước khi nạp vào robot. + * Bộ lọc va chạm vật lý và tính toán lực kẹp an toàn dựa trên khối lượng/ma sát thực của vật thể để ngăn ngừa hư hỏng và tuột vật trong PyBullet. + +--- + +## 2. Thiết Kế Giao Diện & Trải Nghiệm Người Dùng (UI/UX Design) + +Giao diện được thiết kế theo phong cách **Glassmorphism** hiện đại, bóng bẩy và mang lại cảm giác cao cấp với các hiệu ứng chuyển động vi mô (micro-animations) và cấu trúc phân vùng rõ ràng. + +### A. Triết Lý Thiết Kế Trực Quan (Aesthetic & Style) +* **Màu sắc**: Palette màu tối giản tối đậm (Deep Slate/Charcoal `#0f172a`, `#1e293b`) kết hợp với hiệu ứng làm mờ kính nền (backdrop blur) và các viền màu neon tinh tế (xanh dương `#3b82f6` cho hoạt động bình thường, xanh lá `#10b981` cho thành công, cam `#f59e0b` cho cảnh báo, đỏ `#ef4444` cho lỗi). +* **Typography**: Sử dụng font chữ **Outfit** (cho tiêu đề, mang hơi hướng công nghệ hiện đại) và **Inter** (cho các thông số kỹ thuật và console log, dễ đọc). +* **Chuyển động**: Các nút và thẻ có hiệu ứng hover mượt mà (transition 0.2s), các bước xử lý trong pipeline nhấp nháy đèn LED trạng thái khi đang chạy. + +### B. Các Phân Vùng Giao Diện Trên Trang Workspace Chính + +Giao diện trang làm việc chính được chia thành 4 khu vực chính: + +``` +┌────────────────────────────────────────────────────────────────────────┐ +│ [🤖 LLM-Panda Workspace] [👤 Người vận hành: Operator] │ +├──────────────────────────────────────┬─────────────────────────────────┤ +│ │ 📊 Trạng Thái Hệ Thống │ +│ │ ┌───────────────────────────┐ │ +│ │ │ O LLM Plan -> O Verify │ │ +│ │ │ O PyBullet -> O Score │ │ +│ │ └───────────────────────────┘ │ +│ 3D VIEWPORT ├─────────────────────────────────┤ +│ (Three.js Visualizer) │ 📋 Kế Hoạch Thực Thi (Task) │ +│ │ ┌───────────────────────────┐ │ +│ Hiển thị cánh tay robot Panda │ │ 1. pick_up(banana) │ │ +│ và vật thể YCB trên bàn │ │ 2. place_at(tray) │ │ +│ ở chế độ tương tác kéo/xoay/zoom │ └───────────────────────────┘ │ +│ ├─────────────────────────────────┤ +│ │ 📺 Console Log Vận Hành │ +│ │ ┌───────────────────────────┐ │ +│ │ │ > Đang kết nối server... │ │ +│ │ │ > Nhận lệnh: gắp lon súp │ │ +│ │ └───────────────────────────┘ │ +├──────────────────────────────────────┴─────────────────────────────────┤ +│ [🎙️] [Nhập câu lệnh điều khiển của bạn...] [Mock Plan 🔘] [Reset 🔄] │ +└────────────────────────────────────────────────────────────────────────┘ +``` + +1. **Khung nhìn mô phỏng 3D (3D Viewport)**: + * Chiếm diện tích lớn nhất (bên trái). Vẽ lại chính xác cấu trúc robot và bàn từ dữ liệu PyBullet. + * Hỗ trợ tương tác bằng chuột: Kéo chuột trái để xoay camera, kéo chuột phải để di chuyển tiêu điểm camera, cuộn chuột để zoom gần/xa. + * Vật thể YCB (như chuối, lon súp, hộp bánh) được nạp texture chân thực từ file `.obj` và `.mtl`. Có tùy chọn hiển thị khung va chạm (collision bounding box) màu xanh dương bán trong suốt để kỹ sư kiểm tra không gian làm việc. +2. **Khung điều khiển & Nhận dạng giọng nói (Control Hub)**: + * Nằm cố định ở góc dưới màn hình dưới dạng một thanh Glassmorphic nổi. + * **Nút micro màu đỏ [🎙️]**: Nhấp để bắt đầu ghi âm giọng nói. Khi người dùng nói (ví dụ: *"gắp quả chuối đặt vào khay"*), sóng âm hiển thị dạng hoạt họa nhấp nháy. Khi dừng nói, hệ thống tự động chuyển đổi thành text và điền vào ô nhập liệu. + * **Ô nhập liệu (Input Chatbox)**: Cho phép gõ văn bản trực tiếp. + * **Các thẻ gợi ý nhanh (Preset Badges)**: Cung cấp các nút kịch bản dựng sẵn: + * `🔌 Sửa đồ điện tử`: Dọn các vật chứa nước ra xa, cất đồ nguy hiểm vào khay. + * `🧸 Trẻ em chơi`: Cất dao, pin, đồ thủy tinh dễ vỡ; giữ lại đồ chơi gỗ. + * `📚 Bàn học tập`: Xếp sách vở vào trung tâm bàn, dọn rác. + * **Nút Reset Scene**: Cho phép hoàn tác, đặt lại vị trí ngẫu nhiên của các vật thể trên bàn (reset seed) và đưa cánh tay về tư thế nghỉ (home pose). +3. **Bảng giám sát luồng xử lý (Pipeline Status & Task Plan)**: + * Nằm ở góc trên bên phải. Hiển thị 4 bước xử lý tuần tự bằng các biểu tượng bóng đèn LED đổi màu: + 1. *LLM Planning* (Xanh dương khi đang lập kế hoạch, Xanh lá khi hoàn tất). + 2. *Rule Validation* (Vàng nếu phát hiện cảnh báo tĩnh, Đỏ nếu kế hoạch bị từ chối). + 3. *PyBullet Execution* (Nhấp nháy khi cánh tay đang di chuyển vật lý). + 4. *Scoring & Feedback* (Hiện kết quả đánh giá rearrangement). + * **Task Plan Viewer**: Hiển thị danh sách các kỹ năng thô sẽ được thực hiện (ví dụ: `Step 1: pick_up(banana)`, `Step 2: place_at(Slot_3)`). Bước nào đang chạy sẽ được tô sáng viền neon và có icon chỉ vị trí. +4. **Bảng điều khiển Log Vận Hành & Dashboard Kỹ Thuật (Execution Log & Telemetry)**: + * Hiển thị log chi tiết dạng dòng chảy console, cuộn tự động. Màu sắc phân biệt rõ ràng: cảnh báo có màu vàng cam, lỗi màu đỏ, các chuyển động kẹp/thả có màu xanh lục. + * Telemetry Panel (có thể ẩn/hiện): Hiển thị tọa độ $x,y,z$ thực tế của TCP (Điểm cuối tay kẹp), góc xoay 7 khớp của robot dạng thanh đo (progress bar), lực kẹp hiện tại ($N$) và trạng thái ngón kẹp (đang giữ vật hay trống). + +### C. Modal Báo Cáo Kết Quả Rearrangement (Evaluation Report) +Khi hoàn thành toàn bộ chuỗi hành động, một modal lớn sẽ hiện lên giữa màn hình với hiệu ứng mờ hậu cảnh: +* **Tổng điểm số**: Đánh giá từ `0` đến `100` điểm dựa trên công thức tính điểm rearrangement. +* **Bảng chi tiết**: + * Thành công trong việc đưa vật thể đích đến đúng slot chỉ định: `+50` điểm. + * Thực thi trơn tru toàn bộ kế hoạch không bị lỗi gián đoạn: `+20` điểm. + * Không làm xê dịch hay xô đổ các vật thể không liên quan khác: `+30` điểm. + * *Trừ điểm*: `-15` điểm cho mỗi vật thể bị xô lệch khỏi slot quy định (knock detection), `-50` điểm nếu vật thể đích chưa đến đúng vị trí, `-30` điểm nếu robot bị kẹt hoặc va chạm thô bạo với bàn. + +--- + +## 3. Luồng Hoạt Động Chi Tiết Của Hệ Thống (Data & Control Flow) + +Quy trình khép kín từ khi nhận đầu vào giọng nói/văn bản cho đến khi robot thực thi chuyển động và cập nhật lên màn hình được thể hiện qua biểu đồ tuần tự sau: + +```mermaid +sequenceDiagram + autonumber + actor User as Người dùng + participant UI as Web SPA (Three.js) + participant STT as Dịch vụ STT (Whisper/Web API) + participant API as FastAPI Backend + participant Sim as PyBullet Engine + participant LLM as LLMAgent (Planner) + participant PV as PlanVerifier (Safety) + + User->>UI: Bấm nút micro và nói câu lệnh + UI->>STT: Gửi luồng âm thanh + STT-->>UI: Trả về văn bản ("gắp chuối bỏ vào khay") + UI->>API: Gửi lệnh văn bản qua WebSocket (type: "run") + + Note over API, Sim: Backend khóa tương tác người dùng (Lock Input) + API->>Sim: Lấy trạng thái không gian (Scene State) hiện tại + Sim-->>API: Trả về JSON (Objects, Slots, Occupancy Grid) + + API->>LLM: Gửi câu lệnh + Trạng thái cảnh dạng JSON + LLM->>LLM: Phân rã câu lệnh thành chuỗi hành động JSON + LLM->>PV: Chạy kiểm tra an toàn tĩnh (Reachability, Constraints) + PV-->>LLM: Trả về kết quả xác minh (Warnings/Errors nếu có) + LLM-->>API: Trả về Kế hoạch hành động cuối cùng + + API->>UI: Stream danh sách bước (Task Plan) để hiển thị lên giao diện + + loop Với mỗi hành động trong kế hoạch + API->>Sim: Yêu cầu thực thi bước (ví dụ: pick_up, place_at) + + loop Tần số 30 FPS trong lúc robot di chuyển + Sim->>Sim: Giải IK, dịch chuyển các khớp, cập nhật vật lý + Sim-->>API: Gửi trạng thái khớp & vị trí vật (Joints, Objects) + API-->>UI: Stream gói dữ liệu "state" qua WebSocket + UI->>UI: Cập nhật mô hình Three.js (render chuyển động robot mượt mà) + end + Sim-->>API: Báo cáo hoàn thành bước thực thi + end + + API->>Sim: Tính toán Rearrangement Score cuối cùng + Sim-->>API: Trả về điểm số & chi tiết đánh giá + API-->>UI: Gửi gói tin "result" (Điểm số, báo cáo Markdown) + + Note over API, UI: Mở khóa tương tác người dùng (Unlock Input) + UI->>User: Hiển thị Modal điểm số & Báo cáo chi tiết +``` + +--- + +## 4. Các Thuật Toán An Toàn & Ràng Buộc Vật Lý (Safety & Controls) + +Để hệ thống hoạt động ổn định, tránh các chuyển động hư hỏng trong mô phỏng vật lý, các thuật toán kiểm tra được phân lớp chặt chẽ: + +### A. Kiểm Tra Khả Năng Chạm Tới (Reachability Verification) +Trước khi gửi trạng thái cảnh cho LLM, `SceneManager` chạy hàm kiểm tra tính khả thi của điểm gắp: +1. Truy vấn vị trí thế giới của vật thể. +2. Tra cứu tư thế gắp cục bộ (local grasp pose) trong **Grasp Database** (`grasp_database.json`) để chuyển đổi sang tư thế gắp thế giới (world grasp pose) thông qua phép nhân ma trận biến đổi: + $$T_{world\_grasp} = T_{world\_object} \times T_{local\_grasp}$$ +3. Gọi bộ giải động học nghịch (IK Solver) thử nghiệm trên cánh tay robot. Nếu sai số định vị điểm cuối TCP thực tế so với mục tiêu vượt quá $2$ cm hoặc có va chạm cơ học của robot với bàn $\rightarrow$ Đánh dấu vị trí đó là `Unreachable`. +4. Thông tin này được nạp trực tiếp vào prompt JSON gửi LLM để LLM tránh ra lệnh gắp các vật nằm ngoài tầm với hoặc bị kẹt. + +### B. Hành Lang Di Chuyển An Toàn & Tránh Va Chạm Động (Safety Corridor) +Khi di chuyển giữa các vị trí, robot áp dụng **Quy trình di chuyển trực giao an toàn (Orthogonal Motion)** thay vì di chuyển đường chéo: +* **Pha nhấc (Lift)**: Nhấc thẳng tay kẹp lên độ cao an toàn. +* **Pha tịnh tiến (Pan)**: Di chuyển ngang ở độ cao an toàn đến điểm nằm ngay trên mục tiêu (`pre-grasp` hoặc `above_place`). +* **Pha tiếp cận (Descend)**: Hạ thẳng đứng xuống điểm đích. +* **Tính toán độ cao động**: Chiều cao di chuyển an toàn $Z_{safe}$ được tính toán động bằng cách quét tất cả vật thể nằm trong hành lang di chuyển (corridor) rộng $9$ cm kết nối điểm đầu và điểm cuối trên mặt phẳng XY: + $$Z_{safe} = \max(Z_{corridor\_objects}) + H_{carried\_object} + \text{Margin (5cm)}$$ + Thuật toán này đảm bảo tay kẹp đang giữ vật luôn đi cao hơn tất cả các vật thể cản trên bàn mà không vượt quá giới hạn với tới tối đa của robot. + +### C. Quản Lý Không Gian Đặt Bằng Lưới Chiếm Dụng (Occupancy Grid & SAT) +Để ngăn LLM đặt chồng vật thể lên nhau hoặc đặt sát mép bàn gây rơi vỡ: +1. Mặt bàn được số hóa thành lưới ô vuông kích thước ô $1 \times 1$ cm. +2. Các vật thể đang nằm trên bàn sẽ bị chiếu hộp bao AABB xuống lưới XY, cộng thêm biên an toàn $3$ cm xung quanh và đánh dấu các ô này là bị chiếm (`Occupied = True`). +3. Khi cần đặt một vật thể mới, hệ thống sử dụng thuật toán **Bảng diện tích tích lũy (Summed-Area Table - SAT)** để tìm kiếm các cửa sổ chữ nhật trống trên bàn có kích thước phù hợp với footprint của vật thể. +4. Nếu slot đích mà LLM chọn đã bị chiếm, hệ thống tự động kích hoạt logic **Redirection (Đổi hướng)**: tìm slot trống gần nhất có khả năng với tới, hoặc tìm tọa độ trống liên tục trên bàn bằng SAT, sau đó hướng robot đặt vào vị trí an toàn mới này và phát cảnh báo lên màn hình UI. + +### D. Tối Ưu Lực Kẹp Vật Lý & Cách Ly Va Chạm (Grasp Force & Collision Isolation) +* **Lực kẹp**: Đọc khối lượng $m$ và hệ số ma sát $\mu$ của vật từ PyBullet, tính toán lực kẹp ma sát tối thiểu để vật không bị trượt khi tay di chuyển với gia tốc $a$: + $$F_g = \frac{m \cdot (g + a) \cdot S_f}{2 \cdot \mu}$$ + *Trong đó $S_f = 1.5$ (hệ số an toàn), $g = 9.81 m/s^2$.* Lực kẹp được giới hạn cứng trong dải phần cứng cánh tay $[40.0, 140.0]$ N. +* **Cách ly va chạm**: Trong suốt pha tiếp cận hạ thẳng đứng để kẹp vật, hệ thống tạm thời vô hiệu hóa va chạm giữa các khớp cánh tay (link 0 đến 8) với vật thể mục tiêu, chỉ cho phép hai ngón tay kẹp (finger pads) có va chạm vật lý với vật. Điều này ngăn robot vô tình huých lệch vật trước khi kẹp đóng lại. +* **Khớp cố định (Rigid Constraint)**: Khi kẹp đã đóng sát vật và `is_holding()` xác nhận tiếp xúc, hệ thống tạo một khớp liên kết cứng cố định (`pb.JOINT_FIXED`) giữa tay kẹp và vật thể. Điều này giúp loại bỏ hoàn toàn lỗi rung lắc cơ học hoặc trượt vật do sai số mô phỏng của PyBullet khi robot di chuyển nhanh. Khớp liên kết này được giải phóng ngay khi bắt đầu pha thả vật. + +--- + +## 5. Đăng Nhập, Phân Quyền & Quản Lý Người Dùng (Auth & Roles) + +Để đáp ứng tiêu chuẩn phần mềm hoàn chỉnh, hệ thống tích hợp cơ chế quản lý tài khoản và phân quyền vận hành nghiêm ngặt: + +### A. Cơ Chế Xác Thực (Authentication) +* Sử dụng giao thức **OAuth2 với mã thông báo JWT (JSON Web Tokens)**. +* Mã JWT được lưu trữ an toàn trong `HTTPOnly Cookies` ở phía client để chống tấn công XSS. +* Mọi yêu cầu kết nối WebSocket `/ws` đều phải truyền kèm token xác thực hợp lệ trong tham số truy vấn hoặc header kết nối. + +### B. Các Quyền Hạn Trong Hệ Thống (RBAC - Role-Based Access Control) + +Hệ thống phân chia thành 3 vai trò người dùng rõ rệt: + +| Vai trò | Quyền hạn trên UI/UX | Quyền hạn Backend & Dịch vụ | +| :--- | :--- | :--- | +| **Quản trị viên (Admin)** | Xem toàn bộ workspace, truy cập trang quản trị user, xem lịch sử log toàn hệ thống, thay đổi cấu hình robot. | Toàn quyền thêm/sửa/xóa tài khoản, cấu hình tham số vật lý trong `config.py` qua API, cấu hình LLM Model. | +| **Người vận hành (Operator)** | Gửi câu lệnh bằng text/speech, chạy và dừng mô phỏng, reset môi trường mô phỏng. | Gọi API lập kế hoạch LLM, điều khiển PyBullet Sim thông qua WebSocket. Không có quyền sửa đổi user khác. | +| **Người quan sát (Viewer)** | Chỉ xem luồng mô phỏng 3D thời gian thực, xem log console và bảng điểm. Khóa toàn bộ nút điều khiển, micro và chatbox. | Chỉ được phép lắng nghe (subscribe) luồng truyền tải dữ liệu trạng thái qua WebSocket. Bị chặn mọi API điều khiển. | + +--- + +## 6. Kiến Trúc Triển Khai Trực Tuyến (Deployment & Cloud Hosting) + +Hệ thống được đóng gói hoàn toàn bằng Docker và triển khai trên máy chủ Cloud/VPS công cộng để người dùng có thể truy cập qua URL Internet công cộng. + +### A. Sơ Đồ Triển Khai Container (Docker Composition) + +``` + ┌────────────────────────┐ + │ Nginx Reverse Proxy │ + │ (SSL - Port 443) │ + └───────────┬────────────┘ + │ + ┌─────────────────────┴─────────────────────┐ + │ Port 80/443 (Web Traffic) │ Port 8000 (WebSocket) + ▼ ▼ +┌─────────────────────────┐ ┌─────────────────────────┐ +│ Frontend Service │ │ FastAPI Backend │ +│ (Next.js / Nginx) │ │ (Uvicorn ASGI App) │ +└─────────────────────────┘ └────────────┬────────────┘ + │ + ┌────────────────────┴────────────────────┐ + ▼ ▼ + ┌─────────────────────────┐ ┌─────────────────────────┐ + │ Headless PyBullet │ │ Database Instance │ + │ (Xvfb Virtual Frame) │ │ (PostgreSQL - Auth) │ + └─────────────────────────┘ └─────────────────────────┘ +``` + +### B. Giải Pháp Chạy PyBullet Headless Trên Cloud/VPS +Một thách thức lớn khi triển khai PyBullet lên các máy chủ VPS đám mây thông thường là máy chủ không có màn hình vật lý (Headless) và không có card đồ họa GPU chuyên dụng: +1. **Virtual Framebuffer (Xvfb)**: Backend chạy trong một container Docker chạy hệ điều hành Ubuntu được cài đặt `xvfb` (X virtual framebuffer) và `mesa-utils` (phần mềm kết xuất đồ họa OpenGL bằng CPU). +2. **Khởi động Sim**: PyBullet được khởi tạo trong Python bằng cách kết nối ở chế độ `pb.DIRECT` (không dựng hình đồ họa) hoặc `pb.GUI` nhưng được trỏ ra màn hình ảo Xvfb: + ```bash + # Khởi chạy màn hình ảo ở chế độ background trong Docker entrypoint + Xvfb :99 -screen 0 1024x768x24 & + export DISPLAY=:99 + ``` +3. **Dựng hình ở Backend**: Các tính toán vật lý, phát hiện va chạm và giải IK hoàn toàn sử dụng CPU của VPS thông qua thư viện PyBullet, sau đó xuất tọa độ góc khớp dạng mảng JSON thô. Việc dịch hình 3D (visual rendering) được đẩy toàn bộ về card đồ họa của máy người dùng cuối (Client-side GPU) thông qua thư viện **Three.js** trên trình duyệt, giúp giảm tải tối đa cho máy chủ VPS và mang lại chuyển động 60fps mượt mà cho người dùng. + +--- + +## 7. Các Tính Năng Hệ Thống Nâng Cao Trải Nghiệm Người Dùng (User-Centric System & Platform Features) + +Đối với một hệ thống quản lý và điều khiển robot thực tế chạy trên nền tảng Web/App, ngoài việc mô phỏng chuyển động cơ khí, người dùng cần các tính năng quản lý, phân tích và tương tác trực quan để tối ưu hóa hiệu suất làm việc. Dưới đây là các tính năng hệ thống hướng tới trải nghiệm người dùng (UX) và quản trị vận hành: + +### A. Thiết Kế Không Gian & Kịch Bản Trực Quan (Visual Workspace & Scenario Builder) +Giúp người dùng tự cấu hình môi trường thử nghiệm và làm việc mà không cần can thiệp vào mã nguồn: +* **Kéo thả vật thể trong 3D Viewport**: Người dùng có thể click chọn một vật thể trong không gian Three.js và kéo thả (Drag & Drop) hoặc nhập tọa độ trực tiếp để thay đổi vị trí ban đầu của vật thể trên bàn, thiết lập trạng thái ban đầu của khay và các ô chứa. +* **Lưu mẫu thiết lập bàn (Layout Templates)**: Hỗ trợ người dùng lưu các cấu hình không gian này thành các mẫu có sẵn (ví dụ: *"Bàn học tập bừa bộn"*, *"Chuẩn bị lắp ráp linh kiện"*). Người dùng có thể nhanh chóng nạp lại các mẫu này chỉ bằng 1-click để thử nghiệm lại hoặc chia sẻ cho các Operator khác. +* **Quản lý Preset Badges**: Giao diện cho phép người quản trị tự tạo, chỉnh sửa hoặc xóa các nút kịch bản nhanh (Preset Badges) trực tiếp trên Web UI, tự định nghĩa Prompt tương ứng cho từng nút thay vì cấu hình tĩnh trong code. + +### B. Nhật Ký Câu Lệnh & Tua Lại Chuyển Động (Command History & Replay Timeline) +* **Lịch sử lệnh (Command Log Book)**: Bảng lịch sử lưu giữ danh sách tất cả các câu lệnh từng được gửi bởi các người dùng khác nhau trong hệ thống, bao gồm thời gian chạy, người thực hiện, nội dung câu lệnh, mô hình LLM đã dùng, và điểm rearrangement đánh giá. +* **Trình phát lại trực quan (Execution Video/3D Playback)**: Người dùng có thể click vào bất kỳ bản ghi lịch sử nào để xem lại quá trình thực thi. Hệ thống cung cấp một thanh trượt thời gian (Timeline Slider) để tua nhanh, tua chậm, tạm dừng chuyển động của robot và vật thể trong Viewport 3D, giúp người dùng hiểu rõ tại sao robot thất bại ở một bước cụ thể. + +### C. Quản Lý Thư Viện Vật Thể (Interactive Object Catalog & Asset Library) +Trang quản trị dành cho người dùng cấu hình các thuộc tính phi hình học của vật thể: +* **Quản lý thuộc tính vật thể**: Xem danh sách các vật thể có trong hệ thống, cấu hình các thuộc tính như: tên định danh (ID), tên ngôn ngữ tự nhiên thường gọi (ví dụ: *"tomato_can"* có các tên gọi phụ như *"lon cà chua"*, *"lon súp"*), khối lượng ($kg$), hệ số ma sát, và tính chất an toàn (ví dụ: *"dễ vỡ"*, *"nguy hiểm"*, *"chứa nước"*). +* **Nạp Model 3D tự động**: Hỗ trợ tải lên file 3D Mesh mới (định dạng `.obj`, `.mtl`, hoặc `.gltf`) trực tiếp qua giao diện Web để mở rộng thư viện vật thể mà robot có thể tương tác. + +### D. Gợi Ý Câu Lệnh Thông Minh & Hỗ Trợ Nhập Liệu (Smart Autocomplete & AI Recommendation) +* **Gợi ý ngữ cảnh (Context-aware Autocomplete)**: Khi người dùng gõ câu lệnh vào khung chat, hệ thống dựa trên trạng thái cảnh hiện tại (Scene State) để gợi ý các từ khóa thích hợp (ví dụ: gõ *"gắp"* sẽ tự động gợi ý *"gắp quả chuối ở Slot_2 bỏ vào Tray"* vì hệ thống phát hiện quả chuối đang ở Slot 2). +* **Đề xuất hành động tiếp theo (AI Next-Step Recommendation)**: Phân tích trạng thái cảnh hiện tại và đưa ra các đề xuất hành động cho người dùng. Ví dụ: *"Tôi phát hiện thấy có rác trên bàn học, bạn có muốn tôi 'Dọn dẹp rác bỏ vào thùng' không?"*. + +### E. Thống Kê Hiệu Suất Hệ Thống (Performance Analytics Dashboard) +Báo cáo trực quan bằng biểu đồ (Charts/Graphs): +* **Chỉ số hiệu quả (KPIs)**: Thống kê tỷ lệ thực thi thành công của robot qua các ngày, điểm rearrangement trung bình, thời gian thực thi trung bình cho mỗi tác vụ, và độ trễ trung bình của các mô hình LLM. +* **Phân tích lỗi (Error Distribution)**: Vẽ biểu đồ tròn phân tích các nguyên nhân gây lỗi vận hành (ví dụ: do lỗi lập kế hoạch LLM chiếm 20%, do vật thể ngoài tầm với IK chiếm 50%, do trượt ngón kẹp chiếm 30%), giúp người quản lý biết cần tối ưu hóa khâu nào. + +### F. Trung Tâm Cảnh Báo & Hỗ Trợ Đa Phương Thức (System Alert Center & Audio Feedback) +* **Phản hồi bằng giọng nói (TTS - Text-To-Speech)**: Robot không chỉ nhận giọng nói mà còn phát âm thanh phản hồi lại người dùng: *"Tôi đã hiểu yêu cầu. Tôi sẽ bắt đầu gắp lon snack"* hoặc phát giọng nói cảnh báo: *"Chú ý: Slot 3 đã bị chiếm dụng, tôi sẽ tự động đặt vật thể vào Slot 5"*. + +### G. Quản Lý Dự Án & Không Gian Vận Hành (Multi-Workspace Hub) +* **Phân vùng dự án (Workspaces)**: Người dùng có thể tạo nhiều không gian làm việc khác nhau (ví dụ: *"Dây chuyền lắp ráp A"*, *"Khu vực phân loại rác B"*), mỗi không gian có thiết lập mô hình robot, danh mục vật thể và các mẫu layout bàn riêng biệt. diff --git a/TrajOpt_Implementation_Guide.md b/TrajOpt_Implementation_Guide.md new file mode 100644 index 0000000000000000000000000000000000000000..474616df8ec0935a65b5de314fecf984cb839162 --- /dev/null +++ b/TrajOpt_Implementation_Guide.md @@ -0,0 +1,181 @@ +# TrajOpt Implementation Guide (Robot Franka Panda) + +## 1. Mục tiêu + +Tài liệu này chỉ đặc tả cách cài đặt **TrajOpt** cho bài toán của hệ thống: + +- Đầu vào: + - Trạng thái khớp hiện tại `q_start` + - Grasp pose `T_grasp` (đã được module khác xác định) + - Target placement pose `T_target` + - Robot model (URDF) + - Collision meshes + - Môi trường +- Đầu ra: + - Quỹ đạo khớp liên tục từ `q_start -> grasp -> target`. + +TrajOpt **không** sinh grasp pose. +TrajOpt **không** giải IK. +TrajOpt chỉ tối ưu quỹ đạo. + +--- + +# 2. Biến tối ưu + +Mỗi waypoint: + +`q_t = [q1,...,q7]` + +Toàn bộ trajectory: + +`Q=[q1,q2,...,qT]` + +Nếu T=30 thì số biến là 210. + +TrajOpt tối ưu đồng thời toàn bộ waypoint. + +--- + +# 3. Khởi tạo quỹ đạo + +Không sử dụng random, RRT hay PRM. + +Khởi tạo bằng nội suy tuyến tính: + +- q_start -> q_grasp +- q_grasp -> q_target + +Quỹ đạo ban đầu được phép xuyên vật cản. + +--- + +# 4. Hàm mục tiêu + +Mục tiêu chính: + +J = Σ ||q(t+1)-q(t)||² + +Có thể bổ sung acceleration cost nếu cần quỹ đạo mượt hơn. + +--- + +# 5. Hard Constraints + +## Joint limits + +Mọi waypoint đều phải thỏa: + +q_min ≤ q_t ≤ q_max + +Giới hạn lấy từ URDF. + +## Grasp constraint + +Waypoint grasp phải thỏa: + +FK(q_k)=T_grasp + +Đây là hard equality constraint. + +## Placement constraint + +Waypoint cuối: + +FK(q_T)=T_target + +Đây cũng là hard equality constraint. + +--- + +# 6. Collision World + +TrajOpt không đọc trực tiếp PyBullet. + +Cần xây dựng Collision World gồm: + +- Robot collision mesh +- Object collision mesh +- Table +- Ground +- Static obstacles + +Mỗi object cần: + +- Mesh +- World pose +- Collision margin +- AABB + +Trước mỗi lần planning phải đồng bộ pose từ PyBullet sang Collision World. + +--- + +# 7. Continuous Collision Checking + +Không chỉ kiểm tra tại waypoint. + +TrajOpt kiểm tra chuyển động giữa hai waypoint liên tiếp. + +Đối với mỗi robot link: + +- xây dựng swept volume +- tính signed distance +- lấy contact normal +- lấy closest points + +Nếu signed distance < d_safe thì sinh gradient đẩy quỹ đạo ra xa vật cản. + +--- + +# 8. Tuyến tính hóa + +Khoảng cách va chạm được tuyến tính hóa quanh nghiệm hiện tại: + +sd(q) ≈ sd(q0)+∇sd(q0)(q-q0) + +Gradient được tính từ: + +- contact normal +- robot Jacobian + +Sau đó chuyển thành ràng buộc tuyến tính trong bài toán QP. + +--- + +# 9. SQP + +Mỗi iteration: + +1. Forward Kinematics +2. Collision Query +3. Jacobian +4. Linearization +5. Xây dựng Quadratic Program +6. Giải QP +7. Cập nhật trajectory +8. Kiểm tra hội tụ + +Thông thường 10–30 iteration. + +--- + +# 10. Điều kiện hội tụ + +Thuật toán dừng khi: + +- Không còn vi phạm khoảng cách an toàn. +- Các hard equality constraints được thỏa mãn trong giới hạn chính xác số học của solver. +- Chi phí thay đổi giữa hai iteration nhỏ hơn ngưỡng. +- Trust region không còn cải thiện nghiệm. + +Nếu không hội tụ trước số iteration tối đa thì planner trả về thất bại. + +--- + +# 11. Lưu ý + +- TrajOpt không tìm grasp pose. +- TrajOpt không giải IK. +- IK phải được giải trước. +- Collision World phải được cập nhật trước mỗi lần lập kế hoạch. +- Khi attach object, collision model phải cập nhật để quỹ đạo sau grasp tính cả vật được gắp. diff --git a/WORKLOG.md b/WORKLOG.md new file mode 100644 index 0000000000000000000000000000000000000000..e52aad3c958db3303f59474efc9d9afd9885278c --- /dev/null +++ b/WORKLOG.md @@ -0,0 +1,67 @@ +# Technical Worklog — LLM-Panda + +Tài liệu này ghi lại các quyết định kỹ thuật, phân công công việc, và các lỗi quan trọng được phát hiện & sửa chữa trong quá trình phát triển dự án. + +--- + +## [2026-06-18] Sửa Lỗi: Lệnh Gắp Đơn Thuần Tự Động Thả Vào Khay/Slot + +### 1. Hiện tượng (Symptom) +* Khi người dùng nhập lệnh yêu cầu gắp vật thể lên đơn thuần mà không chỉ định điểm đến (ví dụ: `"nhấc lon súp"`, `"pick up the chips can"`), robot gắp vật thể lên thành công nhưng ngay lập tức di chuyển tay máy để đặt vật thể đó vào khay (`tray`) hoặc một slot trống ngẫu nhiên. +* Việc tự động thả này là sai yêu cầu nghiệp vụ (lẽ ra robot chỉ được gắp và nhấc giữ vật thể ở tư thế trên không). + +### 2. Nguyên nhân gốc rễ (Root Cause) +* Trong System Prompt của `RemoteLLMPlanner` ([llm_agent.py](file:///media/minhnht31/data/vinuni/C2-App-151/llm_panda/llm_agent.py)), điều kiện ràng buộc loại trừ chỉ cho phép tạo duy nhất hành động `pick_up` khi câu lệnh chứa các từ khóa cụ thể nằm trong tập **`('gắp lên', 'nhặt lên')`**. +* Khi người dùng sử dụng các động từ chỉ hành động gắp khác như `"nhấc"`, `"nhặt"`, `"cầm"`, `"nhấc lên"`, `"cầm lên"`, hoặc tiếng Anh `"pick up"`, `"grab"`, `"lift"`, `"take"`, LLM Planner không khớp được với tập từ khóa này. +* Do schema mặc định quy định đầu ra là một chuỗi tuần tự `[pick_up, place_at]`, LLM tự động suy luận ra một địa điểm trống thích hợp để tạo hành động `place_at` tương ứng dẫn đến hành vi tự động thả. + +### 3. Giải pháp (Fix) +* Cập nhật System Prompt trong lớp `RemoteLLMPlanner` ([llm_agent.py](file:///media/minhnht31/data/vinuni/C2-App-151/llm_panda/llm_agent.py#L274-L278)), mở rộng điều kiện loại trừ: + > *“If the user only asks to pick up / lift / grab / take an object (e.g., 'gắp', 'nhấc', 'nhặt', 'cầm', 'gắp lên', 'nhấc lên', 'nhặt lên', 'cầm lên', 'pick up', 'grab', 'take', 'lift') and does not specify any destination, output ONLY the pick_up action and do NOT append a place_at action.”* +* Điều này ép buộc LLM không được tự ý thêm hành động thả khi câu lệnh gắp không có đích đến cụ thể. + +### 4. Kiểm chứng (Verification) +* Thêm các ca kiểm thử hành động đơn lẻ vào `tests/test_prompts.json` dưới dạng `level_1_basic` (như `"gắp lon snack lên"`, `"nhấc lon súp"`, `"pick up the banana"`). +* Chạy thử nghiệm qua `tests/test_auto.py`, các lệnh trên đều trả về JSON Plan chỉ có duy nhất 1 bước `pick_up`, robot gắp vật thể và giữ nguyên trên không đúng như thiết kế. + +## [2026-06-18] Sửa Lỗi: Tay Robot Bị Kẹt Vật Lý (Physical Collision) + +### 1. Hiện tượng (Symptom) +* Cánh tay robot bị kẹt vật lý khi hạ xuống (descend) gắp hoặc thả vật thể tại khay (tray) hoặc ô (slots) gần đế. +* Lỗi báo: `place: arm deviated X m from target XY` và ở bước tiếp theo báo `TCP is too far from grasp position! Grasp aborted` làm dừng toàn bộ chương trình gắp/thả kế tiếp. + +### 2. Nguyên nhân gốc rễ (Root Cause) +* Bộ giải IK (`pb.calculateInverseKinematics`) không có ràng buộc về va chạm vật lý nên đã tính ra các nghiệm khớp có tư thế cùi chỏ hướng xuống (elbow-down) khi cánh tay duỗi xa/gần đế. +* Tư thế khuỷu tay/cánh tay này đè trực tiếp lên mặt bàn/khay (Z = 0.3m, trong khi đế robot ở Z = 0.0m) gây va chạm vật lý, kẹt khớp và lệch vị trí TCP. + +### 3. Giải pháp (Fix) +* Cập nhật bộ giải IK trong `RobotController._ik` ([robot_controller.py](file:///media/minhnht31/data/vinuni/C2-App-151/llm_panda/robot_controller.py)): Truy vấn các giới hạn khớp (`lowerLimits`, `upperLimits`), khoảng khớp (`jointRanges`) và tư thế nghỉ `ARM_REST_POSE` (tư thế cùi chỏ hướng lên - elbow-up) từ cấu hình để truyền làm tham số ràng buộc cho hàm giải IK của PyBullet. +* Cập nhật `RobotController.is_reachable` để kiểm tra thêm va chạm vật lý của cánh tay robot (links từ -1 đến 8) với bàn và khay sau khi giải IK bằng hàm `pb.performCollisionDetection`. +* Truyền thêm `table_id` và `tray_id` cho robot controller trong `main.py` ([main.py](file:///media/minhnht31/data/vinuni/C2-App-151/main.py)). + +### 4. Kiểm chứng (Verification) +* Chạy kiểm thử tự động toàn bộ 29 unittests (`pytest`) đều đạt kết quả tốt. +* Xác minh thủ công luồng lệnh bị kẹt trước đó (gắp/thả chips_can vào khay và gắp soup_can từ Slot_5) đã chạy mượt mà, cùi chỏ hướng lên cao và không còn va chạm vật lý với bàn. + +## [2026-06-18] Sửa Lỗi: Rung Lắc Cánh Tay, Lọc Vật Thể Rơi & Tránh Gắp Vào Không Khí + +### 1. Hiện tượng (Symptom) +* Cánh tay robot bị rung lắc dữ dội khi gắp giữ vật thể lơ lửng trong thời gian chờ (idle), làm hất văng hộp snack (`chips_can`) rơi khỏi bàn xuống đất. +* Hộp snack sau khi rơi xuống đất vẫn báo trạng thái `reachable: true` trong scene state, dẫn đến LLM Planner cố gắp lại và bị trượt (`slipped during lift`). +* Robot gắp quả chuối (`banana`) vào khoảng không khí phía trên quả chuối, làm 2 ngón tay kẹp khép chặt về `0.0 mm` và không có điểm tiếp xúc vật lý (`contacts = [False, False]`), nhưng quả chuối vẫn tự bay lên theo tay robot. + +### 2. Nguyên nhân gốc rễ (Root Cause) +* **Rung lắc vật lý**: Xảy ra xung đột lực (feedback loop) giữa mối liên kết kẹp cứng (`pb.createConstraint`) và lực đóng ngón kẹp liên tục (`self.close(force)`) trong lúc chạy mô phỏng thời gian thực (`setRealTimeSimulation(1)`). +* **Tiếp cận vật rơi**: Hàm `is_reachable` chỉ kiểm tra tầm vươn hình học của cánh tay robot chứ chưa lọc bỏ các vật thể đã rơi ra khỏi khu vực làm việc (ranh giới bàn và khay). +* **Gắp vào không khí**: Điểm gắp (TCP) của quả chuối mặc định được tính ở đỉnh cao nhất của hộp bao AABB (`aabb_max[2]`). Vì đầu kẹp của robot Panda (`panda_grasptarget`) nằm ở đầu mút của ngón tay, khi đặt TCP tại đỉnh cao nhất, 2 ngón tay kẹp cơ học sẽ nằm hoàn toàn trên không khí và trượt qua nhau khi đóng lại. + +### 3. Giải pháp (Fix) +* **Triệt tiêu rung lắc**: Bổ sung hàm `isolate_gripper_collisions` trong `robot_controller.py` để tạm thời tắt va chạm giữa 2 ngón tay kẹp và vật thể đang giữ ngay sau khi hoàn tất ghi log kiểm chứng tiếp xúc. Va chạm sẽ tự động được khôi phục khi nhả kẹp trong hàm `place`. +* **Lọc vật thể rơi**: Cập nhật hàm `reachability_fn` trong `main.py` để lập tức trả về `False` nếu vật thể nằm ở vị trí ngoài bàn (`"elsewhere"`). +* **Tránh gắp vào không khí**: Cập nhật hằng số độ sâu gắp `_DEPTH_FROM_TOP` trong `grasp_planner.py` ([grasp_planner.py](file:///media/minhnht31/data/vinuni/C2-App-151/llm_panda/grasp_planner.py#L61-L67)) để hạ thấp điểm đặt đầu kẹp xuống dưới đỉnh AABB đối với tất cả các lớp vật thể (chips: 6cm, can: 5cm, banana: 3cm). Điều này giúp 2 ngón tay kẹp đi xuống ôm trọn thân vật thể và tiếp xúc trực tiếp. +* **Cấu hình OpenRouter**: Cập nhật `.env` để chuyển đổi API key, base URL sang OpenRouter nhằm sử dụng mô hình miễn phí `google/gemma-4-31b-it:free`. + +### 4. Kiểm chứng (Verification) +* Quan sát cánh tay robot đứng im hoàn toàn ổn định sau khi gắp giữ vật thể lơ lửng, không còn rung lắc. +* Khi gạt thử vật thể rơi xuống đất, scene state lập tức báo `reachable: false`. +* Khi gắp quả chuối, 2 ngón tay kẹp kẹp trúng thân quả chuối, log kiểm chứng báo kích thước kẹp thực tế lớn hơn `0.0 mm` và các điểm tiếp xúc `contacts = [True, True]`. diff --git a/__pycache__/main.cpython-310.pyc b/__pycache__/main.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..922fc1bdfe1ef528f94f69855cb7fe723abf2f15 Binary files /dev/null and b/__pycache__/main.cpython-310.pyc differ diff --git a/debug_log.txt b/debug_log.txt new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/docs/CLOSED_LOOP_AND_GLOBAL_COSTMAP.md b/docs/CLOSED_LOOP_AND_GLOBAL_COSTMAP.md new file mode 100644 index 0000000000000000000000000000000000000000..84ec2063ec190eb961c00ba1b4dd7b4497ea5c8a --- /dev/null +++ b/docs/CLOSED_LOOP_AND_GLOBAL_COSTMAP.md @@ -0,0 +1,405 @@ +# Closed-Loop Control & Global Cost Map + +> Tài liệu giải thích chi tiết hai phần nâng cấp lớn của hệ thống LLM-Panda, dành +> cho người đọc sau hiểu **đã làm gì, tại sao, và ở đâu trong code**. +> +> 1. **Global / Layered / Height-Aware Cost Map** — quy hoạch đường đi 2D né +> vật cản theo chiều cao. +> 2. **Closed-Loop Control (Perceive → Plan → Monitor → Re-plan)** — vòng điều +> khiển khép kín dùng LLM làm bộ não chiến lược. + +--- + +## 0. Bức tranh tổng thể + +Hệ thống điều khiển cánh tay Franka Panda trong PyBullet theo kiến trúc 3 thành phần: + +| Thành phần | Vai trò | File chính | +|---|---|---| +| **1. State Parser** | Quét thế giới PyBullet → mô tả môi trường dạng JSON text | `llm_panda/scene_manager.py` | +| **2. Decomposition (LLM)** | Nhận state + câu lệnh người dùng → sinh chuỗi hàm JSON (Chain-of-Thought) | `llm_panda/llm_agent.py` | +| **3. Monitoring loop** | Chạy từng hàm, kiểm tra kết quả thực tế, lỗi thì khôi phục + bắt LLM sinh lại | `main.py` (`run_command`) | + +Luồng một câu lệnh: + +``` +User: "gắp lon soup bỏ vào khay" + │ + ▼ +[1] State Parser ──► JSON: {objects:[...], carried_object:null, tray:{...}} + │ + ▼ +[2] LLM Decompose ──► [ {pick_up soup_can}, {move_to tray}, {place_down} ] + │ + ▼ +[3] Monitor loop: + for step in plan: + execute(step) + ok, reason = verify(step) # vật có ở đúng vị trí kỳ vọng? + if not ok: + recover_to_safe_state() # quay về trạng thái tốt nhất + break ──► quay lại [1] lấy state mới, [2] sinh plan mới +``` + +Hai phần dưới đây mô tả chi tiết phần **mới được xây dựng / nâng cấp**. + +--- + +## 1. Global / Layered / Height-Aware Cost Map + +**File:** `llm_panda/cost_map.py` · cấu hình ở `llm_panda/config.py` · test ở +`tests/test_cost_map.py`. + +### 1.1. Vấn đề của thiết kế cũ + +Bản cũ dựng cost map **trên từng mặt phẳng riêng lẻ** (table *hoặc* tray) và coi +**mọi vật thể là tường chắn** bất kể chiều cao. Hệ quả: + +* **Start-point snapping:** khi di chuyển sang khay, điểm xuất phát (TCP) đang ở + *trên bàn* — nằm ngoài biên của lưới khay — nên `world_to_cell` **kẹp (clamp)** + điểm xuất phát vào mép khay. Đường đi bắt đầu sai vị trí. +* **Không phân biệt chiều cao:** một quả chuối nằm bẹp (~3 cm) cũng tạo tường + chắn như một lon cao 14 cm, buộc cánh tay đi vòng một cách không cần thiết + thay vì *bay qua bên trên*. + +### 1.2. Giải pháp — 3 ý tưởng + +#### (a) Global Map — sửa start-point snapping + +Cost map giờ trải trên **toàn bộ vùng làm việc** = hợp của bàn + khay, nới thêm +một biên `WORKSPACE_MARGIN`. Vì điểm xuất phát của tay luôn nằm *bên trong* lưới +toàn cục nên **không còn bị kẹp vào mép mặt phẳng** — đường đi bắt đầu đúng chỗ +TCP đang đứng. + +```python +# cost_map.py +def workspace_bounds(): + """Hợp footprint của bàn và khay, nới thêm WORKSPACE_MARGIN.""" + tx0, tx1, ty0, ty1 = surface_bounds("table") + rx0, rx1, ry0, ry1 = surface_bounds("tray") + m = config.WORKSPACE_MARGIN + return (min(tx0, rx0) - m, max(tx1, rx1) + m, + min(ty0, ry0) - m, max(ty1, ry1) + m) +``` + +#### (b) Layered Architecture — tách Hình học (Elevation) khỏi Logic (Cost) + +`CostMap` giữ **hai mảng** trên cùng một lưới: + +* `elevation[j, i]` — **lớp vật lý**: độ cao Z (world) của vật cao nhất phủ ô đó. + Là hình học thuần: *mọi* vật, footprint *thật* (không nở/inflation). +* `cost[j, i]` — **lớp quy hoạch**, *suy ra* từ elevation. Chỉ những vật **quá + cao không bay qua được** mới trở thành tường (`COSTMAP_OBSTACLE_COST`), có nở + thêm `COSTMAP_INFLATION` để chừa khoảng an toàn. + +Tách lớp như vậy giữ cho A* "sạch về toán học": A* **chỉ đọc lớp `cost`**, không +bao giờ trộn lẫn chiều cao vật lý vào hàm chi phí. + +#### (c) Height-Aware — bay qua vật thấp, đi vòng vật cao + +Ngưỡng quyết định một vật là "tường" hay "bay qua được": + +```python +# cost_map.py +def fly_over_clearance_z(carried_height=0.0): + """Cao độ Z mà ĐÁY vật đang cầm vượt qua khi nâng ở mức cơ bản. + Vật cản có đỉnh ≤ ngưỡng này thì bay qua được; cao hơn thì phải đi vòng.""" + ceiling = config.TABLE_TOP_Z + config.LIFT_HEIGHT + return ceiling - carried_height - config.TRAVEL_CLEARANCE +``` + +Logic này **đồng bộ với tầng quỹ đạo** (`RobotController.plan_u_path`): tay luôn +nâng lên tối thiểu `TABLE_TOP_Z + LIFT_HEIGHT`, nên đáy vật đang cầm ở +`ceiling - carried_height`; vật cản "lọt" nếu đỉnh của nó còn thấp hơn mức đó +một khoảng `TRAVEL_CLEARANCE`. + +→ Ngưỡng **co giãn theo vật đang cầm**: cầm vật càng cao thì mặt phẳng bay càng +thấp, càng nhiều vật trở thành tường. Ví dụ điển hình: **chuối** (thấp) → bay qua; +**lon chips** (cao) → tường, phải đi vòng. + +### 1.3. Dựng map (`CostMap.from_scene`) + +```python +elevation = np.full((n, n), config.TABLE_TOP_Z) # mặc định = mặt bàn +cost = np.zeros((n, n)) +for oid in scene.object_ids: + poly = scene.footprint_polygon(oid) # hull thật của mesh + top_z = scene.get_aabb(oid)[1][2] # đỉnh AABB + + # Lớp vật lý: footprint thật, lấy max độ cao (không inflation) + rasterize_footprint(patch, ..., poly, 0.0, top_z) + np.maximum(elevation, patch, out=elevation) + + # Lớp quy hoạch: chỉ vật quá cao mới thành tường (có inflation) + if top_z > clearance_z: + rasterize_footprint(cost, ..., poly, inflation, config.COSTMAP_OBSTACLE_COST) +``` + +### 1.4. A* và hiệu năng (real-time) + +`astar()` chạy 8-connected trên lưới toàn cục (mặc định 100×100). Hai tối ưu để +giữ thời gian trong **vài mili-giây**: + +1. **Hoist lưới ra list Python** một lần ở đầu hàm: + ```python + cost_rows = costmap.cost.tolist() + free = [[c < obstacle for c in row] for row in cost_rows] + ``` + Truy cập `list[j][i]` nhanh hơn ~10× so với indexing scalar của numpy hoặc + gọi method `is_free()` trong vòng lặp nóng. +2. **Greedy weight nhẹ** trên heuristic (`COSTMAP_ASTAR_WEIGHT = 1.2`) để bớt số + ô phải mở rộng ở vùng trống — đường đi gần như không đổi. + +Đo thực tế: trường hợp xấu (đi vòng chéo cả bàn) ~6–7 ms; trường hợp điển hình +(bàn → khay) ~6 ms cho cả `from_scene` + A*. Cánh tay chuyển động mất hàng giây, +nên đây là thừa real-time. + +### 1.5. Tham số config liên quan + +```python +# config.py +COSTMAP_GRID_N = 100 # lưới NxN phủ toàn vùng làm việc +COSTMAP_OBSTACLE_COST = 100.0 +WORKSPACE_MARGIN = 0.06 # nới biên vùng làm việc (m) +COSTMAP_INFLATION = 0.045 # bán kính nở footprint vật cản (m) +COSTMAP_ASTAR_WEIGHT = 1.2 # trọng số greedy của heuristic A* +``` + +### 1.6. Tích hợp & tương thích + +* `main.py` (`_move_to`) gọi `plan_path(..., carried_height=carried_height)` để + ngưỡng tường phản ánh đúng vật đang cầm. +* `plan_path(scene, surface=None, ...)` vẫn nhận tham số `surface` cho tương + thích/log, nhưng **map đã là toàn cục** nên `surface` không còn giới hạn vùng. +* `surface_bounds()` được giữ lại (dùng để phân loại vị trí / test). + +> ⚠️ **Điểm cần lưu ý cho người sau:** ngưỡng bay-qua giả định mức nâng cơ bản +> `TABLE_TOP_Z + LIFT_HEIGHT` luôn với tới được. `RobotController._travel_ceiling` +> có thể *hạ trần* thấp hơn khi gần giới hạn tầm với. Trong tình huống hiếm đó, +> một vật bị coi là "bay qua được" có thể không được chừa đủ khoảng cách như giả +> định. Đây là *điểm bảo thủ* (conservative gap), không phải nguy cơ va chạm, vì +> tầng quỹ đạo tự tính lại trần thực tế. Nếu cần chính xác hơn, hãy ghép +> `clearance_z` với trần do robot thật tính ra. + +--- + +## 2. Closed-Loop Control (Perceive → Plan → Monitor → Re-plan) + +**File:** `main.py` (`PandaSimulation.run_command` và các helper) · +`llm_panda/robot_controller.py` (cờ kẹt khớp) · test ở `tests/test_monitor.py`. + +### 2.1. Vấn đề của vòng cũ + +Bản cũ chỉ **chạy plan một lần, tuần tự**, kèm cảnh báo "knock" (vật bị va) và +log. Nhưng: + +* Lỗi **kẹt khớp** (`[IK-STUCK]`) trong `move_to_pose` chỉ được *log rồi `break`* + — **không lan lên** `run_command`, nên vòng vẫn chạy tiếp các bước sau một + cách mù quáng. +* **Không kiểm tra kết quả kỳ vọng** sau mỗi hàm (vật có thật sự đến khay không?). +* **Không có khả năng sinh lại plan** khi thất bại. +* Không có cơ chế **"quay về trạng thái tốt nhất"** khi kẹt giữa không trung. + +### 2.2. Lan truyền lỗi — cờ kẹt khớp ở controller + +`robot_controller.py` thêm một cờ **sticky** `_stuck`: + +```python +def reset_stuck(self): self._stuck = False # gọi trước mỗi action +def is_stuck(self): return self._stuck # đọc sau mỗi action +``` + +`move_to_pose` set `self._stuck = True` ngay tại nhánh phát hiện waypoint không +với tới (sai số EE > `_WAYPOINT_STUCK_TOL`). "Sticky" nghĩa là: nếu **bất kỳ** +sub-move nào trong một action bị kẹt thì cờ vẫn bật cho tới khi executor chủ động +`reset_stuck()` — không bị che bởi một sub-move thành công sau đó. + +### 2.3. Vòng giám sát + sinh lại plan (`run_command`) + +```python +for attempt in range(self.MAX_REPLANS + 1): # MAX_REPLANS = 2 + scene_state = parse_state() # [1] State Parser + plan = self.agent.plan(nl_command, state_text) # [2] LLM Decompose (CoT) + + sig = self._plan_signature(plan) + if attempt > 0 and sig == last_failed_sig: + # plan mới TRÙNG plan vừa fail → không có thông tin mới → dừng + return plan + + result = self._execute_plan(plan, ...) # [3] chạy + giám sát + if result["ok"]: + return plan # thành công + + last_failed_sig = sig + if attempt < self.MAX_REPLANS: + self._recover_to_safe_state() # quay về trạng thái tốt nhất + # → vòng lặp tiếp: lấy state MỚI, bắt LLM sinh plan MỚI +``` + +Hai chốt chặn vòng lặp vô hạn (quan trọng vì `RuleBasedPlanner` là tất định): + +* **Số lần giới hạn:** `MAX_REPLANS = 2` (tổng tối đa 3 lượt). +* **Chốt "không tiến triển":** nếu plan sinh lại giống hệt plan vừa thất bại + (so bằng `_plan_signature` = JSON sorted) thì dừng ngay, vì retry vô nghĩa. + +### 2.4. Chạy từng bước + kiểm tra (`_execute_plan`) + +```python +expected_location = None +for i, step in enumerate(plan): + held_before = self._carried + self.controller.reset_stuck() # bật detector kẹt cho action này + self._execute(step) # gọi pick_up / move_to / place_down + ... knock-detection + log trạng thái sau action (giữ nguyên bản cũ) ... + + ok, reason = self._verify_step(step, held_before, expected_location) + if step["function"] == "move_to": + expected_location = step["args"].get("location_id") # cho place_down kế tiếp + if not ok: + return {"ok": False, "failed_index": i, "step": step, "reason": reason} +return {"ok": True} +``` + +### 2.5. Tiêu chí "đúng vị trí kỳ vọng" (`_verify_step`) + +Trả về `(ok, reason)`. **Kẹt khớp luôn là lỗi**; ngoài ra mỗi loại hàm có tiêu +chí riêng: + +| Hàm | Điều kiện thành công | +|---|---| +| *(mọi hàm)* | `controller.is_stuck()` là `False` | +| `pick_up(obj)` | `self._carried == id(obj)` **và** vật đã được nhấc (`z > TABLE_TOP_Z + 0.05`) | +| `move_to(loc)` | đang cầm vật **và** TCP dừng cách XID đích < `_MOVE_XY_TOL` (0.12 m) | +| `place_down` | gripper đã rỗng, vật **không rơi** (`z ≥ _PLACE_FALL_Z`), và vật nằm đúng mặt phẳng `expected_location` | + +### 2.6. "Quay về trạng thái tốt nhất" (`_recover_to_safe_state`) + +```python +safe_z = config.TABLE_TOP_Z + config.LIFT_HEIGHT +self.controller.reset_stuck() +self.controller.move_to_pose([tcp_x, tcp_y, safe_z]) # 1) nâng thẳng lên +self.controller.move_to_pose([TABLE_CENTER_x, 0.0, safe_z]) # 2) bay về home +if self.controller.is_stuck(): + # phương án cuối: teleport về rest pose, KHÔNG mở gripper nếu đang cầm vật + self.controller.recover_to_rest(open_gripper=self._carried is None) +``` + +Quan trọng: nếu đang cầm vật mà phải teleport, **không mở gripper** để khỏi làm +rơi vật — tay nhảy về cấu hình known-good rồi LLM sinh plan mới từ state mới. + +### 2.7. Helper trên controller + +`recover_to_rest(open_gripper=False)` — teleport khớp tay về `ARM_REST_POSE`, +chỉ mở gripper khi được yêu cầu, settle 30 bước, rồi xóa cờ kẹt. + +### 2.8. Một sự thật cần biết về `place()` + +`RobotController.place()` có cơ chế **"snap"**: nếu IK lệch nhẹ khỏi XY đích, nó +*dịch* vật về đúng tọa độ đích khi nhả. Vì vậy `place_down` gần như luôn đặt vật +đúng chỗ → kiểm tra "vật ở đúng vị trí" sau `place_down` **hiếm khi fail**. + +→ Tín hiệu lỗi mà vòng giám sát bắt được trên thực tế chủ yếu là **grasp thất +bại** và **kẹt khớp** — đúng các tình huống mục tiêu đề ra. Nếu muốn giám sát đặt +vật nghiêm ngặt hơn, cần **bỏ/giới hạn cơ chế snap** trong `place()`. + +--- + +## 2bis. Xử lý vật cản theo đồ thị phụ thuộc + phá deadlock bằng push + +**File:** `llm_panda/llm_agent.py` (`_inject_obstacle_clearing` và helper) · +push primitive ở `main.py` (`_push`) · test ở `tests/test_obstacle_graph.py`. + +### Vấn đề +Bản cũ chỉ dọn **một tầng** vật cản trực tiếp và **không phát hiện chu trình**. +Khi `blocking_objects` tạo vòng (vd **chuối chặn lê, lê chặn chuối**), nó vẫn phát +`pick_up(blocker)` cho một vật mà bản thân vật đó đang bị chặn → **va chạm vật +lý** + **vòng re-plan lặp vô hạn** (mỗi lần replan lại ra cùng plan hỏng). + +### Thuật toán mới (đồ thị có hướng + DFS) +1. **`_build_block_graph`** — dựng đồ thị có hướng `A -> [B]` nghĩa là "B chặn lối + gắp A" (từ `blocking_objects`). +2. **`_clearing_order`** — DFS tô màu trắng/xám/đen từ `target`: + * cạnh lùi về node đang "xám" (đang trong ngăn xếp) ⇒ **phát hiện chu trình**, + gom các node trên vòng vào `cycle`; + * trả về `order` = hậu thứ tự (post-order) các vật cản bắc cầu — **sâu nhất + dọn trước** (dọn từ ngoài vào trong), đảm bảo mỗi vật được giải phóng lối + tiếp cận trước khi tới lượt nó. +3. **Không có chu trình** → sinh chuỗi `pick_up(B) → move_to(table) → + place_down` cho từng vật trong `order`, rồi mới `pick_up(target)`. +4. **Có chu trình (deadlock)** → **giữ chiến lược "gắp vật cản đặt chỗ khác"** + (sạch hơn đẩy): `_choose_cycle_breaker` chọn một vật cản trên vòng (không phải + target) và phát `pick_up(B) → move_to(buffer, avoid=[...]) → place_down`. Vật + B đang bị chặn từ trên nên tầng điều khiển **gắp ngang** nó ra; đặt vào một + **điểm đệm (buffer)** xa các vật còn lại của vòng → phá khoá hình học → rồi + `pick_up(target)` bằng gắp top-down bình thường. **Không còn `push`.** + +### Multi-Angle Approach — gắp ngang (`grasp_planner.compute_side_grasp_pose` + +`robot_controller.pick_side`, kích hoạt bởi `scene_manager.grasp_obstruction_dir`) +* **Nhận thức:** `grasp_obstruction_dir(obj)` trả hướng "thoáng" (đơn vị xy chỉ ra + xa vật cản gần nhất) nếu có vật nằm trong `SIDE_GRASP_TRIGGER_RADIUS` (0.10m) → + top-down bị chặn; ngược lại trả `None` → gắp top-down. +* **Điều khiển:** khi bị chặn, gắp **nghiêng `SIDE_GRASP_TILT` (45°)** đưa tay vào + chéo từ phía thoáng (nếu ngang 90° thì cẳng tay đập mặt bàn — đã đo thực + nghiệm; 45° vừa luồn qua vật chặn vừa tránh bàn), kẹp ở giữa thân vật rồi nhấc + thẳng lên. + +### Buffer Allocation — điểm đặt tạm (`scene_manager.find_buffer_spot`) +Tầng chiến lược tính trước một tọa độ (X,Y): **trống** (qua occupancy optimiser), +**trong tầm với** (`reachable_fn`), và **cách các vật cần tránh ≥ +`BUFFER_MIN_CLEARANCE` (0.16m)** (> `OBSTACLE_RADIUS` nên dời tới đó là hết chặn); +ưu tiên spot gần tâm bàn (tầm với tốt). Executor lấy qua `move_to(location_id= +"buffer", avoid=[...])` trong `_resolve_target`. + +### Kiểm chứng thực tế +Đặt chuối⇄lê cách **0.082m** (cùng chặn nhau, < ngưỡng 0.10 nên top-down thật sự +bị chặn) → `[DEADLOCK] cycle ['banana','pear']` → **gắp ngang** `pear` (perception +trả `clear_dir=[0,1]`) → đặt vào **buffer** xa chuối → gắp chuối top-down bỏ khay +**thành công**; pear nằm gọn trên bàn (dọn sạch), không kẹt, không lặp vô hạn. + +## 3. Cách kiểm chứng + +```bash +# Toàn bộ unit/integration test +python -m pytest tests/test_cost_map.py tests/test_occupancy.py \ + tests/test_pipeline.py tests/test_monitor.py -q +# → 54 passed + +# Chạy thử một câu lệnh đầu-cuối (headless) +python -c " +from main import PandaSimulation +sim = PandaSimulation(gui=False, seed=3) +sim.run_command('gắp lon soup bỏ vào khay', verbose=False) +sim.disconnect() +" +``` + +### Bộ test mới + +* `tests/test_cost_map.py` — global bounds, hai lớp elevation/cost, vật thấp được + bay qua vs vật cao thành tường, ngưỡng co giãn theo `carried_height`, start + không bị kẹp vào mép khay, A* né tường. +* `tests/test_monitor.py` (6 test): + * dừng khi replan lặp lại plan đã fail; + * replan + recover đúng `MAX_REPLANS` lần rồi bỏ cuộc; + * không recover/replan khi thành công; + * `_verify_step` bắt được grasp fail và kẹt khớp; + * recovery nâng tay về độ cao an toàn và xóa cờ kẹt. + +--- + +## 4. Bản đồ file → thay đổi + +| File | Thay đổi | +|---|---| +| `llm_panda/cost_map.py` | Viết lại: global map, lớp elevation+cost, height-aware, A* tối ưu | +| `llm_panda/config.py` | Thêm `WORKSPACE_MARGIN`, `COSTMAP_ASTAR_WEIGHT`; cập nhật chú thích | +| `llm_panda/robot_controller.py` | Cờ `_stuck` + `reset_stuck`/`is_stuck`; set khi IK-stuck; `recover_to_rest()` | +| `llm_panda/llm_agent.py` | `_inject_obstacle_clearing` dùng đồ thị + DFS phát hiện chu trình; `_build_block_graph`/`_clearing_order`/`_choose_cycle_breaker`; deadlock → relocate vật cản vào `buffer` (không còn `push`) | +| `llm_panda/grasp_planner.py` | `compute_side_grasp_pose` — gắp ngang nghiêng 45° từ phía thoáng | +| `llm_panda/robot_controller.py` | Cờ `_stuck`/`recover_to_rest` (vòng khép kín) + `pick_side` (thực thi gắp ngang) | +| `llm_panda/scene_manager.py` | `grasp_obstruction_dir` (nhận thức bị chặn top-down) + `find_buffer_spot` (cấp phát điểm đặt tạm) | +| `main.py` | Vòng khép kín; `_pick_up` chọn top-down/side grasp; `_resolve_target` xử lý `location_id="buffer"` | +| `tests/test_cost_map.py` | Viết lại cho thiết kế global/layered/height-aware | +| `tests/test_monitor.py` | Mới — test vòng giám sát + sinh lại plan | +| `tests/test_obstacle_graph.py` | Mới — đồ thị phụ thuộc, phát hiện chu trình, deadlock → relocate buffer | +| `tests/test_multi_angle.py` | Mới — nhận thức bị chặn, gắp ngang, cấp phát buffer | diff --git a/docs/architecture-diagrams.md b/docs/architecture-diagrams.md new file mode 100644 index 0000000000000000000000000000000000000000..c5780a1eacf47d1931fd1a8f9e4ca55696ebeda3 --- /dev/null +++ b/docs/architecture-diagrams.md @@ -0,0 +1,367 @@ +# LLM-Panda Architecture Diagrams + +Tài liệu này mô tả kiến trúc hiện tại của repo dựa trên code trong `main.py`, `llm_panda/` và `frontend/`. + +Ghi chú về schema hành động: planner hiện phát ra schema chính `pick_up`, `move_to`, `place_down`. Executor trong `main.py` vẫn hỗ trợ thêm `place_at` như API tương thích cũ. + +## 1. System Context + +```mermaid +flowchart LR + User["User
    Natural-language command
    Camera / reset / GUI controls"] + + subgraph App["LLM-Panda Application"] + UI["UI / Entrypoints
    CLI, Tkinter, PySide6, Web"] + Core["Core Simulation + Executor
    PandaSimulation"] + Planner["Planning Layer
    LLMAgent"] + Safety["PlanVerifier
    structural checks"] + Physics["PyBullet World
    robot, table, tray, YCB objects"] + end + + RemoteLLM["OpenAI-compatible LLM API
    optional"] + YCB["pybullet_object_models
    YCB URDF assets"] + Env[".env / environment
    OPENAI_API_KEY, LLM_API_KEY, model/base URL"] + + User <--> UI + UI <--> Core + Core <--> Planner + UI --> Safety + Planner -. "optional remote planner" .-> RemoteLLM + RemoteLLM -. "API key / model config" .-> Env + Core <--> Physics + Physics --> YCB +``` + +## 2. Core Component Architecture + +```mermaid +flowchart TB + subgraph Core["Core: main.py / llm_panda"] + Panda["PandaSimulation
    builds world, spawns robot/objects,
    runs NL commands and action steps"] + + Scene["SceneManager
    registered object metadata
    pose/AABB queries
    symbolic slots/tray state
    occupancy grid"] + Agent["LLMAgent
    planner wrapper + action schema filtering"] + Rule["RuleBasedPlanner
    offline EN/VI keyword planner
    obstacle clearing"] + Remote["RemoteLLMPlanner
    OpenAI-compatible JSON plan"] + Verifier["PlanVerifier
    unknown refs, reachability,
    double-pick, move/place without held object"] + Grasp["GraspPlanner
    AABB top-down grasp pose
    class-specific depth"] + Robot["RobotController
    IK, reachability,
    collision isolation,
    pick/place trajectories"] + Gripper["GripperController
    finger motors, force model,
    fixed grasp constraint"] + Config["config.py
    geometry, slots, tray,
    joint indices, forces, timing"] + DB["data/grasp_database.json
    legacy/local grasp DB"] + Log["logger.py
    console + timestamped test_log file"] + end + + PyBullet["PyBullet API
    physics, IK, rendering, bodies"] + OpenAI["OpenAI-compatible API"] + + Panda --> Scene + Panda --> Agent + Panda --> Grasp + Panda --> Robot + Panda --> Gripper + Panda --> Config + Panda --> PyBullet + + Agent --> Rule + Agent --> Remote + Agent --> Verifier + Remote -. "chat.completions.create" .-> OpenAI + + Scene --> Config + Scene --> PyBullet + Grasp --> Config + Grasp --> DB + Grasp --> PyBullet + Robot --> Config + Robot --> Gripper + Robot --> PyBullet + Gripper --> Config + Gripper --> PyBullet + Log --> Panda +``` + +## 3. Core Command Data Flow + +```mermaid +flowchart LR + NL["Natural-language command"] + Snapshot["Scene snapshot
    SceneManager.get_scene_state()"] + StateJSON["JSON scene state
    objects, locations, reachability,
    free/occupied slots, occupancy, carried_object"] + Plan["Plan array
    pick_up / move_to / place_down"] + Filtered["Schema-filtered plan
    LLMAgent._valid"] + Warnings["Plan warnings
    PlanVerifier.check"] + Execute["PandaSimulation._execute()"] + Primitive["Action primitive
    _pick_up / _move_to / _place_down / _place_at"] + Motion["Robot motion
    IK + PyBullet stepping"] + Final["Updated world state
    SceneManager.describe() / score"] + + NL --> Snapshot + Snapshot --> StateJSON + StateJSON --> Plan + Plan --> Filtered + Filtered --> Warnings + Warnings --> Execute + Execute --> Primitive + Primitive --> Motion + Motion --> Final + Final -. "next command reads fresh state" .-> Snapshot +``` + +## 4. Pick-and-Place Sequence + +```mermaid +sequenceDiagram + actor U as User + participant UI as UI / CLI + participant Sim as PandaSimulation + participant Scene as SceneManager + participant Agent as LLMAgent + participant PV as PlanVerifier + participant GP as GraspPlanner + participant RC as RobotController + participant GC as GripperController + participant PB as PyBullet + + U->>UI: Submit command + UI->>Sim: run_command(command) + Sim->>Scene: get_scene_state(reachability_fn, carried_object) + Scene->>PB: getBasePositionAndOrientation / getAABB + Scene-->>Sim: structured scene state + Sim->>Agent: plan(command, state_json) + Agent->>PV: check(plan, state) + PV-->>Agent: warnings + Agent-->>Sim: valid action steps + + loop each step + alt pick_up(object_id) + Sim->>GP: compute_grasp_pose(object_id, class) + GP->>PB: getAABB(object_id) + GP-->>Sim: grasp_pos, grasp_ori + Sim->>RC: pick(object_id, grasp_pos, grasp_ori) + RC->>PB: isolate arm/object collisions + RC->>RC: move to safe pre-grasp + RC->>PB: calculateInverseKinematics + stepSimulation + RC->>GC: grasp(object_id) + GC->>PB: getDynamicsInfo + createConstraint + RC->>RC: lift held object + RC-->>Sim: force, held + else move_to(location_id) + Sim->>Scene: footprint + occupancy grid + Scene->>PB: getAABB for registered objects + Sim->>RC: move_to_pose(above target) + RC->>PB: IK + stepSimulation + Sim->>Sim: remember pending target position + else place_down() + Sim->>RC: place(pending target) + RC->>PB: safe travel, lower, release, snap Z/XY if needed + RC->>GC: open() + GC->>PB: removeConstraint + open fingers + RC->>PB: restore collisions + Sim->>Sim: clear carried/pending state + end + end + + Sim->>Scene: describe() + Scene-->>UI: final state/logs +``` + +## 5. Planner and Validation Flow + +```mermaid +flowchart TB + Command["User command"] + SceneState["Scene state JSON"] + Agent["LLMAgent.plan()"] + + subgraph Planners["Planner implementations"] + Rule["RuleBasedPlanner
    keyword/object/location matching
    nearby obstacle clearing
    retry last plan"] + Remote["RemoteLLMPlanner
    system prompt + scene + instruction
    JSON extraction"] + end + + RawPlan["Raw action plan"] + Verify["PlanVerifier.check()"] + Warnings["Warnings logged
    execution may still continue"] + Valid["Action schema filter
    allowed: pick_up, move_to, place_down"] + Executor["PandaSimulation executor"] + + Command --> Agent + SceneState --> Agent + Agent --> Rule + Agent --> Remote + Rule --> RawPlan + Remote --> RawPlan + RawPlan --> Verify + Verify --> Warnings + RawPlan --> Valid + Valid --> Executor +``` + +## 6. Scene State Data Model + +```mermaid +flowchart TB + SceneState["SceneState
    objects: ObjectState[]
    slots: string[]
    reachable_slots: string[]
    occupied_slots: string[]
    free_slots: string[]
    carried_object: string or null"] + ObjectState["ObjectState
    name: string
    class: string
    location: Slot_N / tray / elsewhere
    position: float[3]
    reachable: bool optional
    neighbor_count: int optional"] + Occupancy["OccupancySummary
    table_area_m2: float
    occupied_area_m2: float
    free_area_m2: float
    occupancy_ratio: float"] + Tray["TrayState
    empty: bool
    occupants: string[]"] + + SceneState --> ObjectState + SceneState --> Occupancy + SceneState --> Tray +``` + +## 7. Action Plan Schema + +```mermaid +flowchart TB + PlanStep["PlanStep
    function: string
    args: object"] + PickUp["pick_up args
    object_id: banana / soup_can / chips_can / ..."] + MoveTo["move_to args
    location_id: Slot_1..Slot_6 / tray"] + PlaceDown["place_down args
    no required fields"] + PlaceAt["legacy place_at args
    location_id: Slot_1..Slot_6 / tray
    supported by executor"] + + PlanStep --> PickUp + PlanStep --> MoveTo + PlanStep --> PlaceDown + PlanStep -.-> PlaceAt +``` + +## 8. Web Runtime and WebSocket Contract + +```mermaid +flowchart TB + Browser["Browser
    index.html + app.js"] + Canvas["Canvas viewport
    draws JPEG frames"] + Controls["Chat, presets, reset,
    mock toggle, GUI toggle,
    camera controls"] + FastAPI["FastAPI app
    GET /, static files, WS /ws"] + WS["WebSocket /ws
    JSON messages + binary JPEG"] + Lock["executor_lock + pybullet_lock"] + Sim["current_sim: PandaSimulation"] + Agent["LLMAgent
    RuleBasedPlanner or RemoteLLMPlanner"] + Verifier["PlanVerifier"] + Camera["get_camera_image_bytes()
    PyBullet getCameraImage + cv2 JPEG"] + + Browser --> Canvas + Browser --> Controls + Controls -- "JSON: run/reset/camera_*" --> WS + WS --> FastAPI + FastAPI --> Lock + Lock --> Sim + Sim --> Agent + Sim --> Verifier + Sim --> Camera + Camera -- "binary JPEG ArrayBuffer" --> Canvas + FastAPI -- "JSON: log/plan/result" --> Browser +``` + +### WebSocket Message Types + +```mermaid +sequenceDiagram + participant B as Browser app.js + participant S as FastAPI /ws + participant Sim as PandaSimulation + participant PB as PyBullet + + B->>S: connect /ws?gui=true|false + S->>Sim: create or reset current_sim + S->>PB: render first camera frame + S-->>B: binary JPEG frame + + B->>S: {"type":"run","prompt": "...", "mock": true|false} + S-->>B: {"type":"log","message":"[1/5] ..."} + S->>Sim: scene_state -> plan -> validate -> execute + S-->>B: {"type":"plan","plan":[...]} + loop during movement + Sim->>PB: stepSimulation() + S->>PB: getCameraImage() + S-->>B: binary JPEG frame + end + S-->>B: {"type":"result","score_display":"...", "score_value": 0..100} + + B->>S: {"type":"reset"} + S->>Sim: reset_objects() + reset_to_home() + S-->>B: binary JPEG frame + log + + B->>S: {"type":"camera_rotate|camera_pan|camera_zoom", ...} + S->>PB: render camera_state + S-->>B: binary JPEG frame +``` + +## 9. Physical World Setup + +```mermaid +flowchart LR + Init["PandaSimulation.__init__"] + Connect["pb.connect(GUI or DIRECT)
    gravity + timestep + debug camera"] + Static["Static scene
    plane, table box, tray box"] + Robot["Robot
    franka_panda/panda.urdf
    fixed base"] + Controllers["Controllers
    GripperController + RobotController"] + Objects["YCB objects
    banana, soup_can, chips_can
    spawned on shuffled slots"] + Registry["SceneManager registry
    body id -> name/class"] + Settle["stepSimulation x120
    settle objects"] + + Init --> Connect + Connect --> Static + Static --> Robot + Robot --> Controllers + Controllers --> Objects + Objects --> Registry + Registry --> Settle +``` + +## 10. Occupancy and Collision-Avoidance Flow + +```mermaid +flowchart TB + Target["Target location
    Slot_N or tray"] + Footprint["SceneManager.get_footprint(carried_object)
    AABB width_x/width_y"] + Grid["compute_occupancy_grid()
    usable table raster, edge margin,
    optional safety margin"] + Blocked{"Target footprint overlaps
    occupied cells?"} + Named["Nearest free named slot
    reachable_slots order,
    not occupied"] + FreeSpot["find_free_placements()
    continuous free XY fallback"] + Attempt["Attempt original target
    if no alternative found"] + Redirect["Redirect target"] + Move["RobotController.place()/move_to_pose()"] + + Target --> Footprint + Footprint --> Grid + Grid --> Blocked + Blocked -- "no" --> Move + Blocked -- "yes" --> Named + Named -- "found" --> Redirect + Named -- "none" --> FreeSpot + FreeSpot -- "found" --> Redirect + FreeSpot -- "none" --> Attempt + Redirect --> Move + Attempt --> Move +``` + +## 11. Scoring Flow + +```mermaid +flowchart TB + Plan["Executed plan"] + Success["executed_successfully flag"] + Target["Extract target_object
    from pick_up"] + Location["Extract target_location
    from move_to/place_down/place_at"] + FinalPose["Read final object poses
    pb.getBasePositionAndOrientation"] + Classify["SceneManager.classify_location()"] + Placement["Placement score
    right target location or penalty"] + Knock["Knock/side-effect score
    other objects classified as elsewhere"] + Exec["Execution success score"] + Report["Markdown report
    score 0..100"] + + Plan --> Target + Plan --> Location + Target --> FinalPose + Location --> FinalPose + FinalPose --> Classify + Classify --> Placement + Classify --> Knock + Success --> Exec + Placement --> Report + Knock --> Report + Exec --> Report +``` diff --git a/dump.txt b/dump.txt new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/frontend/__pycache__/app.cpython-310.pyc b/frontend/__pycache__/app.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..987686ddf00a9910032babaeb0bd2a6a897e428a Binary files /dev/null and b/frontend/__pycache__/app.cpython-310.pyc differ diff --git a/frontend/__pycache__/interactive_server.cpython-310.pyc b/frontend/__pycache__/interactive_server.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..43133e21299d33011fb5c9446511952f0fc8ce8f Binary files /dev/null and b/frontend/__pycache__/interactive_server.cpython-310.pyc differ diff --git a/frontend/app.js b/frontend/app.js new file mode 100644 index 0000000000000000000000000000000000000000..53e3a151549eb956fbea849040e2c51448b4f89b --- /dev/null +++ b/frontend/app.js @@ -0,0 +1,1181 @@ +// ─── WebSocket and Visualizer Setup ──────────────────────────────────────── +const canvas = document.getElementById('pybullet-viewport'); +// Three.js Core Variables +let renderer, scene, camera, controls; +let robotGroup, tableMesh, trayMesh; +const slotHelpers = []; +const joints = {}; +const ycbMeshes = {}; +let transformControls = null; +let eeDummy = null; +const OBJ_LOADER = new THREE.OBJLoader(); +const MTL_LOADER = new THREE.MTLLoader(); +let socket = null; +let currentPrompt = ''; +function initVisualizer() { + // Set default coordinate system to Z-up + THREE.Object3D.DefaultUp.set(0, 0, 1); + // Renderer + renderer = new THREE.WebGLRenderer({ canvas: canvas, antialias: true }); + const width = canvas.clientWidth || window.innerWidth; + const height = canvas.clientHeight || window.innerHeight; + renderer.setSize(width, height, false); + renderer.setPixelRatio(window.devicePixelRatio); + renderer.shadowMap.enabled = true; + // Scene + scene = new THREE.Scene(); + scene.background = new THREE.Color('#f1f5f9'); // Light smoke gray background + // Camera + camera = new THREE.PerspectiveCamera(50, width / height, 0.1, 100); + // Position camera to look down at the table, matching PyBullet default view + camera.position.set(1.2, -1.2, 1.2); + // Controls + controls = new THREE.OrbitControls(camera, renderer.domElement); + controls.target.set(0.5, 0.0, 0.2); + controls.enableDamping = true; + controls.dampingFactor = 0.05; + controls.maxPolarAngle = Math.PI / 2 - 0.02; // do not go below table plane + controls.update(); + // Lights + const ambientLight = new THREE.AmbientLight(0xffffff, 0.7); + scene.add(ambientLight); + const dirLight = new THREE.DirectionalLight(0xffffff, 0.85); + dirLight.position.set(2, -2, 4); + dirLight.castShadow = true; + dirLight.shadow.mapSize.width = 1024; + dirLight.shadow.mapSize.height = 1024; + dirLight.shadow.camera.near = 0.5; + dirLight.shadow.camera.far = 15; + scene.add(dirLight); + const dirLight2 = new THREE.DirectionalLight(0xaaccff, 0.35); + dirLight2.position.set(-2, 2, 2); + scene.add(dirLight2); + // Floor plane + const planeGeo = new THREE.PlaneGeometry(10, 10); + const planeMat = new THREE.MeshStandardMaterial({ color: 0xe2e8f0, roughness: 0.85 }); + const plane = new THREE.Mesh(planeGeo, planeMat); + plane.receiveShadow = true; + scene.add(plane); + // Caro background / Grid Helper + const gridHelper = new THREE.GridHelper(10, 100, 0x94a3b8, 0xcbd5e1); + gridHelper.rotation.x = Math.PI / 2; + gridHelper.position.z = 0.001; + scene.add(gridHelper); + // Axes helper (X: Red, Y: Green, Z: Blue) + const axesHelper = new THREE.AxesHelper(0.5); + axesHelper.position.z = 0.002; + scene.add(axesHelper); + // Initialize Transform Controls + transformControls = new THREE.TransformControls(camera, renderer.domElement); + transformControls.addEventListener('dragging-changed', function (event) { + controls.enabled = !event.value; + if (!event.value && transformControls.object && transformControls.object !== eeDummy) { + const obj = transformControls.object; + if (socket && socket.readyState === WebSocket.OPEN) { + const pos = [obj.position.x, obj.position.y, obj.position.z]; + const ori = [obj.quaternion.x, obj.quaternion.y, obj.quaternion.z, obj.quaternion.w]; + socket.send(JSON.stringify({ + type: "update_object_pose", + name: obj.name, + pos: pos, + ori: ori + })); + writeLog(`Đã đặt vật thể ${obj.name} xuống vị trí mới.`, "success"); + } + } + }); + transformControls.addEventListener('change', function () { + if (transformControls.object) { + const obj = transformControls.object; + if (obj === eeDummy) { + if (socket && socket.readyState === WebSocket.OPEN) { + socket.send(JSON.stringify({ + type: "update_robot_ee", + pos: [eeDummy.position.x, eeDummy.position.y, eeDummy.position.z] + })); + } + } else { + obj.position.x = Math.max(0.15, Math.min(0.85, obj.position.x)); + obj.position.y = Math.max(-0.65, Math.min(0.65, obj.position.y)); + obj.position.z = Math.max(0.02, Math.min(0.85, obj.position.z)); + if (targetObjects[obj.name]) { + targetObjects[obj.name].pos.copy(obj.position); + } + } + } + }); + scene.add(transformControls); + // Start animation loop + animate(); +} +let targetJoints = null; +const targetObjects = {}; +let isInitialStateSynced = false; +function animate() { + requestAnimationFrame(animate); + if (controls) controls.update(); + + // Smooth interpolation (Lerp / Slerp) to eliminate visual stutter + if (targetJoints && targetJoints.length >= 11) { + if (!isInitialStateSynced) { + // First tick or after reset: snap immediately to avoid sliding from rest position + joints.joint1.rotation.z = targetJoints[0]; + joints.joint2.rotation.z = targetJoints[1]; + joints.joint3.rotation.z = targetJoints[2]; + joints.joint4.rotation.z = targetJoints[3]; + joints.joint5.rotation.z = targetJoints[4]; + joints.joint6.rotation.z = targetJoints[5]; + joints.joint7.rotation.z = targetJoints[6]; + joints.fingerJoint1.position.y = targetJoints[9]; + joints.fingerJoint2.position.y = -targetJoints[10]; + + Object.entries(targetObjects).forEach(([name, target]) => { + if (transformControls && transformControls.object && transformControls.object.name === name) return; + const group = ycbMeshes[name]; + if (group) { + group.position.copy(target.pos); + group.quaternion.copy(target.ori); + } + }); + isInitialStateSynced = true; + } else { + // Incremental interpolation towards target poses at client framerate (60+ FPS) + const lerpFactor = 0.15; // Balanced tracking speed vs smoothness + joints.joint1.rotation.z = THREE.MathUtils.lerp(joints.joint1.rotation.z, targetJoints[0], lerpFactor); + joints.joint2.rotation.z = THREE.MathUtils.lerp(joints.joint2.rotation.z, targetJoints[1], lerpFactor); + joints.joint3.rotation.z = THREE.MathUtils.lerp(joints.joint3.rotation.z, targetJoints[2], lerpFactor); + joints.joint4.rotation.z = THREE.MathUtils.lerp(joints.joint4.rotation.z, targetJoints[3], lerpFactor); + joints.joint5.rotation.z = THREE.MathUtils.lerp(joints.joint5.rotation.z, targetJoints[4], lerpFactor); + joints.joint6.rotation.z = THREE.MathUtils.lerp(joints.joint6.rotation.z, targetJoints[5], lerpFactor); + joints.joint7.rotation.z = THREE.MathUtils.lerp(joints.joint7.rotation.z, targetJoints[6], lerpFactor); + + joints.fingerJoint1.position.y = THREE.MathUtils.lerp(joints.fingerJoint1.position.y, targetJoints[9], lerpFactor); + joints.fingerJoint2.position.y = THREE.MathUtils.lerp(joints.fingerJoint2.position.y, -targetJoints[10], lerpFactor); + + Object.entries(targetObjects).forEach(([name, target]) => { + if (transformControls && transformControls.object && transformControls.object.name === name) return; + const group = ycbMeshes[name]; + if (group) { + group.position.lerp(target.pos, lerpFactor); + group.quaternion.slerp(target.ori, lerpFactor); + } + }); + } + } + // Update joint sliders to match current animation if user is not actively dragging them + const activeEl = document.activeElement; + const isEditingSliders = activeEl && activeEl.id && activeEl.id.startsWith('slider-'); + if (!isEditingSliders && targetJoints) { + const j1 = document.getElementById('slider-j1'); + if (j1) j1.value = joints.joint1.rotation.z.toFixed(2); + const v1 = document.getElementById('val-j1'); + if (v1) v1.textContent = joints.joint1.rotation.z.toFixed(2); + + const j2 = document.getElementById('slider-j2'); + if (j2) j2.value = joints.joint2.rotation.z.toFixed(2); + const v2 = document.getElementById('val-j2'); + if (v2) v2.textContent = joints.joint2.rotation.z.toFixed(2); + + const j3 = document.getElementById('slider-j3'); + if (j3) j3.value = joints.joint3.rotation.z.toFixed(2); + const v3 = document.getElementById('val-j3'); + if (v3) v3.textContent = joints.joint3.rotation.z.toFixed(2); + + const j4 = document.getElementById('slider-j4'); + if (j4) j4.value = joints.joint4.rotation.z.toFixed(2); + const v4 = document.getElementById('val-j4'); + if (v4) v4.textContent = joints.joint4.rotation.z.toFixed(2); + + const j5 = document.getElementById('slider-j5'); + if (j5) j5.value = joints.joint5.rotation.z.toFixed(2); + const v5 = document.getElementById('val-j5'); + if (v5) v5.textContent = joints.joint5.rotation.z.toFixed(2); + + const j6 = document.getElementById('slider-j6'); + if (j6) j6.value = joints.joint6.rotation.z.toFixed(2); + const v6 = document.getElementById('val-j6'); + if (v6) v6.textContent = joints.joint6.rotation.z.toFixed(2); + + const j7 = document.getElementById('slider-j7'); + if (j7) j7.value = joints.joint7.rotation.z.toFixed(2); + const v7 = document.getElementById('val-j7'); + if (v7) v7.textContent = joints.joint7.rotation.z.toFixed(2); + + const jg = document.getElementById('slider-jg'); + if (jg) jg.value = joints.fingerJoint1.position.y.toFixed(3); + const vg = document.getElementById('val-jg'); + if (vg) vg.textContent = joints.fingerJoint1.position.y.toFixed(3); + } + + // Align eeDummy position to handJoint if not being dragged + if (eeDummy && joints.handJoint && (!transformControls || !transformControls.object || transformControls.object !== eeDummy)) { + const handWorldPos = new THREE.Vector3(); + joints.handJoint.getWorldPosition(handWorldPos); + eeDummy.position.copy(handWorldPos); + } + + renderer.render(scene, camera); +} +// Window resizing +window.addEventListener('resize', () => { + const width = canvas.clientWidth; + const height = canvas.clientHeight; + if (canvas.width !== width || canvas.height !== height) { + renderer.setSize(width, height, false); + camera.aspect = width / height; + camera.updateProjectionMatrix(); + } +}); +// ─── Three.js Scene Construction ──────────────────────────────────────────── +function createTable(tableConfig) { + if (tableMesh) scene.remove(tableMesh); + const ext = tableConfig.half_extents; + const geo = new THREE.BoxGeometry(ext[0] * 2, ext[1] * 2, ext[2] * 2); + const color = new THREE.Color().fromArray(tableConfig.color.slice(0, 3)); + const mat = new THREE.MeshStandardMaterial({ color: color, roughness: 0.6, metalness: 0.1 }); + tableMesh = new THREE.Mesh(geo, mat); + tableMesh.position.set(tableConfig.center[0], tableConfig.center[1], tableConfig.center[2]); + tableMesh.castShadow = true; + tableMesh.receiveShadow = true; + scene.add(tableMesh); +} +function createTray(trayConfig) { + if (trayMesh) scene.remove(trayMesh); + const ext = trayConfig.half_extents; + const geo = new THREE.BoxGeometry(ext[0] * 2, ext[1] * 2, ext[2] * 2); + const color = new THREE.Color().fromArray(trayConfig.color.slice(0, 3)); + const mat = new THREE.MeshStandardMaterial({ color: color, roughness: 0.7 }); + trayMesh = new THREE.Mesh(geo, mat); + trayMesh.position.set(trayConfig.position[0], trayConfig.position[1], trayConfig.position[2] - ext[2]); + trayMesh.castShadow = true; + trayMesh.receiveShadow = true; + scene.add(trayMesh); +} +function createSlotHelpers(slots) { + slotHelpers.forEach(mesh => scene.remove(mesh)); + slotHelpers.length = 0; + + const geom = new THREE.RingGeometry(0.045, 0.05, 32); + const mat = new THREE.MeshBasicMaterial({ color: 0x3b82f6, side: THREE.DoubleSide, transparent: true, opacity: 0.45 }); + + Object.entries(slots).forEach(([name, pos]) => { + const ring = new THREE.Mesh(geom, mat); + ring.position.set(pos[0], pos[1], pos[2] + 0.001); // slightly above table + scene.add(ring); + slotHelpers.push(ring); + }); +} +function initRobotStructure() { + if (robotGroup) scene.remove(robotGroup); + robotGroup = new THREE.Group(); + scene.add(robotGroup); + + joints.joint1 = new THREE.Group(); + joints.joint2 = new THREE.Group(); + joints.joint3 = new THREE.Group(); + joints.joint4 = new THREE.Group(); + joints.joint5 = new THREE.Group(); + joints.joint6 = new THREE.Group(); + joints.joint7 = new THREE.Group(); + joints.joint8 = new THREE.Group(); + joints.handJoint = new THREE.Group(); + joints.fingerJoint1 = new THREE.Group(); + joints.fingerJoint2 = new THREE.Group(); + + const link0 = new THREE.Group(); + const link1 = new THREE.Group(); + const link2 = new THREE.Group(); + const link3 = new THREE.Group(); + const link4 = new THREE.Group(); + const link5 = new THREE.Group(); + const link6 = new THREE.Group(); + const link7 = new THREE.Group(); + const link8 = new THREE.Group(); + const hand = new THREE.Group(); + const leftFinger = new THREE.Group(); + const rightFinger = new THREE.Group(); + + robotGroup.add(link0); + + link0.add(joints.joint1); + joints.joint1.position.set(0, 0, 0.333); + joints.joint1.add(link1); + + link1.add(joints.joint2); + joints.joint2.position.set(0, 0, 0); + joints.joint2.rotation.set(-1.57079632679, 0, 0); + joints.joint2.add(link2); + + link2.add(joints.joint3); + joints.joint3.position.set(0, -0.316, 0); + joints.joint3.rotation.set(1.57079632679, 0, 0); + joints.joint3.add(link3); + + link3.add(joints.joint4); + joints.joint4.position.set(0.0825, 0, 0); + joints.joint4.rotation.set(1.57079632679, 0, 0); + joints.joint4.add(link4); + + link4.add(joints.joint5); + joints.joint5.position.set(-0.0825, 0.384, 0); + joints.joint5.rotation.set(-1.57079632679, 0, 0); + joints.joint5.add(link5); + + link5.add(joints.joint6); + joints.joint6.position.set(0, 0, 0); + joints.joint6.rotation.set(1.57079632679, 0, 0); + joints.joint6.add(link6); + + link6.add(joints.joint7); + joints.joint7.position.set(0.088, 0, 0); + joints.joint7.rotation.set(1.57079632679, 0, 0); + joints.joint7.add(link7); + + link7.add(joints.joint8); + joints.joint8.position.set(0, 0, 0.107); + joints.joint8.add(link8); + + link8.add(joints.handJoint); + joints.handJoint.position.set(0, 0, 0); + joints.handJoint.rotation.set(0, 0, -0.785398163397); + joints.handJoint.add(hand); + + hand.add(joints.fingerJoint1); + joints.fingerJoint1.position.set(0, 0, 0.0584); + joints.fingerJoint1.add(leftFinger); + + hand.add(joints.fingerJoint2); + joints.fingerJoint2.position.set(0, 0, 0.0584); + joints.fingerJoint2.add(rightFinger); + + const defaultPandaMaterial = new THREE.MeshStandardMaterial({ + color: 0xdddddd, + roughness: 0.35, + metalness: 0.15 + }); + const loadModel = (parent, objPath, mtlPath = null, rotateRightFinger = false) => { + const applyRotation = (obj) => { + if (rotateRightFinger) { + obj.rotation.z = Math.PI; + } + parent.add(obj); + }; + if (mtlPath) { + MTL_LOADER.load(mtlPath, (materials) => { + materials.preload(); + + const objLoader = new THREE.OBJLoader(); + objLoader.setMaterials(materials); + objLoader.load(objPath, (obj) => { + obj.traverse(child => { + if (child.isMesh) { + child.castShadow = true; + child.receiveShadow = true; + } + }); + applyRotation(obj); + }); + }); + } else { + const objLoader = new THREE.OBJLoader(); + objLoader.load(objPath, (obj) => { + obj.traverse(child => { + if (child.isMesh) { + child.material = defaultPandaMaterial; + child.castShadow = true; + child.receiveShadow = true; + } + }); + applyRotation(obj); + }); + } + }; + loadModel(link0, '/assets/panda/meshes/collision/link0.obj'); + loadModel(link1, '/assets/panda/meshes/visual/link1.obj', '/assets/panda/meshes/visual/link1.mtl'); + loadModel(link2, '/assets/panda/meshes/visual/link2.obj', '/assets/panda/meshes/visual/link2.mtl'); + loadModel(link3, '/assets/panda/meshes/visual/link3.obj', '/assets/panda/meshes/visual/link3.mtl'); + loadModel(link4, '/assets/panda/meshes/visual/link4.obj', '/assets/panda/meshes/visual/link4.mtl'); + loadModel(link5, '/assets/panda/meshes/visual/link5.obj', '/assets/panda/meshes/visual/link5.mtl'); + loadModel(link6, '/assets/panda/meshes/visual/link6.obj', '/assets/panda/meshes/visual/link6.mtl'); + loadModel(link7, '/assets/panda/meshes/collision/link7.obj'); + loadModel(hand, '/assets/panda/meshes/visual/hand.obj', '/assets/panda/meshes/visual/hand.mtl'); + loadModel(leftFinger, '/assets/panda/meshes/visual/finger.obj', '/assets/panda/meshes/visual/finger.mtl'); + loadModel(rightFinger, '/assets/panda/meshes/visual/finger.obj', '/assets/panda/meshes/visual/finger.mtl', true); + // Create eeDummy sphere representing the end-effector target + if (eeDummy) scene.remove(eeDummy); + const dummyGeo = new THREE.SphereGeometry(0.035, 16, 16); + const dummyMat = new THREE.MeshStandardMaterial({ + color: 0x3b82f6, + transparent: true, + opacity: 0.65, + roughness: 0.1, + metalness: 0.9 + }); + eeDummy = new THREE.Mesh(dummyGeo, dummyMat); + eeDummy.name = 'robot'; + eeDummy.visible = false; + scene.add(eeDummy); +} +function loadYcbObjects(objectsConfig) { + // Clear old meshes/groups from scene + Object.values(ycbMeshes).forEach(group => scene.remove(group)); + for (const key in ycbMeshes) delete ycbMeshes[key]; + + Object.entries(objectsConfig).forEach(([name, config]) => { + const folder = config.folder; + let objFile = ""; + let mtlFile = ""; + + if (folder === "YcbBanana" || folder === "YcbTomatoSoupCan" || folder === "YcbCrackerBox" || folder === "YcbMustardBottle" || folder === "YcbPottedMeatCan") { + objFile = `/assets/ycb/${folder}/textured_simple_reoriented.obj`; + mtlFile = `/assets/ycb/${folder}/textured_simple_reoriented.mtl`; + } else if (folder === "YcbChipsCan") { + objFile = `/assets/ycb/${folder}/textured.obj`; + mtlFile = `/assets/ycb/${folder}/textured.mtl`; + } else if (folder === "YcbPear") { + objFile = `/assets/ycb/${folder}/textured_reoriented.obj`; + mtlFile = `/assets/ycb/${folder}/textured_reoriented.mtl`; + } else if (folder === "YcbTennisBall") { + objFile = `/assets/ycb/${folder}/textured_reoriented.obj`; + mtlFile = `/assets/ycb/${folder}/textured_reoriented.obj.mtl`; + } + + if (!objFile) return; + // Create a parent group to represent the object's body link pose + const objectGroup = new THREE.Group(); + objectGroup.name = name; + objectGroup.position.fromArray(config.initial_pos); + objectGroup.quaternion.fromArray(config.initial_ori); + scene.add(objectGroup); + ycbMeshes[name] = objectGroup; + // 1. Load Visual Mesh + MTL_LOADER.load(mtlFile, (materials) => { + materials.preload(); + + const objLoader = new THREE.OBJLoader(); + objLoader.setMaterials(materials); + objLoader.load(objFile, (visObj) => { + visObj.traverse(child => { + if (child.isMesh) { + child.castShadow = true; + child.receiveShadow = true; + } + }); + + // Position, rotate and scale relative to parent group + if (config.vis_local_pos) visObj.position.fromArray(config.vis_local_pos); + if (config.vis_local_ori) visObj.quaternion.fromArray(config.vis_local_ori); + if (config.vis_scale) visObj.scale.fromArray(config.vis_scale); + + objectGroup.add(visObj); + }); + }); + // 2. Load Collision Mesh (Semi-transparent Blue) + const collObjFile = `/assets/ycb/${folder}/collision_vhacd.obj`; + const collLoader = new THREE.OBJLoader(); + collLoader.load(collObjFile, (collObj) => { + collObj.traverse(child => { + if (child.isMesh) { + child.material = new THREE.MeshStandardMaterial({ + color: 0x0000ff, // blue + transparent: true, + opacity: 0.5, // semi-transparent + roughness: 0.4, + metalness: 0.1 + }); + child.castShadow = true; + child.receiveShadow = true; + } + }); + + // Position, rotate and scale relative to parent group + if (config.coll_local_pos) collObj.position.fromArray(config.coll_local_pos); + if (config.coll_local_ori) collObj.quaternion.fromArray(config.coll_local_ori); + if (config.coll_scale) collObj.scale.fromArray(config.coll_scale); + + objectGroup.add(collObj); + }); + }); +} +function updateSimulationState(jointsData, objectsData) { + if (jointsData && jointsData.length >= 11) { + targetJoints = jointsData; + } + + if (objectsData) { + Object.entries(objectsData).forEach(([name, data]) => { + targetObjects[name] = { + pos: new THREE.Vector3().fromArray(data.pos), + ori: new THREE.Quaternion().fromArray(data.ori) + }; + }); + } +} +let reconnectTimeout = null; +function connectWebSocket() { + if (reconnectTimeout) { + clearTimeout(reconnectTimeout); + reconnectTimeout = null; + } + const guiToggle = document.getElementById('gui-toggle'); + const showGui = guiToggle ? guiToggle.checked : false; + const wsProtocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:'; + const wsUrl = `${wsProtocol}//${window.location.host}/ws?gui=${showGui}`; + + updateBadgeStatus('disconnected'); + + socket = new WebSocket(wsUrl); + socket.onopen = () => { + console.log("WebSocket connected."); + updateBadgeStatus('connected'); + writeLog("Kết nối thành công đến Backend server.", "success"); + }; + socket.onmessage = (event) => { + const msg = JSON.parse(event.data); + handleSocketMessage(msg); + }; + socket.onclose = () => { + console.log("WebSocket disconnected."); + updateBadgeStatus('disconnected'); + writeLog("Mất kết nối đến Backend server. Đang thử kết nối lại...", "error"); + reconnectTimeout = setTimeout(connectWebSocket, 3000); + }; + socket.onerror = (err) => { + console.error("WebSocket Error: ", err); + }; +} +function handleSocketMessage(msg) { + switch(msg.type) { + case 'init': + createTable(msg.table); + createTray(msg.tray); + createSlotHelpers(msg.slots); + loadYcbObjects(msg.objects); + initRobotStructure(); + isInitialStateSynced = false; // Reset sync state for new simulations + break; + + case 'state': + updateSimulationState(msg.joints, msg.objects); + break; + + case 'log': + writeLog(msg.message, getLogClass(msg.message)); + updatePipelineUI(msg.message); + break; + + case 'plan': + displayPlan(msg.plan); + break; + + case 'result': + showRearrangementScore(msg.score_display); + unlockInput(); + + // Add new run record to history log dynamically + const now = new Date(); + const timeStr = now.toTimeString().split(' ')[0]; + const scoreVal = msg.score_value !== undefined ? msg.score_value : 100; + const scoreClass = scoreVal >= 90 ? "high" : (scoreVal >= 60 ? "medium" : "low"); + + historyData.unshift({ + time: timeStr, + operator: "Operator", + prompt: currentPrompt || "Câu lệnh nhanh", + score: scoreVal, + class: scoreClass + }); + renderHistory(); + + // Speak speech feedback + speakFeedback(`Đã hoàn thành vận hành. Điểm rearrangement đạt ${scoreVal} điểm.`); + break; + } +} +// ─── UI Updates and Interactions ──────────────────────────────────────────── +const badge = document.getElementById('connection-badge'); +const logConsole = document.getElementById('log-console'); +const planList = document.getElementById('plan-list'); +const chatInput = document.getElementById('chat-input'); +const submitBtn = document.getElementById('submit-btn'); +const mockToggle = document.getElementById('mock-toggle'); +const guiToggle = document.getElementById('gui-toggle'); +const resetBtn = document.getElementById('reset-btn'); +const scoreModal = document.getElementById('score-modal'); +const scoreContent = document.getElementById('score-md-content'); +const closeModalBtn = document.getElementById('close-modal-btn'); +const ttsToggle = document.getElementById('tts-toggle'); +const autocompletePanel = document.getElementById('autocomplete-panel'); +// 1. Tab switching logic +document.querySelectorAll('.tab-btn').forEach(btn => { + btn.addEventListener('click', () => { + document.querySelectorAll('.tab-btn').forEach(b => b.classList.remove('active')); + document.querySelectorAll('.tab-panel').forEach(p => p.classList.remove('active')); + btn.classList.add('active'); + const tabId = btn.dataset.tab; + document.getElementById(`panel-${tabId}`).classList.add('active'); + }); +}); +// 2. Scenario template click events +document.querySelectorAll('.scenario-card').forEach(card => { + card.addEventListener('click', () => { + const prompt = card.dataset.prompt; + chatInput.value = prompt; + chatInput.focus(); + }); +}); +document.querySelectorAll('.preset-command-item').forEach(item => { + item.addEventListener('click', () => { + const prompt = item.dataset.prompt; + chatInput.value = prompt; + chatInput.focus(); + }); +}); +// 3. Object Catalog Data & Render +const activeObjects = [ + { id: "banana", name: "Quả chuối (YCB)", mass: 0.066, friction: 0.8, trait: "Safe" }, + { id: "soup_can", name: "Lon súp cà chua", mass: 0.349, friction: 0.8, trait: "Safe" }, + { id: "chips_can", name: "Lon snack khoai tây", mass: 0.205, friction: 0.5, trait: "Safe" } +]; +function renderObjectsTable() { + const objectsTableBody = document.getElementById('objects-table-body'); + if (!objectsTableBody) return; + objectsTableBody.innerHTML = activeObjects.map(obj => ` + + ${obj.name}
    ${obj.id} + ${obj.mass} + ${obj.friction} + ${obj.trait} + + `).join(''); +} +// 4. History Logs Data & Render +const historyData = [ + { time: "14:20:15", operator: "Operator", prompt: "gắp lon snack đặt vào khay", score: 100, class: "high" }, + { time: "14:15:32", operator: "Operator", prompt: "dọn dẹp chướng ngại vật ở khay", score: 85, class: "medium" }, + { time: "14:02:10", operator: "Operator", prompt: "gắp quả chuối đặt vào Slot_2", score: 100, class: "high" } +]; +function renderHistory() { + const historyList = document.getElementById('history-list'); + if (!historyList) return; + historyList.innerHTML = historyData.map((item, index) => ` +
    +
    + 🕒 ${item.time} - ${item.operator} + ${item.score}/100 +
    +

    "${item.prompt}"

    + +
    + `).join(''); +} +window.runHistoryPrompt = function(index) { + const item = historyData[index]; + if (item) { + chatInput.value = item.prompt; + chatInput.focus(); + document.getElementById('chat-form').dispatchEvent(new Event('submit')); + } +}; +// 5. Speech Synthesis (Text-to-Speech) +function speakFeedback(text) { + if (!ttsToggle || !ttsToggle.checked) return; + + // Determine language based on text content (Vietnamese by default, English if it contains mostly technical terms) + let lang = 'vi'; + const textLower = text.toLowerCase(); + if (textLower.includes('evaluation') || textLower.includes('score') || textLower.includes('report') || textLower.includes('step') || textLower.includes('verification')) { + lang = 'en'; + } + + // Call Google Translate TTS (free API) for high-quality English & Vietnamese voices + const encodedText = encodeURIComponent(text); + const ttsUrl = `https://translate.google.com/translate_tts?ie=UTF-8&tl=${lang}&client=tw-ob&q=${encodedText}`; + + const audio = new Audio(ttsUrl); + audio.play().catch(err => { + console.warn("Google Translate TTS failed, falling back to local speech synthesis:", err); + if ('speechSynthesis' in window) { + window.speechSynthesis.cancel(); + const utterance = new SpeechSynthesisUtterance(text); + utterance.lang = lang === 'vi' ? 'vi-VN' : 'en-US'; + utterance.rate = 1.0; + utterance.pitch = 1.0; + + const voices = window.speechSynthesis.getVoices(); + const matchingVoice = voices.find(voice => voice.lang.includes(lang)); + if (matchingVoice) utterance.voice = matchingVoice; + + window.speechSynthesis.speak(utterance); + } + }); +} +// 6. Voice Recognition (Speech-to-Text) +const micBtn = document.getElementById('mic-btn'); +let recognition = null; +let isRecording = false; +if ('webkitSpeechRecognition' in window || 'SpeechRecognition' in window) { + const SpeechRecognition = window.SpeechRecognition || window.webkitSpeechRecognition; + recognition = new SpeechRecognition(); + recognition.continuous = false; + recognition.interimResults = false; + recognition.lang = 'vi-VN'; + recognition.onstart = () => { + isRecording = true; + micBtn.classList.add('recording'); + writeLog("Đang nghe giọng nói của bạn... Hãy nói đi.", "info"); + speakFeedback("Tôi đang nghe."); + }; + recognition.onresult = (event) => { + const resultText = event.results[0][0].transcript; + chatInput.value = resultText; + writeLog(`Nhận dạng giọng nói: "${resultText}"`, "success"); + speakFeedback(`Đã nhận diện: ${resultText}`); + }; + recognition.onerror = (event) => { + console.error("Speech Recognition Error: ", event.error); + writeLog("Nhận diện giọng nói gặp lỗi: " + event.error, "warn"); + isRecording = false; + micBtn.classList.remove('recording'); + }; + recognition.onend = () => { + isRecording = false; + micBtn.classList.remove('recording'); + }; + micBtn.addEventListener('click', () => { + if (isRecording) { + recognition.stop(); + } else { + recognition.start(); + } + }); +} else { + micBtn.style.display = 'none'; +} +// 7. Smart Autocomplete suggestions +const autocompleteVocabulary = [ + "gắp quả chuối đặt vào khay", + "gắp quả chuối đặt vào Slot_2", + "gắp quả chuối đặt vào Slot_4", + "gắp lon súp cà chua đặt vào khay", + "gắp lon súp cà chua đặt vào Slot_3", + "gắp lon snack đặt vào khay", + "gắp lon snack đặt vào Slot_6", + "dọn dẹp chướng ngại vật trên bàn", + "sắp xếp lại bàn học tập", + "cất dọn đồ vật nguy hiểm" +]; +if (chatInput && autocompletePanel) { + chatInput.addEventListener('input', (e) => { + const query = e.target.value.toLowerCase().trim(); + if (!query || query.length < 2) { + autocompletePanel.classList.add('hidden'); + return; + } + + const matches = autocompleteVocabulary.filter(item => item.includes(query)).slice(0, 4); + if (matches.length === 0) { + autocompletePanel.classList.add('hidden'); + return; + } + + autocompletePanel.innerHTML = matches.map(match => ` +
    ${match}
    + `).join(''); + autocompletePanel.classList.remove('hidden'); + + document.querySelectorAll('.autocomplete-item').forEach(item => { + item.addEventListener('click', () => { + chatInput.value = item.dataset.value; + autocompletePanel.classList.add('hidden'); + chatInput.focus(); + }); + }); + }); + + document.addEventListener('click', (e) => { + if (!e.target.closest('#chat-form')) { + autocompletePanel.classList.add('hidden'); + } + }); +} +// 8. Log and Pipeline functions +function updateBadgeStatus(status) { + if (status === 'connected') { + badge.className = 'badge online'; + badge.textContent = 'Connected'; + } else { + badge.className = 'badge offline'; + badge.textContent = 'Disconnected'; + } +} +function writeLog(text, className = 'info') { + const entry = document.createElement('div'); + entry.className = `log-entry ${className}`; + entry.textContent = `> ${text}`; + + const placeholder = logConsole.querySelector('.placeholder-text'); + if (placeholder) placeholder.remove(); + logConsole.appendChild(entry); + logConsole.scrollTop = logConsole.scrollHeight; +} +function getLogClass(message) { + if (message.includes('✅')) return 'success'; + if (message.includes('❌')) return 'error'; + if (message.includes('⚠️')) return 'warn'; + if (message.includes('🚀') || message.includes('⏳')) return 'info'; + return ''; +} +function updatePipelineUI(message) { + const stepLlm = document.getElementById('step-llm'); + const stepVal = document.getElementById('step-val'); + const stepExec = document.getElementById('step-exec'); + const stepScore = document.getElementById('step-score'); + if (message.includes('[1/5]')) { + setActiveStep(stepLlm); + } else if (message.includes('✅ [1]')) { + setCompletedStep(stepLlm); + } else if (message.includes('❌ [1]')) { + setErrorStep(stepLlm); + unlockInput(); + speakFeedback("Lập kế hoạch thất bại. Vui lòng kiểm tra lại câu lệnh."); + } + else if (message.includes('[2/5]')) { + setActiveStep(stepVal); + } else if (message.includes('✅ [2]')) { + setCompletedStep(stepVal); + } else if (message.includes('❌ [2]') || message.includes('⚠️ [2]')) { + if (message.includes('❌')) { + setErrorStep(stepVal); + unlockInput(); + speakFeedback("Kế hoạch không hợp lệ. Vi phạm các quy tắc an toàn."); + } else { + stepVal.className = 'status-step active warn'; + } + } + else if (message.includes('[3/5]')) { + setActiveStep(stepExec); + } else if (message.includes('Thực thi thành công')) { + setCompletedStep(stepExec); + } else if (message.includes('Thực thi kết thúc có bước lỗi')) { + setErrorStep(stepExec); + speakFeedback("Quá trình thực thi gặp sự cố va chạm."); + } + else if (message.includes('[5/5]')) { + setActiveStep(stepScore); + } else if (message.includes('Rearrangement Evaluation Report') || message.includes('result')) { + setCompletedStep(stepScore); + unlockInput(); + } +} +function setActiveStep(el) { + el.className = 'status-step active'; +} +function setCompletedStep(el) { + el.className = 'status-step completed'; +} +function setErrorStep(el) { + el.className = 'status-step error'; +} +function displayPlan(plan) { + planList.innerHTML = ''; + plan.forEach(step => { + const item = document.createElement('div'); + item.className = 'plan-item'; + item.id = `plan-step-${step.step}`; + + const argsStr = Object.entries(step.args) + .map(([k, v]) => `${k}:${v}`) + .join(', '); + + item.innerHTML = ` + Step ${step.step}: ${step.skill}(${step.object}) + ${argsStr} + `; + planList.appendChild(item); + }); +} +function showRearrangementScore(markdownText) { + let html = markdownText + .replace(/### (.*)/g, '

    $1

    ') + .replace(/\*\*(.*?)\*\*/g, '$1') + .replace(/- (.*)/g, '
  • $1
  • ') + .replace(/\n\n/g, '
    ') + .replace(/✅/g, '✅') + .replace(/⚠️/g, '⚠️') + .replace(/❌/g, '❌'); + + scoreContent.innerHTML = html; + scoreModal.classList.remove('hidden'); +} +function lockInput() { + chatInput.disabled = true; + submitBtn.disabled = true; + resetBtn.disabled = true; + mockToggle.disabled = true; + if (guiToggle) guiToggle.disabled = true; +} +document.getElementById('chat-form').addEventListener('submit', (e) => { + e.preventDefault(); + const prompt = chatInput.value.trim(); + if (!prompt || !socket || socket.readyState !== WebSocket.OPEN) return; + currentPrompt = prompt; + chatInput.value = ''; + + logConsole.innerHTML = ''; + planList.innerHTML = '

    Đang tải kế hoạch...

    '; + + ['step-llm', 'step-val', 'step-exec', 'step-score'].forEach(id => { + document.getElementById(id).className = 'status-step'; + }); + writeLog(`Gửi yêu cầu: "${prompt}"`, "info"); + lockInput(); + + speakFeedback("Bắt đầu xử lý câu lệnh điều khiển của bạn."); + socket.send(JSON.stringify({ + type: 'run', + prompt: prompt, + mock: mockToggle.checked + })); +}); +function unlockInput() { + chatInput.disabled = false; + submitBtn.disabled = false; + resetBtn.disabled = false; + mockToggle.disabled = false; + if (guiToggle) guiToggle.disabled = false; +} +resetBtn.addEventListener('click', () => { + if (!socket || socket.readyState !== WebSocket.OPEN) return; + + logConsole.innerHTML = ''; + planList.innerHTML = '

    Chưa có kế hoạch...

    '; + + ['step-llm', 'step-val', 'step-exec', 'step-score'].forEach(id => { + document.getElementById(id).className = 'status-step'; + }); + socket.send(JSON.stringify({ + type: 'reset' + })); +}); +closeModalBtn.addEventListener('click', () => { + scoreModal.classList.add('hidden'); + unlockInput(); +}); +if (guiToggle) { + guiToggle.addEventListener('change', () => { + writeLog("Thay đổi thiết lập hiển thị cửa sổ PyBullet. Đang kết nối lại...", "info"); + if (socket) { + socket.onclose = null; + socket.close(); + } + connectWebSocket(); + }); +} +// 10. Manual joint controls sending +function sendManualJoints() { + if (!socket || socket.readyState !== WebSocket.OPEN) return; + const q0 = parseFloat(document.getElementById('slider-j1').value); + const q1 = parseFloat(document.getElementById('slider-j2').value); + const q2 = parseFloat(document.getElementById('slider-j3').value); + const q3 = parseFloat(document.getElementById('slider-j4').value); + const q4 = parseFloat(document.getElementById('slider-j5').value); + const q5 = parseFloat(document.getElementById('slider-j6').value); + const q6 = parseFloat(document.getElementById('slider-j7').value); + const qg = parseFloat(document.getElementById('slider-jg').value); + + socket.send(JSON.stringify({ + type: "update_joints", + joints: [q0, q1, q2, q3, q4, q5, q6, 0.0, 0.0, qg, qg] + })); +} +const slidersList = ['j1', 'j2', 'j3', 'j4', 'j5', 'j6', 'j7', 'jg']; +slidersList.forEach(id => { + const slider = document.getElementById(`slider-${id}`); + const label = document.getElementById(`val-${id}`); + if (slider && label) { + slider.addEventListener('input', (e) => { + const val = parseFloat(e.target.value); + label.textContent = id === 'jg' ? val.toFixed(3) : val.toFixed(2); + sendManualJoints(); + }); + } +}); +// 11. Interactive Drag and Drop for YCB objects and Robot End Effector using THREE.TransformControls +const raycaster = new THREE.Raycaster(); +const mouse = new THREE.Vector2(); +// State variables for Hover Highlight +const originalEmissives = new Map(); +let hoveredGroup = null; +canvas.addEventListener('mousedown', onMouseDown); +canvas.addEventListener('mousemove', onMouseMove); +// Helper to determine if an intersected object belongs to a draggable group (YCB or Robot) +function findDraggableTarget(hitObject) { + let curr = hitObject; + while (curr && curr !== scene) { + if (curr === robotGroup) { + return { type: 'robot', group: robotGroup, name: 'robot' }; + } + const ycbEntry = Object.entries(ycbMeshes).find(([name, group]) => group === curr); + if (ycbEntry) { + return { type: 'ycb', group: ycbEntry[1], name: ycbEntry[0] }; + } + curr = curr.parent; + } + return null; +} +// Helper to set/restore emissive highlight glow on all child meshes of a group +function highlightGroup(group, highlightColor = null) { + if (!group) return; + group.traverse(child => { + if (child.isMesh) { + if (highlightColor) { + if (!originalEmissives.has(child.uuid)) { + if (child.material && child.material.emissive) { + originalEmissives.set(child.uuid, { + color: child.material.emissive.clone(), + material: child.material + }); + } + } + if (child.material && child.material.emissive) { + child.material.emissive.copy(highlightColor); + } + } else { + const orig = originalEmissives.get(child.uuid); + if (orig && orig.material && orig.material.emissive) { + orig.material.emissive.copy(orig.color); + } + } + } + }); +} +function onMouseDown(event) { + if (event.button !== 0 || chatInput.disabled) return; + + // Ignore clicks if we are already dragging the transform controls handles + if (transformControls && transformControls.dragging) return; + const rect = canvas.getBoundingClientRect(); + mouse.x = ((event.clientX - rect.left) / rect.width) * 2 - 1; + mouse.y = -((event.clientY - rect.top) / rect.height) * 2 + 1; + raycaster.setFromCamera(mouse, camera); + const hits = raycaster.intersectObjects(scene.children, true); + let target = null; + + // Check if the click hit the Gizmo itself + for (let i = 0; i < hits.length; i++) { + // Exclude the gizmo meshes themselves + let isGizmo = false; + let p = hits[i].object; + while (p) { + if (p === transformControls) { + isGizmo = true; + break; + // Click is on the gizmo handles; let TransformControls handle it + return; + } + p = p.parent; + } + if (isGizmo) continue; + } + for (let i = 0; i < hits.length; i++) { + const found = findDraggableTarget(hits[i].object); + if (found) { + target = found; + break; + } + } + if (target) { + if (target.type === 'robot') { + if (eeDummy && joints.handJoint) { + const handWorldPos = new THREE.Vector3(); + joints.handJoint.getWorldPosition(handWorldPos); + eeDummy.position.copy(handWorldPos); + eeDummy.visible = true; + + transformControls.attach(eeDummy); + writeLog("Đã kích hoạt Gizmo điều khiển cánh tay robot. Kéo các trục mũi tên để dịch chuyển.", "info"); + } + } else { + if (transformControls.object === eeDummy) { + eeDummy.visible = false; + } + transformControls.attach(target.group); + writeLog(`Đã chọn vật thể: ${target.name}. Kéo các trục mũi tên để dịch chuyển.`, "info"); + } + } else { + if (transformControls && !transformControls.dragging) { + if (transformControls.object === eeDummy) { + eeDummy.visible = false; + } + transformControls.detach(); + } + } +} +function onMouseMove(event) { + if (transformControls && transformControls.dragging) { + return; + } + const rect = canvas.getBoundingClientRect(); + mouse.x = ((event.clientX - rect.left) / rect.width) * 2 - 1; + mouse.y = -((event.clientY - rect.top) / rect.height) * 2 + 1; + raycaster.setFromCamera(mouse, camera); + const hits = raycaster.intersectObjects(scene.children, true); + let hoverTarget = null; + + // Check if the mouse is hovering over the Gizmo itself + for (let i = 0; i < hits.length; i++) { + let isGizmo = false; + let p = hits[i].object; + while (p) { + if (p === transformControls) { + isGizmo = true; + break; + // Let Gizmo handle cursors and mouse interaction + return; + } + p = p.parent; + } + if (isGizmo) continue; + } + for (let i = 0; i < hits.length; i++) { + const found = findDraggableTarget(hits[i].object); + if (found) { + hoverTarget = found; + break; + } + } + if (hoverTarget) { + if (hoveredGroup !== hoverTarget.group) { + if (hoveredGroup) { + highlightGroup(hoveredGroup, null); + } + originalEmissives.clear(); + + hoveredGroup = hoverTarget.group; + const glowColor = new THREE.Color(hoverTarget.type === 'robot' ? '#1e40af' : '#2563eb'); + highlightGroup(hoveredGroup, glowColor); + + canvas.style.cursor = 'pointer'; + } + } else { + if (hoveredGroup) { + highlightGroup(hoveredGroup, null); + hoveredGroup = null; + originalEmissives.clear(); + canvas.style.cursor = ''; + } + } +} +// 12. Initial runs +initVisualizer(); +connectWebSocket(); +renderObjectsTable(); +renderHistory(); diff --git a/frontend/app.py b/frontend/app.py new file mode 100644 index 0000000000000000000000000000000000000000..ba2f5cf0d5463506d9125e771d59137dea99ef84 --- /dev/null +++ b/frontend/app.py @@ -0,0 +1,95 @@ +import sys +import os +from dotenv import load_dotenv + +# Ensure project source root is in path +PROJECT_SRC = os.path.abspath(os.path.join(os.path.dirname(__file__), "..")) +if PROJECT_SRC not in sys.path: + sys.path.insert(0, PROJECT_SRC) + +# Load environment variables (API Keys, etc.) +load_dotenv() + +from PySide6.QtCore import Qt +from PySide6.QtWidgets import QApplication +from PySide6.QtGui import QFont, QPalette, QColor + +from frontend.windows.main_window import MainWindow + +# Global QSS styling matching index.css styles +STYLE_SHEET = """ +QMainWindow { + background-color: #070a13; +} + +/* Glass panel style for widgets */ +QFrame#sidebar_widget, QFrame#chat_widget, QFrame#header_widget, QFrame#plan_frame { + background: rgba(255, 255, 255, 0.65); + border: 1px solid rgba(0, 0, 0, 0.08); + border-radius: 12px; +} + +/* Labels */ +QLabel { + font-family: 'Segoe UI', -apple-system, sans-serif; + color: #000000; +} + +/* Scrollbars styling */ +QScrollBar:vertical { + border: none; + background: transparent; + width: 6px; + margin: 0px 0px 0px 0px; +} +QScrollBar::handle:vertical { + background: rgba(37, 99, 235, 0.25); + border-radius: 3px; + min-height: 20px; +} +QScrollBar::handle:vertical:hover { + background: rgba(37, 99, 235, 0.45); +} +QScrollBar::add-line:vertical, QScrollBar::sub-line:vertical { + border: none; + background: none; + height: 0px; +} +QScrollBar::up-arrow:vertical, QScrollBar::down-arrow:vertical { + border: none; + background: none; + height: 0px; +} +QScrollBar::add-page:vertical, QScrollBar::sub-page:vertical { + background: none; +} +""" + +def main(): + # Set PyQt/PySide attribute for high DPI scaling if supported + QApplication.setHighDpiScaleFactorRoundingPolicy( + Qt.HighDpiScaleFactorRoundingPolicy.PassThrough + ) + + app = QApplication(sys.argv) + + # Configure clean Segoe UI font as default + font = QFont("Segoe UI", 9) + app.setFont(font) + + # Set dark palette styling for application fallback + palette = QPalette() + palette.setColor(QPalette.ColorRole.Window, QColor("#070a13")) + palette.setColor(QPalette.ColorRole.WindowText, QColor("#ffffff")) + app.setPalette(palette) + + # Apply stylesheet + app.setStyleSheet(STYLE_SHEET) + + window = MainWindow() + window.show() + + sys.exit(app.exec()) + +if __name__ == "__main__": + main() diff --git a/frontend/controllers/__pycache__/ui_controller.cpython-310.pyc b/frontend/controllers/__pycache__/ui_controller.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c88724f86e7845d3a13e1e230b967cf655f4bfab Binary files /dev/null and b/frontend/controllers/__pycache__/ui_controller.cpython-310.pyc differ diff --git a/frontend/controllers/ui_controller.py b/frontend/controllers/ui_controller.py new file mode 100644 index 0000000000000000000000000000000000000000..03be353d0cc99103454b49fdf16a79e100fcb44a --- /dev/null +++ b/frontend/controllers/ui_controller.py @@ -0,0 +1,201 @@ +import sys +import os +import json +from PySide6.QtCore import QObject, Slot + +# Ensure project source root is in path +PROJECT_SRC = os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "..")) +if PROJECT_SRC not in sys.path: + sys.path.insert(0, PROJECT_SRC) + +from frontend.threads.llm_thread import LLMThread +from frontend.threads.simulation_thread import SimulationThread +from llm_panda.plan_verifier import PlanVerifier + +class UIController(QObject): + """ + Main controller coordinates widgets and background threads (LLM Planning & PyBullet Simulation). + """ + def __init__(self, main_window): + super().__init__() + self.main_window = main_window + + # References to widgets + self.viewport_widget = None + self.chat_widget = None + self.log_widget = None + self.status_widget = None + self.score_modal = None + + # Threads + self.sim_thread = None + self.llm_thread = None + self.last_scene_state = None + + def start(self): + """Initializes and starts the simulation background thread.""" + self.viewport_widget = self.main_window.viewport_widget + self.chat_widget = self.main_window.chat_widget + self.log_widget = self.main_window.log_widget + self.status_widget = self.main_window.status_widget + self.score_modal = self.main_window.score_modal + + # Bind Viewport events to simulation camera actions + self.viewport_widget.camera_rotated.connect(self.handle_camera_rotate) + self.viewport_widget.camera_panned.connect(self.handle_camera_pan) + self.viewport_widget.camera_zoomed.connect(self.handle_camera_zoom) + self.viewport_widget.viewport_clicked.connect(self.handle_viewport_clicked) + + # Bind Chat events + self.chat_widget.command_submitted.connect(self.handle_command_submit) + self.chat_widget.preset_clicked.connect(self.handle_preset_click) + self.chat_widget.reset_clicked.connect(self.handle_reset_click) + self.chat_widget.gui_toggled.connect(self.handle_gui_toggle) + + # Create and run simulation thread + self.sim_thread = SimulationThread() + + # Connect simulation thread signals + self.sim_thread.frame_ready.connect(self.viewport_widget.update_frame) + self.sim_thread.log_message.connect(self.log_widget.append_log) + self.sim_thread.fps_updated.connect(self.status_widget.update_fps) + self.sim_thread.step_completed.connect(self.handle_step_completed) + self.sim_thread.finished.connect(self.handle_execution_finished) + self.sim_thread.init_completed.connect(self.handle_sim_init_completed) + + self.sim_thread.start() + + def handle_sim_init_completed(self): + self.status_widget.update_connection_badge(True) + + def handle_camera_rotate(self, dx, dy): + if self.sim_thread: + self.sim_thread.queue_command("camera_rotate", (dx, dy)) + + def handle_camera_pan(self, dx, dy): + if self.sim_thread: + self.sim_thread.queue_command("camera_pan", (dx, dy)) + + def handle_camera_zoom(self, delta): + if self.sim_thread: + self.sim_thread.queue_command("camera_zoom", delta) + + def handle_viewport_clicked(self, x, y): + if self.sim_thread: + w = self.viewport_widget.width() + h = self.viewport_widget.height() + self.sim_thread.queue_command("viewport_click", (x, y, w, h)) + + def handle_preset_click(self, prompt_text): + self.chat_widget.set_prompt_text(prompt_text) + + def handle_reset_click(self): + if self.sim_thread: + self.log_widget.clear_logs() + self.chat_widget.clear_plan() + self.status_widget.reset_steps() + self.sim_thread.queue_command("reset") + + def handle_gui_toggle(self, checked): + if self.sim_thread: + self.sim_thread.queue_command("gui_toggle", checked) + + def handle_command_submit(self, prompt, use_mock): + if not prompt: + return + + self.log_widget.clear_logs() + self.chat_widget.clear_plan() + self.status_widget.reset_steps() + + self.log_widget.append_log(f"Gửi yêu cầu: \"{prompt}\"", "info") + self.chat_widget.lock_inputs() + + # Capture current scene state thread-safely + scene_state = {} + with self.sim_thread.pybullet_lock: + # Define reachability check for scene state + def reachability_fn(oid): + cls = self.sim_thread.sim.scene.get_class(oid) + try: + grasp_pos, grasp_ori = self.sim_thread.sim.grasp_planner.compute_grasp_pose(oid, cls) + return self.sim_thread.sim.controller.is_reachable(grasp_pos, grasp_ori) + except Exception: + return False + + carried_name = self.sim_thread.sim.scene.get_name(self.sim_thread.sim._carried) if self.sim_thread.sim._carried is not None else None + scene_state = self.sim_thread.sim.scene.get_scene_state(reachability_fn=reachability_fn, carried_object=carried_name) + + self.last_scene_state = scene_state + + # Start LLM Planning Thread + self.status_widget.set_step_active("llm") + self.llm_thread = LLMThread(prompt, scene_state, use_mock) + self.llm_thread.plan_ready.connect(self.handle_plan_ready) + self.llm_thread.log_message.connect(self.log_widget.append_log) + self.llm_thread.failed.connect(self.handle_llm_failed) + self.llm_thread.start() + + def handle_llm_failed(self, error_msg): + self.status_widget.set_step_error("llm") + self.chat_widget.unlock_inputs() + + def handle_plan_ready(self, plan_steps): + self.status_widget.set_step_completed("llm") + self.chat_widget.display_plan(plan_steps) + + if not plan_steps: + self.log_widget.append_log("⚠️ [1] Kế hoạch rỗng.", "warn") + self.status_widget.set_step_active("score") + # Calculate score immediately for empty plan + self.sim_thread.queue_command("execute_plan", []) + return + + # Step 2: Validation + self.status_widget.set_step_active("val") + self.log_widget.append_log("⏳ [2/5] Đang kiểm tra kế hoạch (Validator)...", "info") + + try: + warnings = PlanVerifier.check(plan_steps, self.last_scene_state) + if not warnings: + self.log_widget.append_log("✅ [2] Kế hoạch hợp lệ.", "success") + self.status_widget.set_step_completed("val") + else: + self.log_widget.append_log(f"⚠️ [2] Validator phát hiện {len(warnings)} cảnh báo.", "warn") + for w in warnings: + self.log_widget.append_log(f" - {w}", "warn") + self.status_widget.set_step_active("val") # Set to warning/active state (orange dot visually) + except Exception as e: + self.log_widget.append_log(f"❌ [2] Lỗi kiểm tra kế hoạch: {e}", "error") + self.status_widget.set_step_error("val") + self.chat_widget.unlock_inputs() + return + + # Step 3: Execution + self.status_widget.set_step_active("exec") + self.sim_thread.queue_command("execute_plan", plan_steps) + + def handle_step_completed(self, step_idx): + self.chat_widget.mark_step_completed(step_idx) + + def handle_execution_finished(self, success, score_md, score_val): + if success: + self.status_widget.set_step_completed("exec") + else: + self.status_widget.set_step_error("exec") + + self.status_widget.set_step_completed("score") + + # Show rearrangement report modal + self.score_modal.show_score(score_md) + + # Re-enable inputs + self.chat_widget.unlock_inputs() + + def shutdown(self): + """Safely stops background threads.""" + if self.llm_thread and self.llm_thread.isRunning(): + self.llm_thread.terminate() + self.llm_thread.wait() + if self.sim_thread: + self.sim_thread.shutdown() diff --git a/frontend/index.css b/frontend/index.css new file mode 100644 index 0000000000000000000000000000000000000000..2369dc7253a216f4a5363e7c69bea379843ff831 --- /dev/null +++ b/frontend/index.css @@ -0,0 +1,937 @@ +:root { + --primary-color: #1e3a8a; /* Dark Navy Blue */ + --primary-glow: rgba(30, 58, 138, 0.3); + --accent-success: #064e3b; /* Very Dark Green */ + --accent-warning: #78350f; /* Dark Amber/Brown */ + --accent-error: #7f1d1d; /* Dark Red */ + --bg-dark: #f8fafc; + --text-main: #000000; /* Pure Black for maximum contrast */ + --text-muted: #1e293b; /* Dark Slate */ + --hud-text-shadow: 0 1px 3px rgba(255, 255, 255, 0.95), 0 0 6px rgba(255, 255, 255, 0.85); +} +* { + box-sizing: border-box; + margin: 0; + padding: 0; +} +body { + font-family: 'Outfit', -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif; + background-color: #f1f5f9; + color: var(--text-main); + overflow: hidden; + width: 100vw; + height: 100vh; +} +button, input, select, table { + font-family: inherit; +} +/* Fullscreen Viewport Container */ +#viewport-container { + position: absolute; + top: 0; + left: 0; + width: 100vw; + height: 100vh; + background-color: #f1f5f9; + z-index: 1; + overflow: hidden; +} +#pybullet-viewport { + width: 100%; + height: 100%; + object-fit: cover; + border: none; + border-radius: 0; + box-shadow: none; + cursor: grab; +} +#pybullet-viewport:active { + cursor: grabbing; +} +/* Transparent HUD Panels with Premium Glassmorphism */ +.glass { + background: rgba(255, 255, 255, 0.75); + backdrop-filter: blur(12px); + -webkit-backdrop-filter: blur(12px); + border: 1px solid rgba(255, 255, 255, 0.4); + box-shadow: 0 8px 32px 0 rgba(31, 38, 135, 0.08); + border-radius: 16px; +} +/* Sidebar Styling (Light-HUD layout) */ +.sidebar { + position: absolute; + top: 20px; + left: 20px; + width: 360px; + height: calc(100vh - 40px); + z-index: 10; + padding: 20px; + display: flex; + flex-direction: column; + gap: 16px; + pointer-events: auto; +} +.sidebar-header { + display: flex; + justify-content: space-between; + align-items: center; + border-bottom: 2px solid rgba(37, 99, 235, 0.2); + padding-bottom: 10px; +} +.sidebar-header .brand { + display: flex; + align-items: center; + gap: 8px; + color: #1e3a8a; +} +.sidebar-header h2 { + font-size: 1.4rem; + font-weight: 700; + letter-spacing: -0.025em; + text-shadow: var(--hud-text-shadow); +} +.brand-icon { + filter: drop-shadow(0 1px 2px rgba(255,255,255,0.8)); +} +.badge { + font-size: 0.7rem; + font-weight: 700; + padding: 4px 10px; + border-radius: 10px; + text-transform: uppercase; + letter-spacing: 0.05em; + display: inline-flex; + align-items: center; + gap: 6px; + text-shadow: var(--hud-text-shadow); + border: 1px solid currentColor; +} +.badge::before { + content: ''; + display: inline-block; + width: 6px; + height: 6px; + border-radius: 50%; +} +.badge.online { + background: rgba(16, 185, 129, 0.15); + color: var(--accent-success); +} +.badge.online::before { + background: var(--accent-success); + box-shadow: 0 0 8px var(--accent-success); +} +.badge.offline { + background: rgba(239, 68, 68, 0.15); + color: var(--accent-error); +} +.badge.offline::before { + background: var(--accent-error); +} +/* Tab Bar Navigation inside Sidebar */ +.sidebar-tabs { + display: flex; + gap: 4px; + background: rgba(15, 23, 42, 0.05); + border: 1px solid rgba(0, 0, 0, 0.05); + border-radius: 10px; + padding: 3px; + justify-content: space-between; +} +.tab-btn { + flex-grow: 1; + display: flex; + justify-content: center; + align-items: center; + padding: 8px 4px; + background: transparent; + border: none; + border-radius: 6px; + color: var(--text-muted); + cursor: pointer; + transition: all 0.2s ease; + outline: none; +} +.tab-btn:hover { + background: rgba(255, 255, 255, 0.5); + color: var(--primary-color); +} +.tab-btn.active { + background: white; + color: var(--primary-color); + box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06); +} +/* Tab Panel Transitions */ +.tab-panel { + display: none; + opacity: 0; + transition: opacity 0.3s ease; +} +.tab-panel.active { + display: flex; + flex-direction: column; + gap: 16px; + opacity: 1; + flex-grow: 1; + min-height: 0; +} +.sidebar-section { + display: flex; + flex-direction: column; + gap: 8px; +} +.sidebar-section.flex-grow { + flex-grow: 1; + min-height: 0; +} +.sidebar-section h3 { + font-size: 0.8rem; + font-weight: 700; + text-transform: uppercase; + color: var(--primary-color); + letter-spacing: 0.05em; + text-shadow: var(--hud-text-shadow); +} +/* Operations Steps */ +.status-steps { + display: flex; + flex-direction: column; + gap: 8px; +} +.status-step { + display: flex; + align-items: center; + gap: 10px; + font-size: 0.9rem; + color: var(--text-muted); + font-weight: 600; + text-shadow: var(--hud-text-shadow); + transition: all 0.2s ease; +} +.status-step .dot { + width: 8px; + height: 8px; + border-radius: 50%; + background: rgba(15, 23, 42, 0.3); + border: 1px solid rgba(15, 23, 42, 0.5); + transition: all 0.2s ease; +} +.status-step.active { + color: var(--primary-color); +} +.status-step.active .dot { + background: var(--primary-color); + box-shadow: 0 0 8px var(--primary-color); + border-color: var(--primary-color); +} +.status-step.completed { + color: var(--accent-success); +} +.status-step.completed .dot { + background: var(--accent-success); + border-color: var(--accent-success); +} +.status-step.error { + color: var(--accent-error); +} +.status-step.error .dot { + background: var(--accent-error); + border-color: var(--accent-error); +} +/* Task Plan List */ +.plan-list { + background: rgba(255, 255, 255, 0.65); + backdrop-filter: blur(8px); + border: 1px solid rgba(0, 0, 0, 0.08); + border-radius: 10px; + max-height: 120px; + overflow-y: auto; + padding: 8px; + display: flex; + flex-direction: column; + gap: 5px; + box-shadow: 0 4px 20px rgba(0,0,0,0.03); +} +.plan-item { + font-size: 0.8rem; + padding: 6px 10px; + background: rgba(255, 255, 255, 0.4); + border-radius: 6px; + border-left: 3px solid rgba(0, 0, 0, 0.1); + color: var(--text-main); + font-weight: 500; + display: flex; + justify-content: space-between; +} +.plan-item.active { + background: rgba(37, 99, 235, 0.08); + border-left-color: var(--primary-color); + color: var(--primary-color); + font-weight: 600; +} +.plan-item.completed { + border-left-color: var(--accent-success); + color: rgba(15, 23, 42, 0.4); + text-decoration: line-through; + opacity: 0.6; +} +/* Monospace Log Console */ +.log-console { + background: rgba(255, 255, 255, 0.65); + backdrop-filter: blur(8px); + border: 1px solid rgba(0, 0, 0, 0.08); + font-family: 'Consolas', 'Fira Code', monospace; + font-size: 0.8rem; + line-height: 1.4; + border-radius: 10px; + padding: 10px; + overflow-y: auto; + flex-grow: 1; + display: flex; + flex-direction: column; + gap: 5px; + box-shadow: 0 4px 20px rgba(0,0,0,0.03); +} +.log-entry { + color: var(--text-main); + font-weight: 600; +} +.log-entry.info { color: #1e3a8a; } +.log-entry.success { color: #064e3b; } +.log-entry.warn { color: #78350f; } +.log-entry.error { color: #7f1d1d; } +.placeholder-text { + color: var(--text-muted); + font-style: italic; + text-align: center; + margin: auto; + font-size: 0.85rem; +} +/* Scenarios Tab styling */ +.scenarios-grid { + display: grid; + grid-template-columns: repeat(3, 1fr); + gap: 8px; +} +.scenario-card { + background: rgba(255, 255, 255, 0.6); + border: 1px solid rgba(0, 0, 0, 0.08); + border-radius: 10px; + padding: 10px 6px; + display: flex; + flex-direction: column; + align-items: center; + gap: 6px; + text-align: center; + cursor: pointer; + transition: all 0.2s ease; + user-select: none; +} +.scenario-card:hover { + background: rgba(255, 255, 255, 0.95); + border-color: var(--primary-color); + box-shadow: 0 4px 12px rgba(30, 58, 138, 0.08); + transform: translateY(-1.5px); +} +.scenario-icon { + color: var(--primary-color); + background: rgba(30, 58, 138, 0.06); + padding: 6px; + border-radius: 8px; + display: flex; + align-items: center; + justify-content: center; +} +.scenario-card h4 { + font-size: 0.7rem; + font-weight: 700; + color: var(--text-muted); + line-height: 1.2; +} +.preset-commands-list { + display: flex; + flex-direction: column; + gap: 6px; +} +.preset-command-item { + background: rgba(255, 255, 255, 0.55); + border: 1px solid rgba(0, 0, 0, 0.06); + border-radius: 8px; + padding: 8px 12px; + font-size: 0.8rem; + font-weight: 600; + color: var(--text-muted); + text-align: left; + cursor: pointer; + transition: all 0.2s ease; +} +.preset-command-item:hover { + background: rgba(255, 255, 255, 0.85); + border-color: var(--primary-color); + color: var(--primary-color); +} +/* Objects Tab Table */ +.table-container { + background: rgba(255, 255, 255, 0.65); + border: 1px solid rgba(0, 0, 0, 0.06); + border-radius: 10px; + overflow: hidden; + box-shadow: 0 4px 20px rgba(0,0,0,0.03); +} +.objects-table { + width: 100%; + border-collapse: collapse; + font-size: 0.8rem; + text-align: left; +} +.objects-table th, .objects-table td { + padding: 10px 10px; + border-bottom: 1px solid rgba(0, 0, 0, 0.05); +} +.objects-table th { + background: rgba(15, 23, 42, 0.03); + color: var(--primary-color); + font-weight: 700; + text-transform: uppercase; + font-size: 0.7rem; + letter-spacing: 0.05em; +} +.objects-table tr:last-child td { + border-bottom: none; +} +.objects-table td { + color: var(--text-main); + font-weight: 600; +} +.tag-badge { + display: inline-block; + padding: 2px 6px; + border-radius: 4px; + font-size: 0.65rem; + font-weight: 700; + text-transform: uppercase; +} +.tag-badge.safe { + background: rgba(16, 185, 129, 0.1); + color: #047857; +} +/* History Tab list */ +.history-list { + display: flex; + flex-direction: column; + gap: 8px; + max-height: calc(100vh - 120px); + overflow-y: auto; + padding-right: 2px; +} +.history-card { + background: rgba(255, 255, 255, 0.6); + border: 1px solid rgba(0, 0, 0, 0.06); + border-radius: 10px; + padding: 10px 12px; + display: flex; + flex-direction: column; + gap: 6px; + transition: all 0.2s ease; +} +.history-card:hover { + background: rgba(255, 255, 255, 0.85); + border-color: var(--primary-color); +} +.history-card-header { + display: flex; + justify-content: space-between; + font-size: 0.7rem; + color: var(--text-muted); + font-weight: 600; +} +.history-card-prompt { + font-size: 0.8rem; + font-style: italic; + color: var(--text-main); + font-weight: 600; + line-height: 1.3; +} +.history-card-footer { + display: flex; + justify-content: space-between; + align-items: center; + border-top: 1px solid rgba(0, 0, 0, 0.04); + padding-top: 6px; + margin-top: 2px; +} +.history-score { + font-size: 0.85rem; + font-weight: 700; +} +.history-score.high { color: #047857; } +.history-score.medium { color: #b45309; } +.history-score.low { color: #b91c1c; } +.history-actions { + display: flex; + gap: 4px; +} +.history-action-btn { + background: transparent; + border: 1px solid rgba(37, 99, 235, 0.2); + color: var(--primary-color); + padding: 3px 6px; + border-radius: 4px; + font-size: 0.7rem; + font-weight: 600; + cursor: pointer; + display: flex; + align-items: center; + gap: 3px; + transition: all 0.2s ease; +} +.history-action-btn:hover { + background: rgba(37, 99, 235, 0.08); + border-color: var(--primary-color); +} +/* Analytics Tab KPIs & Charts */ +.kpi-grid { + display: grid; + grid-template-columns: repeat(3, 1fr); + gap: 8px; +} +.kpi-card { + background: rgba(255, 255, 255, 0.65); + border: 1px solid rgba(0, 0, 0, 0.06); + border-radius: 10px; + padding: 10px 4px; + display: flex; + flex-direction: column; + align-items: center; + text-align: center; + box-shadow: 0 2px 8px rgba(0,0,0,0.02); +} +.kpi-value { + font-size: 1.15rem; + font-weight: 700; + color: var(--primary-color); +} +.kpi-label { + font-size: 0.65rem; + font-weight: 700; + color: var(--text-muted); + text-transform: uppercase; + margin-top: 2px; + letter-spacing: 0.02em; +} +.analytics-chart { + display: flex; + flex-direction: column; + gap: 10px; + background: rgba(255, 255, 255, 0.5); + border: 1px solid rgba(0, 0, 0, 0.06); + border-radius: 10px; + padding: 12px; +} +.chart-bar-group { + display: flex; + flex-direction: column; + gap: 4px; +} +.chart-label-row { + display: flex; + justify-content: space-between; + font-size: 0.75rem; + font-weight: 600; + color: var(--text-muted); +} +.chart-track { + width: 100%; + height: 8px; + background: rgba(0, 0, 0, 0.05); + border-radius: 4px; + overflow: hidden; +} +.chart-bar { + height: 100%; + border-radius: 4px; + transition: width 0.6s cubic-bezier(0.16, 1, 0.3, 1); +} +/* System settings form controls */ +.form-group { + display: flex; + flex-direction: column; + gap: 4px; +} +.form-label { + font-size: 0.8rem; + font-weight: 600; + color: var(--text-muted); +} +.select-wrapper { + position: relative; + width: 100%; +} +.glass-select { + width: 100%; + background: rgba(255, 255, 255, 0.7); + border: 1px solid rgba(0, 0, 0, 0.1); + border-radius: 8px; + padding: 8px 24px 8px 10px; + font-size: 0.8rem; + font-weight: 600; + color: var(--text-main); + outline: none; + cursor: pointer; + transition: all 0.2s ease; + appearance: none; +} +.glass-select:focus { + border-color: var(--primary-color); + box-shadow: 0 0 10px rgba(37, 99, 235, 0.1); +} +.select-wrapper::after { + content: ''; + position: absolute; + right: 10px; + top: 50%; + transform: translateY(-50%); + width: 0; + height: 0; + border-left: 4px solid transparent; + border-right: 4px solid transparent; + border-top: 4px solid var(--text-muted); + pointer-events: none; +} +/* Floating Chat Input Box & Buttons */ +.chat-container { + position: absolute; + bottom: 30px; + left: calc(50% + 180px); + transform: translateX(-50%); + width: 650px; + z-index: 10; + padding: 12px; + display: flex; + flex-direction: column; + gap: 8px; + pointer-events: auto; +} +#chat-form { + display: flex; + gap: 8px; + align-items: center; + position: relative; +} +#chat-input { + flex-grow: 1; + background: rgba(255, 255, 255, 0.75); + backdrop-filter: blur(10px); + border: 2px solid var(--primary-color); + box-shadow: 0 4px 20px rgba(0,0,0,0.05); + padding: 12px 18px; + border-radius: 12px; + color: #0f172a; + font-size: 0.95rem; + font-weight: 600; + outline: none; + transition: all 0.2s ease; +} +#chat-input:focus { + border-color: #1d4ed8; + background: rgba(255, 255, 255, 0.9); + box-shadow: 0 0 15px rgba(37, 99, 235, 0.2); +} +.chat-action-btn { + background: rgba(255, 255, 255, 0.85); + border: 2px solid var(--primary-color); + color: var(--primary-color); + width: 46px; + height: 46px; + border-radius: 12px; + cursor: pointer; + display: flex; + justify-content: center; + align-items: center; + transition: all 0.2s ease; + box-shadow: 0 4px 12px rgba(0, 0, 0, 0.03); + outline: none; +} +.chat-action-btn:hover { + background: rgba(255, 255, 255, 0.95); + transform: translateY(-1px); + box-shadow: 0 4px 16px rgba(30, 58, 138, 0.12); +} +.chat-action-btn:active { + transform: translateY(0); +} +#submit-btn { + background: var(--primary-color); + color: white; +} +#submit-btn:hover { + background: #1d4ed8; +} +#submit-btn:disabled, #chat-input:disabled, #mic-btn:disabled { + opacity: 0.4; + cursor: not-allowed; + box-shadow: none; +} +/* Pulsing voice recorder active glow */ +#mic-btn.recording { + border-color: var(--accent-error); + color: var(--accent-error); + background: rgba(239, 68, 68, 0.08); + animation: pulseMic 1.5s infinite alternate; +} +@keyframes pulseMic { + 0% { + box-shadow: 0 0 4px rgba(239, 68, 68, 0.2); + } + 100% { + box-shadow: 0 0 16px rgba(239, 68, 68, 0.5); + } +} +.chat-options { + display: flex; + justify-content: space-between; + align-items: center; + font-size: 0.8rem; + color: #0f172a; + font-weight: 600; + text-shadow: var(--hud-text-shadow); +} +/* Toggle Switch styling */ +.toggle-switch { + display: flex; + align-items: center; + gap: 6px; + cursor: pointer; +} +.toggle-switch input { + display: none; +} +.slider { + position: relative; + display: inline-block; + width: 32px; + height: 18px; + background-color: rgba(15, 23, 42, 0.2); + border-radius: 18px; + transition: .3s; + border: 1px solid rgba(0, 0, 0, 0.15); +} +.slider:before { + position: absolute; + content: ""; + height: 12px; + width: 12px; + left: 2px; + bottom: 2px; + background-color: #0f172a; + border-radius: 50%; + transition: .3s; +} +.toggle-switch input:checked + .slider { + background-color: var(--primary-color); + border-color: #1d4ed8; +} +.toggle-switch input:checked + .slider:before { + background-color: white; + transform: translateX(14px); +} +.toggle-label { + user-select: none; +} +/* Custom Text and Primary Buttons */ +.text-btn { + background: none; + border: none; + color: #1d4ed8; + cursor: pointer; + font-weight: 700; + transition: color 0.2s; + font-size: 0.8rem; + text-shadow: var(--hud-text-shadow); +} +.text-btn:hover { + color: #0f172a; +} +.primary-btn { + background: var(--primary-color); + color: white; + border: none; + padding: 10px 24px; + border-radius: 8px; + font-weight: 600; + cursor: pointer; + transition: all 0.3s; + box-shadow: 0 4px 12px var(--primary-glow); +} +.primary-btn:hover { + background: #1d4ed8; + box-shadow: 0 4px 20px rgba(29, 78, 216, 0.4); +} +/* Header overlays */ +.header-overlay { + position: absolute; + top: 20px; + left: 390px; + right: 20px; + z-index: 10; + pointer-events: none; +} +.header-overlay h1 { + font-size: 1.3rem; + font-weight: 700; + letter-spacing: -0.015em; + color: #0f172a; + text-shadow: var(--hud-text-shadow); + margin-bottom: 2px; +} +.header-overlay p { + font-size: 0.8rem; + color: var(--text-muted); + text-shadow: var(--hud-text-shadow); +} +/* Autocomplete Suggestion Panel styling */ +.autocomplete-panel { + position: absolute; + bottom: calc(100% + 10px); + left: 0; + width: 100%; + background: rgba(255, 255, 255, 0.9); + backdrop-filter: blur(12px); + border: 1px solid rgba(30, 58, 138, 0.15); + border-radius: 12px; + box-shadow: 0 -8px 32px rgba(0, 0, 0, 0.08); + padding: 6px; + display: flex; + flex-direction: column; + gap: 3px; + z-index: 100; + max-height: 150px; + overflow-y: auto; +} +.autocomplete-panel.hidden { + display: none; +} +.autocomplete-item { + padding: 8px 12px; + font-size: 0.8rem; + font-weight: 600; + color: var(--text-muted); + border-radius: 6px; + cursor: pointer; + transition: all 0.2s ease; + text-align: left; +} +.autocomplete-item:hover { + background: rgba(30, 58, 138, 0.06); + color: var(--primary-color); +} +/* Modal Overlay for Score Card */ +.modal-overlay { + position: fixed; + top: 0; + left: 0; + width: 100vw; + height: 100vh; + background: rgba(15, 23, 42, 0.45); + backdrop-filter: blur(10px); + z-index: 1000; + display: flex; + justify-content: center; + align-items: center; + opacity: 1; + transition: opacity 0.3s ease; +} +.modal-overlay.hidden { + opacity: 0; + pointer-events: none; +} +.modal-content { + width: 500px; + max-width: 90%; + padding: 24px; + display: flex; + flex-direction: column; + gap: 16px; + background: rgba(255, 255, 255, 0.9) !important; + border: 2px solid var(--primary-color) !important; + box-shadow: 0 10px 40px rgba(0, 0, 0, 0.2) !important; + border-radius: 16px; + animation: scaleUp 0.3s cubic-bezier(0.34, 1.56, 0.64, 1); +} +@keyframes scaleUp { + from { transform: scale(0.9); opacity: 0; } + to { transform: scale(1); opacity: 1; } +} +.modal-content h2 { + font-size: 1.35rem; + text-align: center; + border-bottom: 2px solid rgba(37, 99, 235, 0.2); + padding-bottom: 10px; + color: #0f172a; +} +.score-md-content { + font-size: 0.9rem; + line-height: 1.5; + color: #334155; +} +.score-md-content h3 { + margin: 10px 0 4px 0; + font-size: 1rem; + color: #1d4ed8; +} +.score-md-content ul { + padding-left: 18px; + margin-bottom: 8px; +} +.score-md-content li { + margin-bottom: 2px; +} +.score-md-content strong { + color: #0f172a; +} +/* Scrollbars styling */ +::-webkit-scrollbar { + width: 6px; +} +::-webkit-scrollbar-track { + background: transparent; +} +::-webkit-scrollbar-thumb { + background: rgba(37, 99, 235, 0.25); + border-radius: 3px; +} +::-webkit-scrollbar-thumb:hover { + background: rgba(37, 99, 235, 0.45); +} +/* Manual controls range sliders styling */ +.manual-controls { + display: flex; + flex-direction: column; + gap: 8px; + background: rgba(255, 255, 255, 0.5); + border: 1px solid rgba(0, 0, 0, 0.06); + border-radius: 10px; + padding: 12px; + max-height: 240px; + overflow-y: auto; +} +.slider-group { + display: flex; + flex-direction: column; + gap: 2px; +} +.slider-group label { + font-size: 0.75rem; + font-weight: 600; + color: var(--text-muted); + display: flex; + justify-content: space-between; +} +.slider-group input[type="range"] { + width: 100%; + height: 4px; + background: rgba(15, 23, 42, 0.1); + border-radius: 2px; + outline: none; + accent-color: var(--primary-color); +} \ No newline at end of file diff --git a/frontend/index.html b/frontend/index.html new file mode 100644 index 0000000000000000000000000000000000000000..0f991f6131ca55ca407406b922b75298bb91bb48 --- /dev/null +++ b/frontend/index.html @@ -0,0 +1,388 @@ + + + + + + LLM-Panda Web-Embedded PyBullet Simulation + + + + + + + + + + + + + + + +
    + +
    + + + +
    +
    + + + + + +
    +
    + + + +
    +
    + +
    +

    Mô phỏng điều khiển Franka Panda

    +

    Thao tác: Kéo chuột trái để xoay camera, Kéo chuột phải để di chuyển camera, Cuộn chuột để Zoom

    +
    + + + + + + \ No newline at end of file diff --git a/frontend/interactive_server.py b/frontend/interactive_server.py new file mode 100644 index 0000000000000000000000000000000000000000..02dc3cb4814257ee3e627de5dbba2d13f759576e --- /dev/null +++ b/frontend/interactive_server.py @@ -0,0 +1,574 @@ +import sys +import os +import json +import asyncio +import math +import time +import threading +from typing import Optional +from fastapi import FastAPI, WebSocket, WebSocketDisconnect +from fastapi.staticfiles import StaticFiles +from fastapi.responses import HTMLResponse +import uvicorn +import cv2 +import numpy as np +import pybullet as pb +# Ensure project source root is in path +PROJECT_SRC = os.path.abspath(os.path.join(os.path.dirname(__file__), "..")) +if PROJECT_SRC not in sys.path: + sys.path.insert(0, PROJECT_SRC) +from dotenv import load_dotenv +load_dotenv() +from main import PandaSimulation, _YCB_CATALOG +from llm_panda.llm_agent import LLMAgent, RemoteLLMPlanner, RuleBasedPlanner +from llm_panda.plan_verifier import PlanVerifier +from llm_panda import config +import pybullet_data +from pybullet_object_models import ycb_objects +app = FastAPI(title="LLM-Panda Web-Embedded PyBullet Simulation") +# Serve static files from the frontend directory itself +static_dir = os.path.dirname(__file__) +app.mount("/static", StaticFiles(directory=static_dir), name="static") +# Mount robot meshes and YCB object assets +panda_data_path = os.path.join(pybullet_data.getDataPath(), "franka_panda") +ycb_data_path = ycb_objects.getDataPath() +app.mount("/assets/panda", StaticFiles(directory=panda_data_path), name="panda") +app.mount("/assets/ycb", StaticFiles(directory=ycb_data_path), name="ycb") +@app.get("/") +async def get(): + html_file = os.path.join(static_dir, "index.html") + if os.path.exists(html_file): + with open(html_file, "r", encoding="utf-8") as f: + return HTMLResponse(content=f.read(), status_code=200) + return HTMLResponse(content="

    index.html not found!

    ", status_code=404) +# Global variables to track the current active simulation, lock, and thread lock +current_sim: Optional[PandaSimulation] = None +executor_lock = asyncio.Lock() +pybullet_lock = threading.RLock() +def get_init_payload(sim: PandaSimulation) -> dict: + """Gathers the initial static geometry and YCB object definitions.""" + with pybullet_lock: + objects_info = {} + if sim and sim.scene: + for oid in sim.scene.object_ids: + name = sim.scene.get_name(oid) + cls = sim.scene.get_class(oid) + folder = "" + for cat_name, cat_cls, cat_folder in _YCB_CATALOG: + if cat_name == name: + folder = cat_folder + break + pos, ori = pb.getBasePositionAndOrientation(oid, physicsClientId=sim.client) + + # Query collision shape data for CoM-to-link offset + collision_data = pb.getCollisionShapeData(oid, -1, physicsClientId=sim.client) + coll_scale = [1.0, 1.0, 1.0] + coll_local_pos = [0.0, 0.0, 0.0] + coll_local_ori = [0.0, 0.0, 0.0, 1.0] + if collision_data: + cd = collision_data[0] + coll_scale = list(cd[3]) + coll_local_pos = list(cd[5]) + coll_local_ori = list(cd[6]) + # Query visual shape data for exact dimensions/scales and offsets relative to link + visual_data = pb.getVisualShapeData(oid, physicsClientId=sim.client) + vis_scale = [1.0, 1.0, 1.0] + vis_local_pos = [0.0, 0.0, 0.0] + vis_local_ori = [0.0, 0.0, 0.0, 1.0] + if visual_data: + vd = visual_data[0] + vis_scale = list(vd[3]) + # Transform visual frame to be relative to CoM: CoM_to_visual = CoM_to_link * link_to_visual + vis_pos_com, vis_ori_com = pb.multiplyTransforms( + coll_local_pos, coll_local_ori, + list(vd[5]), list(vd[6]) + ) + vis_local_pos = list(vis_pos_com) + vis_local_ori = list(vis_ori_com) + + objects_info[name] = { + "class": cls, + "folder": folder, + "initial_pos": list(pos), + "initial_ori": list(ori), + "vis_scale": vis_scale, + "vis_local_pos": vis_local_pos, + "vis_local_ori": vis_local_ori, + "coll_scale": coll_scale, + "coll_local_pos": coll_local_pos, + "coll_local_ori": coll_local_ori + } + return { + "type": "init", + "table": { + "center": [config.TABLE_CENTER[0], config.TABLE_CENTER[1], config.TABLE_BASE_Z], + "half_extents": list(config.TABLE_HALF_EXTENTS), + "color": list(config.TABLE_COLOR), + "top_z": config.TABLE_TOP_Z + }, + "tray": { + "position": list(config.TRAY_POSITION), + "half_extents": list(config.TRAY_HALF_EXTENTS), + "color": list(config.TRAY_COLOR) + }, + "slots": {name: list(pos) for name, pos in getattr(config, 'SLOTS', {}).items()}, + "objects": objects_info + } +def get_simulation_state_payload(sim: PandaSimulation) -> dict: + """Gathers the current robot joint positions and YCB object poses.""" + with pybullet_lock: + if sim is None or sim.client is None or not pb.isConnected(sim.client): + return {} + + # Read all joints (12 joints including arm joints and gripper fingers) + num_joints = pb.getNumJoints(sim.robot_id, physicsClientId=sim.client) + joints_state = [] + for i in range(num_joints): + pos, _, _, _ = pb.getJointState(sim.robot_id, i, physicsClientId=sim.client) + joints_state.append(pos) + + # Read objects pos/ori + objects_state = {} + for oid in sim.scene.object_ids: + name = sim.scene.get_name(oid) + pos, ori = pb.getBasePositionAndOrientation(oid, physicsClientId=sim.client) + objects_state[name] = { + "pos": list(pos), + "ori": list(ori) + } + + return { + "type": "state", + "joints": joints_state, + "objects": objects_state + } +def set_pybullet_window_visibility(visible: bool): + """Finds the PyBullet GUI window on Windows and sets its visibility by moving it on/off-screen.""" + import sys + if sys.platform != "win32": + return False + import ctypes + import time + + EnumWindowsProc = ctypes.WINFUNCTYPE(ctypes.c_bool, ctypes.c_void_p, ctypes.c_void_p) + + for _ in range(30): + found_hwnd = [] + + def foreach_window(hwnd, lParam): + length = ctypes.windll.user32.GetWindowTextLengthW(hwnd) + buff = ctypes.create_unicode_buffer(length + 1) + ctypes.windll.user32.GetWindowTextW(hwnd, buff, length + 1) + title = buff.value + if "bullet physics examplebrowser" in title.lower(): + found_hwnd.append(hwnd) + return False + return True + + ctypes.windll.user32.EnumWindows(EnumWindowsProc(foreach_window), 0) + if found_hwnd: + hwnd = found_hwnd[0] + # Ensure the window is shown/restored from minimized state first (SW_SHOW = 5) + ctypes.windll.user32.ShowWindow(hwnd, 5) + + # SWP_NOSIZE = 0x0001, SWP_NOZORDER = 0x0004 + if visible: + # Move window to visible region + ctypes.windll.user32.SetWindowPos(hwnd, 0, 100, 100, 0, 0, 0x0001 | 0x0004) + else: + # Move window far off-screen to hide it without destroying OpenGL context + ctypes.windll.user32.SetWindowPos(hwnd, 0, -10000, -10000, 0, 0, 0x0001 | 0x0004) + print(f"[Window Visibility] Set PyBullet window (HWND: {hwnd}) visibility to: {visible}", flush=True) + return True + time.sleep(0.1) + return False +def compute_and_format_score(sim: PandaSimulation, plan: list, executed_successfully: bool): + """Calculates rearrangement score based on final object locations and collisions.""" + with pybullet_lock: + score = 100 + details = [] + + # Check target placement if we had a plan + target_location = None + target_object = None + for step in plan: + if step.get("function") in ("place_at", "place_down", "move_to"): + args = step.get("args", {}) + if "location_id" in args: + target_location = args["location_id"] + if step.get("function") == "pick_up": + target_object = step.get("args", {}).get("object_id") + + if target_object and target_location: + obj_id = sim.scene.name_to_id(target_object) + if obj_id is not None: + pos, _ = pb.getBasePositionAndOrientation(obj_id) + current_loc = sim.scene.classify_location(pos) + if current_loc == target_location: + details.append(f"✅ **Đã đặt {target_object} đúng vị trí {target_location}**: +50 điểm") + else: + details.append(f"❌ **{target_object} chưa đến đúng vị trí {target_location} (đang ở {current_loc})**: -50 điểm") + score -= 50 + else: + details.append(f"❌ **Không tìm thấy vật thể {target_object}**: -50 điểm") + score -= 50 + else: + details.append("ℹ️ Không có yêu cầu di chuyển vật thể cụ thể nào được phát hiện.") + + # Knock detection + knocked_count = 0 + for oid in sim.scene.object_ids: + if oid == sim.scene.name_to_id(target_object): + continue + pos, _ = pb.getBasePositionAndOrientation(oid) + loc = sim.scene.classify_location(pos) + if loc == "elsewhere": + name = sim.scene.get_name(oid) + details.append(f"⚠️ **Vật thể '{name}' bị lệch khỏi vị trí quy định**: -15 điểm") + score -= 15 + knocked_count += 1 + + if knocked_count == 0: + details.append("✅ **Không có vật thể nào khác bị va chạm hay xê dịch**: +30 điểm") + else: + score = max(0, score) + + # Execution success + if executed_successfully: + details.append("✅ **Thực thi toàn bộ kế hoạch thành công**: +20 điểm") + else: + details.append("❌ **Thực thi gặp lỗi gián đoạn**: -30 điểm") + score -= 30 + + score = max(0, min(100, score)) + + md = f"### 🏆 Rearrangement Evaluation Report\n\n**Tổng điểm: {score}/100**\n\n**Chi tiết:**\n" + "\n".join([f"- {d}" for d in details]) + return score, md +def run_pipeline_threadsafe(websocket: WebSocket, user_prompt: str, loop, use_mock: bool, camera_state: Optional[dict] = None): + """Runs the planning, validation, execution with image streaming, and scoring.""" + global current_sim + + def log(message: str, step: Optional[int] = None): + try: + print(f"[WS Log] {message}", flush=True) + except Exception: + pass + asyncio.run_coroutine_threadsafe( + websocket.send_json({"type": "log", "message": message, "step": step}), + loop + ) + # Step 1: Planning + log("⏳ [1/5] Đang lập kế hoạch (LLM Planner)...") + + if use_mock: + planner = RuleBasedPlanner() + log("✅ [1] Đang sử dụng RuleBasedPlanner (Offline)") + else: + api_key = os.environ.get("OPENAI_API_KEY") or os.environ.get("LLM_API_KEY") + if not api_key: + log("❌ [1] Lỗi: Không tìm thấy OPENAI_API_KEY / LLM_API_KEY. Vui lòng chọn Mock.") + return + planner = RemoteLLMPlanner() + log(f"✅ [1] Đang sử dụng RemoteLLMPlanner (Model: {planner.model})") + + with pybullet_lock: + current_sim.agent = LLMAgent(planner=planner) + + # Settle physics in case the user placed objects hovering or overlapping in the UI + if current_sim.controller: + current_sim.controller._settle(60) + + # Define reachability check for scene state + def reachability_fn(oid): + cls = current_sim.scene.get_class(oid) + try: + grasp_pos, grasp_ori = current_sim.grasp_planner.compute_grasp_pose(oid, cls) + return current_sim.controller.is_reachable(grasp_pos, grasp_ori) + except Exception: + return False + carried_name = current_sim.scene.get_name(current_sim._carried) if current_sim._carried is not None else None + scene_state = current_sim.scene.get_scene_state(reachability_fn=reachability_fn, carried_object=carried_name) + state_text = json.dumps(scene_state, indent=2) + + try: + with pybullet_lock: + plan = current_sim.agent.plan(user_prompt, state_text) + log(f"✅ [1] Đã tạo kế hoạch: {len(plan)} bước.") + except Exception as e: + log(f"❌ [1] Lập kế hoạch thất bại: {e}") + return + # Send steps to client + plan_steps = [] + for idx, step in enumerate(plan, 1): + func = step.get("function") + args = step.get("args", {}) + obj = args.get("object_id") or args.get("location_id") or "" + plan_steps.append({ + "step": idx, + "skill": func, + "object": obj, + "args": args + }) + + asyncio.run_coroutine_threadsafe( + websocket.send_json({"type": "plan", "plan": plan_steps}), + loop + ) + if not plan: + log("⚠️ [1] Kế hoạch rỗng.") + log("⏳ [5/5] Đang tính toán điểm sắp xếp...") + score_val, score_md = compute_and_format_score(current_sim, [], True) + asyncio.run_coroutine_threadsafe( + websocket.send_json({ + "type": "result", + "score_display": score_md, + "score_value": score_val + }), + loop + ) + state_payload = get_simulation_state_payload(current_sim) + if state_payload: + asyncio.run_coroutine_threadsafe(websocket.send_json(state_payload), loop) + return + # Step 2: Validation + log("⏳ [2/5] Đang kiểm tra kế hoạch (Validator)...") + try: + with pybullet_lock: + warnings = PlanVerifier.check(plan, scene_state) + if not warnings: + log("✅ [2] Kế hoạch hợp lệ.") + else: + log(f"⚠️ [2] Validator phát hiện {len(warnings)} cảnh báo.") + for w in warnings: + log(f" - {w}") + except Exception as e: + log(f"❌ [2] Lỗi kiểm tra kế hoạch: {e}") + return + # Step 3: PyBullet Execution (Live!) + log("⏳ [3/5] Đang thực thi hành động của robot...") + + # Hook pb.stepSimulation to capture states during movements + original_step = pb.stepSimulation + last_stream_time = [0.0] + throttle_interval = 0.033 + + def wrapped_step(): + original_step() + if not current_sim.gui: + # Sleep slightly in headless mode to simulate arm speed and avoid freezing + time.sleep(0.001) + curr_time = time.time() + if curr_time - last_stream_time[0] >= throttle_interval: + last_stream_time[0] = curr_time + state_payload = get_simulation_state_payload(current_sim) + if state_payload: + asyncio.run_coroutine_threadsafe( + websocket.send_json(state_payload), + loop + ) + + with pybullet_lock: + pb.stepSimulation = wrapped_step + + executed_successfully = True + try: + # Trigger an initial simulation state transmission + state_payload = get_simulation_state_payload(current_sim) + if state_payload: + asyncio.run_coroutine_threadsafe(websocket.send_json(state_payload), loop) + + for i, step in enumerate(plan, 1): + log(f"🚀 [3/5] Đang chạy bước {i}/{len(plan)}: {step['function']}") + with pybullet_lock: + current_sim._execute(step, verbose=True) + + log("✅ [3] Thực thi thành công toàn bộ kế hoạch.") + except Exception as e: + log(f"❌ Lỗi trong lúc thực thi mô phỏng: {e}") + executed_successfully = False + finally: + with pybullet_lock: + pb.stepSimulation = original_step + + # Send a final state to ensure visual sync + state_payload = get_simulation_state_payload(current_sim) + if state_payload: + asyncio.run_coroutine_threadsafe(websocket.send_json(state_payload), loop) + # Step 5: Scoring + log("⏳ [5/5] Đang tính toán điểm sắp xếp...") + score_val, score_md = compute_and_format_score(current_sim, plan, executed_successfully) + + asyncio.run_coroutine_threadsafe( + websocket.send_json({ + "type": "result", + "score_display": score_md, + "score_value": score_val + }), + loop + ) +@app.websocket("/ws") +async def websocket_endpoint(websocket: WebSocket): + global current_sim + await websocket.accept() + loop = asyncio.get_running_loop() + + # Retrieve user's desktop display preference from client query params + client_wants_gui = websocket.query_params.get("gui", "false").lower() == "true" + + # Force gui = False to run PyBullet completely headless (DIRECT mode) + gui = False + + camera_state = { + "target": [0.5, 0.0, 0.3], + "dist": 1.3, + "yaw": 45.0, + "pitch": -35.0 + } + + async with executor_lock: + def init_sim(): + global current_sim + with pybullet_lock: + is_connected = False + if current_sim is not None and current_sim.client is not None: + try: + is_connected = pb.isConnected(current_sim.client) + except Exception: + is_connected = False + + if is_connected and current_sim.gui == gui: + current_sim.reset_objects(seed=0) + current_sim.controller.reset_to_home() + for _ in range(5): + pb.stepSimulation(physicsClientId=current_sim.client) + else: + if is_connected: + try: + current_sim.disconnect() + except Exception as e: + print(f"[Teardown Error] {e}") + current_sim = PandaSimulation(gui=gui, seed=0) + + await asyncio.to_thread(init_sim) + # Apply the client's visibility preference to show/hide the PyBullet GUI window on the desktop + await asyncio.to_thread(set_pybullet_window_visibility, client_wants_gui) + + try: + # Send static scene configuration + init_payload = await asyncio.to_thread(get_init_payload, current_sim) + await websocket.send_json(init_payload) + # Send the first simulation state to sync objects and joints + state_payload = await asyncio.to_thread(get_simulation_state_payload, current_sim) + if state_payload: + await websocket.send_json(state_payload) + + while True: + data = await websocket.receive_text() + payload = json.loads(data) + + p_type = payload.get("type") + if p_type == "run": + prompt = payload.get("prompt", "") + use_mock = payload.get("mock", False) + asyncio.create_task( + asyncio.to_thread( + run_pipeline_threadsafe, + websocket, + prompt, + loop, + use_mock + ) + ) + + elif p_type == "reset": + async with executor_lock: + def reset_sim(): + with pybullet_lock: + current_sim.reset_objects(seed=0) + current_sim.controller.reset_to_home() + await asyncio.to_thread(reset_sim) + + state_payload = await asyncio.to_thread(get_simulation_state_payload, current_sim) + if state_payload: + await websocket.send_json(state_payload) + await websocket.send_json({"type": "log", "message": "🔄 Đã reset môi trường mô phỏng."}) + + elif p_type == "update_object_pose": + name = payload.get("name") + pos = payload.get("pos") + ori = payload.get("ori") + async with executor_lock: + def move_obj(): + with pybullet_lock: + oid = current_sim.scene.name_to_id(name) + if oid is not None: + pb.resetBasePositionAndOrientation(oid, pos, ori) + await asyncio.to_thread(move_obj) + + state_payload = await asyncio.to_thread(get_simulation_state_payload, current_sim) + if state_payload: + await websocket.send_json(state_payload) + + elif p_type == "update_joints": + joints_data = payload.get("joints") + async with executor_lock: + def move_joints(): + with pybullet_lock: + for idx, q in enumerate(joints_data[:7]): + pb.resetJointState(current_sim.robot_id, idx, q) + if len(joints_data) >= 11: + pb.resetJointState(current_sim.robot_id, 9, joints_data[9]) + pb.resetJointState(current_sim.robot_id, 10, joints_data[10]) + await asyncio.to_thread(move_joints) + + state_payload = await asyncio.to_thread(get_simulation_state_payload, current_sim) + if state_payload: + await websocket.send_json(state_payload) + elif p_type == "update_robot_ee": + pos = payload.get("pos") + async with executor_lock: + def move_robot_ee(): + with pybullet_lock: + link_state = pb.getLinkState( + current_sim.robot_id, + current_sim.controller.ee_index, + physicsClientId=current_sim.client + ) + ee_ori = link_state[1] + + solution = pb.calculateInverseKinematics( + current_sim.robot_id, + current_sim.controller.ee_index, + pos, + ee_ori, + lowerLimits=current_sim.controller._lower_limits, + upperLimits=current_sim.controller._upper_limits, + jointRanges=current_sim.controller._joint_ranges, + restPoses=current_sim.controller._rest_poses, + maxNumIterations=300, + residualThreshold=1e-5, + physicsClientId=current_sim.client + ) + + for idx, q in enumerate(solution[:7]): + pb.resetJointState( + current_sim.robot_id, + idx, + q, + physicsClientId=current_sim.client + ) + await asyncio.to_thread(move_robot_ee) + + state_payload = await asyncio.to_thread(get_simulation_state_payload, current_sim) + if state_payload: + await websocket.send_json(state_payload) + elif p_type in ("camera_rotate", "camera_pan", "camera_zoom"): + pass + + except WebSocketDisconnect: + print("Client disconnected") + except Exception as e: + print(f"WS Exception: {e}") +if __name__ == "__main__": + port = int(os.environ.get("PORT", 8000)) + uvicorn.run("interactive_server:app", host="0.0.0.0", port=port, reload=False) \ No newline at end of file diff --git a/frontend/layouts/__pycache__/main_layout.cpython-310.pyc b/frontend/layouts/__pycache__/main_layout.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f8a874a668762b591615ff49b8733373abfeb436 Binary files /dev/null and b/frontend/layouts/__pycache__/main_layout.cpython-310.pyc differ diff --git a/frontend/layouts/main_layout.py b/frontend/layouts/main_layout.py new file mode 100644 index 0000000000000000000000000000000000000000..82954cca2ef93a5d29ed27a0b3338de2f509594c --- /dev/null +++ b/frontend/layouts/main_layout.py @@ -0,0 +1,85 @@ +import sys +import os +from PySide6.QtCore import Qt, QRect +from PySide6.QtWidgets import QWidget, QVBoxLayout, QFrame + +# Ensure project source root is in path +PROJECT_SRC = os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "..")) +if PROJECT_SRC not in sys.path: + sys.path.insert(0, PROJECT_SRC) + +from frontend.widgets.viewport_widget import ViewportWidget +from frontend.widgets.chat_widget import ChatWidget +from frontend.widgets.log_widget import LogWidget +from frontend.widgets.status_widget import StatusWidget +from frontend.widgets.header_widget import HeaderWidget + +class MainLayout(QWidget): + """ + Main layout widget holding all UI overlays. + Positions widgets using absolute geometries in resizeEvent to match the web HUD look. + """ + def __init__(self, parent=None): + super().__init__(parent) + self.setup_ui() + + def setup_ui(self): + # 1. Background Viewport + self.viewport_widget = ViewportWidget(self) + self.viewport_widget.lower() # Ensure viewport is in background + + # 2. Transparent Sidebar container (left overlay) + self.sidebar_widget = QWidget(self) + self.sidebar_layout = QVBoxLayout(self.sidebar_widget) + self.sidebar_layout.setContentsMargins(0, 0, 0, 0) + self.sidebar_layout.setSpacing(20) + + self.status_widget = StatusWidget(self.sidebar_widget) + self.log_widget = LogWidget(self.sidebar_widget) + + self.sidebar_layout.addWidget(self.status_widget) + self.sidebar_layout.addWidget(self.log_widget, 1) # log takes up expanding space + + # 3. Header overlay (top-right overlay) + self.header_widget = HeaderWidget(self) + + # 4. Chat controls overlay (bottom-right overlay) + self.chat_widget = ChatWidget(self) + + # Ensure overlays are on top of viewport + self.sidebar_widget.raise_() + self.header_widget.raise_() + self.chat_widget.raise_() + + def resizeEvent(self, event): + super().resizeEvent(event) + width = self.width() + height = self.height() + + # Viewport covers entire screen + self.viewport_widget.setGeometry(0, 0, width, height) + + # Layout metrics matching index.css + margin = 20 + sidebar_width = 360 + + # Sidebar positioning (left) + self.sidebar_widget.setGeometry(margin, margin, sidebar_width, height - 2 * margin) + + # Header positioning (top right) + header_left = sidebar_width + margin + 10 # 390 + header_w = max(200, width - header_left - margin) + self.header_widget.setGeometry(header_left, margin, header_w, 110) + + # Chat container positioning (centered on remaining horizontal space, near bottom) + chat_width = 650 + chat_height = 160 + + # Calculate horizontal center for chat in the right-pane area + chat_x = header_left + (header_w - chat_width) // 2 + # Clamp to avoid sidebar overlap if window is resized narrow + chat_x = max(header_left, chat_x) + chat_w = min(chat_width, width - chat_x - margin) + + chat_y = height - chat_height - margin - 10 + self.chat_widget.setGeometry(chat_x, chat_y, chat_w, chat_height) diff --git a/frontend/overlay_app.py b/frontend/overlay_app.py new file mode 100644 index 0000000000000000000000000000000000000000..d693ff4412a5395eff303f2c56ddd0acc0df2df9 --- /dev/null +++ b/frontend/overlay_app.py @@ -0,0 +1,408 @@ +import sys +import os +import time +import json +import argparse +import tkinter as tk +from tkinter import font as tkfont +from tkinter import messagebox +import pybullet as pb + +# Ensure project source root is in path +PROJECT_SRC = os.path.abspath(os.path.join(os.path.dirname(__file__), "..")) +if PROJECT_SRC not in sys.path: + sys.path.insert(0, PROJECT_SRC) + +from dotenv import load_dotenv +load_dotenv() + +from main import PandaSimulation +from llm_panda.llm_agent import LLMAgent, RemoteLLMPlanner, RuleBasedPlanner +from llm_panda.plan_verifier import PlanVerifier + +# Preset prompts matching CLI +PRESETS = { + "repair": ( + "🔌 Sửa đồ điện tử", + "Tôi cần chuẩn bị bàn để sửa một thiết bị điện tử nhỏ. Hãy dọn các vật chứa nước ra xa, cất đồ nguy hiểm vào khu an toàn, đặt công cụ gần trung tâm, và dọn khay đựng dụng cụ trước nếu bị chặn." + ), + "child": ( + "🧸 Trẻ em chơi", + "Hãy dọn bàn này để một đứa trẻ có thể chơi an sau. Cất ngay tất cả dao, pin tiểu, và đồ thủy tinh dễ vỡ đi. Chỉ để lại khối đồ chơi xếp hình ở giữa. Bỏ rác vào thùng rác." + ), + "study": ( + "📚 Bàn học tập", + "Sắp xếp lại bàn để tôi có thể ngồi học bài tập trung. Để sách/vở gần trung tâm, dọn đồ chơi gây mất tập trung đi, cốc nước để ở góc xa nhưng vẫn giữ lại, bỏ rác vào thùng rác." + ) +} + +class TkinterOverlay: + def __init__(self, on_submit_callback, on_reset_callback, on_exit_callback): + self.on_submit = on_submit_callback + self.on_reset = on_reset_callback + self.on_exit = on_exit_callback + + self.root = tk.Tk() + self.root.title("LLM-Panda Chat Command Overlay") + self.root.attributes("-alpha", 0.90) # Sleek translucent glass + self.root.attributes("-topmost", True) # Float on top of PyBullet OpenGL window + self.root.overrideredirect(True) # Borderless window + self.root.configure(bg="#0f172a") # Dark slate theme + + # Position at bottom center of the screen + screen_width = self.root.winfo_screenwidth() + screen_height = self.root.winfo_screenheight() + width = 700 + height = 220 + x = (screen_width - width) // 2 + y = screen_height - height - 100 # Float above taskbar + self.root.geometry(f"{width}x{height}+{x}+{y}") + + # Dragging logic + self.root.bind("", self.start_drag) + self.root.bind("", self.drag) + + # Fonts + self.custom_font = tkfont.Font(family="Segoe UI", size=9) + self.bold_font = tkfont.Font(family="Segoe UI", size=9, weight="bold") + self.title_font = tkfont.Font(family="Segoe UI", size=10, weight="bold") + + # Top Header Frame + self.header_frame = tk.Frame(self.root, bg="#0f172a") + self.header_frame.pack(fill="x", padx=10, pady=(5, 0)) + + self.title_label = tk.Label( + self.header_frame, text="🤖 LLM-Panda Command Overlay (Drag to move)", + font=self.title_font, fg="#3b82f6", bg="#0f172a", anchor="w" + ) + self.title_label.pack(side="left") + + # Close button in header + self.close_btn = tk.Button( + self.header_frame, text="✕", font=self.title_font, fg="#ef4444", bg="#0f172a", + activebackground="#ef4444", activeforeground="white", bd=0, cursor="hand2", command=self.exit_app + ) + self.close_btn.pack(side="right") + + # Preset buttons row + self.presets_frame = tk.Frame(self.root, bg="#0f172a") + self.presets_frame.pack(fill="x", padx=10, pady=(2, 2)) + + for key, (label, prompt_text) in PRESETS.items(): + btn = tk.Button( + self.presets_frame, text=label, font=self.custom_font, fg="#f8fafc", bg="#1e293b", + activebackground="#334155", activeforeground="#f8fafc", bd=0, padx=8, pady=2, cursor="hand2", + command=lambda p=prompt_text: self.load_preset(p) + ) + btn.pack(side="left", padx=(0, 6)) + + # Logs box with scrollbar + self.log_frame = tk.Frame(self.root, bg="#0f172a") + self.log_frame.pack(fill="both", expand=True, padx=10, pady=5) + + self.scrollbar = tk.Scrollbar(self.log_frame) + self.scrollbar.pack(side="right", fill="y") + + self.log_text = tk.Text( + self.log_frame, height=5, font=self.custom_font, fg="#cbd5e1", bg="#1e293b", + bd=0, highlightthickness=0, yscrollcommand=self.scrollbar.set, selectbackground="#3b82f6" + ) + self.log_text.pack(side="left", fill="both", expand=True) + self.scrollbar.config(command=self.log_text.yview) + + self.log_text.insert("1.0", "Môi trường PyBullet đã sẵn sàng. Hãy chọn kịch bản hoặc nhập lệnh rồi nhấn Enter...\n") + self.log_text.configure(state="disabled") + + # Bottom Input Row + self.input_frame = tk.Frame(self.root, bg="#0f172a") + self.input_frame.pack(fill="x", padx=10, pady=(2, 6)) + + self.entry = tk.Entry( + self.input_frame, font=self.custom_font, fg="#ffffff", bg="#1e293b", + insertbackground="white", bd=0, highlightthickness=1, highlightcolor="#3b82f6", + highlightbackground="#475569" + ) + self.entry.pack(side="left", fill="x", expand=True, ipady=5) + self.entry.bind("", self.submit) + + self.submit_btn = tk.Button( + self.input_frame, text="🚀 Gửi", font=self.bold_font, fg="white", bg="#3b82f6", + activebackground="#2563eb", activeforeground="white", bd=0, padx=15, cursor="hand2", command=self.submit + ) + self.submit_btn.pack(side="left", padx=(8, 0)) + + self.reset_btn = tk.Button( + self.input_frame, text="🔄 Reset", font=self.custom_font, fg="white", bg="#475569", + activebackground="#334155", activeforeground="white", bd=0, padx=12, cursor="hand2", command=self.reset + ) + self.reset_btn.pack(side="left", padx=(6, 0)) + + # Options row + self.options_frame = tk.Frame(self.root, bg="#0f172a") + self.options_frame.pack(fill="x", padx=10, pady=(0, 4)) + + self.mock_var = tk.BooleanVar(value=True) + self.mock_check = tk.Checkbutton( + self.options_frame, text="Chạy Mock Preset Plans (Không tốn API Key)", variable=self.mock_var, + font=self.custom_font, fg="#94a3b8", bg="#0f172a", activebackground="#0f172a", + activeforeground="#f8fafc", selectcolor="#1e293b", bd=0, highlightthickness=0 + ) + self.mock_check.pack(side="left") + + def start_drag(self, event): + self.x = event.x + self.y = event.y + + def drag(self, event): + deltax = event.x - self.x + deltay = event.y - self.y + x = self.root.winfo_x() + deltax + y = self.root.winfo_y() + deltay + self.root.geometry(f"+{x}+{y}") + + def load_preset(self, prompt_text): + self.entry.delete(0, "end") + self.entry.insert(0, prompt_text) + self.entry.focus() + + def write_log(self, text): + self.log_text.configure(state="normal") + self.log_text.insert("end", f"> {text}\n") + self.log_text.see("end") + self.log_text.configure(state="disabled") + self.root.update() + + def submit(self, event=None): + prompt = self.entry.get().strip() + if not prompt: + return + self.entry.delete(0, "end") + self.write_log(f"Lệnh của bạn: '{prompt}'") + + self.entry.configure(state="disabled") + self.submit_btn.configure(state="disabled") + self.reset_btn.configure(state="disabled") + self.root.update() + + try: + self.on_submit(prompt, self.mock_var.get()) + finally: + self.entry.configure(state="normal") + self.submit_btn.configure(state="normal") + self.reset_btn.configure(state="normal") + self.root.update() + + def reset(self): + self.on_reset() + self.write_log("🔄 Đã reset môi trường bàn làm việc về ban đầu.") + + def exit_app(self): + if messagebox.askokcancel("Thoát", "Bạn muốn thoát ứng dụng và đóng PyBullet?"): + self.on_exit() + + def update(self): + try: + client_id = getattr(self, "sim", None) and self.sim.client + if client_id is not None and not pb.isConnected(client_id): + os._exit(0) + except Exception: + pass + self.root.update() + +def compute_and_format_score(sim: PandaSimulation, plan: list, executed_successfully: bool): + """Calculates rearrangement score based on final object locations and collisions.""" + score = 100 + details = [] + + # Check target placement if we had a plan + target_location = None + target_object = None + for step in plan: + if step.get("function") in ("place_at", "place_down", "move_to"): + args = step.get("args", {}) + if "location_id" in args: + target_location = args["location_id"] + if step.get("function") == "pick_up": + target_object = step.get("args", {}).get("object_id") + + if target_object and target_location: + obj_id = sim.scene.name_to_id(target_object) + if obj_id is not None: + pos, _ = pb.getBasePositionAndOrientation(obj_id) + current_loc = sim.scene.classify_location(pos) + if current_loc == target_location: + details.append(f"✅ **Đã đặt {target_object} đúng vị trí {target_location}**: +50 điểm") + else: + details.append(f"❌ **{target_object} chưa đến đúng vị trí {target_location} (đang ở {current_loc})**: -50 điểm") + score -= 50 + else: + details.append(f"❌ **Không tìm thấy vật thể {target_object}**: -50 điểm") + score -= 50 + else: + details.append("ℹ️ Không có yêu cầu di chuyển vật thể cụ thể nào được phát hiện.") + + # Knock detection + knocked_count = 0 + for oid in sim.scene.object_ids: + if oid == sim.scene.name_to_id(target_object): + continue + pos, _ = pb.getBasePositionAndOrientation(oid) + loc = sim.scene.classify_location(pos) + if loc == "elsewhere": + name = sim.scene.get_name(oid) + details.append(f"⚠️ **Vật thể '{name}' bị lệch khỏi vị trí quy định**: -15 điểm") + score -= 15 + knocked_count += 1 + + if knocked_count == 0: + details.append("✅ **Không có vật thể nào khác bị va chạm hay xê dịch**: +30 điểm") + else: + score = max(0, score) + + # Execution success + if executed_successfully: + details.append("✅ **Thực thi toàn bộ kế hoạch thành công**: +20 điểm") + else: + details.append("❌ **Thực thi gặp lỗi gián đoạn**: -30 điểm") + score -= 30 + + score = max(0, min(100, score)) + + md = f"### 🏆 Rearrangement Evaluation Report\n\n**Tổng điểm: {score}/100**\n\n**Chi tiết:**\n" + "\n".join([f"- {d}" for d in details]) + return score, md + +class AppOrchestrator: + def __init__(self, is_mock: bool = True): + self.is_mock = is_mock + + self.overlay = TkinterOverlay( + on_submit_callback=self.handle_submit, + on_reset_callback=self.handle_reset, + on_exit_callback=self.handle_exit + ) + + # Configure LLM Agent based on parameter + from llm_panda.llm_agent import LLMAgent, RemoteLLMPlanner, RuleBasedPlanner + if self.is_mock: + planner = RuleBasedPlanner() + else: + planner = RemoteLLMPlanner() + agent = LLMAgent(planner=planner) + + self.overlay.write_log("Đang mở cửa sổ OpenGL của Pybullet...") + self.sim = PandaSimulation(gui=True, agent=agent) + + self.overlay.sim = self.sim + self.overlay.write_log("✅ Môi trường mô phỏng Pybullet đã sẵn sàng!") + + def handle_submit(self, prompt: str, use_mock: bool): + self.overlay.write_log("⏳ [1/5] Đang lập kế hoạch hành động...") + self.overlay.update() + + # Re-configure agent planner on demand + from llm_panda.llm_agent import LLMAgent, RemoteLLMPlanner, RuleBasedPlanner + if use_mock: + planner = RuleBasedPlanner() + self.overlay.write_log("✅ [1] Đang sử dụng RuleBasedPlanner (Offline)") + else: + api_key = os.environ.get("OPENAI_API_KEY") or os.environ.get("LLM_API_KEY") + if not api_key: + self.overlay.write_log("❌ [1] Lỗi: Không tìm thấy OPENAI_API_KEY/LLM_API_KEY. Vui lòng chọn Mock.") + return + planner = RemoteLLMPlanner() + self.overlay.write_log(f"✅ [1] Đang sử dụng RemoteLLMPlanner (Model: {planner.model})") + + self.sim.agent = LLMAgent(planner=planner) + + # Define reachability check for scene state + def reachability_fn(oid): + cls = self.sim.scene.get_class(oid) + try: + grasp_pos, grasp_ori = self.sim.grasp_planner.compute_grasp_pose(oid, cls) + return self.sim.controller.is_reachable(grasp_pos, grasp_ori) + except Exception: + return False + + carried_name = self.sim.scene.get_name(self.sim._carried) if self.sim._carried is not None else None + scene_state = self.sim.scene.get_scene_state(reachability_fn=reachability_fn, carried_object=carried_name) + state_text = json.dumps(scene_state, indent=2) + + try: + plan = self.sim.agent.plan(prompt, state_text) + self.overlay.write_log("✅ LLM Planner tạo kế hoạch thành công.") + except Exception as e: + self.overlay.write_log(f"❌ LLM Planner thất bại: {e}") + return + + for idx, step in enumerate(plan, 1): + self.overlay.write_log(f" Bước {idx}: {step['function']}({step.get('args', {})})") + + self.overlay.write_log("⏳ [2/5] Đang kiểm tra luật an toàn (Validator)...") + self.overlay.update() + + try: + from llm_panda.plan_verifier import PlanVerifier + warnings = PlanVerifier.check(plan, scene_state) + if not warnings: + self.overlay.write_log("✅ [2] Kế hoạch hợp lệ.") + else: + self.overlay.write_log(f"⚠️ [2] Validator phát hiện {len(warnings)} cảnh báo.") + for w in warnings: + self.overlay.write_log(f" - Cảnh báo: {w}") + except Exception as e: + self.overlay.write_log(f"❌ Lỗi kiểm tra kế hoạch: {e}") + return + + self.overlay.write_log("⏳ [3/5] Bắt đầu thực thi trên Robot (Live Action)...") + self.overlay.update() + + # Hook step simulation to update Tkinter + original_step = pb.stepSimulation + def wrapped_step(): + original_step() + self.overlay.update() + pb.stepSimulation = wrapped_step + + executed_successfully = True + try: + for i, step in enumerate(plan, 1): + self.overlay.write_log(f"🤖 Đang chạy bước {i}/{len(plan)}: {step['function']}...") + self.sim._execute(step, verbose=True) + self.overlay.write_log("✅ [3] Robot thực thi thành công toàn bộ kế hoạch!") + except Exception as e: + self.overlay.write_log(f"❌ Lỗi nghiêm trọng trong lúc thực thi: {e}") + executed_successfully = False + finally: + pb.stepSimulation = original_step + + self.overlay.write_log("⏳ [5/5] Đang tính toán điểm rearrangement...") + self.overlay.update() + + score_val, score_md = compute_and_format_score(self.sim, plan, executed_successfully) + + messagebox.showinfo("Báo cáo kết quả Rearrangement", f"Rearrangement Score: {score_val:.1f}/100.0\n\nXem chi tiết điểm trong cửa sổ terminal chính.") + print("\n" + score_md) + + def handle_reset(self): + self.sim.reset_objects(seed=0) + self.sim.controller.reset_to_home() + + def handle_exit(self): + try: + self.sim.disconnect() + except Exception: + pass + os._exit(0) + + def run(self): + self.overlay.root.mainloop() + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description="LLM-Panda Desktop Command Overlay App") + parser.add_argument("--mock", action="store_true", default=True, help="Chạy mock preset mặc định") + parser.add_argument("--no-mock", dest="mock", action="store_false", help="Sử dụng LLM API trực tiếp") + + args = parser.parse_args() + + app = AppOrchestrator(is_mock=args.mock) + app.run() diff --git a/frontend/threads/__pycache__/llm_thread.cpython-310.pyc b/frontend/threads/__pycache__/llm_thread.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ec2713874af6e41aee38d6ea1334b91aa0e1e1bd Binary files /dev/null and b/frontend/threads/__pycache__/llm_thread.cpython-310.pyc differ diff --git a/frontend/threads/__pycache__/simulation_thread.cpython-310.pyc b/frontend/threads/__pycache__/simulation_thread.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2c9e8a3b48782f2e8a4b38a8e0c5f5e8792a2e4f Binary files /dev/null and b/frontend/threads/__pycache__/simulation_thread.cpython-310.pyc differ diff --git a/frontend/threads/llm_thread.py b/frontend/threads/llm_thread.py new file mode 100644 index 0000000000000000000000000000000000000000..da7f9c600ac6dc5c9eab7df016cf3e54d42cc637 --- /dev/null +++ b/frontend/threads/llm_thread.py @@ -0,0 +1,74 @@ +import sys +import os +import json +import traceback +from PySide6.QtCore import QThread, Signal + +# Ensure project source root is in path +PROJECT_SRC = os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "..")) +if PROJECT_SRC not in sys.path: + sys.path.insert(0, PROJECT_SRC) + +from llm_panda.llm_agent import LLMAgent, RemoteLLMPlanner, RuleBasedPlanner + +class LLMThread(QThread): + """ + Background thread to run the LLM Planner. + Prevents the PySide6 UI from freezing during remote API calls. + """ + plan_ready = Signal(list) + log_message = Signal(str, str) # message, type (info, success, warn, error) + failed = Signal(str) + + def __init__(self, prompt: str, scene_state: dict, use_mock: bool = True): + super().__init__() + self.prompt = prompt + self.scene_state = scene_state + self.use_mock = use_mock + + def run(self): + try: + self.log_message.emit("⏳ [1/5] Đang lập kế hoạch (LLM Planner)...", "info") + + if self.use_mock: + planner = RuleBasedPlanner() + self.log_message.emit("✅ [1] Đang sử dụng RuleBasedPlanner (Offline)", "success") + else: + # Retrieve API keys from env + api_key = os.environ.get("OPENAI_API_KEY") or os.environ.get("LLM_API_KEY") + if not api_key: + error_msg = "❌ [1] Lỗi: Không tìm thấy OPENAI_API_KEY / LLM_API_KEY. Vui lòng chọn Mock." + self.log_message.emit(error_msg, "error") + self.failed.emit(error_msg) + return + planner = RemoteLLMPlanner() + self.log_message.emit(f"✅ [1] Đang sử dụng RemoteLLMPlanner (Model: {planner.model})", "success") + + agent = LLMAgent(planner=planner) + state_text = json.dumps(self.scene_state, indent=2) + + # Run planning + plan = agent.plan(self.prompt, state_text) + + # Send results + plan_steps = [] + for idx, step in enumerate(plan, 1): + func = step.get("function") + args = step.get("args", {}) + obj = args.get("object_id") or args.get("location_id") or "" + plan_steps.append({ + "step": idx, + "skill": func, + "object": obj, + "args": args + }) + + self.log_message.emit(f"✅ [1] Đã tạo kế hoạch: {len(plan)} bước.", "success") + self.plan_ready.emit(plan_steps) + + except Exception as e: + error_trace = traceback.format_exc() + print(f"[LLMThread Error] {error_trace}") + error_msg = f"❌ [1] Lập kế hoạch thất bại: {str(e)}" + self.log_message.emit(error_msg, "error") + self.failed.emit(error_msg) diff --git a/frontend/threads/simulation_thread.py b/frontend/threads/simulation_thread.py new file mode 100644 index 0000000000000000000000000000000000000000..5031471597d9096bc9cdd489e05500187d991821 --- /dev/null +++ b/frontend/threads/simulation_thread.py @@ -0,0 +1,424 @@ +import sys +import os +import time +import math +import traceback +import threading +from PySide6.QtCore import QThread, Signal, Slot, QTimer, QMutex, QMutexLocker + +# Ensure project source root is in path +PROJECT_SRC = os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "..")) +if PROJECT_SRC not in sys.path: + sys.path.insert(0, PROJECT_SRC) + +import pybullet as pb +import numpy as np +import cv2 + +from main import PandaSimulation +from llm_panda.plan_verifier import PlanVerifier + +def set_pybullet_window_visibility(visible: bool): + """Finds the PyBullet GUI window on Windows and sets its visibility by moving it on/off-screen.""" + if sys.platform != "win32": + return False + import ctypes + + EnumWindowsProc = ctypes.WINFUNCTYPE(ctypes.c_bool, ctypes.c_void_p, ctypes.c_void_p) + + for _ in range(30): + found_hwnd = [] + + def foreach_window(hwnd, lParam): + length = ctypes.windll.user32.GetWindowTextLengthW(hwnd) + buff = ctypes.create_unicode_buffer(length + 1) + ctypes.windll.user32.GetWindowTextW(hwnd, buff, length + 1) + title = buff.value + if "bullet physics examplebrowser" in title.lower(): + found_hwnd.append(hwnd) + return False + return True + + ctypes.windll.user32.EnumWindows(EnumWindowsProc(foreach_window), 0) + if found_hwnd: + hwnd = found_hwnd[0] + # Ensure the window is shown/restored from minimized state first (SW_SHOW = 5) + ctypes.windll.user32.ShowWindow(hwnd, 5) + + # SWP_NOSIZE = 0x0001, SWP_NOZORDER = 0x0004 + if visible: + # Move window to visible region + ctypes.windll.user32.SetWindowPos(hwnd, 0, 100, 100, 0, 0, 0x0001 | 0x0004) + else: + # Move window far off-screen to hide it without destroying OpenGL context + ctypes.windll.user32.SetWindowPos(hwnd, 0, -10000, -10000, 0, 0, 0x0001 | 0x0004) + print(f"[Window Visibility] Set PyBullet window (HWND: {hwnd}) visibility to: {visible}", flush=True) + return True + time.sleep(0.1) + return False + +class SimulationThread(QThread): + """ + Manages the PyBullet simulator. Handles stepping the physics, running plans, + camera movements, resetting, and emitting captured frames to the UI. + """ + frame_ready = Signal(object) + log_message = Signal(str, str) + fps_updated = Signal(float) + init_completed = Signal() + step_completed = Signal(int) # step number (1-based) + finished = Signal(bool, str, float) # executed_successfully, score_md, score_val + + def __init__(self): + super().__init__() + self.sim = None + self.pybullet_lock = threading.RLock() + self.camera_state = { + "target": [0.5, 0.0, 0.3], + "dist": 1.3, + "yaw": 45.0, + "pitch": -35.0 + } + self.show_gui_window = True + self.running = True + self.last_view_matrix = None + self.last_proj_matrix = None + + # Command Queue variables + self.pending_command = None + self.pending_data = None + self.cmd_lock = QMutex() + + # Frame rate tracking + self.last_frame_time = 0.0 + self.frame_count = 0 + self.fps_timer_time = 0.0 + + def run(self): + # 1. Initialize PyBullet Simulation in DIRECT mode + self.log_message.emit("🔌 Khởi tạo môi trường mô phỏng PyBullet...", "info") + with self.pybullet_lock: + self.sim = PandaSimulation(gui=False, seed=0) + + self.init_completed.emit() + self.log_message.emit("✅ Môi trường mô phỏng PyBullet đã sẵn sàng!", "success") + + # Stream the initial frame + self.capture_and_emit_frame() + + # 2. Start Simulation Loop + self.last_frame_time = time.time() + self.fps_timer_time = time.time() + + while self.running: + # Check for commands from UI thread + cmd = None + data = None + + self.cmd_lock.lock() + if self.pending_command is not None: + cmd = self.pending_command + data = self.pending_data + self.pending_command = None + self.pending_data = None + self.cmd_lock.unlock() + + if cmd is not None: + self.process_command(cmd, data) + + # Perform a continuous idle step & render at ~30 FPS if not executing a plan + # (PyBullet real-time physics is active, so we just capture and emit frames) + curr_time = time.time() + elapsed = curr_time - self.last_frame_time + if elapsed >= 0.033: # limit to ~30 FPS to save CPU + self.capture_and_emit_frame() + self.track_fps(curr_time) + self.last_frame_time = curr_time + + time.sleep(0.005) + + def track_fps(self, current_time): + self.frame_count += 1 + interval = current_time - self.fps_timer_time + if interval >= 1.0: + fps = self.frame_count / interval + self.fps_updated.emit(fps) + self.frame_count = 0 + self.fps_timer_time = current_time + + def capture_and_emit_frame(self): + with self.pybullet_lock: + if self.sim is None or self.sim.client is None or not pb.isConnected(self.sim.client): + return + + try: + target = self.camera_state["target"] + dist = self.camera_state["dist"] + yaw = self.camera_state["yaw"] + pitch = self.camera_state["pitch"] + + width = 640 + height = 360 + renderer = pb.ER_TINY_RENDERER + + view_matrix = pb.computeViewMatrixFromYawPitchRoll( + cameraTargetPosition=target, + distance=dist, + yaw=yaw, + pitch=pitch, + roll=0.0, + upAxisIndex=2, + physicsClientId=self.sim.client + ) + proj_matrix = pb.computeProjectionMatrixFOV( + fov=55, aspect=width/height, nearVal=0.1, farVal=5.0, + physicsClientId=self.sim.client + ) + + # Store view & projection matrices for picking + self.last_view_matrix = view_matrix + self.last_proj_matrix = proj_matrix + + _, _, rgba, _, _ = pb.getCameraImage( + width=width, height=height, + viewMatrix=view_matrix, + projectionMatrix=proj_matrix, + renderer=renderer, + physicsClientId=self.sim.client + ) + + img_np = np.array(rgba, dtype=np.uint8).reshape(height, width, 4) + self.frame_ready.emit(img_np) + except Exception as e: + print(f"[SimulationThread Frame Capture Error] {e}") + + def queue_command(self, cmd: str, data=None): + QMutexLocker(self.cmd_lock) + self.pending_command = cmd + self.pending_data = data + + def process_command(self, cmd: str, data): + if cmd == "reset": + self.log_message.emit("🔄 Đang reset môi trường mô phỏng...", "info") + with self.pybullet_lock: + self.sim.reset_objects(seed=0) + self.sim.controller.reset_to_home() + self.log_message.emit("🔄 Đã reset môi trường mô phỏng.", "success") + self.capture_and_emit_frame() + + elif cmd == "gui_toggle": + self.show_gui_window = bool(data) + self.log_message.emit(f"👁️ Hiển thị cửa sổ PyBullet (Chỉ khả dụng ở chế độ GUI): {self.show_gui_window}", "info") + + elif cmd == "camera_rotate": + dx, dy = data + self.camera_state["yaw"] += dx * 0.4 + self.camera_state["pitch"] = max(-89, min(-5, self.camera_state["pitch"] - dy * 0.4)) + + elif cmd == "camera_pan": + dx, dy = data + rad_yaw = math.radians(self.camera_state["yaw"]) + rx = -math.sin(rad_yaw) + ry = math.cos(rad_yaw) + ux = -math.cos(rad_yaw) + uy = -math.sin(rad_yaw) + self.camera_state["target"][0] += (rx * dx + ux * dy) * 0.0015 + self.camera_state["target"][1] += (ry * dx + uy * dy) * 0.0015 + + elif cmd == "camera_zoom": + delta = data + self.camera_state["dist"] = max(0.4, min(3.0, self.camera_state["dist"] + delta * 0.0015)) + + elif cmd == "viewport_click": + x, y, w, h = data + self.perform_picking(x, y, w, h) + + elif cmd == "execute_plan": + plan = data + self.run_execution(plan) + + def run_execution(self, plan): + self.log_message.emit("⏳ [3/5] Đang thực thi hành động của robot...", "info") + + # Hook pb.stepSimulation to capture frames during movements + original_step = pb.stepSimulation + last_stream_time = [0.0] + + def wrapped_step(): + original_step() + curr_time = time.time() + if curr_time - last_stream_time[0] >= 0.033: + last_stream_time[0] = curr_time + self.capture_and_emit_frame() + + with self.pybullet_lock: + pb.stepSimulation = wrapped_step + + executed_successfully = True + try: + # Send initial frame + self.capture_and_emit_frame() + + for idx, step in enumerate(plan, 1): + self.log_message.emit(f"🚀 [3/5] Đang chạy bước {idx}/{len(plan)}: {step['skill']}", "info") + # Build executor format step + exec_step = { + "function": step["skill"], + "args": step["args"] + } + with self.pybullet_lock: + self.sim._execute(exec_step, verbose=True) + + self.step_completed.emit(idx) + + self.log_message.emit("✅ [3] Thực thi thành công toàn bộ kế hoạch.", "success") + except Exception as e: + error_trace = traceback.format_exc() + print(f"[SimulationThread Execution Error] {error_trace}") + self.log_message.emit(f"❌ Lỗi trong lúc thực thi mô phỏng: {e}", "error") + executed_successfully = False + finally: + with self.pybullet_lock: + pb.stepSimulation = original_step + + # Step 5: Scoring + self.log_message.emit("⏳ [5/5] Đang tính toán điểm sắp xếp...", "info") + score_val, score_md = self.compute_and_format_score(plan, executed_successfully) + + self.finished.emit(executed_successfully, score_md, score_val) + + def compute_and_format_score(self, plan: list, executed_successfully: bool): + """Calculates rearrangement score based on final object locations and collisions.""" + with self.pybullet_lock: + score = 100 + details = [] + + # Check target placement if we had a plan + target_location = None + target_object = None + for step in plan: + func = step.get("skill") + args = step.get("args", {}) + if func in ("place_at", "place_down", "move_to"): + if "location_id" in args: + target_location = args["location_id"] + if func == "pick_up": + target_object = args.get("object_id") + + if target_object and target_location: + obj_id = self.sim.scene.name_to_id(target_object) + if obj_id is not None: + pos, _ = pb.getBasePositionAndOrientation(obj_id) + current_loc = self.sim.scene.classify_location(pos) + if current_loc == target_location: + details.append(f"✅ **Đã đặt {target_object} đúng vị trí {target_location}**: +50 điểm") + else: + details.append(f"❌ **{target_object} chưa đến đúng vị trí {target_location} (đang ở {current_loc})**: -50 điểm") + score -= 50 + else: + details.append(f"❌ **Không tìm thấy vật thể {target_object}**: -50 điểm") + score -= 50 + else: + details.append("ℹ️ Không có yêu cầu di chuyển vật thể cụ thể nào được phát hiện.") + + # Knock detection + knocked_count = 0 + for oid in self.sim.scene.object_ids: + if oid == self.sim.scene.name_to_id(target_object): + continue + pos, _ = pb.getBasePositionAndOrientation(oid) + loc = self.sim.scene.classify_location(pos) + if loc == "elsewhere": + name = self.sim.scene.get_name(oid) + details.append(f"⚠️ **Vật thể '{name}' bị lệch khỏi vị trí quy định**: -15 điểm") + score -= 15 + knocked_count += 1 + + if knocked_count == 0: + details.append("✅ **Không có vật thể nào khác bị va chạm hay xê dịch**: +30 điểm") + else: + score = max(0, score) + + # Execution success + if executed_successfully: + details.append("✅ **Thực thi toàn bộ kế hoạch thành công**: +20 điểm") + else: + details.append("❌ **Thực thi gặp lỗi gián đoạn**: -30 điểm") + score -= 30 + + score = max(0, min(100, score)) + + md = f"### 🏆 Rearrangement Evaluation Report\n\n**Tổng điểm: {score}/100**\n\n**Chi tiết:**\n" + "\n".join([f"- {d}" for d in details]) + return score, md + + def perform_picking(self, x, y, w, h): + """Calculates 3D ray from screen coordinates and tests for intersection in PyBullet.""" + with self.pybullet_lock: + if self.sim is None or self.last_view_matrix is None or self.last_proj_matrix is None: + return + + try: + # NDC (Normalized Device Coordinates) + ndc_x = (2.0 * x) / w - 1.0 + ndc_y = 1.0 - (2.0 * y) / h # Invert Y for OpenGL NDC + + # Near and far vectors in NDC + ndc_near = np.array([ndc_x, ndc_y, -1.0, 1.0]) + ndc_far = np.array([ndc_x, ndc_y, 1.0, 1.0]) + + # Reshape matrix list (16 elements) to 4x4 matrix and transpose (column-major) + view_m = np.array(self.last_view_matrix).reshape(4, 4).T + proj_m = np.array(self.last_proj_matrix).reshape(4, 4).T + + vp_m = proj_m @ view_m + inv_vp_m = np.linalg.inv(vp_m) + + # Transform NDC to World coordinates + world_near = inv_vp_m @ ndc_near + world_near /= world_near[3] + + world_far = inv_vp_m @ ndc_far + world_far /= world_far[3] + + start_point = world_near[:3] + end_point = world_far[:3] + + # Perform PyBullet raycast test + ray_test_result = pb.rayTest(start_point, end_point, physicsClientId=self.sim.client) + if ray_test_result: + hit_id, hit_link, hit_fraction, hit_position, hit_normal = ray_test_result[0] + if hit_id >= 0: + # Safety check: static bodies (plane, table, tray, robot) are not in scene manager registry + if hit_id in self.sim.scene._registry: + name = self.sim.scene.get_name(hit_id) + pos_str = ", ".join([f"{c:.2f}" for c in hit_position]) + self.log_message.emit(f"🖱️ Đã click chọn vật thể '{name}' tại vị trí 3D [{pos_str}]", "success") + else: + # Map static bodies to names + body_name = "Môi trường" + if hasattr(self.sim, 'table_id') and hit_id == self.sim.table_id: + body_name = "Bàn làm việc" + elif hasattr(self.sim, 'tray_id') and hit_id == self.sim.tray_id: + body_name = "Khay chứa đồ" + elif hasattr(self.sim, 'robot_id') and hit_id == self.sim.robot_id: + body_name = "Robot Franka" + elif hit_id == 0: # Plane is always loaded first + body_name = "Sàn nhà" + + pos_str = ", ".join([f"{c:.2f}" for c in hit_position]) + self.log_message.emit(f"🖱️ Đã click chọn: {body_name} tại vị trí 3D [{pos_str}]", "info") + else: + self.log_message.emit("🖱️ Đã click vào không gian trống.", "info") + except Exception as e: + print(f"[Picking Error] {e}") + + def shutdown(self): + self.running = False + # Wait a moment for loop to exit before disconnecting + self.wait(1000) + with self.pybullet_lock: + if self.sim is not None: + try: + self.sim.disconnect() + except Exception: + pass diff --git a/frontend/widgets/__pycache__/chat_widget.cpython-310.pyc b/frontend/widgets/__pycache__/chat_widget.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b726ae5a53d9b721a158f71b5b9a9a5d2596a245 Binary files /dev/null and b/frontend/widgets/__pycache__/chat_widget.cpython-310.pyc differ diff --git a/frontend/widgets/__pycache__/header_widget.cpython-310.pyc b/frontend/widgets/__pycache__/header_widget.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..101b6b4ecb68f721ff7f8dc18ef8270962224f66 Binary files /dev/null and b/frontend/widgets/__pycache__/header_widget.cpython-310.pyc differ diff --git a/frontend/widgets/__pycache__/log_widget.cpython-310.pyc b/frontend/widgets/__pycache__/log_widget.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5e1902fa8901349b1e819d952f6d8d4178d3b312 Binary files /dev/null and b/frontend/widgets/__pycache__/log_widget.cpython-310.pyc differ diff --git a/frontend/widgets/__pycache__/score_modal.cpython-310.pyc b/frontend/widgets/__pycache__/score_modal.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3a7e50b6ca4565a13b058e01df898f6506360196 Binary files /dev/null and b/frontend/widgets/__pycache__/score_modal.cpython-310.pyc differ diff --git a/frontend/widgets/__pycache__/status_widget.cpython-310.pyc b/frontend/widgets/__pycache__/status_widget.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b9d5f197adf6644b553ad4fd2865100106fedd1e Binary files /dev/null and b/frontend/widgets/__pycache__/status_widget.cpython-310.pyc differ diff --git a/frontend/widgets/__pycache__/viewport_widget.cpython-310.pyc b/frontend/widgets/__pycache__/viewport_widget.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e8fb8a4f0ac4a86ef6986cd29fb3be79c4f5eb31 Binary files /dev/null and b/frontend/widgets/__pycache__/viewport_widget.cpython-310.pyc differ diff --git a/frontend/widgets/chat_widget.py b/frontend/widgets/chat_widget.py new file mode 100644 index 0000000000000000000000000000000000000000..7ad297dae394439fde67aafc9341cf82d29f5110 --- /dev/null +++ b/frontend/widgets/chat_widget.py @@ -0,0 +1,333 @@ +import sys +import os +from PySide6.QtCore import Qt, Signal, Slot +from PySide6.QtWidgets import ( + QWidget, QVBoxLayout, QHBoxLayout, QScrollArea, QLineEdit, + QPushButton, QLabel, QCheckBox, QFrame, QSizePolicy +) + +class ChatBubble(QFrame): + """A custom widget representing a single chat bubble.""" + def __init__(self, text: str, is_user: bool = True): + super().__init__() + self.layout = QHBoxLayout(self) + self.layout.setContentsMargins(5, 5, 5, 5) + + self.bubble = QFrame() + self.bubble_layout = QVBoxLayout(self.bubble) + self.bubble_layout.setContentsMargins(12, 10, 12, 10) + + self.label = QLabel(text) + self.label.setWordWrap(True) + self.label.setTextInteractionFlags(Qt.TextInteractionFlag.TextSelectableByMouse) + self.bubble_layout.addWidget(self.label) + + self.bubble.setSizePolicy(QSizePolicy.Policy.Preferred, QSizePolicy.Policy.Maximum) + + # Style sheet to mimic index.css design + if is_user: + self.bubble.setStyleSheet(""" + QFrame { + background-color: #1e3a8a; /* Dark Navy Blue */ + border-radius: 12px; + border: 1px solid rgba(255, 255, 255, 0.1); + } + QLabel { + color: #ffffff; + font-size: 13px; + font-weight: 500; + } + """) + self.layout.addStretch() + self.layout.addWidget(self.bubble) + else: + self.bubble.setStyleSheet(""" + QFrame { + background-color: rgba(255, 255, 255, 0.75); /* Light glass bubble */ + border-radius: 12px; + border: 1px solid #1e3a8a; + } + QLabel { + color: #0f172a; + font-size: 13px; + font-weight: 600; + } + """) + self.layout.addWidget(self.bubble) + self.layout.addStretch() + +class ChatWidget(QWidget): + """ + Manages prompt input, conversation history rendering (bubbles), + mock planning options, and action buttons. + """ + command_submitted = Signal(str, bool) # prompt, use_mock + preset_clicked = Signal(str) + reset_clicked = Signal() + gui_toggled = Signal(bool) + + def __init__(self, parent=None): + super().__init__(parent) + self.setup_ui() + + def setup_ui(self): + self.main_layout = QVBoxLayout(self) + self.main_layout.setSpacing(10) + self.main_layout.setContentsMargins(0, 0, 0, 0) + + # 1. Conversation History (Scrollable Area) + self.scroll_area = QScrollArea() + self.scroll_area.setWidgetResizable(True) + self.scroll_area.setHorizontalScrollBarPolicy(Qt.ScrollBarPolicy.ScrollBarAlwaysOff) + self.scroll_area.setStyleSheet(""" + QScrollArea { + background: transparent; + border: none; + } + QWidget#scroll_content { + background: transparent; + } + """) + + self.scroll_content = QWidget() + self.scroll_content.setObjectName("scroll_content") + self.history_layout = QVBoxLayout(self.scroll_content) + self.history_layout.setSpacing(10) + self.history_layout.addStretch() # Keep messages pinned to bottom + + self.scroll_area.setWidget(self.scroll_content) + self.main_layout.addWidget(self.scroll_area) + + # 2. Plan Display Area (Task Plan from LLM) + self.plan_frame = QFrame() + self.plan_frame.setStyleSheet(""" + QFrame { + background: rgba(255, 255, 255, 0.65); + border: 1px solid rgba(0, 0, 0, 0.08); + border-radius: 10px; + } + """) + self.plan_layout = QVBoxLayout(self.plan_frame) + self.plan_layout.setContentsMargins(10, 10, 10, 10) + + self.plan_title = QLabel("📋 TASK PLAN") + self.plan_title.setStyleSheet("font-weight: 700; color: #1e3a8a; font-size: 11px;") + self.plan_layout.addWidget(self.plan_title) + + self.plan_list_container = QFrame() + self.plan_list_container.setStyleSheet("background: transparent; border: none;") + self.plan_list_layout = QVBoxLayout(self.plan_list_container) + self.plan_list_layout.setSpacing(6) + self.plan_list_layout.setContentsMargins(0, 5, 0, 0) + + self.plan_placeholder = QLabel("Chưa có kế hoạch...") + self.plan_placeholder.setStyleSheet("color: #1e293b; font-style: italic;") + self.plan_list_layout.addWidget(self.plan_placeholder) + + self.plan_layout.addWidget(self.plan_list_container) + self.main_layout.addWidget(self.plan_frame) + self.plan_items = [] + + # 3. Input form (Field + Submit) + input_layout = QHBoxLayout() + input_layout.setSpacing(10) + + self.chat_input = QLineEdit() + self.chat_input.setPlaceholderText("Nhập yêu cầu dọn bàn... (e.g. 'Sắp xếp bàn học tập')") + self.chat_input.setStyleSheet(""" + QLineEdit { + background: rgba(255, 255, 255, 0.75); + border: 2px solid #1e3a8a; + border-radius: 12px; + padding: 12px 18px; + color: #0f172a; + font-size: 14px; + font-weight: 600; + } + QLineEdit:focus { + border-color: #1d4ed8; + background: rgba(255, 255, 255, 0.9); + } + """) + self.chat_input.returnPressed.connect(self.submit_command) + input_layout.addWidget(self.chat_input) + + self.submit_btn = QPushButton("🚀") + self.submit_btn.setToolTip("Gửi yêu cầu") + self.submit_btn.setStyleSheet(""" + QPushButton { + background-color: #1e3a8a; + color: white; + border: none; + border-radius: 12px; + min-width: 46px; + min-height: 46px; + font-size: 16px; + } + QPushButton:hover { + background-color: #1d4ed8; + } + QPushButton:pressed { + transform: scale(0.98); + } + QPushButton:disabled { + background-color: rgba(30, 58, 138, 0.4); + } + """) + self.submit_btn.clicked.connect(self.submit_command) + input_layout.addWidget(self.submit_btn) + + self.main_layout.addLayout(input_layout) + + # 4. Chat Options Row (Checkboxes + Reset) + options_layout = QHBoxLayout() + options_layout.setContentsMargins(5, 0, 5, 0) + + self.mock_toggle = QCheckBox("Use Mock Preset Plans") + self.mock_toggle.setChecked(True) + self.mock_toggle.setStyleSheet(""" + QCheckBox { + color: #0f172a; + font-weight: 600; + font-size: 11px; + } + QCheckBox::indicator { + width: 14px; + height: 14px; + } + """) + options_layout.addWidget(self.mock_toggle) + + self.gui_toggle = QCheckBox("Hiển thị cửa sổ PyBullet") + self.gui_toggle.setChecked(True) + self.gui_toggle.setStyleSheet(""" + QCheckBox { + color: #0f172a; + font-weight: 600; + font-size: 11px; + } + """) + self.gui_toggle.toggled.connect(self.gui_toggled.emit) + options_layout.addWidget(self.gui_toggle) + + options_layout.addStretch() + + self.reset_btn = QPushButton("🔄 Reset Scene") + self.reset_btn.setStyleSheet(""" + QPushButton { + background: transparent; + border: none; + color: #1d4ed8; + font-weight: 700; + font-size: 11px; + } + QPushButton:hover { + color: #0f172a; + text-decoration: underline; + } + """) + self.reset_btn.clicked.connect(self.reset_clicked.emit) + options_layout.addWidget(self.reset_btn) + + self.main_layout.addLayout(options_layout) + + def add_message(self, text: str, is_user: bool = True): + # Insert bubble above the stretch item + bubble = ChatBubble(text, is_user) + self.history_layout.insertWidget(self.history_layout.count() - 1, bubble) + # Scroll to bottom + self.scroll_area.verticalScrollBar().setValue(self.scroll_area.verticalScrollBar().maximum()) + + def set_prompt_text(self, text: str): + self.chat_input.setText(text) + self.chat_input.setFocus() + + def submit_command(self): + prompt = self.chat_input.text().strip() + if not prompt: + return + + self.add_message(prompt, is_user=True) + self.chat_input.clear() + + self.command_submitted.emit(prompt, self.mock_toggle.isChecked()) + + def display_plan(self, plan_steps): + self.clear_plan() + + if not plan_steps: + return + + # Remove placeholder + self.plan_placeholder.hide() + + for step in plan_steps: + item = QFrame() + item.setObjectName(f"plan-step-{step['step']}") + item.setStyleSheet(""" + QFrame { + background: rgba(255, 255, 255, 0.4); + border-radius: 6px; + border-left: 3px solid rgba(0, 0, 0, 0.1); + padding: 6px 10px; + } + QFrame#plan-step-{step} { + background: rgba(37, 99, 235, 0.08); + border-left-color: #1e3a8a; + } + """) + + args_str = ", ".join([f"{k}:{v}" for k, v in step['args'].items()]) + text = f"Step {step['step']}: {step['skill']}({step['object']})" + + lbl_layout = QHBoxLayout(item) + lbl_layout.setContentsMargins(5, 2, 5, 2) + + lbl_main = QLabel(text) + lbl_main.setStyleSheet("font-weight: 600; color: #000000; font-size: 12px; border: none; background: transparent;") + lbl_args = QLabel(args_str) + lbl_args.setStyleSheet("font-size: 10px; color: #1e293b; opacity: 0.8; border: none; background: transparent;") + lbl_args.setAlignment(Qt.AlignmentFlag.AlignRight | Qt.AlignmentFlag.AlignVCenter) + + lbl_layout.addWidget(lbl_main) + lbl_layout.addStretch() + lbl_layout.addWidget(lbl_args) + + self.plan_list_layout.addWidget(item) + self.plan_items.append((step['step'], item, lbl_main)) + + def mark_step_completed(self, step_idx): + for idx, item, lbl in self.plan_items: + if idx == step_idx: + item.setStyleSheet(""" + QFrame { + background: rgba(255, 255, 255, 0.4); + border-radius: 6px; + border-left: 3px solid #064e3b; + padding: 6px 10px; + opacity: 0.6; + } + """) + lbl.setStyleSheet("font-weight: 500; color: rgba(15, 23, 42, 0.4); text-decoration: line-through; border: none; background: transparent;") + + def clear_plan(self): + # Clear plan list items + for _, item, _ in self.plan_items: + self.plan_list_layout.removeWidget(item) + item.deleteLater() + self.plan_items.clear() + self.plan_placeholder.show() + + def lock_inputs(self): + self.chat_input.setDisabled(True) + self.submit_btn.setDisabled(True) + self.mock_toggle.setDisabled(True) + self.gui_toggle.setDisabled(True) + self.reset_btn.setDisabled(True) + + def unlock_inputs(self): + self.chat_input.setEnabled(True) + self.submit_btn.setEnabled(True) + self.mock_toggle.setEnabled(True) + self.gui_toggle.setEnabled(True) + self.reset_btn.setEnabled(True) diff --git a/frontend/widgets/header_widget.py b/frontend/widgets/header_widget.py new file mode 100644 index 0000000000000000000000000000000000000000..c15c59bb52f9e766c27ad5dd324202d81e464ef5 --- /dev/null +++ b/frontend/widgets/header_widget.py @@ -0,0 +1,96 @@ +import sys +import os +from PySide6.QtCore import Qt, Signal, Slot +from PySide6.QtWidgets import ( + QWidget, QVBoxLayout, QHBoxLayout, QLabel, QPushButton +) + +class HeaderWidget(QWidget): + """ + Header Overlay Widget displaying title, camera usage instructions, + and clickable preset task buttons. + """ + preset_clicked = Signal(str) + + # Preset prompts matching index.html / overlay_app.py + PRESETS = [ + { + "label": "🔌 Sửa đồ điện tử", + "prompt": "Tôi cần chuẩn bị bàn để sửa một thiết bị điện tử nhỏ. Hãy dọn các vật chứa nước ra xa, cất đồ nguy hiểm vào khu an toàn, đặt công cụ gần trung tâm, và dọn khay đựng dụng cụ trước nếu bị chặn. Không cần chạm vào đồ dễ vỡ trừ khi thật sự cần thiết." + }, + { + "label": "🧸 Trẻ em chơi", + "prompt": "Hãy dọn bàn này để một đứa trẻ có thể chơi an toàn. Cất ngay tất cả dao, pin tiểu, và đồ thủy tinh dễ vỡ đi. Chỉ để lại khối đồ chơi xếp hình ở giữa. Bỏ rác vào thùng rác." + }, + { + "label": "📚 Bàn học tập", + "prompt": "Sắp xếp lại bàn để tôi có thể ngồi học bài tập trung. Để sách/vở gần trung tâm, dọn đồ chơi gây mất tập trung đi, cốc nước để ở góc xa nhưng vẫn giữ lại, bỏ rác vào thùng rác." + } + ] + + def __init__(self, parent=None): + super().__init__(parent) + self.setup_ui() + + def setup_ui(self): + self.layout = QVBoxLayout(self) + self.layout.setContentsMargins(0, 0, 0, 0) + self.layout.setSpacing(6) + + # Title + self.title_lbl = QLabel("Franka AI Assistant Desktop Interface") + self.title_lbl.setStyleSheet(""" + font-size: 22px; + font-weight: 700; + color: #0f172a; + background: transparent; + border: none; + """) + self.layout.addWidget(self.title_lbl) + + # Instructions + self.instruction_lbl = QLabel( + "Tương tác trực tiếp: Kéo chuột trái để xoay camera, " + "Kéo chuột phải để di chuyển camera, Cuộn chuột để Zoom" + ) + self.instruction_lbl.setStyleSheet(""" + font-size: 12px; + color: #1e293b; + background: transparent; + border: none; + """) + self.layout.addWidget(self.instruction_lbl) + + # Preset Badges layout + self.badges_layout = QHBoxLayout() + self.badges_layout.setSpacing(8) + self.badges_layout.setContentsMargins(0, 5, 0, 0) + + for preset in self.PRESETS: + btn = QPushButton(preset["label"]) + btn.setCursor(Qt.CursorShape.PointingHandCursor) + btn.setStyleSheet(""" + QPushButton { + background-color: rgba(255, 255, 255, 0.75); + border: 1.5px solid #1e3a8a; + color: #000000; + font-weight: 600; + font-size: 12px; + border-radius: 8px; + padding: 6px 14px; + } + QPushButton:hover { + background-color: rgba(255, 255, 255, 0.95); + border-color: #1d4ed8; + } + QPushButton:pressed { + transform: scale(0.98); + } + """) + + # Use default argument binding to lock down closure variables properly + btn.clicked.connect(lambda checked=False, p=preset["prompt"]: self.preset_clicked.emit(p)) + self.badges_layout.addWidget(btn) + + self.badges_layout.addStretch() + self.layout.addLayout(self.badges_layout) diff --git a/frontend/widgets/log_widget.py b/frontend/widgets/log_widget.py new file mode 100644 index 0000000000000000000000000000000000000000..4f4dfd2d09dde62e5fe28eac5deadaa37a9749df --- /dev/null +++ b/frontend/widgets/log_widget.py @@ -0,0 +1,71 @@ +import sys +import os +from PySide6.QtCore import Qt, Slot +from PySide6.QtWidgets import QWidget, QVBoxLayout, QTextEdit, QLabel + +class LogWidget(QWidget): + """ + Console log widget displaying simulation logs. + Supports auto-scroll and HTML-based log text colorization. + """ + def __init__(self, parent=None): + super().__init__(parent) + self.setup_ui() + + def setup_ui(self): + layout = QVBoxLayout(self) + layout.setContentsMargins(0, 0, 0, 0) + layout.setSpacing(5) + + title = QLabel("📺 EXECUTION LOG") + title.setStyleSheet("font-weight: 700; color: #1e3a8a; font-size: 11px;") + layout.addWidget(title) + + self.console = QTextEdit() + self.console.setReadOnly(True) + self.console.setUndoRedoEnabled(False) + self.console.setStyleSheet(""" + QTextEdit { + background: rgba(255, 255, 255, 0.65); + border: 1px solid rgba(0, 0, 0, 0.08); + border-radius: 10px; + font-family: 'Courier New', Courier, monospace; + font-size: 12px; + padding: 10px; + color: #000000; + } + """) + # Prevent focus rectangle + self.console.setFocusPolicy(Qt.FocusPolicy.NoFocus) + layout.addWidget(self.console) + + self.clear_logs() + + @Slot(str, str) + def append_log(self, text: str, message_type: str = "info"): + """Appends log entry with colors based on classification type.""" + # Convert type to lower to avoid capitalization mismatches + msg_type = message_type.lower() + + # Color mapping corresponding to index.css + color = "#000000" + if msg_type == "info": + color = "#1e3a8a" # Dark Navy + elif msg_type in ("success", "ok"): + color = "#064e3b" # Very Dark Green + elif msg_type in ("warn", "warning"): + color = "#78350f" # Dark Amber + elif msg_type in ("error", "err"): + color = "#7f1d1d" # Dark Red + + # Format and append + html_msg = f'
    > {text}
    ' + self.console.append(html_msg) + + # Force scroll to bottom + scrollbar = self.console.verticalScrollBar() + scrollbar.setValue(scrollbar.maximum()) + + def clear_logs(self): + self.console.clear() + self.console.setHtml('
    Đang đợi yêu cầu...
    ') diff --git a/frontend/widgets/score_modal.py b/frontend/widgets/score_modal.py new file mode 100644 index 0000000000000000000000000000000000000000..ae076842a4991118af921e3b941c30df6c0454f2 --- /dev/null +++ b/frontend/widgets/score_modal.py @@ -0,0 +1,114 @@ +import sys +import os +from PySide6.QtCore import Qt +from PySide6.QtWidgets import ( + QDialog, QVBoxLayout, QHBoxLayout, QLabel, QTextBrowser, QPushButton, QFrame +) + +class ScoreModal(QDialog): + """ + Modal popup dialog displaying the Rearrangement Evaluation Report. + Renders evaluation criteria, scores, and warnings inside a styled QTextBrowser. + """ + def __init__(self, parent=None): + super().__init__(parent) + self.setModal(True) + self.setWindowFlags(Qt.WindowType.Dialog | Qt.WindowType.FramelessWindowHint) + self.setAttribute(Qt.WidgetAttribute.WA_TranslucentBackground, True) + self.setup_ui() + + def setup_ui(self): + # We wrap in a outer container frame to apply border radii and shadow styling + self.resize(500, 420) + + main_layout = QVBoxLayout(self) + main_layout.setContentsMargins(10, 10, 10, 10) + + # Container Widget + container = QFrame(self) + container.setObjectName("container") + container.setStyleSheet(""" + QFrame#container { + background-color: rgba(255, 255, 255, 0.95); + border: 2px solid #1e3a8a; + border-radius: 16px; + } + """) + + container_layout = QVBoxLayout(container) + container_layout.setSpacing(15) + container_layout.setContentsMargins(25, 25, 25, 25) + + # Title + title = QLabel("🏆 Rearrangement Evaluation Report") + title.setAlignment(Qt.AlignmentFlag.AlignCenter) + title.setStyleSheet(""" + font-size: 18px; + font-weight: bold; + color: #0f172a; + border-bottom: 2px solid rgba(37, 99, 235, 0.2); + padding-bottom: 12px; + """) + container_layout.addWidget(title) + + # Markdown/HTML content browser + self.content_browser = QTextBrowser() + self.content_browser.setFocusPolicy(Qt.FocusPolicy.NoFocus) + self.content_browser.setStyleSheet(""" + QTextBrowser { + background: transparent; + border: none; + font-size: 13px; + line-height: 150%; + color: #334155; + } + """) + container_layout.addWidget(self.content_browser) + + # Close button + close_btn = QPushButton("Đóng") + close_btn.setStyleSheet(""" + QPushButton { + background-color: #1e3a8a; + color: white; + border: none; + border-radius: 8px; + padding: 10px 24px; + font-weight: 600; + font-size: 13px; + } + QPushButton:hover { + background-color: #1d4ed8; + } + """) + close_btn.clicked.connect(self.accept) + + btn_layout = QHBoxLayout() + btn_layout.addStretch() + btn_layout.addWidget(close_btn) + btn_layout.addStretch() + container_layout.addLayout(btn_layout) + + main_layout.addWidget(container) + + def show_score(self, markdown_text: str): + # Format markdown to basic HTML matching web replacement rules + html = markdown_text + html = html.replace("### ", "

    ") + # Ensure correct closing tag for h3 + lines = html.split("\n") + formatted_lines = [] + for line in lines: + if line.startswith("

    "): + line = line + "

    " + formatted_lines.append(line) + html = "\n".join(formatted_lines) + + html = html.replace("**", "") # note: we'd need to properly close strong, but let's do standard replace + + # A simpler way to handle markdown-like markers: + # replace double stars with alternating open/close tags or use QTextBrowser's markdown parser! + # QTextBrowser supports setMarkdown natively since Qt 5.14! That's awesome! + self.content_browser.setMarkdown(markdown_text) + self.exec() + diff --git a/frontend/widgets/status_widget.py b/frontend/widgets/status_widget.py new file mode 100644 index 0000000000000000000000000000000000000000..feb3b071caf08d98eaf631bd92ea1ed3da640308 --- /dev/null +++ b/frontend/widgets/status_widget.py @@ -0,0 +1,193 @@ +import sys +import os +from PySide6.QtCore import Qt, Slot +from PySide6.QtWidgets import ( + QWidget, QVBoxLayout, QHBoxLayout, QLabel, QFrame +) + +class StatusStep(QFrame): + """A single status step widget consisting of a colored dot and a label.""" + def __init__(self, text: str): + super().__init__() + self.layout = QHBoxLayout(self) + self.layout.setContentsMargins(0, 0, 0, 0) + self.layout.setSpacing(10) + + # The dot indicator + self.dot = QFrame() + self.dot.setFixedSize(8, 8) + self.dot.setObjectName("dot") + self.layout.addWidget(self.dot) + + # The step label + self.label = QLabel(text) + self.label.setStyleSheet("font-weight: 600; font-size: 13px; background: transparent; border: none;") + self.layout.addWidget(self.label) + self.layout.addStretch() + + self.set_state("idle") + + def set_state(self, state: str): + """Sets step state: idle, active, completed, error.""" + self.state = state + if state == "idle": + self.label.setStyleSheet("font-weight: 600; color: #1e293b; font-size: 13px; background: transparent; border: none;") + self.dot.setStyleSheet(""" + QFrame#dot { + background-color: rgba(15, 23, 42, 0.3); + border: 1px solid rgba(15, 23, 42, 0.5); + border-radius: 4px; + } + """) + elif state == "active": + self.label.setStyleSheet("font-weight: 600; color: #1e3a8a; font-size: 13px; background: transparent; border: none;") + self.dot.setStyleSheet(""" + QFrame#dot { + background-color: #1e3a8a; + border: 1px solid #1e3a8a; + border-radius: 4px; + } + """) + elif state == "completed": + self.label.setStyleSheet("font-weight: 600; color: #064e3b; font-size: 13px; background: transparent; border: none;") + self.dot.setStyleSheet(""" + QFrame#dot { + background-color: #064e3b; + border: 1px solid #064e3b; + border-radius: 4px; + } + """) + elif state == "error": + self.label.setStyleSheet("font-weight: 600; color: #7f1d1d; font-size: 13px; background: transparent; border: none;") + self.dot.setStyleSheet(""" + QFrame#dot { + background-color: #7f1d1d; + border: 1px solid #7f1d1d; + border-radius: 4px; + } + """) + +class StatusWidget(QWidget): + """ + Status Widget displaying the connection badge, the pipeline status steps, and simulation FPS. + """ + def __init__(self, parent=None): + super().__init__(parent) + self.setup_ui() + + def setup_ui(self): + self.main_layout = QVBoxLayout(self) + self.main_layout.setContentsMargins(0, 0, 0, 0) + self.main_layout.setSpacing(15) + + # 1. Connection Header & Badge & FPS + header_layout = QHBoxLayout() + header_layout.setContentsMargins(0, 0, 0, 0) + + self.title_label = QLabel("🤖 LLM-Panda") + self.title_label.setStyleSheet("font-weight: 700; color: #1e3a8a; font-size: 20px;") + header_layout.addWidget(self.title_label) + + header_layout.addStretch() + + # FPS Counter + self.fps_label = QLabel("FPS: --") + self.fps_label.setStyleSheet("color: #1e293b; font-size: 11px; font-weight: 700;") + header_layout.addWidget(self.fps_label) + + # Connection Badge + self.badge = QLabel("Disconnected") + self.badge.setObjectName("badge") + self.update_connection_badge(False) + header_layout.addWidget(self.badge) + + self.main_layout.addLayout(header_layout) + + # Divider line + divider = QFrame() + divider.setFrameShape(QFrame.Shape.HLine) + divider.setStyleSheet("color: rgba(37, 99, 235, 0.3); line-height: 2px;") + self.main_layout.addWidget(divider) + + # 2. Pipeline Status Section + section_title = QLabel("📊 PIPELINE STATUS") + section_title.setStyleSheet("font-weight: 700; color: #1e3a8a; font-size: 11px;") + self.main_layout.addWidget(section_title) + + # List of pipeline status steps + self.steps_container = QFrame() + self.steps_container.setStyleSheet("background: transparent; border: none;") + self.steps_layout = QVBoxLayout(self.steps_container) + self.steps_layout.setSpacing(10) + self.steps_layout.setContentsMargins(5, 0, 0, 0) + + self.step_llm = StatusStep("1. LLM Planning") + self.step_val = StatusStep("2. Rule Validation") + self.step_exec = StatusStep("3. PyBullet Execution") + self.step_score = StatusStep("4. Scoring & Feedback") + + self.steps_layout.addWidget(self.step_llm) + self.steps_layout.addWidget(self.step_val) + self.steps_layout.addWidget(self.step_exec) + self.steps_layout.addWidget(self.step_score) + + self.main_layout.addWidget(self.steps_container) + + @Slot(bool) + def update_connection_badge(self, connected: bool): + if connected: + self.badge.setText("Connected") + self.badge.setStyleSheet(""" + QLabel#badge { + background-color: rgba(16, 185, 129, 0.15); + color: #064e3b; + font-size: 10px; + font-weight: 700; + padding: 4px 10px; + border-radius: 10px; + border: 1px solid #064e3b; + } + """) + else: + self.badge.setText("Disconnected") + self.badge.setStyleSheet(""" + QLabel#badge { + background-color: rgba(239, 68, 68, 0.15); + color: #7f1d1d; + font-size: 10px; + font-weight: 700; + padding: 4px 10px; + border-radius: 10px; + border: 1px solid #7f1d1d; + } + """) + + @Slot(float) + def update_fps(self, fps: float): + self.fps_label.setText(f"FPS: {fps:.1f}") + + def reset_steps(self): + self.step_llm.set_state("idle") + self.step_val.set_state("idle") + self.step_exec.set_state("idle") + self.step_score.set_state("idle") + + def set_step_active(self, step_key: str): + self.get_step_widget(step_key).set_state("active") + + def set_step_completed(self, step_key: str): + self.get_step_widget(step_key).set_state("completed") + + def set_step_error(self, step_key: str): + self.get_step_widget(step_key).set_state("error") + + def get_step_widget(self, step_key: str) -> StatusStep: + if step_key == "llm": + return self.step_llm + elif step_key == "val": + return self.step_val + elif step_key == "exec": + return self.step_exec + elif step_key == "score": + return self.step_score + return self.step_llm diff --git a/frontend/widgets/viewport_widget.py b/frontend/widgets/viewport_widget.py new file mode 100644 index 0000000000000000000000000000000000000000..37b8efc8fac4d1599032402164538188585b5b6b --- /dev/null +++ b/frontend/widgets/viewport_widget.py @@ -0,0 +1,118 @@ +from PySide6.QtCore import Qt, Signal, QPoint, Slot +from PySide6.QtGui import QImage, QPainter, QColor +from PySide6.QtOpenGL import QOpenGLTexture +from PySide6.QtOpenGLWidgets import QOpenGLWidget + +class ViewportWidget(QOpenGLWidget): + """ + OpenGL Viewport Widget displaying PyBullet camera frames. + Handles mouse drag actions to orbit/pan the camera, scroll to zoom, and click to pick objects. + """ + camera_rotated = Signal(float, float) # dx, dy + camera_panned = Signal(float, float) # dx, dy + camera_zoomed = Signal(float) # delta + viewport_clicked = Signal(int, int) # clicked x, y + + def __init__(self, parent=None): + super().__init__(parent) + self.current_image = QImage() + self.texture = None + self.drag_start = QPoint() + self.click_start_pos = QPoint() + self.is_dragging = False + self.is_drag_active = False + self.drag_button = Qt.MouseButton.NoButton + + # Set default widget settings + self.setMouseTracking(True) + self.setFocusPolicy(Qt.FocusPolicy.StrongFocus) + + def initializeGL(self): + """Called once before the first call to paintGL() or resizeGL().""" + pass + + def resizeGL(self, w: int, h: int): + """Called upon widget resizing.""" + pass + + def paintGL(self): + """Renders the current camera frame.""" + painter = QPainter(self) + if not self.current_image.isNull(): + # Draw frame image to scale and fill the widget + painter.drawImage(self.rect(), self.current_image) + else: + # Draw fallback dark background + painter.fillRect(self.rect(), QColor("#070a13")) + painter.setPen(QColor("#ffffff")) + painter.drawText(self.rect(), Qt.AlignmentFlag.AlignCenter, "Chờ hình ảnh từ Simulator...") + painter.end() + + @Slot(object) + def update_frame(self, img_np): + """Receives new raw RGB/RGBA NumPy array and updates QOpenGLTexture.""" + try: + height, width, channels = img_np.shape + + # Select correct QImage format based on channels count + if channels == 4: + fmt = QImage.Format.Format_RGBA8888 + elif channels == 3: + fmt = QImage.Format.Format_RGB888 + else: + return + + # Copy to avoid garbage collection issues on NumPy memory buffer + img = QImage(img_np.data, width, height, width * channels, fmt).copy() + if not img.isNull(): + self.current_image = img + + # Update texture on GPU + if self.texture is not None: + self.texture.destroy() + self.texture = QOpenGLTexture(img) + + self.update() + except Exception as e: + print(f"[ViewportWidget update_frame Error] {e}") + + def mousePressEvent(self, event): + self.is_dragging = True + self.is_drag_active = False + self.drag_start = event.pos() + self.click_start_pos = event.pos() + self.drag_button = event.button() + if self.drag_button in (Qt.MouseButton.LeftButton, Qt.MouseButton.RightButton): + self.setCursor(Qt.CursorShape.ClosedHandCursor) + + def mouseMoveEvent(self, event): + if self.is_dragging and self.drag_button != Qt.MouseButton.NoButton: + delta = event.pos() - self.click_start_pos + if delta.manhattanLength() > 3: + self.is_drag_active = True + + dx = event.pos().x() - self.drag_start.x() + dy = event.pos().y() - self.drag_start.y() + self.drag_start = event.pos() + + if self.drag_button == Qt.MouseButton.LeftButton: + # Rotate + self.camera_rotated.emit(dx, dy) + elif self.drag_button == Qt.MouseButton.RightButton: + # Pan + self.camera_panned.emit(dx, dy) + + def mouseReleaseEvent(self, event): + # Click detection: if mouse didn't drag much, emit click signal for Picking + delta = event.pos() - self.click_start_pos + if not self.is_drag_active and delta.manhattanLength() <= 3 and event.button() == Qt.MouseButton.LeftButton: + self.viewport_clicked.emit(event.pos().x(), event.pos().y()) + + self.is_dragging = False + self.is_drag_active = False + self.drag_button = Qt.MouseButton.NoButton + self.setCursor(Qt.CursorShape.ArrowCursor) + + def wheelEvent(self, event): + delta = event.angleDelta().y() + self.camera_zoomed.emit(-delta) # Reverse delta to zoom in on scroll forward diff --git a/frontend/windows/__pycache__/main_window.cpython-310.pyc b/frontend/windows/__pycache__/main_window.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1f6356992d8c9f26f00fdcfd3c0eab4a40781a81 Binary files /dev/null and b/frontend/windows/__pycache__/main_window.cpython-310.pyc differ diff --git a/frontend/windows/main_window.py b/frontend/windows/main_window.py new file mode 100644 index 0000000000000000000000000000000000000000..04ba940dd64d747efefc4710a04f7c9210fa220a --- /dev/null +++ b/frontend/windows/main_window.py @@ -0,0 +1,61 @@ +import sys +import os +from PySide6.QtCore import Slot +from PySide6.QtWidgets import QMainWindow, QWidget, QMessageBox +from PySide6.QtGui import QCloseEvent + +# Ensure project source root is in path +PROJECT_SRC = os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "..")) +if PROJECT_SRC not in sys.path: + sys.path.insert(0, PROJECT_SRC) + +from frontend.layouts.main_layout import MainLayout +from frontend.widgets.score_modal import ScoreModal +from frontend.controllers.ui_controller import UIController + +class MainWindow(QMainWindow): + """ + Main Application Window. + Loads layouts, overlay dialogs, and delegates execution lifecycle to UIController. + """ + def __init__(self): + super().__init__() + self.setWindowTitle("LLM-Panda Desktop Controller") + self.resize(1366, 768) + self.setMinimumSize(1024, 600) + + self.setup_ui() + + def setup_ui(self): + # 1. Main Overlay Layout + self.main_layout = MainLayout(self) + self.setCentralWidget(self.main_layout) + + # 2. Viewport and Widget references (aliased for easy controller access) + self.viewport_widget = self.main_layout.viewport_widget + self.chat_widget = self.main_layout.chat_widget + self.log_widget = self.main_layout.log_widget + self.status_widget = self.main_layout.status_widget + + # 3. Score Evaluation Modal + self.score_modal = ScoreModal(self) + + # 4. Controller initialization + self.ui_controller = UIController(self) + self.ui_controller.start() + + def closeEvent(self, event: QCloseEvent): + """Asks for confirmation before shutting down PyBullet and exiting.""" + reply = QMessageBox.question( + self, "Thoát ứng dụng", + "Bạn muốn thoát ứng dụng và đóng môi trường mô phỏng?", + QMessageBox.StandardButton.Yes | QMessageBox.StandardButton.No, + QMessageBox.StandardButton.No + ) + + if reply == QMessageBox.StandardButton.Yes: + # Shutdown controller (disconnects PyBullet and stops QThreads) + self.ui_controller.shutdown() + event.accept() + else: + event.ignore() diff --git a/inspect_aabb.py b/inspect_aabb.py new file mode 100644 index 0000000000000000000000000000000000000000..a7f405892f79867b73856f453384a3cfd35d9bf7 --- /dev/null +++ b/inspect_aabb.py @@ -0,0 +1,44 @@ +import pybullet as pb +import os +from main import PandaSimulation +from llm_panda import config + +def inspect(): + # Run headless simulation with seed 0 (or any seed, since slots have same table height) + sim = PandaSimulation(gui=False, seed=0) + + print("TABLE_TOP_Z:", config.TABLE_TOP_Z) + + for obj_id in sim.scene.object_ids: + name = sim.scene.get_name(obj_id) + cls = sim.scene.get_class(obj_id) + + pos, ori = pb.getBasePositionAndOrientation(obj_id) + aabb_min, aabb_max = pb.getAABB(obj_id) + + height = aabb_max[2] - aabb_min[2] + + # Calculate where the base link z is relative to the AABB + base_z_rel_to_aabb_bottom = pos[2] - aabb_min[2] + base_z_rel_to_aabb_top = aabb_max[2] - pos[2] + + print(f"\nObject: {name} (class: {cls})") + print(f" Base Position: {pos}") + print(f" AABB Min: {aabb_min}") + print(f" AABB Max: {aabb_max}") + print(f" AABB Height: {height:.4f} m") + print(f" Base Link Z offset from AABB Bottom: {base_z_rel_to_aabb_bottom:.4f} m") + print(f" Base Link Z offset from AABB Top: {base_z_rel_to_aabb_top:.4f} m") + + # Check database settings + local_db_pos = sim.grasp_planner.get_local_grasp(cls)["local_position"] + print(f" Database local position: {local_db_pos}") + + # Compute grasp pose in world coordinate + grasp_pos, grasp_ori = sim.grasp_planner.compute_grasp_pose(obj_id, cls) + print(f" Computed Grasp Pose World Z: {grasp_pos[2]:.4f}") + + sim.disconnect() + +if __name__ == "__main__": + inspect() diff --git a/ke_hoach_huong1_ik_panda.md b/ke_hoach_huong1_ik_panda.md new file mode 100644 index 0000000000000000000000000000000000000000..094a5fb97f06ec8ed54be8f59160c7f5ca0af41c --- /dev/null +++ b/ke_hoach_huong1_ik_panda.md @@ -0,0 +1,808 @@ +# Kế hoạch triển khai **Hướng 1**: Giữ PyBullet nhưng sửa cách dùng IK để đạt độ chính xác cao hơn cho Panda + +## 1. Mục tiêu của kế hoạch + +Mục tiêu của hướng này **không phải** là thay toàn bộ bộ giải IK bằng một solver mới, mà là: + +- **giữ nguyên nền tảng PyBullet** và cấu trúc pipeline hiện tại, +- nhưng **sửa cách sử dụng `calculateInverseKinematics(...)`** để: + 1. tạo **multi-IK thực sự** thay vì chỉ “multi-IK giả”, + 2. **giảm mạnh độ lệch** giữa grasp pose mong muốn và pose FK thực tế của nghiệm IK, + 3. biến tầng IK thành một tầng **“pose-first”**: nghiệm chỉ được chấp nhận nếu bám đủ sát pose đích, + 4. giữ nguyên các bước collision checking / RRT phía sau, nhưng đặt chúng **sau** khi đã có nghiệm IK chính xác hơn. + +Nói ngắn gọn, kế hoạch này nhằm đưa phần IK từ kiểu: + +> “lấy một nghiệm numerical tương đối gần rồi lọc dần” + +thành kiểu: + +> “tìm nhiều nghiệm numerical nhưng phải **bám sát pose đích**, sau đó mới qua collision validation và motion planning”. + +--- + +# 2. Phạm vi sửa + +Kế hoạch này chỉ tập trung vào **Hướng 1** — tức là **vẫn dùng PyBullet IK**, chưa chuyển sang solver tối ưu riêng. + +Các phần cần sửa chủ yếu nằm ở: + +- `pipeline_executor.py` + - `_solve_ik_candidates(...)` + - `_validate_ik_solution(...)` + - `_check_joint_limits(...)` + - các hằng số tolerance / tham số IK +- có thể thêm một số helper mới: + - `_build_ik_seed_list(...)` + - `_is_valid_ik_vector(...)` + - `_compute_pose_error(...)` + - `_deduplicate_joint_solutions(...)` + +Kế hoạch này **không đụng vào bản chất của RRT / collision checker tổng thể**, trừ phần cần phối hợp với IK validation. + +--- + +# 3. Chẩn đoán chính xác vấn đề hiện tại + +## 3.1. IK hiện tại là numerical IK có bias, không phải “exact IK” +Hiện tại bạn đang dùng `pb.calculateInverseKinematics(...)` với: +- `lowerLimits` +- `upperLimits` +- `jointRanges` +- `restPoses` +- `maxNumIterations` +- `residualThreshold` + +Điều này khiến nghiệm bị chi phối bởi: +- tư thế nghỉ (`restPoses`), +- seed / trạng thái robot hiện tại, +- damping / cơ chế numerical nội bộ của PyBullet. + +Bản chất của nó là: + +- **giải gần đúng** +- **có xu hướng ưu tiên posture “đẹp” / gần rest pose** +- **không đảm bảo pose cuối cùng khớp chặt target pose** + +## 3.2. Multi-IK hiện tại chưa phải multi-IK thật +Hiện tại code reset robot về nhiều `q_seed`, nhưng khi gọi IK vẫn truyền: +- `restPoses = self.sim.controller._rest_poses` + +cho mọi lần solve. + +Hệ quả: +- solver vẫn bị kéo về cùng một tư thế ưu tiên, +- các nghiệm thu được có thể gần giống nhau, +- orientation grasp mong muốn dễ bị lệch để thỏa posture bias. + +## 3.3. IK validation hiện tại cho phép sai số pose còn quá lớn +Hiện tại validation đang chấp nhận đại loại: +- `pos_err <= 0.01 m` +- `ori_err <= 0.05 rad` + +Đối với grasp pose, đặc biệt khi grasp được dựng từ contact pair, mức này quá lỏng vì: +- lệch 1 cm có thể làm finger không còn đúng vị trí mong muốn, +- lệch gần 3 độ có thể làm hướng kẹp bị sai rõ rệt. + +## 3.4. Joint limit hiện tại được solver xử lý theo kiểu bias mềm trong solve phase +Joint limit hiện nay được đưa vào `calculateInverseKinematics(...)`, nhưng bản chất solver vẫn là numerical IK có regularization. Sau solve mới có bước check cứng bằng `_check_joint_limits(...)`. + +Tức là: +- solve phase: **mềm** +- validation phase: **cứng** + +Điều này chấp nhận được, nhưng nếu muốn tăng độ chính xác thì phải siết mạnh hơn tầng validation và cách sinh seed. + +--- + +# 4. Mục tiêu kỹ thuật cụ thể sau khi sửa + +Sau khi hoàn thành kế hoạch này, phần IK cần đạt các tính chất sau: + +## 4.1. Multi-IK phải là multi-IK thực sự +Với **mỗi seed**: +- solver phải thật sự được “neo” quanh seed đó, +- thay vì luôn bị kéo về một `restPose` cố định. + +## 4.2. Pose accuracy phải trở thành điều kiện bắt buộc +Một nghiệm IK chỉ được xem là hợp lệ nếu: +- sai số vị trí nhỏ hơn ngưỡng chặt (mm-level hoặc vài mm), +- sai số orientation nhỏ hơn ngưỡng chặt (cỡ dưới 1 độ hoặc xấp xỉ vậy). + +## 4.3. IK validation phải được tách thành 2 lớp rõ ràng +### Lớp A — IK feasibility / pose accuracy +Kiểm tra: +- vector nghiệm có hợp lệ không, +- joint limits, +- FK khớp pose đến đâu. + +### Lớp B — planning feasibility +Kiểm tra: +- self-collision, +- collision với object / môi trường theo collision policy của pipeline. + +## 4.4. Cơ chế seed phải có chủ đích +Seed không được sinh một cách tùy tiện, mà phải có thứ tự ưu tiên rõ ràng: +1. trạng thái hiện tại của robot, +2. home / rest pose, +3. random seeds, +4. nếu cần: các posture template. + +## 4.5. Dừng sớm khi đã có nghiệm tốt +Nếu tìm được nghiệm: +- khớp pose rất sát, +- không collision, +thì có thể dừng sớm và chuyển sang RRT. + +--- + +# 5. Kiến trúc sửa tổng thể + +Phần IK sau sửa nên được tổ chức theo luồng sau: + +## 5.1. Input +- `target_pos` +- `target_ori` +- `seed_q` (thường là cấu hình hiện tại hoặc cấu hình liên quan) +- mode validation (`grasp` / `place`) +- target object id nếu cần collision policy + +## 5.2. Bước A — Sinh danh sách seed +Tạo một danh sách `seed_list` có thứ tự ưu tiên. + +## 5.3. Bước B — Với mỗi seed, gọi PyBullet IK theo kiểu “seed-conditioned” +Với từng `q_seed`: +- reset robot về `q_seed` (nếu cần cho solver ổn định) +- gọi `calculateInverseKinematics(...)` với: + - `restPoses=q_seed` + - không dùng chung một `restPose` cố định cho tất cả lần solve + +## 5.4. Bước C — Chuẩn hóa và lọc nghiệm IK thô +Sau mỗi lần solve: +- cắt đúng số joint arm của Panda, +- kiểm tra dữ liệu hợp lệ, +- loại nghiệm trùng / gần trùng. + +## 5.5. Bước D — Validate pose accuracy trước +Với từng nghiệm: +- set robot vào `q` +- tính FK +- đo lỗi vị trí / orientation +- chỉ giữ nghiệm đạt tolerance chặt. + +## 5.6. Bước E — Validate collision sau +Chỉ sau khi pose accuracy đạt mới: +- check self-collision, +- check collision với môi trường / target object theo mode. + +## 5.7. Bước F — Trả danh sách nghiệm hợp lệ theo thứ tự chất lượng +Danh sách nghiệm trả về nên được sắp theo: +1. pose error thấp hơn, +2. gần seed hơn (nếu muốn), +3. ít collision hơn (thực tế collision đã pass nên tiêu chí này chủ yếu là pose error). + +--- + +# 6. Kế hoạch sửa chi tiết theo từng hạng mục + +--- + +# 7. Hạng mục 1 — Thiết kế lại `_solve_ik_candidates(...)` + +## 7.1. Mục tiêu +Biến `_solve_ik_candidates(...)` thành một hàm: +- sinh **nhiều nghiệm IK thực sự khác nhau**, +- mỗi nghiệm được solve quanh một seed cụ thể, +- ưu tiên độ chính xác pose thay vì chỉ lấy bất kỳ nghiệm numerical nào. + +## 7.2. Hành động sửa +Hàm `_solve_ik_candidates(...)` sau sửa nên làm 6 bước: + +### Bước 1 — Nhận input rõ ràng +Input nên gồm: +- `target_pos` +- `target_ori` +- `seed_q=None` +- `max_candidates` +- `rng_seed` nếu cần +- có thể thêm `pos_tol`, `ori_tol` nếu muốn cấu hình tại đây + +### Bước 2 — Gọi helper tạo seed list +Không viết seed logic rải rác trong hàm nữa. +Tạo helper riêng: + +```python +_build_ik_seed_list(seed_q, num_random=..., include_rest=True, include_current=True) +``` + +Helper này trả về danh sách seed theo đúng thứ tự ưu tiên. + +### Bước 3 — Với mỗi `q_seed`, solve IK bằng `restPoses=q_seed` +Đây là thay đổi quan trọng nhất của Hướng 1. + +**Nguyên tắc bắt buộc:** +- nếu đang thử seed `q_seed` +- thì lời gọi `calculateInverseKinematics(...)` phải dùng: + - `restPoses=q_seed` + +không được dùng `self.sim.controller._rest_poses` cho mọi lần gọi nữa. + +### Bước 4 — Tăng chất lượng solve +Đổi tham số solve theo hướng chặt hơn: +- `maxNumIterations`: tăng đáng kể +- `residualThreshold`: giảm xuống + +Ví dụ định hướng: +- `maxNumIterations = 1000` +- `residualThreshold = 1e-8` + +Không nhất thiết phải đúng y hệt con số này, nhưng phải **chặt hơn hiện tại**. + +### Bước 5 — Chuẩn hóa output của PyBullet +Kết quả từ `calculateInverseKinematics(...)` phải được: +- cắt đúng số arm joint Panda, +- ép sang `np.ndarray(dtype=float)`, +- kiểm tra finite. + +### Bước 6 — Loại nghiệm trùng +Nếu hai nghiệm gần nhau dưới một ngưỡng rất nhỏ trong joint space thì chỉ giữ một nghiệm. + +Ví dụ: +- nếu `||q_i - q_j|| < 1e-4` hoặc ngưỡng phù hợp thì xem là trùng. + +## 7.3. Kết quả mong muốn +Sau khi sửa, `_solve_ik_candidates(...)` phải: +- trả về **danh sách các nghiệm IK khác nhau thật sự**, +- mỗi nghiệm là sản phẩm của một seed khác nhau, +- không còn hiện tượng “multi-IK nhưng tất cả vẫn bị kéo về cùng rest pose”. + +--- + +# 8. Hạng mục 2 — Tách riêng logic sinh seed thành `_build_ik_seed_list(...)` + +## 8.1. Mục tiêu +Biến phần sinh seed thành một thành phần có cấu trúc, dễ kiểm soát, dễ điều chỉnh. + +## 8.2. Seed strategy đề xuất cho Panda + +Danh sách seed nên có thứ tự như sau: + +### Nhóm 1 — seed hiện tại / seed ngữ cảnh +1. `seed_q` truyền vào hàm (nếu có) +2. `q_current` của robot tại thời điểm solve (nếu khác seed_q) + +### Nhóm 2 — rest / home pose +3. `config.ARM_REST_POSE` +4. nếu controller có home pose khác thì thêm home pose đó + +### Nhóm 3 — random seeds +Sinh `N_random` seed ngẫu nhiên trong joint limit. + +Khuyến nghị: +- `N_random = 10` hoặc `15` +- nếu bài toán khó có thể nâng lên `20` + +### Nhóm 4 — posture templates (nếu cần) +Chỉ dùng nếu bạn muốn tăng khả năng khám phá các nhánh nghiệm khác nhau. Ví dụ: +- elbow-up template +- elbow-down template +- wrist-flipped template + +## 8.3. Quy tắc loại trùng seed +Các seed quá gần nhau thì chỉ giữ một bản để tránh solve lặp vô ích. + +## 8.4. Kết quả mong muốn +Bạn sẽ có một danh sách seed có chất lượng tốt, thay vì: +- 1–2 seed ngẫu nhiên rời rạc +- hoặc seed list không rõ thứ tự ưu tiên. + +--- + +# 9. Hạng mục 3 — Sửa lời gọi `calculateInverseKinematics(...)` + +## 9.1. Mục tiêu +Đảm bảo mỗi lần solve IK thật sự là solve quanh seed tương ứng. + +## 9.2. Cách gọi sau sửa +Mỗi vòng lặp seed cần có logic đại khái như sau: + +1. lấy `q_seed` +2. reset robot về `q_seed` (nếu bạn muốn solver có current state nhất quán) +3. gọi: + +- `lowerLimits = self.lower_limits` +- `upperLimits = self.upper_limits` +- `jointRanges = self.upper_limits - self.lower_limits` +- `restPoses = q_seed` + +### Điểm bắt buộc +**`restPoses` phải là `q_seed`, không phải rest pose cố định toàn cục.** + +## 9.3. Tham số solve đề xuất +Bạn nên gom các tham số solve thành hằng số cấu hình: + +- `IK_MAX_ITER` +- `IK_RESIDUAL_THRESHOLD` + +Giá trị khuyến nghị ban đầu: +- `IK_MAX_ITER = 1000` +- `IK_RESIDUAL_THRESHOLD = 1e-8` + +## 9.4. Kết quả mong muốn +- seed khác → bias solver khác +- tăng khả năng tìm nhiều nhánh nghiệm +- giảm lệch pose do solver bị kéo về một posture mặc định không phù hợp. + +--- + +# 10. Hạng mục 4 — Thêm bước “IK vector sanity check” + +## 10.1. Mục tiêu +Không cho những nghiệm IK lỗi dữ liệu lọt vào validation sâu hơn. + +## 10.2. Tạo helper `_is_valid_ik_vector(q)` +Hàm này nên kiểm tra: +1. `q is not None` +2. `q` có đúng kiểu / chuyển được sang mảng số thực +3. số chiều đúng bằng số joint arm của Panda +4. tất cả phần tử là finite (`not NaN`, `not inf`) + +## 10.3. Vị trí gọi +Gọi helper này ngay sau khi nhận `q_sol` từ PyBullet và trước: +- deduplication, +- joint limit check, +- collision check. + +## 10.4. Kết quả mong muốn +Loại bỏ sớm nghiệm lỗi, tránh làm bẩn pipeline validation. + +--- + +# 11. Hạng mục 5 — Thiết kế lại `_validate_ik_solution(...)` theo thứ tự ưu tiên đúng + +## 11.1. Mục tiêu +Biến `_validate_ik_solution(...)` thành hàm kiểm tra IK **đúng bản chất**: +1. kiểm tra dữ liệu nghiệm, +2. kiểm tra joint limit, +3. kiểm tra độ khớp pose, +4. sau đó mới collision. + +## 11.2. Thứ tự validate đề xuất + +### Bước 1 — sanity check +- `q` hợp lệ? +- đúng số chiều? +- finite? + +### Bước 2 — joint limit check +- tất cả joint nằm trong `[lower, upper]` với tolerance rất nhỏ nếu cần. + +### Bước 3 — set robot state +- reset robot tạm thời về `q` + +### Bước 4 — tính FK +Lấy: +- `ee_pos` +- `ee_ori` + +### Bước 5 — đo pose error +Tính: +- `pos_err` +- `ori_err` + +### Bước 6 — so với tolerance chặt +Chỉ nếu: +- `pos_err <= pos_tol` +- `ori_err <= ori_tol` +thì mới đi tiếp. + +### Bước 7 — self-collision +Nếu self-collision → reject. + +### Bước 8 — collision môi trường / target +Tùy mode: +- grasp mode → static collision theo collision policy của bạn +- place mode → static collision tương ứng + +## 11.3. Điều quan trọng về tư duy +**Pose accuracy phải đứng trước collision validation**. +Lý do: +- nếu nghiệm còn lệch nhiều so với grasp pose mong muốn thì dù collision-free cũng không nên dùng, +- collision-free không cứu được một grasp pose sai. + +--- + +# 12. Hạng mục 6 — Siết chặt tolerance pose cho IK + +## 12.1. Mục tiêu +Biến IK thành một bước “grasp pose bám sát target” thay vì “gần gần là được”. + +## 12.2. Tolerance đề xuất +Bạn nên đưa tolerance vào cấu hình, ví dụ: + +- `IK_POS_TOL` +- `IK_ORI_TOL` + +### Giá trị khuyến nghị ban đầu +Để thử nghiệm ban đầu cho Panda grasp: +- `IK_POS_TOL = 0.002` m (2 mm) +- `IK_ORI_TOL = 0.01` rad (~0.57 độ) + +Nếu bài toán quá khó có thể nới nhẹ: +- `IK_POS_TOL = 0.003` +- `IK_ORI_TOL = 0.015` + +Nhưng **không nên quay lại mức 1 cm / 0.05 rad** nếu mục tiêu là grasp chính xác. + +## 12.3. Lưu ý thực tế +- Nếu object lớn, grasp thô hơn thì có thể nới. +- Nếu object nhỏ / contact pair sát nhau thì nên giữ tolerance rất chặt. + +--- + +# 13. Hạng mục 7 — Chuẩn hóa cách tính orientation error + +## 13.1. Mục tiêu +Đảm bảo orientation error được tính ổn định và nhất quán. + +## 13.2. Cách làm +Tạo helper: +```python +_compute_pose_error(target_pos, target_ori, actual_pos, actual_ori) +``` + +Helper trả về: +- `pos_err` +- `ori_err` + +## 13.3. Yêu cầu +Phần orientation error phải: +- dùng metric nhất quán giữa quaternion target và quaternion thực tế, +- tránh lỗi do dấu quaternion (`q` và `-q` là cùng orientation). + +Nếu code hiện tại đã có cách tính ổn thì giữ, nhưng nên gom thành helper riêng để dễ kiểm soát. + +--- + +# 14. Hạng mục 8 — Phân tách “IK solve” và “IK ranking” + +## 14.1. Mục tiêu +Khi có nhiều nghiệm IK hợp lệ, cần có cách sắp xếp để nghiệm tốt nhất được thử trước khi vào RRT. + +## 14.2. Cách chấm / xếp hạng nghiệm +Sau khi một nghiệm đã: +- pass pose tolerance, +- pass collision validation, + +thì có thể gán điểm theo: +1. **pose error** nhỏ hơn là tốt hơn, +2. **gần seed_q hoặc q_current** hơn là tốt hơn, +3. nếu muốn, gần rest pose hơn là tốt hơn, nhưng tiêu chí này phải đứng sau pose accuracy. + +## 14.3. Kết quả mong muốn +Danh sách nghiệm trả về từ `_solve_ik_candidates(...)` hoặc sau validate sẽ có thứ tự tốt hơn, giúp RRT thử nghiệm hợp lý trước. + +--- + +# 15. Hạng mục 9 — Tách rõ seed solve cho grasp và place + +## 15.1. Mục tiêu +Giúp IK ở từng giai đoạn dùng seed hợp lý hơn. + +## 15.2. Nguyên tắc +### Với grasp IK +Ưu tiên seed: +1. `q_current` của robot trước khi đi gắp +2. rest pose +3. random seeds + +### Với place IK +Ưu tiên seed: +1. `q_grasp_goal` hoặc cấu hình cuối của robot sau khi carry +2. `q_current` +3. rest pose +4. random seeds + +## 15.3. Lý do +Place pose thường liên quan trực tiếp đến trạng thái robot đang mang vật. +Nếu vẫn seed từ một posture quá xa thì solver dễ rơi vào nhánh nghiệm không mong muốn. + +--- + +# 16. Hạng mục 10 — Ghi log IK đầy đủ để debug độ lệch pose + +## 16.1. Mục tiêu +Giúp bạn thấy rõ vì sao solver chọn nghiệm đó, và nghiệm đó lệch bao nhiêu. + +## 16.2. Với mỗi seed, nên log: +- seed index +- loại seed (current / rest / random / template) +- `pos_err` +- `ori_err` +- pass / fail vì lý do gì: + - invalid vector + - joint limit + - pose error + - self-collision + - env collision + +## 16.3. Với nghiệm được chọn cuối cùng, log: +- seed nào sinh ra nghiệm này +- pose error cuối cùng +- khoảng cách tới seed +- mode: grasp / place + +## 16.4. Kết quả mong muốn +Bạn có thể nhìn log và biết: +- solver fail vì pose accuracy, +- hay vì collision, +- hay vì seed strategy. + +--- + +# 17. Hạng mục 11 — Tạo cấu hình IK tập trung + +## 17.1. Mục tiêu +Không để các tham số IK rải rác trong code. + +## 17.2. Tạo nhóm cấu hình +Ví dụ trong `config.py` hoặc phần config của executor: + +- `IK_MAX_ITER` +- `IK_RESIDUAL_THRESHOLD` +- `IK_POS_TOL` +- `IK_ORI_TOL` +- `IK_NUM_RANDOM_SEEDS` +- `IK_DUPLICATE_Q_TOL` +- `IK_JOINT_LIMIT_EPS` + +## 17.3. Lợi ích +- dễ tune, +- dễ so sánh giữa grasp và place, +- dễ audit lại pipeline. + +--- + +# 18. Hạng mục 12 — Giữ nguyên collision checker nhưng đổi vai trò của nó trong pipeline IK + +## 18.1. Mục tiêu +Không để collision checker “cứu” một nghiệm pose sai. + +## 18.2. Quy tắc mới +Một nghiệm IK phải đi qua thứ tự: + +1. hợp lệ dữ liệu +2. trong joint limit +3. khớp pose trong tolerance chặt +4. collision-free theo policy + +Nếu bước 3 fail thì **không cần** collision check nữa. + +## 18.3. Ý nghĩa +Điều này giữ cho pipeline bám đúng mục tiêu của bạn: +- grasp pose phải thật sự là grasp pose mong muốn, +- không phải một pose “na ná” nhưng collision-free. + +--- + +# 19. Hạng mục 13 — Chính sách fallback khi không tìm được IK tốt + +## 19.1. Mục tiêu +Khi solver không tìm được nghiệm đạt tolerance chặt, pipeline phải phản ứng có kiểm soát. + +## 19.2. Trình tự fallback đề xuất +Nếu không có nghiệm nào pass: +1. thử hết seed list hiện tại, +2. tăng số random seeds, +3. nếu vẫn fail: + - reject grasp candidate hiện tại, + - quay lại chọn grasp candidate khác. + +## 19.3. Điều không nên làm +Không nên: +- nới tolerance quá mạnh chỉ để “có nghiệm cho xong”, +- hoặc lấy một nghiệm pose lệch nhiều rồi đẩy sang RRT. + +--- + +# 20. Hạng mục 14 — Kế hoạch test sau khi sửa + +Sau khi sửa xong IK, cần test theo nhiều lớp. + +--- + +# 21. Bộ test 1 — Unit test cho `_solve_ik_candidates(...)` + +## 21.1. Mục tiêu +Kiểm tra hàm có thực sự tạo ra nhiều nghiệm từ nhiều seed khác nhau hay không. + +## 21.2. Các test cần có + +### Test A — pose dễ, không collision +- chọn một pose Panda chắc chắn reachable +- gọi solver với nhiều seed +- kiểm tra có ít nhất 1 nghiệm pass + +### Test B — cùng pose nhưng nhiều seed +- xác nhận solver không luôn trả cùng một nghiệm duy nhất nếu bài toán có nhiều nhánh + +### Test C — target pose khó / unreachable +- hàm phải trả về danh sách rỗng hoặc fail sạch sẽ +- không được crash. + +--- + +# 22. Bộ test 2 — Unit test cho `_validate_ik_solution(...)` + +## 22.1. Test dữ liệu lỗi +- `q=None` +- `q` sai chiều +- `q` có NaN + +Kết quả mong muốn: reject đúng cách. + +## 22.2. Test pose error +- đưa vào một `q` lệch pose nhiều → fail vì pose error +- đưa vào một `q` khớp pose sát → pass pose layer + +## 22.3. Test collision +- `q` khớp pose nhưng self-collision → fail +- `q` khớp pose nhưng env collision → fail + +--- + +# 23. Bộ test 3 — Integration test grasp IK + +## 23.1. Mục tiêu +Kiểm tra trên grasp pose thật từ pipeline. + +## 23.2. Các chỉ số cần ghi +Với mỗi grasp candidate: +- có bao nhiêu seed được thử +- nghiệm tốt nhất có: + - `pos_err = ?` + - `ori_err = ?` +- pass hay fail vì lý do gì + +## 23.3. Tiêu chí đạt +Nghiệm grasp được chọn phải: +- có pose error thấp rõ rệt hơn trước khi sửa, +- không còn tình trạng “grasp pose lệch nhiều nhưng vẫn pass”. + +--- + +# 24. Bộ test 4 — Integration test full pick-place + +## 24.1. Mục tiêu +Đảm bảo sửa IK không phá vỡ pipeline tổng thể. + +## 24.2. Các kịch bản test +1. object đơn giản, không vật cản +2. object có vật cản gần đó +3. nhiều object liên tiếp +4. place pose cần orientation tương đối chính xác + +## 24.3. Theo dõi +- tỷ lệ tìm được IK +- tỷ lệ RRT thành công +- pose error của grasp / place +- số lần backtrack do IK fail + +--- + +# 25. Trình tự triển khai thực tế + +Dưới đây là thứ tự triển khai mình khuyên để sửa ít rủi ro nhất. + +--- + +# 26. Giai đoạn 1 — Sửa lõi solve IK + +## Việc cần làm +1. Tạo helper `_build_ik_seed_list(...)` +2. Tạo helper `_is_valid_ik_vector(...)` +3. Sửa `_solve_ik_candidates(...)` để: + - dùng `restPoses=q_seed` + - tăng iterations + - giảm residual + - deduplicate nghiệm + +## Kết quả mong muốn +Bạn đã có một solver multi-seed đúng bản chất hơn. + +--- + +# 27. Giai đoạn 2 — Sửa tầng validate IK + +## Việc cần làm +1. Chuẩn hóa `_check_joint_limits(...)` +2. Sửa `_validate_ik_solution(...)` theo thứ tự: + - sanity + - joint limit + - FK pose error + - collision +3. thêm helper `_compute_pose_error(...)` + +## Kết quả mong muốn +Nghiệm IK chỉ pass nếu thật sự bám sát pose. + +--- + +# 28. Giai đoạn 3 — Tạo cấu hình IK tập trung + +## Việc cần làm +Đưa toàn bộ tham số vào config: +- `IK_MAX_ITER` +- `IK_RESIDUAL_THRESHOLD` +- `IK_POS_TOL` +- `IK_ORI_TOL` +- `IK_NUM_RANDOM_SEEDS` +- `IK_DUPLICATE_Q_TOL` +- `IK_JOINT_LIMIT_EPS` + +## Kết quả mong muốn +Dễ tune, dễ so sánh trước/sau. + +--- + +# 29. Giai đoạn 4 — Thêm logging và benchmark + +## Việc cần làm +1. log chi tiết cho từng seed +2. log pose error của nghiệm được chọn +3. benchmark trước / sau sửa trên cùng một bộ grasp pose + +## Kết quả mong muốn +Bạn biết chính xác: +- sửa xong có giảm độ lệch grasp pose hay không, +- vấn đề còn nằm ở IK hay ở grasp candidate. + +--- + +# 30. Giai đoạn 5 — Tinh chỉnh tham số + +## Việc cần làm +Tune theo thứ tự: +1. `IK_POS_TOL`, `IK_ORI_TOL` +2. `IK_NUM_RANDOM_SEEDS` +3. `IK_MAX_ITER` +4. thứ tự seed ưu tiên + +## Lưu ý +Không tune collision trước khi tune xong pose accuracy, vì mục tiêu của Hướng 1 là **đưa pose IK về đúng trước**. + +--- + +# 31. Tiêu chí hoàn thành của Hướng 1 + +Kế hoạch này được xem là hoàn thành khi đạt đủ các điều kiện sau: + +## 31.1. Về mặt code +- `_solve_ik_candidates(...)` không còn dùng cùng một `restPose` cố định cho mọi seed +- đã có seed builder rõ ràng +- đã có sanity check cho nghiệm IK +- `_validate_ik_solution(...)` ưu tiên pose accuracy trước collision + +## 31.2. Về mặt hành vi +- grasp pose cuối cùng khớp target tốt hơn rõ rệt +- số nghiệm “pose lệch nhưng vẫn pass” giảm mạnh hoặc biến mất +- solver có thể sinh nhiều nghiệm khác nhau hơn khi đổi seed + +## 31.3. Về mặt log / đo lường +- có log `pos_err`, `ori_err` cho từng nghiệm được thử +- benchmark trước/sau cho thấy chất lượng IK tăng. + +--- + +# 32. Kết luận + +Hướng 1 là cách sửa **ít phá vỡ pipeline nhất** nhưng vẫn có khả năng cải thiện rất mạnh chất lượng IK cho Panda nếu triển khai đúng. + +Cốt lõi của hướng này là 4 điểm: + +1. **Biến multi-IK thành multi-IK thật** bằng cách solve quanh từng seed riêng, không dùng chung một `restPose` cố định. +2. **Siết mạnh pose tolerance** để IK chỉ pass khi grasp pose thực sự bám sát pose mong muốn. +3. **Tách rõ solve IK và validate IK**, trong đó pose accuracy phải được kiểm tra trước collision. +4. **Đưa seed strategy và tham số IK vào cấu trúc rõ ràng**, có logging để benchmark trước/sau. + +Nếu triển khai đầy đủ kế hoạch trên, bạn sẽ có một tầng IK tốt hơn đáng kể mà vẫn giữ nguyên PyBullet và phần lớn cấu trúc pipeline hiện tại. Điều này rất phù hợp làm bước chuyển tiếp trước khi cân nhắc sang **Hướng 2: solver IK tối ưu riêng / exact hơn cho Panda**. diff --git a/ke_hoach_sua_pipeline_executor.md b/ke_hoach_sua_pipeline_executor.md new file mode 100644 index 0000000000000000000000000000000000000000..4a2b1fc559816dabd9bcb396e73be2331705e51f --- /dev/null +++ b/ke_hoach_sua_pipeline_executor.md @@ -0,0 +1,996 @@ +# Kế hoạch sửa file cài đặt `pipeline_executor.py` để khớp với pipeline đã chốt + +## Mục tiêu của tài liệu + +Tài liệu này lập kế hoạch **sửa file cài đặt full pipeline** để nó khớp với pipeline mà bạn đã chốt trước đó, **chỉ tập trung vào các điểm lệch bản chất** đã được audit, **ngoại trừ điểm số 18**: + +- **Không xử lý lại điểm 18**: *trong lúc check collision khi đang mang vật, vẫn cho phép mô hình “attach ảo” để kiểm tra collision*. +- Tất cả các điểm lệch bản chất còn lại sẽ được chuyển thành **kế hoạch sửa chi tiết**, bao gồm: + - mục tiêu sửa, + - phạm vi ảnh hưởng, + - thay đổi thuật toán, + - thay đổi cấu trúc code, + - thứ tự triển khai, + - tiêu chí kiểm thử. + +--- + +# 1. Phạm vi các hạng mục phải sửa + +Dựa trên phần audit trước đó, các **điểm lệch bản chất cần sửa** là: + +## (A) Collision policy chưa đúng với rule đã chốt +Hiện tại code còn cho phép: +- penetration nhỏ với obstacle / target, +- finger với target có ngưỡng âm riêng, +- grasp pose chưa bám đúng rule **“chỉ cần có bất kỳ distance < 0 là collision”**. + +## (B) Collision policy tại grasp pose chưa đúng định nghĩa grasp pose +Hiện tại code cho phép finger-target chạm/penetrate theo tolerance tại grasp pose. +Trong khi theo pipeline của bạn: +- robot motion plan đến **grasp pose**, +- grasp pose là trạng thái để **đóng gripper**, +- collision rule vẫn là **không được va chạm với bất kỳ object nào kể cả target**. + +## (C) Thiếu self-collision checking rõ ràng +Hiện tại code kiểm tra robot với object ngoài, nhưng chưa có lớp kiểm tra self-collision đầy đủ và có hệ thống. + +## (D) IK stage chưa có cơ chế thử nhiều nghiệm IK cho cùng một pose +Hiện tại mỗi grasp pose / place pose mới gọi IK một lần. +Theo pipeline của bạn, cần: +- thử nhiều nghiệm IK cho cùng một pose, +- nghiệm nào collision-free thì dùng, +- nếu nghiệm đầu fail chưa được loại grasp pose ngay. + +## (E) Kiểm tra “đang giữ được vật” quá yếu +Hiện tại chỉ dùng kiểu: +- số lượng contact >= 2. + +Điều này chưa đủ để xác nhận object đang thực sự được giữ ổn định giữa 2 finger. + +## (F) Có cơ chế “snap object” về vị trí đích sau place +Đây là heuristic không đúng với tinh thần pipeline thực tế của bạn: +- object phải được đặt xuống bởi chuyển động + mở gripper, +- không được teleport object về đích để “cứu” pipeline. + +## (G) IK validation chưa đầy đủ +Ngoài chuyện chưa có multi-solution, hiện tại còn thiếu lớp kiểm tra: +- IK có trả về nghiệm hợp lệ không, +- nghiệm có NaN / sai kích thước không, +- nghiệm FK lại có thực sự đạt pose yêu cầu trong sai số cho phép không. + +--- + +# 2. Các nguyên tắc sửa chung + +Trước khi đi vào từng hạng mục, toàn bộ quá trình sửa sẽ tuân theo các nguyên tắc sau. + +## 2.1. Không thay đổi triết lý pipeline đã chốt +Pipeline sau khi sửa vẫn giữ đúng tinh thần hiện tại: + +- Sinh contact pair từ collision mesh. +- Duyệt tuần tự từng contact pair. +- Từ contact pair sinh grasp pose candidate. +- Với từng grasp pose candidate: + - giải IK, + - check collision, + - RRT-Connect pick, + - đóng gripper, + - kiểm tra có giữ được vật không, + - RRT-Connect place, + - đặt vật xuống. +- Nếu fail ở bất kỳ giai đoạn nào thì quay lui candidate / contact pair khác. +- Sau khi đặt xong nếu còn task thì plan từ trạng thái hiện tại, không quay về home. +- Chỉ khi hết nhiệm vụ mới plan về home. + +## 2.2. Không sửa điểm 18 +Trong tài liệu này **không đụng vào cơ chế collision checking khi carrying theo mô hình attach ảo**. +Nghĩa là: +- khi check collision cho quỹ đạo mang vật, +- vẫn cho phép dùng transform tương đối `T_obj_to_ee` để “đi theo” end-effector trong collision checker. + +## 2.3. Ưu tiên sửa các lớp nền tảng trước +Thứ tự sửa phải đi từ các lớp nền tảng vì các lớp sau phụ thuộc vào chúng: + +1. Chuẩn hóa **collision policy**. +2. Bổ sung **self-collision**. +3. Chuẩn hóa **IK validation + multi-solution IK**. +4. Chuẩn hóa **grasp success validation**. +5. Loại bỏ **snap object**. +6. Rà soát lại luồng backtracking và logging. + +## 2.4. Không phá vỡ API tổng thể của `PipelineExecutor` +Nếu có thể, nên giữ nguyên API ở mức cao như: +- `execute_tasks(...)` +- `_pick_and_place_single_object(...)` + +và tập trung thay đổi vào: +- các helper function, +- collision checker, +- IK helper, +- grasp validation helper. + +Mục tiêu là để phần sửa ít làm hỏng kiến trúc hiện tại nhất. + +--- + +# 3. Kế hoạch sửa chi tiết theo từng hạng mục + +--- + +# 4. Hạng mục A — Sửa collision policy về đúng rule của bài toán + +## 4.1. Mục tiêu +Đưa toàn bộ collision checking về đúng rule đã chốt: + +> Trong mọi giai đoạn (IK check, grasp pose check, motion planning, place check), robot **không được va chạm với bất kỳ object nào**, kể cả target object. +> Chỉ cần có **bất kỳ khoảng cách âm** (`distance < 0`) là coi như collision. + +## 4.2. Hiện trạng cần sửa +Hiện tại các hàm collision đang dùng ngưỡng như: +- `distance < -0.002` +- `distance < -0.005` + +và có logic nới riêng cho finger-target tại grasp pose. + +Điều này phải bị loại bỏ. + +## 4.3. Phạm vi code cần sửa +Các hàm cần rà soát trực tiếp: + +- `_check_static_collision(...)` +- `_check_carrying_collision(...)` +- mọi helper phụ gọi `pb.getClosestPoints(...)` hoặc `pb.getContactPoints(...)` để xác định collision +- mọi nhánh đặc biệt kiểu `is_grasp_pose=True` đang nới rule cho finger-target + +## 4.4. Kế hoạch sửa chi tiết + +### Bước A1 — Tạo một hàm primitive thống nhất để đọc khoảng cách collision +Tạo helper dùng chung, ví dụ: + +- `_has_penetration_between(bodyA, bodyB, linkA=None, linkB=None, max_distance=...)` +- `_collect_penetrations(bodyA, bodyB, ...)` + +Nhiệm vụ của helper: +1. gọi `pb.getClosestPoints(...)`, +2. duyệt toàn bộ point trả về, +3. nếu tồn tại `pt[8] < 0.0` thì kết luận có collision. + +### Bước A2 — Chuẩn hóa định nghĩa collision ở mức thấp nhất +Không để mỗi nơi tự viết một ngưỡng riêng. +Tất cả phải đi qua một định nghĩa chung: + +- `distance < 0.0` → collision +- `distance >= 0.0` → không collision + +Nếu muốn log, chỉ log riêng nhưng **không thay đổi rule**. + +### Bước A3 — Bỏ toàn bộ tolerance âm cho target và finger +Xóa toàn bộ logic kiểu: +- finger-target được phép `-0.005` +- non-finger được phép `-0.002` + +Sau khi sửa: +- finger vs target cũng áp dụng rule như mọi collision khác, +- obstacle vs arm cũng áp dụng y hệt, +- self-collision cũng áp dụng y hệt. + +### Bước A4 — Tách khái niệm “gần chạm” và “đã collision” +Nếu cần giữ thông tin chẩn đoán, có thể log thêm: +- `min_distance` +- danh sách pair gần chạm + +Nhưng tuyệt đối không dùng nó để nới collision policy. + +## 4.5. Kết quả mong muốn sau sửa +- Không còn bất kỳ “collision tolerance âm” nào trong code. +- Mọi collision checker trả kết quả nhất quán theo rule `distance < 0`. +- Không còn nhánh đặc biệt “grasp pose thì finger được phép chạm xuyên”. + +--- + +# 5. Hạng mục B — Sửa collision policy riêng của grasp pose + +## 5.1. Mục tiêu +Đảm bảo **grasp pose** trong code khớp với định nghĩa grasp pose của pipeline: + +- robot motion plan đến grasp pose, +- grasp pose là trạng thái để chuẩn bị đóng gripper, +- tại grasp pose **không được có collision** với target hay object khác, +- sau khi robot tới grasp pose mới thực hiện hành động đóng gripper. + +## 5.2. Vấn đề hiện tại +Code hiện tại đang có xu hướng coi grasp pose là trạng thái: +- finger đã áp sát target, +- thậm chí cho phép một ít penetration. + +Điều này không còn đúng với collision policy mà bạn chốt. + +## 5.3. Kế hoạch sửa chi tiết + +### Bước B1 — Định nghĩa lại grasp pose trong code +Viết rõ trong comment / docstring nội bộ: + +- `grasp pose` = pose của end-effector dùng để giải IK và motion planning. +- Ở pose này, gripper **chưa đóng**. +- Collision checker của grasp pose **không có ngoại lệ cho target**. + +### Bước B2 — Xóa nhánh logic “is_grasp_pose cho phép finger chạm target” +Nếu trong `_check_static_collision(q, target_object_id, is_grasp_pose=True, ...)` đang có nhánh đặc biệt cho finger-target thì phải xóa. + +Sau khi sửa: +- `is_grasp_pose=True` chỉ còn có ý nghĩa cho logging/debug nếu cần, +- không được thay đổi rule collision. + +### Bước B3 — Đồng bộ collision checker của RRT pick với checker của IK grasp +Điểm quan trọng là: +- state cuối `q_grasp` mà IK chấp nhận, +- và các state dọc đường trong RRT pick, + +phải dùng **cùng một collision policy**. +Không được có chuyện: +- IK check thì cấm, +- nhưng RRT edge check lại cho phép, +hoặc ngược lại. + +## 5.4. Kết quả mong muốn sau sửa +- grasp pose trở thành một trạng thái collision-free thật sự. +- RRT pick đang plan đến đúng một state hợp lệ theo policy. +- không còn “nới collision chỉ vì đây là grasp pose”. + +--- + +# 6. Hạng mục C — Bổ sung self-collision checking đầy đủ + +## 6.1. Mục tiêu +Bổ sung lớp kiểm tra **self-collision** để mọi nghiệm IK và mọi node/edge trong RRT đều bị loại nếu robot tự va chạm vào chính nó. + +## 6.2. Vấn đề hiện tại +Code hiện tại chủ yếu duyệt: +- robot vs object target, +- robot vs obstacle. + +Nhưng chưa có một lớp self-collision checker đầy đủ, rõ ràng, có thể tái sử dụng. + +## 6.3. Kế hoạch sửa kiến trúc + +### Bước C1 — Xây dựng danh sách cặp link self-collision cần kiểm tra +Tạo một cấu trúc dữ liệu ở lúc khởi tạo pipeline, ví dụ: + +- `self.self_collision_link_pairs` + +Danh sách này gồm các cặp link của robot cần kiểm tra collision. +Không nên kiểm tra mọi cặp một cách mù quáng; cần lọc bỏ các cặp: +- cùng một link, +- link cha-con kề nhau nếu mô hình robot khiến chúng luôn gần nhau, +- các cặp đã biết là luôn overlap hình học nhưng không phải collision thực. + +### Bước C2 — Tạo helper `_check_self_collision(q, diagnose=False)` +Hàm này: +1. set robot về cấu hình `q`, +2. duyệt các cặp link trong `self.self_collision_link_pairs`, +3. dùng `pb.getClosestPoints(robot_id, robot_id, ...)`, +4. nếu có `distance < 0` thì kết luận self-collision. + +### Bước C3 — Chèn self-collision vào tất cả các collision pipeline +Self-collision phải được gọi ở: +- kiểm tra IK grasp, +- kiểm tra IK place, +- collision function của RRT pick, +- collision function của RRT place / carrying. + +### Bước C4 — Chuẩn hóa thứ tự check trong `is_state_valid` +Đề xuất thứ tự: + +1. joint limit +2. self-collision +3. robot vs environment collision +4. robot vs target collision +5. nếu là carrying state thì thêm carried-object vs environment collision + +Thứ tự này giúp fail sớm ở những check rẻ hơn. + +## 6.4. Kiểm thử cần có +- cấu hình robot gập ngược vào chính nó phải bị loại. +- cấu hình không chạm object ngoài nhưng tự đâm vào thân robot vẫn phải bị loại. +- RRT không được trả về path có self-collision ở bất kỳ state nội suy nào. + +--- + +# 7. Hạng mục D — Bổ sung cơ chế multi-solution IK + +## 7.1. Mục tiêu +Với mỗi grasp pose / place pose, không được chỉ thử một nghiệm IK duy nhất. +Cần có cơ chế: + +- sinh nhiều nghiệm IK ứng viên, +- lọc joint limit, +- lọc sai số pose, +- lọc collision, +- nghiệm đầu tiên hợp lệ thì dùng. + +## 7.2. Vấn đề hiện tại +Hiện tại code kiểu: +- `q = _ik(pos, ori)` +- nếu `q` collision thì loại luôn grasp pose / place pose + +Điều này loại bỏ quá sớm rất nhiều pose vốn có nghiệm khác hợp lệ. + +## 7.3. Kế hoạch sửa kiến trúc + +### Bước D1 — Tách IK thành một solver wrapper riêng +Tạo helper mới, ví dụ: + +- `_solve_ik_candidates(target_pos, target_ori, seed_q=None, max_trials=K, context="grasp"|"place")` + +Hàm này **không trả một nghiệm**, mà trả về **một danh sách nghiệm IK ứng viên**. + +## 7.4. Cách sinh nhiều nghiệm IK + +### Phương án đề xuất +Vì đang dùng PyBullet IK, có thể sinh nhiều nghiệm bằng cách lặp qua nhiều seed / rest pose: + +- seed hiện tại `q_start` +- seed home pose +- seed ngẫu nhiên trong joint limits +- seed lấy từ một số posture template nếu có + +Với mỗi seed: +1. reset robot về seed đó, +2. gọi IK, +3. lấy ra nghiệm, +4. lưu lại nếu không trùng nghiệm đã có. + +### Số lượng trial đề xuất +- grasp IK: 10–30 seeds / candidate +- place IK: 10–20 seeds / candidate + +## 7.5. Pipeline lọc nghiệm IK + +Mỗi nghiệm IK ứng viên phải qua 4 tầng lọc: + +### Tầng D2.1 — Kiểm tra cấu trúc nghiệm +- không `None` +- không NaN +- đúng số chiều joint +- nằm trong domain số hợp lệ + +### Tầng D2.2 — Kiểm tra joint limits +- mọi khớp trong giới hạn + +### Tầng D2.3 — Kiểm tra pose error bằng forward kinematics +Sau khi set robot về nghiệm IK: +- đo lại pose của end-effector, +- so với pose yêu cầu. + +Đặt ngưỡng ví dụ: +- sai số vị trí ≤ `eps_pos` +- sai số orientation ≤ `eps_ori` + +Nghiệm nào không đạt pose target đủ gần thì loại. + +### Tầng D2.4 — Kiểm tra collision +Tùy context: +- grasp IK → check static collision +- place IK → check static collision hoặc place-state collision tương ứng + +## 7.6. Chính sách sử dụng nghiệm IK trong pipeline + +### Với grasp pose candidate +- sinh danh sách nghiệm IK hợp lệ cho grasp pose +- duyệt từng nghiệm: + 1. check collision, + 2. thử RRT pick, + 3. nếu pick plan thành công thì mới đi tiếp. + +### Với place pose candidate +- tương tự: place pose phải thử nhiều nghiệm IK, +- nghiệm nào cho RRT place thành công thì dùng. + +## 7.7. Tối ưu để tránh nổ chi phí tính toán +Vì multi-IK có thể làm pipeline chậm, cần các biện pháp: + +- giới hạn số seed / số nghiệm tối đa, +- cache nghiệm IK theo `(target_pose, seed_bucket)` nếu cần, +- dừng sớm ngay khi tìm được nghiệm hợp lệ đầu tiên. + +--- + +# 8. Hạng mục E — Chuẩn hóa IK validation + +## 8.1. Mục tiêu +Ngoài việc sinh nhiều nghiệm, còn phải chuẩn hóa khâu **validation** cho từng nghiệm IK để tránh các lỗi ngầm. + +## 8.2. Kế hoạch sửa +Tạo helper: + +- `_validate_ik_solution(q, target_pos, target_ori, mode, target_object_id=None, carrying_info=None, diagnose=False)` + +Helper này làm toàn bộ: +1. kiểm tra `q` có hợp lệ về mặt dữ liệu không, +2. check joint limits, +3. set robot vào `q`, +4. forward kinematics để đo sai số, +5. gọi collision checker tương ứng, +6. trả về: + - `valid / invalid` + - `reason` + - `pose_error` + - `collision_info` nếu cần log. + +## 8.3. Lợi ích +- grasp IK và place IK dùng chung một quy trình kiểm định, +- dễ debug vì biết nghiệm bị loại vì: + - out of limit, + - FK sai số lớn, + - self-collision, + - collision với target, + - collision với obstacle. + +--- + +# 9. Hạng mục F — Sửa logic xác nhận “đang giữ được vật” + +## 9.1. Mục tiêu +Thay thế tiêu chí hiện tại `len(contacts) >= 2` bằng một tiêu chí chặt hơn, bám đúng bài toán grasp hai finger. + +## 9.2. Vấn đề hiện tại +`len(contacts) >= 2` không đảm bảo: +- contact đến từ 2 finger khác nhau, +- object được giữ ổn định, +- object không chỉ chạm vào palm / arm. + +## 9.3. Kế hoạch sửa chi tiết + +### Bước F1 — Xác định rõ finger links +Ở lúc khởi tạo pipeline, lưu: +- `left_finger_link_id` +- `right_finger_link_id` + +Nếu gripper có nhiều pad/khớp con, cần lưu cả tập link tương ứng cho mỗi bên: +- `left_finger_links` +- `right_finger_links` + +### Bước F2 — Tạo helper `_check_grasp_success(object_id, settle_steps=..., diagnose=False)` +Hàm này chỉ được gọi **sau khi đóng gripper**. + +### Bước F3 — Điều kiện grasp success tối thiểu +Đề xuất điều kiện tối thiểu: + +#### Điều kiện 1 — Có contact ở cả hai bên finger +Phải có: +- ít nhất một contact giữa object và **finger trái**, +- ít nhất một contact giữa object và **finger phải**. + +#### Điều kiện 2 — Object không bị rơi sau giai đoạn settle ngắn +Sau khi đóng gripper, step simulation thêm `N` bước nhỏ để object ổn định. +So sánh: +- vị trí object trước và sau settle, +- nếu object tụt xuống quá nhiều hoặc rơi khỏi vùng giữa 2 finger thì fail. + +#### Điều kiện 3 — Object không chỉ đang cấn vào arm / palm +Có thể thêm kiểm tra: +- contact chính phải đến từ finger links, +- nếu object chỉ chạm palm mà không chạm đủ hai finger thì không coi là grasp success. + +## 9.4. Điều kiện nâng cao có thể thêm sau +Nếu muốn chặt hơn ở bản sau: +- kiểm tra hướng contact normal, +- kiểm tra object center nằm gần vùng giữa hai finger, +- kiểm tra khoảng mở gripper sau khi đóng. + +## 9.5. Cách tích hợp vào pipeline +Sau khi execute pick path và đóng gripper: +1. gọi `_check_grasp_success(object_id)`, +2. nếu fail: + - restore snapshot của candidate hiện tại, + - thử candidate / IK khác. + +--- + +# 10. Hạng mục G — Loại bỏ cơ chế “snap object” về đích + +## 10.1. Mục tiêu +Loại bỏ hoàn toàn heuristic teleport object về vị trí đặt nếu place execution bị lệch. + +## 10.2. Vấn đề hiện tại +Hiện tại code có nhánh: +- nếu sau khi thả object mà object lệch quá xa place goal, +- thì reset object về đúng vị trí đích. + +Điều này trái với tinh thần mô phỏng thực tế mà bạn đang theo. + +## 10.3. Kế hoạch sửa chi tiết + +### Bước G1 — Xóa nhánh `resetBasePositionAndOrientation(...)` dùng để snap về đích +Bất kỳ logic nào kiểu: +- nếu `dist_err > threshold` thì teleport object về goal +đều phải bị bỏ. + +### Bước G2 — Thay snap bằng kiểm tra place success thực sự +Tạo helper: + +- `_check_place_success(object_id, desired_place_pose, pos_tol, ori_tol=None, diagnose=False)` + +Hàm này: +1. sau khi robot mở gripper và settle vài bước, +2. đo pose thật của object, +3. so với place goal. + +Nếu sai số vượt ngưỡng: +- **coi là fail**, +- rollback candidate, +- thử candidate khác. + +### Bước G3 — Xác định chuẩn place success phù hợp với bài toán +Vì pipeline hiện tại có vẻ đang đặt vật lên tray/slot, có thể dùng: + +- sai số vị trí tâm object so với goal ≤ `place_pos_tol` +- nếu bài toán chưa quan tâm orientation thì chỉ cần check vị trí +- nếu sau này có full pose place thì check cả orientation + +## 10.4. Tác động đến luồng pipeline +Sau khi bỏ snap: +- tỷ lệ fail place có thể tăng, +- nhưng kết quả sẽ đúng hơn với bài toán thật. + +Do đó cần đảm bảo: +- pipeline có rollback state tốt, +- place failure sẽ quay lui candidate hợp lý. + +--- + +# 11. Hạng mục H — Chuẩn hóa luồng rollback / backtracking khi pick hoặc place fail + +## 11.1. Mục tiêu +Dù file hiện tại đã có `saveState()/restoreState()`, sau khi sửa thêm multi-IK và grasp validation, cần chuẩn hóa lại luồng rollback để tránh trạng thái rác. + +## 11.2. Kế hoạch sửa +Với **mỗi contact pair candidate**, khi bắt đầu thử cần tạo snapshot. +Mọi failure trong nhánh đó phải quay về snapshot này trước khi thử candidate tiếp theo. + +## 11.3. Đề xuất cấu trúc rollback + +### Snapshot cấp contact pair +Ngay trước khi bắt đầu thử một contact pair: +- lưu state snapshot của toàn simulation. + +### Snapshot cấp grasp candidate / IK candidate +Nếu cần tối ưu rollback mịn hơn, có thể dùng thêm snapshot ở cấp grasp candidate, nhưng không bắt buộc nếu snapshot cấp contact pair đủ sạch. + +## 11.4. Các tình huống bắt buộc rollback +Rollback phải xảy ra nếu: +- grasp IK fail hết, +- pick RRT fail, +- grasp execution fail, +- grasp success fail, +- place IK fail hết, +- place RRT fail, +- place execution fail, +- place success fail. + +## 11.5. Mục tiêu của rollback +Sau rollback, trạng thái phải quay về đúng trước khi thử candidate: +- pose robot, +- pose object, +- trạng thái gripper, +- động học mô phỏng. + +--- + +# 12. Thiết kế lại lớp helper validity để giảm lặp code + +Sau khi sửa các hạng mục trên, nếu vẫn giữ cách viết rải logic ở nhiều nơi thì file sẽ rất khó bảo trì. +Vì vậy cần gom lại các helper validity. + +## 12.1. Bộ helper đề xuất + +### Nhóm collision +- `_has_penetration_between(...)` +- `_check_self_collision(q, ...)` +- `_check_static_collision(q, target_object_id, ...)` +- `_check_carrying_collision(q, target_object_id, T_obj_to_ee, ...)` + +### Nhóm IK +- `_solve_ik_candidates(...)` +- `_validate_ik_solution(...)` + +### Nhóm execution validation +- `_check_grasp_success(...)` +- `_check_place_success(...)` + +### Nhóm motion validity +- `_make_pick_collision_fn(target_object_id)` +- `_make_place_collision_fn(target_object_id, T_obj_to_ee)` + +## 12.2. Lợi ích +- tránh lặp logic giữa grasp/place, +- dễ test đơn vị từng phần, +- dễ bật `diagnose=True` để debug. + +--- + +# 13. Kế hoạch thay đổi luồng `_pick_and_place_single_object(...)` + +Đây là phần quan trọng nhất vì mọi sửa lớn cuối cùng đều hội tụ về luồng chính. + +## 13.1. Luồng mới sau khi sửa + +### Bước 1 — Sinh contact pair +- load mesh collision, +- sinh antipodal contact pairs, +- duyệt tuần tự. + +### Bước 2 — Với từng contact pair, sinh grasp pose candidates +- từ contact pair sinh các orientation roll candidates, +- duyệt tuần tự. + +### Bước 3 — Với mỗi grasp pose candidate, giải nhiều nghiệm IK +- gọi `_solve_ik_candidates(grasp_pose, seed_q=q_start, context="grasp")` +- nhận danh sách `grasp_ik_candidates` + +### Bước 4 — Duyệt từng grasp IK candidate +Mỗi `q_grasp` phải qua: +1. `_validate_ik_solution(..., mode="grasp")` +2. nếu hợp lệ thì thử `RRT pick` + +### Bước 5 — Nếu pick path thành công thì execute pick +- thực thi quỹ đạo pick, +- đóng gripper, +- settle vài bước, +- gọi `_check_grasp_success(object_id)` + +Nếu grasp fail: +- rollback snapshot, +- thử IK / grasp candidate khác. + +### Bước 6 — Nếu grasp thành công thì sinh place pose và giải nhiều nghiệm IK place +- tính place target object pose, +- suy ra desired EE place pose, +- gọi `_solve_ik_candidates(..., context="place")` + +### Bước 7 — Duyệt từng place IK candidate +Mỗi `q_place` phải qua: +1. `_validate_ik_solution(..., mode="place")` +2. `RRT place` với carrying collision checker + +### Bước 8 — Nếu place path thành công thì execute place +- thực thi quỹ đạo place, +- mở gripper, +- settle simulation, +- gọi `_check_place_success(object_id, desired_place_pose, ...)` + +Nếu place fail: +- rollback snapshot, +- thử candidate khác. + +### Bước 9 — Nếu place success +- cập nhật `q_current`, +- trả `success=True`. + +### Bước 10 — Nếu tất cả contact pair / grasp candidate / IK candidate đều fail +- trả `success=False`. + +--- + +# 14. Kế hoạch triển khai theo từng phase lập trình + +Để tránh sửa một lúc quá nhiều thứ rồi vỡ code, nên triển khai theo 5 phase. + +--- + +# Phase 1 — Chuẩn hóa collision nền tảng + +## Mục tiêu +Sửa xong: +- Hạng mục A, +- Hạng mục B, +- phần lõi của Hạng mục C. + +## Việc phải làm +1. Tạo helper `_has_penetration_between(...)`. +2. Sửa `_check_static_collision(...)` theo rule `distance < 0`. +3. Sửa `_check_carrying_collision(...)` theo cùng rule. +4. Xóa mọi tolerance âm. +5. Xóa mọi ngoại lệ finger-target ở grasp pose. +6. Tạo danh sách self-collision link pairs. +7. Viết `_check_self_collision(...)`. +8. Chèn self-collision vào collision checker. + +## Kết quả mong muốn +- collision policy đúng tuyệt đối với rule bài toán, +- self-collision đã được check ở mọi state validity. + +--- + +# Phase 2 — Xây lớp IK chuẩn + +## Mục tiêu +Sửa xong: +- Hạng mục D, +- Hạng mục E. + +## Việc phải làm +1. Viết `_solve_ik_candidates(...)`. +2. Viết `_validate_ik_solution(...)`. +3. Thêm FK pose error check. +4. Thêm multi-seed IK. +5. Tích hợp vào nhánh grasp. +6. Tích hợp vào nhánh place. + +## Kết quả mong muốn +- không còn phụ thuộc vào một nghiệm IK duy nhất, +- lý do fail của IK được phân loại rõ. + +--- + +# Phase 3 — Chuẩn hóa grasp success + +## Mục tiêu +Sửa xong: +- Hạng mục F. + +## Việc phải làm +1. Khai báo rõ left/right finger links. +2. Viết `_check_grasp_success(...)`. +3. Sau khi close gripper, dùng helper mới thay cho `len(contacts) >= 2`. +4. Kiểm thử các case object chỉ chạm một finger hoặc chạm palm. + +## Kết quả mong muốn +- chỉ coi là pick thành công khi object thực sự được giữ giữa hai finger. + +--- + +# Phase 4 — Loại bỏ snap object và chuẩn hóa place success + +## Mục tiêu +Sửa xong: +- Hạng mục G. + +## Việc phải làm +1. Xóa nhánh teleport object về goal. +2. Viết `_check_place_success(...)`. +3. Sau khi mở gripper, settle rồi đo pose object. +4. Nếu fail thì rollback candidate thay vì snap. + +## Kết quả mong muốn +- place result hoàn toàn đến từ motion + release thật, +- không còn heuristic cứu hộ. + +--- + +# Phase 5 — Chuẩn hóa rollback, logging và regression test + +## Mục tiêu +Sửa xong: +- Hạng mục H, +- dọn sạch luồng chính. + +## Việc phải làm +1. Rà lại mọi nhánh `continue` trong `_pick_and_place_single_object(...)`. +2. Đảm bảo mỗi nhánh fail đều restore snapshot đúng mức. +3. Thêm logging reason theo từng tầng: + - grasp IK fail vì gì, + - pick RRT fail vì gì, + - grasp success fail vì gì, + - place IK fail vì gì, + - place RRT fail vì gì, + - place success fail vì gì. +4. Viết regression test cơ bản. + +--- + +# 15. Ma trận sửa đổi theo hàm + +Dưới đây là danh sách các hàm dự kiến cần sửa / thêm. + +## 15.1. Hàm cần sửa mạnh + +### `_check_static_collision(...)` +Sửa: +- bỏ tolerance âm, +- thêm self-collision, +- bỏ grasp exception. + +### `_check_carrying_collision(...)` +Sửa: +- bỏ tolerance âm, +- thêm self-collision, +- giữ nguyên mô hình attach ảo khi carrying vì điểm 18 được miễn sửa. + +### `_pick_and_place_single_object(...)` +Sửa: +- thay 1 nghiệm IK bằng multi-IK, +- thay grasp success checker, +- thay place success checker, +- bỏ snap object, +- chuẩn hóa rollback. + +## 15.2. Hàm mới cần thêm + +### Collision / validity +- `_has_penetration_between(...)` +- `_check_self_collision(...)` + +### IK +- `_solve_ik_candidates(...)` +- `_validate_ik_solution(...)` + +### Execution result +- `_check_grasp_success(...)` +- `_check_place_success(...)` + +### Utility +- `_build_self_collision_pairs()` +- `_fk_end_effector_pose(q)` hoặc helper tương đương + +--- + +# 16. Chi tiết tiêu chí kiểm thử sau sửa + +Sau khi sửa xong, cần test ít nhất các nhóm sau. + +--- + +# 17. Test nhóm collision policy + +## Test C1 — Penetration rất nhỏ vẫn phải fail +Tạo một state mà finger hoặc link robot đâm vào object chỉ rất nhỏ, ví dụ `-1e-4`. +Kết quả mong muốn: +- collision checker trả **collision**. + +## Test C2 — Finger-target ở grasp pose cũng không được phép xuyên +Một grasp pose mà finger chạm xuyên nhẹ vào target phải bị loại. + +## Test C3 — State không penetration thì pass +Nếu mọi distance đều ≥ 0 thì collision checker phải pass. + +--- + +# 18. Test nhóm self-collision + +## Test S1 — Robot tự gập đâm vào chính nó +Cấu hình self-collision phải bị loại cả ở: +- IK validation, +- RRT state validity. + +## Test S2 — Không self-collision thì không bị loại oan +Cấu hình bình thường không được bị đánh dấu self-collision. + +--- + +# 19. Test nhóm multi-IK + +## Test I1 — Nghiệm IK đầu tiên collision, nghiệm thứ hai hợp lệ +Pipeline phải vẫn tiếp tục được nhờ nghiệm thứ hai. + +## Test I2 — Nghiệm IK sai pose do solver lỗi +Nếu FK lại không khớp target pose, nghiệm phải bị loại. + +## Test I3 — Tất cả nghiệm đều fail +Grasp candidate / place candidate phải bị loại sạch và quay lui đúng. + +--- + +# 20. Test nhóm grasp success + +## Test G1 — Object chỉ chạm một finger +Không được coi là grasp thành công. + +## Test G2 — Object chạm cả hai finger nhưng tụt xuống sau settle +Không được coi là grasp thành công. + +## Test G3 — Object được giữ ổn định giữa hai finger +Phải pass. + +--- + +# 21. Test nhóm place success + +## Test P1 — Object được thả gần goal trong tolerance +Phải pass. + +## Test P2 — Object lệch goal quá xa +Phải fail, **không được snap về goal**. + +## Test P3 — Place fail thì pipeline phải quay lui candidate khác +Kiểm tra rollback hoạt động đúng. + +--- + +# 22. Test tích hợp end-to-end + +## Test E2E1 — Một object, một contact pair thành công +Pipeline hoàn tất pick-place. + +## Test E2E2 — Contact pair đầu fail, contact pair sau thành công +Pipeline phải backtrack đúng. + +## Test E2E3 — Grasp thành công nhưng place fail, sau đó thử candidate khác thành công +Pipeline phải rollback sạch và hoàn tất. + +## Test E2E4 — Nhiều object liên tiếp +Sau object thứ nhất, robot phải plan tiếp từ trạng thái hiện tại thay vì về home. + +--- + +# 23. Thứ tự ưu tiên sửa bắt buộc / nên có / tối ưu thêm + +## 23.1. Bắt buộc phải sửa ngay +1. Collision policy `distance < 0`. +2. Bỏ mọi grasp exception cho finger-target. +3. Self-collision checking. +4. Multi-solution IK. +5. Bỏ snap object. +6. Grasp success checker mới. + +## 23.2. Nên sửa ngay trong cùng đợt +1. IK validation có FK error check. +2. Chuẩn hóa rollback và logging fail reason. +3. Chuẩn hóa helper validity để giảm lặp code. + +## 23.3. Có thể để đợt sau nếu cần +1. Tối ưu cache IK. +2. Tối ưu self-collision pair filtering. +3. Chấm điểm / ưu tiên contact pair thông minh hơn. +4. Cải thiện heuristic sinh orientation từ contact pair. + +--- + +# 24. Kế hoạch công việc dạng checklist triển khai + +## Giai đoạn 1 — Chuẩn hóa collision +- [ ] Tạo helper `_has_penetration_between(...)` +- [ ] Xóa mọi tolerance âm trong `_check_static_collision(...)` +- [ ] Xóa mọi tolerance âm trong `_check_carrying_collision(...)` +- [ ] Xóa ngoại lệ finger-target tại grasp pose +- [ ] Tạo `self_collision_link_pairs` +- [ ] Viết `_check_self_collision(...)` +- [ ] Chèn self-collision vào static/carrying collision + +## Giai đoạn 2 — Nâng cấp IK +- [ ] Viết `_solve_ik_candidates(...)` +- [ ] Viết `_validate_ik_solution(...)` +- [ ] Thêm FK pose error check +- [ ] Thêm multi-seed IK cho grasp +- [ ] Thêm multi-seed IK cho place +- [ ] Tích hợp vào luồng pick-place + +## Giai đoạn 3 — Nâng cấp grasp validation +- [ ] Khai báo rõ left/right finger links +- [ ] Viết `_check_grasp_success(...)` +- [ ] Thay logic `len(contacts) >= 2` + +## Giai đoạn 4 — Nâng cấp place validation +- [ ] Xóa snap object +- [ ] Viết `_check_place_success(...)` +- [ ] Tích hợp place success vào pipeline +- [ ] Nếu place fail thì rollback thay vì teleport + +## Giai đoạn 5 — Hoàn thiện pipeline +- [ ] Chuẩn hóa rollback mọi nhánh fail +- [ ] Thêm logging reason +- [ ] Viết test unit cho collision / IK / grasp / place +- [ ] Viết test end-to-end + +--- + +# 25. Kết luận + +Nếu chỉ xét **những điểm lệch bản chất** cần sửa trong file `pipeline_executor.py` và **bỏ qua điểm 18 theo yêu cầu**, thì kế hoạch sửa nên được triển khai theo đúng thứ tự sau: + +1. **Sửa collision policy** về đúng rule `distance < 0` cho mọi giai đoạn. +2. **Xóa ngoại lệ grasp pose** và đồng bộ lại định nghĩa grasp pose. +3. **Bổ sung self-collision checking** ở toàn bộ state validity. +4. **Xây lại tầng IK** theo hướng nhiều nghiệm + validation chuẩn. +5. **Thay logic grasp success** để thật sự xác nhận object được giữ giữa hai finger. +6. **Bỏ snap object** và thay bằng kiểm tra place success thật. +7. **Chuẩn hóa rollback / logging / test** để pipeline ổn định sau khi sửa. + +Nếu hoàn thành đầy đủ các hạng mục trên, file cài đặt sẽ tiến gần hơn rất nhiều tới pipeline mà bạn đã chốt: +- grasp pose collision-free thật sự, +- IK không còn loại ứng viên quá sớm, +- robot không tự đâm vào chính nó, +- pick success / place success được xác nhận bằng tiêu chí vật lý hợp lý hơn, +- không còn cơ chế “cứu” pipeline bằng teleport object về đích. + diff --git a/ke_hoach_sua_pipeline_gui_direct_playback.md b/ke_hoach_sua_pipeline_gui_direct_playback.md new file mode 100644 index 0000000000000000000000000000000000000000..8be683862e2f6ea506c9bb6f9bb48c7e07373ead --- /dev/null +++ b/ke_hoach_sua_pipeline_gui_direct_playback.md @@ -0,0 +1,1061 @@ +# Kế hoạch sửa `pipeline_executor.py` +## Mục tiêu: **Planning/test chạy ngầm trong DIRECT, chỉ playback nghiệm cuối trên GUI** + **loại bỏ hiện tượng robot giật ở cuối khi về home** + +--- + +# 1. Mục tiêu sửa chính thức + +Tài liệu này là **kế hoạch sửa code chi tiết dựa trên file `pipeline_executor.py` hiện tại** để đạt đúng hai mục tiêu bạn đã chốt: + +## Mục tiêu A — Không dùng GUI để search/test candidate +Toàn bộ các bước sau phải chạy **ngầm trong DIRECT**: +- sinh candidate grasp +- dựng grasp pose +- IK +- collision check +- RRT pick / place +- **physical verification** của candidate: + - chạy pick path + - close gripper + - step simulation + - carry + - place + - kiểm tra grasp/place thành công + +## Mục tiêu B — GUI chỉ dùng để playback nghiệm cuối +Khi **đã chọn được candidate thắng cuối cùng** cho object hiện tại: +- bắt buộc restore GUI về đúng trạng thái đầu của object đó +- phát lại **đúng trajectory thắng cuối cùng** trên GUI: + - pick path + - close gripper + - carry / place path + - open gripper + - retreat cuối nếu có + +## Mục tiêu C — Không để robot GUI bị giật/teleport khi return home +- planning về home **không được** collision-check trên robot GUI +- home planning phải chạy trong **DIRECT planning world** +- GUI chỉ playback `home_path` cuối cùng + +--- + +# 2. Kết luận chẩn đoán từ file hiện tại + +Dựa trên file `pipeline_executor.py` hiện tại, có 2 cụm logic gây ra đúng 2 vấn đề bạn mô tả: + +--- + +## 2.1. Vấn đề 1: Candidate đang được “thử thật trên GUI” ngay trong quá trình search + +Trong phiên bản pipeline hiện tại, `_pick_and_place_single_object(...)` đang làm theo pattern: + +1. worker validate candidate +2. worker plan candidate +3. nếu candidate có plan thành công + → **main process restore GUI state rồi chạy pick/place vật lý ngay trên GUI** +4. nếu fail vật lý thì restore snapshot và thử candidate khác + +Phần logic này xuất hiện ở nhánh xử lý kết quả planning trong `_pick_and_place_single_object(...)`, nơi code hiện tại làm những việc như: +- `pb.restoreState(state_snapshot_id)` +- `self.gripper.open()` +- `pb.configureDebugVisualizer(pb.COV_ENABLE_RENDERING, 1)` +- `self._execute_path(val["pick_path"])` +- `self.gripper.close(force)` +- `self._execute_path_carrying(val["place_path"], object_id, force)` +rồi nếu fail lại `restoreState(...)` và tiếp tục thử candidate khác. fileciteturn7file0L684-L724 + +### Hệ quả +GUI hiện tại đang bị dùng làm **execution test world**, không còn là pure playback world. + +--- + +## 2.2. Vấn đề 2: Robot bị giật ở cuối khi return home + +Trong `execute_tasks(...)`, sau khi xong toàn bộ object, code hiện tại tạo `RRTConnectPlanner` với collision function: + +```python +def simple_collision_fn(q): + return self._check_static_collision(q, target_object_id=None) +``` + +rồi gọi: + +```python +home_path = rrt.plan(q_current, q_home) +``` + +và nếu thành công thì `_execute_path(home_path)`. fileciteturn7file0L523-L537 + +### Gốc lỗi +`_check_static_collision(q, ...)` trên main world hiện tại dùng kiểu: +- lưu joint state cũ +- `resetJointState(...)` robot sang q test +- `performCollisionDetection()` +- restore về q cũ + +Điều này bình thường nếu chạy trong **DIRECT planning world**, nhưng hiện tại đang chạy trên **robot GUI**. +Vì RRT thử rất nhiều q mẫu, robot GUI bị nhảy qua lại giữa các q test → tạo cảm giác **giật / teleport**. + +--- + +# 3. Định hướng sửa kiến trúc: tách **Planning / Physical Test / GUI Playback** + +Sau khi sửa, pipeline phải được tổ chức thành **3 vai trò rõ ràng**: + +--- + +# 4. Kiến trúc sau sửa + +## 4.1. GUI world (main world) +Đây là world hiện tại của `self.sim`, `self.robot_id`, `self.scene`, `self.gripper`. + +### GUI world sau sửa chỉ được phép làm: +- hiển thị scene cho người dùng +- playback **nghiệm cuối cùng đã được chọn** +- playback đường về home cuối cùng + +### GUI world tuyệt đối không được dùng để: +- solve IK candidate +- collision-check candidate +- RRT pick / place / home +- physical test candidate thắng tạm thời / candidate fail + +--- + +## 4.2. Planning DIRECT world +Một world PyBullet `DIRECT` chuyên dùng cho: +- IK grasp / place +- collision check grasp-state +- collision check carrying-state +- RRT pick +- RRT place +- RRT home +- các phép teleport state để đọc transform / check collision + +### Planning DIRECT world không làm: +- playback GUI +- render +- quyết định visual + +--- + +## 4.3. Execution DIRECT world +Một world PyBullet `DIRECT` chuyên dùng cho: +- chạy thử `pick_path` +- close gripper +- step physics +- kiểm tra object có được giữ không +- chạy `place_path` +- open gripper +- kiểm tra object được đặt thành công + +### Execution DIRECT world là nơi thay thế cho logic: +> “candidate plan xong → test vật lý ngay trên GUI” + +--- + +# 5. Nguyên tắc sửa bắt buộc + +## 5.1. Candidate thắng chỉ được xác nhận sau **DIRECT physical verification** +Một candidate chỉ được coi là “nghiệm cuối cùng” nếu: +1. plan pick thành công trong DIRECT planning world +2. plan place thành công trong DIRECT planning world +3. physical execution trong DIRECT execution world thành công + +Chỉ sau đó mới được: +- phát lại trên GUI +- cập nhật trạng thái `q_current` +- chốt object đó là hoàn thành + +--- + +## 5.2. GUI playback không được quyết định pass/fail của candidate +GUI chỉ nhận **một gói trajectory cuối** và phát lại. +Nếu GUI playback fail vì visual/sync thì **không được** ảnh hưởng tới logic chọn candidate. + +--- + +## 5.3. Home planning phải tách khỏi GUI hoàn toàn +- planning home trong DIRECT +- GUI chỉ phát lại `home_path` sau khi planner DIRECT đã xong + +--- + +# 6. Cấu trúc dữ liệu mới cần có + +Để chuyển candidate test sang DIRECT nhưng vẫn playback đúng trên GUI, cần chuẩn hóa dữ liệu kết quả của candidate thắng. + +--- + +# 7. `FinalCandidatePlan` — cấu trúc kết quả cuối cho một object + +Đề xuất tạo một cấu trúc dict / dataclass chứa đầy đủ mọi thứ GUI cần để playback: + +```python +FinalCandidatePlan = { + "object_name": ..., + "object_id_name": ..., + "goal_location": ..., + + # Candidate identity + "cp_idx": ..., + "gc_idx": ..., + + # Pose / joint result + "q_start": [...], + "q_grasp": [...], + "q_place": [...], + "q_after": [...], # q sau retreat / sau object hoàn tất + "pick_path": [...], # list[q] + "place_path": [...], # list[q] + "retreat_path": [...], # có thể [] hoặc [q_retreat] + + # Physical execution parameters + "grasp_force": ..., + "T_obj_to_ee": (...), + + # Placement target info + "place_pos": [...], + "object_half_height": ..., + + # Snapshots / scene state + "gui_pre_object_snapshot": ... hoặc GUIWorldSnapshot object, + "direct_exec_final_object_pose": (...), +} +``` + +--- + +# 8. Snapshot cần tách riêng thành 2 loại + +## 8.1. `GUIWorldSnapshot` +Dùng để playback một object trên GUI. +Chụp **trạng thái đầu object đó** trong GUI world, gồm: + +- `robot_joints` +- `gripper_joints` +- pose của mọi object trong scene +- nếu có dynamic object state khác thì lưu thêm + +## 8.2. `DirectSceneSnapshot` +Dùng cho planning/execution DIRECT world. +Chụp trạng thái tương tự nhưng nằm trong **DIRECT world**. + +--- + +# 9. Hàm cần thêm mới + +Đây là phần quan trọng nhất của kế hoạch sửa. + +--- + +# 10. Hàm mới số 1: `_capture_gui_snapshot()` + +## Mục đích +Chụp trạng thái GUI trước khi bắt đầu xử lý một object. + +## Chữ ký gợi ý +```python +def _capture_gui_snapshot(self) -> dict: + ... +``` + +## Dữ liệu cần lưu +- joint arm hiện tại +- joint gripper hiện tại +- pose của toàn bộ object trong `self.scene.object_ids` + +## Dùng ở đâu +Đầu `_pick_and_place_single_object(...)`, ngay sau khi xác định `object_id`, `place_pos`, trước khi bắt đầu search candidate. + +--- + +# 11. Hàm mới số 2: `_restore_gui_snapshot(snapshot)` + +## Mục đích +Khôi phục GUI về đúng trạng thái đầu object trước khi playback nghiệm cuối. + +## Chữ ký gợi ý +```python +def _restore_gui_snapshot(self, snapshot: dict) -> None: + ... +``` + +## Yêu cầu +- restore robot joints +- restore gripper joints +- restore object poses + +### Lưu ý +Không dùng `pb.restoreState()` cho snapshot logic dài hạn nếu snapshot đó được tạo trong world khác hoặc dễ bị vòng đời state id ảnh hưởng. +Nên tự restore bằng: +- `resetJointState(...)` +- `resetBasePositionAndOrientation(...)` + +--- + +# 12. Hàm mới số 3: `_simulate_candidate_in_direct(...)` + +Đây là **hàm quan trọng nhất** để thay thế việc candidate được thử trên GUI. + +## Mục đích +Chạy **physical verification ngầm** cho candidate đã có `pick_path` và `place_path`. + +## Chữ ký gợi ý +```python +def _simulate_candidate_in_direct( + self, + exec_world, + object_name: str, + candidate_plan: dict, + direct_snapshot: dict +) -> dict: + ... +``` + +## Input tối thiểu +- execution DIRECT world / wrapper của nó +- `object_name` +- `pick_path` +- `place_path` +- `grasp_force` +- `place_pos` +- `T_obj_to_ee` +- snapshot DIRECT đầu object + +## Logic bên trong +1. restore DIRECT execution world về snapshot đầu object +2. open gripper +3. chạy `pick_path` +4. close gripper với `grasp_force` +5. step simulation một số bước +6. kiểm tra grasp success +7. nếu fail → trả `success=False`, `fail_stage="grasp"` +8. nếu pass → chạy `place_path` +9. kiểm tra object có rơi / slip không +10. open gripper +11. kiểm tra place success +12. nếu pass → tính retreat nếu cần +13. trả về: + - `success=True` + - `q_after` + - `final_object_pose` + - `retreat_path` + - các thông tin phục vụ GUI playback + +--- + +# 13. Hàm mới số 4: `_play_final_candidate_on_gui(...)` + +## Mục đích +Phát lại **candidate thắng cuối cùng** trên GUI. + +## Chữ ký gợi ý +```python +def _play_final_candidate_on_gui( + self, + gui_snapshot: dict, + final_plan: dict +) -> None: + ... +``` + +## Input +- snapshot GUI ở đầu object +- `final_plan` của candidate thắng + +## Logic +1. restore GUI về `gui_snapshot` +2. bật rendering GUI +3. `self.gripper.open()` +4. playback `pick_path` +5. close gripper bằng `grasp_force` +6. step simulation / settle +7. playback `place_path` +8. open gripper +9. step simulation / settle +10. nếu có retreat path thì playback retreat +11. đảm bảo object GUI kết thúc ở trạng thái tương thích với `final_plan` + +--- + +# 14. Hàm mới số 5: `_plan_home_in_direct(...)` + +## Mục đích +Lập kế hoạch về home **không dùng GUI**. + +## Chữ ký gợi ý +```python +def _plan_home_in_direct(self, q_current, q_home) -> list | None: + ... +``` + +## Logic +1. dùng planning DIRECT world +2. restore DIRECT world về scene cuối cùng sau task cuối +3. tạo `collision_fn` trên DIRECT world +4. chạy RRT home +5. trả `home_path` hoặc `None` + +--- + +# 15. Hàm mới số 6: `_play_home_path_on_gui(...)` + +## Mục đích +Playback `home_path` cuối trên GUI sau khi planner DIRECT đã tìm được. + +## Chữ ký gợi ý +```python +def _play_home_path_on_gui(self, home_path) -> None: + ... +``` + +## Logic +- bật rendering GUI nếu cần +- `_execute_path(home_path)` trên GUI world +- không làm collision check gì ở đây + +--- + +# 16. Hàm cần refactor: `_execute_path(...)` + +Hàm hiện tại đang gắn cứng với main GUI world vì dùng `self.robot_id`, `pb.stepSimulation()`, `pb.setJointMotorControl2(...)` trực tiếp trên world hiện tại. fileciteturn7file0L440-L463 + +## Vấn đề +Sau khi tách DIRECT execution world, ta cần khả năng chạy path trên: +- GUI world +- DIRECT execution world +- có thể cả DIRECT planning world nếu cần + +## Hướng sửa +Tách thành phiên bản **world-aware**: + +```python +def _execute_path_on_world(self, world, robot_id, arm_indices, path, visual=False): + ... +``` + +### Hoặc +giữ `_execute_path(...)` cho GUI, nhưng tạo thêm: +- `_execute_path_direct(...)` +- `_execute_path_carrying_direct(...)` + +### Khuyến nghị +Nên dùng cách thứ 2 để tránh đụng quá nhiều code cũ: +- `_execute_path_gui(...)` +- `_execute_path_carrying_gui(...)` +- `_execute_path_direct(...)` +- `_execute_path_carrying_direct(...)` + +--- + +# 17. Hàm cần refactor: `_execute_path_carrying(...)` + +Tương tự `_execute_path`, hàm hiện tại đang gắn với main world hiện tại và kiểm tra `getContactPoints(...)` ngay trên world đó. fileciteturn7file0L465-L488 + +## Hướng sửa +Tách thành: +- `_execute_path_carrying_direct(...)` → dùng trong `_simulate_candidate_in_direct` +- `_execute_path_carrying_gui(...)` → dùng trong `_play_final_candidate_on_gui` + +### Lưu ý quan trọng +GUI playback không phải nơi xác nhận logic thành công. +Vì vậy: +- `*_gui(...)` có thể bỏ các điều kiện fail logic nghiêm ngặt nếu muốn chỉ playback +- nhưng để GUI bám sát DIRECT execution, vẫn nên chạy vật lý thật khi playback + +--- + +# 18. Hàm cần refactor: `_check_grasp_success(...)` và `_check_place_success(...)` + +Nếu hiện tại các hàm này dùng trực tiếp `self.robot_id`, `self.scene`, `pb.getContactPoints(...)` trên main world, thì cần tách thành bản dùng được cho DIRECT execution world. + +## Đề xuất +- `_check_grasp_success_on_world(world, robot_id, object_id, ...)` +- `_check_place_success_on_world(world, object_id, place_pos, ...)` + +Sau đó: +- DIRECT execution gọi bản `on_world(...)` +- GUI playback nếu cần có thể dùng lại bản này, nhưng chỉ để debug chứ không quyết định candidate thắng/thua + +--- + +# 19. Phần phải sửa lớn nhất: `_pick_and_place_single_object(...)` + +Đây là tâm điểm của toàn bộ thay đổi. + +--- + +# 20. Luồng hiện tại của `_pick_and_place_single_object(...)` + +Theo file hiện tại, luồng chính là: + +1. lấy `object_id` +2. load mesh / sample contact pairs +3. tạo snapshot GUI bằng `pb.saveState()` +4. disable rendering GUI +5. sinh candidate / batch +6. worker validation / planning +7. candidate nào planning xong → **main process restore GUI rồi thực thi vật lý trên GUI** +8. nếu fail vật lý → restore GUI snapshot rồi thử candidate khác +9. nếu thành công → object hoàn tất, cập nhật `q_after` + +Trong phiên bản song song gần đây, phần “candidate nào plan xong thì thực thi vật lý trên GUI” nằm ở block xử lý `async_results`. fileciteturn7file0L658-L740 + +--- + +# 21. Luồng mới bắt buộc của `_pick_and_place_single_object(...)` + +Sau khi sửa, hàm này phải được tổ chức thành **4 pha**: + +--- + +# 22. Pha 1 — Chuẩn bị snapshot và scene cho object hiện tại + +Ngay đầu hàm: +1. xác định `object_id`, `place_pos` +2. chụp **GUI snapshot** đầu object bằng `_capture_gui_snapshot()` +3. chụp / dựng **DIRECT snapshot** đầu object cho: + - planning DIRECT world + - execution DIRECT world +4. disable GUI rendering trong suốt search + +## Output của pha 1 +- `gui_snapshot` +- `planning_snapshot` +- `execution_snapshot` + +--- + +# 23. Pha 2 — Validation + planning candidate hoàn toàn ngầm + +Phần này giữ nguyên tinh thần pipeline hiện tại: +- sinh candidate +- batch validation +- batch planning + +Các worker planning vẫn có thể giữ như hiện tại nếu bạn muốn. + +## Nhưng thay đổi bắt buộc: +Khi một candidate `val["success"] == True`, **không được** chạy vật lý trên GUI nữa. + +### Thay vào đó: +- đóng gói thành `candidate_plan` +- gọi `_simulate_candidate_in_direct(...)` + +--- + +# 24. Pha 3 — DIRECT physical verification cho candidate thắng tạm thời + +Trong vòng lặp nhận `async_results`, thay block cũ: + +## Block cũ (cần bỏ) +- `pb.restoreState(state_snapshot_id)` +- `self.gripper.open()` +- bật rendering +- `_execute_path(val["pick_path"])` +- `gripper.close(...)` +- `_execute_path_carrying(...)` +- check grasp/place trên GUI +- fail thì restore GUI snapshot + +## Block mới (cần thay) +```python +candidate_plan = {...} +sim_result = self._simulate_candidate_in_direct( + exec_world=..., + object_name=object_name, + candidate_plan=candidate_plan, + direct_snapshot=execution_snapshot, +) +``` + +### Nếu `sim_result["success"] == False` +- bỏ candidate +- **không restore GUI gì cả** +- tiếp tục candidate tiếp theo + +### Nếu `sim_result["success"] == True` +- tạo `final_plan` +- break khỏi vòng search +- chuyển sang playback GUI + +--- + +# 25. Pha 4 — Playback nghiệm thắng trên GUI + +Sau khi đã có `final_plan`: +1. gọi `_play_final_candidate_on_gui(gui_snapshot, final_plan)` +2. lấy `q_after` sau playback +3. trả về `(True, q_after)` + +### Nếu hết candidate mà không có `final_plan` +- restore GUI về `gui_snapshot` +- bật rendering lại +- trả `(False, q_start)` + +--- + +# 26. Những dòng cụ thể trong `_pick_and_place_single_object(...)` cần thay đổi + +Dựa trên file hiện tại, phần cần sửa mạnh nhất là khối trong vòng lặp `for res, task in async_results:` nơi đang có logic: + +- `pb.restoreState(state_snapshot_id)` +- `self.gripper.open()` +- `pb.configureDebugVisualizer(pb.COV_ENABLE_RENDERING, 1)` +- `self._execute_path(val["pick_path"])` +- `self.gripper.close(force)` +- `self._execute_path_carrying(val["place_path"], object_id, force)` +- nếu fail thì restore GUI snapshot rồi step vài bước để “show reset pose” +- nếu thành công thì tiếp tục object success fileciteturn7file0L684-L740 + +## Kế hoạch sửa cụ thể cho block này +### Xóa / thay hoàn toàn logic “thực thi vật lý trên GUI” +Thay bằng: + +1. `candidate_plan = { pick_path, place_path, q_grasp, q_place, T_obj_to_ee, ... }` +2. `sim_result = self._simulate_candidate_in_direct(...)` +3. nếu `sim_result["success"]`: + - `final_plan = merge(candidate_plan, sim_result, gui_snapshot, place_pos, ...)` + - break +4. nếu fail: + - continue candidate tiếp theo +5. **không restore GUI trong vòng candidate fail** +6. **không show reset pose trên GUI nữa** + +--- + +# 27. Sửa `execute_tasks(...)` + +Đây là nơi sửa vấn đề robot giật ở cuối. + +--- + +# 28. Luồng hiện tại của `execute_tasks(...)` + +Hiện tại: +1. chạy lần lượt `_pick_and_place_single_object(...)` +2. sau khi xong hết object: + - tạo `simple_collision_fn` gọi `_check_static_collision(...)` + - tạo `RRTConnectPlanner` trên main world + - `home_path = rrt.plan(q_current, q_home)` + - nếu có path thì `_execute_path(home_path)` trên GUI + - nếu fail thì teleport home fileciteturn7file0L523-L537 + +## Vấn đề +Planner home đang dùng collision checker trên GUI world. + +--- + +# 29. Luồng mới bắt buộc của `execute_tasks(...)` + +Sau khi sửa: + +## Sau vòng for task +1. gọi: +```python +home_path = self._plan_home_in_direct(q_current, q_home) +``` + +2. nếu `home_path is not None`: + - gọi: + ```python + self._play_home_path_on_gui(home_path) + ``` + - trả `True` + +3. nếu `home_path is None`: + - tùy chính sách: + - hoặc teleport home trên GUI + - hoặc báo fail + - nhưng **không** được thử planner home trên GUI nữa + +--- + +# 30. Các hàm collision check cần world-aware + +Nếu planning / execution chuyển sang DIRECT world, các hàm collision phải có khả năng chạy trên world đó thay vì gắn chặt với GUI world. + +## Các hàm cần xem lại +- `_check_static_collision(...)` +- `_check_carrying_collision(...)` +- `_has_penetration_between(...)` + +### Hiện trạng +Các hàm này nhiều khả năng đang dùng trực tiếp: +- `self.robot_id` +- `pb.resetJointState(...)` +- `pb.getClosestPoints(...)` +- object ids của main world + +### Hướng sửa +Tạo phiên bản world-aware, ví dụ: + +```python +def _check_static_collision_on_world(world_ctx, q, target_object_id=None, ...): + ... +``` + +```python +def _check_carrying_collision_on_world(world_ctx, q, target_object_id, T_obj_to_ee, ...): + ... +``` + +## `world_ctx` nên chứa +- `client_id` +- `robot_id` +- `arm_indices` +- mapping `object_name -> body_id` trong world đó +- gripper / scene wrapper của world đó + +--- + +# 31. Vấn đề object id khác nhau giữa GUI world và DIRECT world + +Khi bạn load cùng scene vào world khác nhau: +- `object_id` trong GUI world +- `object_id` trong DIRECT planning world +- `object_id` trong DIRECT execution world + +**sẽ không giống nhau**. + +Vì vậy, mọi dữ liệu liên quan tới object khi truyền qua world khác **không được truyền bằng GUI object id**. + +## Quy tắc bắt buộc +Khi giao tiếp giữa các world: +- truyền `object_name` +- rồi tra `object_id` trong world tương ứng + +Ví dụ: +- `target_object_name = "cube_1"` +- trong GUI world map thành `gui_object_id` +- trong planning DIRECT world map thành `planning_object_id` +- trong execution DIRECT world map thành `exec_object_id` + +--- + +# 32. `WorldContext` — cấu trúc rất nên có + +Để code đỡ rối, nên tạo wrapper: + +```python +class WorldContext: + def __init__(self, client_id, robot_id, arm_indices, gripper, scene): + ... +``` + +## WorldContext nên chứa +- `client_id` +- `robot_id` +- `arm_indices` +- `gripper wrapper` +- `scene wrapper` +- `name_to_id(name)` +- helper reset / capture state + +### Nên có 3 instance: +- `self.gui_world` +- `self.plan_world` +- `self.exec_world` + +--- + +# 33. Cách xử lý worker hiện tại sau khi sửa + +Phiên bản hiện tại đang dùng `multiprocessing.Pool(...)` cho validation/planning. fileciteturn7file0L607-L679 + +## Kế hoạch sửa +Giữ nguyên tư tưởng worker planning nếu bạn muốn, nhưng cần tách rõ: +- worker validation/planning **không được** đụng GUI +- worker chỉ trả về **candidate plan kinematic** +- main process sau đó gọi `_simulate_candidate_in_direct(...)` trên `exec_world` + +## Tức là worker không đổi vai trò thành “physical execution worker” +Để giảm độ phức tạp, physical execution có thể để main process chạy trên `exec_world` riêng, theo thứ tự candidate thắng tạm thời. + +--- + +# 34. Chiến lược sửa theo từng giai đoạn để tránh làm vỡ pipeline + +Đây là phần thực thi quan trọng nhất. + +--- + +# 35. Giai đoạn sửa 1 — Tách GUI playback khỏi candidate test + +## Mục tiêu +Làm cho candidate không còn chạy trên GUI. + +## Việc cần làm +1. thêm `_capture_gui_snapshot()` và `_restore_gui_snapshot()` +2. thêm `_simulate_candidate_in_direct(...)` +3. trong `_pick_and_place_single_object(...)`, thay block “physical execution on GUI” bằng “simulate in DIRECT” +4. chưa cần sửa đẹp GUI playback ngay, chỉ cần khi candidate thắng thì playback lại sau + +## Kết quả mong đợi +- trong lúc search candidate, GUI đứng yên +- không còn hiện tượng robot đang “tính” mà tự chạy thử trên GUI + +--- + +# 36. Giai đoạn sửa 2 — Tạo GUI playback chuẩn cho nghiệm cuối + +## Việc cần làm +1. thêm `_play_final_candidate_on_gui(...)` +2. đảm bảo `final_plan` lưu đủ: + - pick_path + - place_path + - retreat_path + - grasp_force +3. sau khi DIRECT execution thành công thì GUI playback đúng trajectory thắng + +## Kết quả mong đợi +- mỗi object chỉ hiện **một lần chạy cuối cùng** trên GUI +- không còn playback các candidate fail + +--- + +# 37. Giai đoạn sửa 3 — Tách home planning khỏi GUI + +## Việc cần làm +1. thêm `_plan_home_in_direct(...)` +2. sửa `execute_tasks(...)` dùng planner DIRECT +3. thêm `_play_home_path_on_gui(...)` + +## Kết quả mong đợi +- cuối pipeline robot không còn giật +- GUI chỉ chạy một lần theo `home_path` cuối + +--- + +# 38. Giai đoạn sửa 4 — World-aware collision / execution helpers + +## Việc cần làm +Refactor các hàm: +- `_check_static_collision` +- `_check_carrying_collision` +- `_execute_path` +- `_execute_path_carrying` +- `_check_grasp_success` +- `_check_place_success` + +để chúng có thể chạy trên world cụ thể. + +## Kết quả mong đợi +- code không còn ngầm giả định “chỉ có 1 world” +- dễ bảo trì hơn + +--- + +# 39. Trình tự sửa file khuyến nghị + +Đây là thứ tự sửa cụ thể mình khuyên bạn làm trong code. + +--- + +# 40. Bước 1 — Tạo abstraction world +Tạo: +- `self.gui_world = ...` +- `self.plan_world = ...` +- `self.exec_world = ...` + +Nếu chưa muốn refactor lớn, tối thiểu phải có: +- một object/namespace cho `exec_world` +- một object/namespace cho `plan_world` + +--- + +# 41. Bước 2 — Viết snapshot helper +Viết: +- `_capture_gui_snapshot` +- `_restore_gui_snapshot` +- `_capture_world_snapshot(world_ctx)` +- `_restore_world_snapshot(world_ctx, snapshot)` + +--- + +# 42. Bước 3 — Viết execution helper cho DIRECT +Viết: +- `_execute_path_direct(...)` +- `_execute_path_carrying_direct(...)` +- `_check_grasp_success_on_world(...)` +- `_check_place_success_on_world(...)` + +--- + +# 43. Bước 4 — Viết `_simulate_candidate_in_direct(...)` +Đây là bước khóa. +Khi hàm này chạy ổn, bạn đã có thể bỏ việc test candidate trên GUI. + +--- + +# 44. Bước 5 — Sửa `_pick_and_place_single_object(...)` +Thay toàn bộ block: +- restore GUI +- execute physical on GUI +- fail thì restore GUI snapshot + +bằng: +- `sim_result = _simulate_candidate_in_direct(...)` +- success → lưu `final_plan` +- fail → continue + +--- + +# 45. Bước 6 — Viết `_play_final_candidate_on_gui(...)` +Sau khi có `final_plan`, playback trên GUI. + +--- + +# 46. Bước 7 — Sửa `execute_tasks(...)` để home planning chạy DIRECT +- thêm `_plan_home_in_direct` +- thêm `_play_home_path_on_gui` + +--- + +# 47. Bước 8 — Dọn sạch các chỗ GUI bị lạm dụng trong search +Sau khi logic chính đã chuyển xong, rà lại và loại bỏ: +- `pb.configureDebugVisualizer(..., 1)` trong các nhánh candidate fail +- các đoạn “show reset pose” +- mọi `restoreState(...)` chỉ nhằm hiển thị GUI trong lúc search + +--- + +# 48. Các đoạn cụ thể nên xóa / thay trong file hiện tại + +## 48.1. Trong `_pick_and_place_single_object(...)` +### Cần xóa khỏi vòng candidate: +- bật rendering để chạy candidate thử +- restore GUI state khi candidate fail +- “show reset pose immediately on screen” +- mọi stepSimulation chỉ để GUI hiển thị candidate fail + +Phần này đang nằm trong block xử lý candidate thắng tạm thời / fail vật lý. fileciteturn7file0L684-L724 + +--- + +## 48.2. Trong `execute_tasks(...)` +### Cần thay: +```python +def simple_collision_fn(q): + return self._check_static_collision(q, target_object_id=None) + +rrt = RRTConnectPlanner(...) +home_path = rrt.plan(q_current, q_home) +self._execute_path(home_path) +``` + +bằng: +```python +home_path = self._plan_home_in_direct(q_current, q_home) +if home_path is not None: + self._play_home_path_on_gui(home_path) +``` + +fileciteturn7file0L523-L537 + +--- + +# 49. Chính sách trạng thái sau khi playback GUI xong một object + +Sau khi `_play_final_candidate_on_gui(...)` xong: +- trạng thái GUI phải đúng với object đã được đặt xong +- `q_after` phải phản ánh pose cuối của robot sau retreat (nếu có) +- `execute_tasks(...)` sẽ dùng `q_after` làm `q_start` cho object tiếp theo + +## Quy tắc quan trọng +`q_after` phải lấy từ **candidate final đã được DIRECT execution xác nhận**, không lấy từ candidate fail, cũng không lấy từ GUI search state. + +--- + +# 50. Chính sách khi DIRECT execution thành công nhưng GUI playback có sai khác nhỏ + +Vì GUI playback chạy lại physics lần 2, có thể có sai khác rất nhỏ so với DIRECT execution world. + +## Quy tắc đề xuất +GUI playback chỉ là visualization, nên: +- candidate thắng vẫn là candidate thắng +- nếu cần, sau GUI playback có thể “snap nhẹ” object về final pose từ `final_plan` +- nhưng không được để GUI playback thay đổi quyết định logic của pipeline + +--- + +# 51. Chính sách khi home planning fail + +Sau khi tách home planning sang DIRECT, nếu `home_path is None` thì bạn có 2 lựa chọn: + +## Lựa chọn A — giữ đúng hành vi cũ +- log warning +- teleport robot GUI về home +- return `True` + +## Lựa chọn B — chặt chẽ hơn +- return `False` +- báo pipeline không thể về home + +Nếu muốn giữ đúng behavior hiện tại của file, dùng **Lựa chọn A**. + +--- + +# 52. Kết quả mong đợi sau khi hoàn tất kế hoạch sửa + +Sau khi sửa xong theo đúng kế hoạch này, hành vi của pipeline sẽ trở thành: + +## Với mỗi object +1. GUI đứng yên trong lúc search candidate +2. planning + collision + physical verification chạy ngầm trong DIRECT +3. khi đã tìm được candidate thắng cuối cùng: + - GUI mới phát lại đúng trajectory thắng +4. candidate fail không bao giờ xuất hiện trên GUI + +## Sau khi xong toàn bộ object +1. planner home chạy trong DIRECT +2. GUI chỉ phát lại `home_path` cuối +3. không còn hiện tượng robot giật do RRT test q trên GUI + +--- + +# 53. Tóm tắt hành động sửa bắt buộc + +## Nhóm 1 — thêm hàm mới +- `_capture_gui_snapshot` +- `_restore_gui_snapshot` +- `_simulate_candidate_in_direct` +- `_play_final_candidate_on_gui` +- `_plan_home_in_direct` +- `_play_home_path_on_gui` + +## Nhóm 2 — refactor helper hiện có +- `_execute_path` +- `_execute_path_carrying` +- `_check_grasp_success` +- `_check_place_success` +- `_check_static_collision` +- `_check_carrying_collision` + +## Nhóm 3 — sửa luồng chính +- `_pick_and_place_single_object` +- `execute_tasks` + +--- + +# 54. Kết luận + +Để sửa đúng file `pipeline_executor.py` theo yêu cầu của bạn, cần thay đổi **bản chất vai trò của GUI**: + +- **Trước khi sửa:** GUI vừa là nơi hiển thị, vừa là nơi candidate được thử vật lý, vừa là nơi planner home collision-check. +- **Sau khi sửa:** GUI chỉ còn là **nơi phát lại nghiệm cuối cùng**. + +Còn mọi thứ liên quan đến: +- candidate validation +- IK +- collision check +- RRT +- physical pick/place verification +- home planning + +đều phải được đẩy sang **DIRECT planning / DIRECT execution world**. + +Đây là cách sửa đúng bản chất để đồng thời giải quyết cả hai vấn đề: +1. GUI không còn “nhảy vào giữa quá trình search candidate”. +2. Robot không còn “giật / teleport” ở cuối khi về home. diff --git a/ke_hoach_toi_uu_pipeline_song_song_ma_tran_hoa.md b/ke_hoach_toi_uu_pipeline_song_song_ma_tran_hoa.md new file mode 100644 index 0000000000000000000000000000000000000000..c108106ad4aadfceea2eba6ea4ea8fe4595bd13d --- /dev/null +++ b/ke_hoach_toi_uu_pipeline_song_song_ma_tran_hoa.md @@ -0,0 +1,525 @@ +# Kế hoạch tối ưu hóa pipeline grasp–IK–motion planning +*(Giữ nguyên logic thuật toán, không giảm chất lượng nghiệm, chỉ tối ưu cách tính để giảm thời gian và tránh lặp lại phép tính)* + +## 1. Mục tiêu tối ưu hóa + +Tài liệu này đưa ra **kế hoạch tối ưu hóa thực thi** cho pipeline hiện tại của bài toán robot arm pick–place của bạn, với các ràng buộc sau: + +### 1.1. Ràng buộc bắt buộc +1. **Không thay đổi logic thuật toán cốt lõi**: + - Vẫn sinh contact pair candidate. + - Vẫn dựng grasp pose từ candidate. + - Vẫn giải IK cho grasp pose. + - Vẫn kiểm tra collision theo collision policy hiện tại. + - Vẫn dùng motion planning (RRT-Connect) để đi tới grasp pose / place pose. + - Nếu candidate này fail thì mới chuyển candidate khác. + +2. **Không giảm hiệu năng nghiệm / chất lượng lời giải**: + - Không giảm độ chính xác IK. + - Không bỏ bớt collision check quan trọng. + - Không nới lỏng collision policy. + - Không thay planner khác chỉ để nhanh hơn. + - Không cắt bớt candidate theo kiểu làm mất cơ hội tìm nghiệm đúng. + +3. **Chỉ tối ưu cách thực thi**: + - Song song hóa các candidate độc lập. + - Ma trận hóa / vector hóa các bước hình học số học. + - Cache các kết quả lặp lại. + - Tránh dựng lại scene / mesh / dữ liệu phụ nhiều lần. + - Tránh phải “tính lại từ đầu” cho các phần không đổi giữa các candidate. + +--- + +# 2. Tư tưởng tối ưu hóa tổng thể + +## 2.1. Vấn đề hiện tại của pipeline tuần tự +Hiện tại pipeline của bạn về bản chất là: + +1. Sinh contact pair candidate. +2. Lấy candidate đầu tiên. +3. Từ candidate đó dựng grasp pose. +4. Giải IK. +5. Check collision của nghiệm IK. +6. Chạy motion planning tới grasp pose. +7. Nếu fail ở motion planning thì **quay lại candidate khác** và lại chạy lại gần như toàn bộ quy trình. + +Điểm tốn thời gian lớn nhất là: +- Candidate A fail ở motion planning rất muộn. +- Sau đó candidate B lại phải đi lại từ đầu: + - dựng grasp pose, + - solve IK, + - collision check, + - motion planning. +- Nếu có nhiều candidate fail liên tiếp thì thời gian tăng rất mạnh. + +## 2.2. Nguyên tắc tối ưu +Ta **không đổi logic quyết định** của thuật toán, nhưng đổi cách thực thi theo hướng: + +### Thay vì: +- candidate 1 chạy xong toàn bộ rồi mới candidate 2 +- candidate 2 chạy xong toàn bộ rồi mới candidate 3 + +### Ta làm: +- nhiều candidate được đánh giá **đồng thời** ở các bước độc lập, +- nhiều candidate được **validate song song**, +- các phép tính hình học được **vector hóa**, +- các dữ liệu không đổi được **cache / precompute / tái sử dụng**, +- khi một candidate motion plan thành công thì dừng các candidate còn lại. + +Mục tiêu là: +- **một “đợt tính pipeline” có thể xét nhiều candidate cùng lúc** +- giảm xác suất phải “quay lại từ đầu” một cách tuần tự. + +--- + +# 3. Phạm vi tối ưu hóa được phép + +Ta chia pipeline thành 6 nhóm tối ưu: + +1. **Tối ưu sinh contact pair / grasp candidate** +2. **Tối ưu đánh giá grasp pose candidate** +3. **Tối ưu solve IK nhiều candidate** +4. **Tối ưu collision check nhiều candidate** +5. **Tối ưu motion planning nhiều candidate** +6. **Tối ưu tái sử dụng dữ liệu / cache / scene snapshot** + +--- + +# 4. Pipeline hiện tại của bạn (dưới góc nhìn tối ưu hóa) + +Pipeline logic hiện tại có thể nhìn thành: + +## Giai đoạn A — chuẩn bị object và candidate +A1. Nạp mesh collision / visual +A2. Lấy vertex / normal +A3. Sinh contact pair candidate +A4. Lọc candidate theo width gripper / antipodal gần đúng / rule hình học cơ bản +A5. Dựng grasp pose candidate + +## Giai đoạn B — đánh giá từng grasp candidate +B1. Chọn một grasp candidate +B2. Solve IK cho grasp pose +B3. FK kiểm tra sai số pose +B4. Check joint limits +B5. Check collision theo policy của bạn +B6. Nếu IK hợp lệ → dùng RRT-Connect motion planning tới q_goal +B7. Nếu motion plan fail → quay lại candidate khác + +## Giai đoạn C — khi grasp thành công +C1. Đóng gripper +C2. Lập motion plan cho giai đoạn mang vật / đặt vật +C3. Place +C4. Nếu còn vật khác thì motion planning tiếp từ trạng thái hiện tại + +--- + +# 5. Bản đồ tối ưu hóa: bước nào tối ưu bằng gì + +| Giai đoạn | Có thể tối ưu bằng gì | Mức ưu tiên | +|---|---:|---:| +| Sinh contact pair từ mesh | Ma trận hóa / vector hóa | Rất cao | +| Lọc candidate sơ bộ | Ma trận hóa / vector hóa | Rất cao | +| Dựng grasp pose cho nhiều candidate | Vector hóa một phần + batch hóa | Cao | +| Solve IK cho nhiều candidate | Song song hóa theo candidate / theo seed | Rất cao | +| Collision validate grasp candidate | Song song hóa theo candidate | Rất cao | +| Motion planning đến grasp | Song song hóa theo candidate | Rất cao | +| Tạo scene / load robot / load mesh lặp lại | Cache / worker-local persistent world | Rất cao | +| FK lặp lại trên cùng candidate / cùng q | Cache theo q | Trung bình | +| Tính transform object/world lặp lại | Cache | Trung bình | +| Place planning | Song song hóa nếu có nhiều place candidate | Trung bình | + +--- + +# 6. Kiến trúc tối ưu hóa được đề xuất + +## 6.1. Nguyên tắc kiến trúc +Thay vì một pipeline hoàn toàn tuần tự, ta tổ chức theo mô hình: + +- **Master process**: điều phối candidate, gom kết quả, quyết định dừng. +- **Worker process**: mỗi worker có một world PyBullet riêng, xử lý candidate độc lập. +- **Vectorized preprocessor**: tiền xử lý contact pair / grasp candidate theo mảng NumPy. +- **Cache layer**: giữ các dữ liệu không đổi, tránh tính lại. + +## 6.2. Điều không thay đổi +Điều rất quan trọng là: +- mỗi candidate vẫn phải đi qua đúng các bước logic cũ: + - grasp pose → IK → validate → collision → RRT +- candidate fail vẫn bị loại +- candidate pass vẫn được dùng như cũ + +Khác biệt chỉ là: +- **nhiều candidate được xử lý cùng lúc** +- **nhiều phép hình học được tính theo batch** +- **các phần không đổi không bị tính lại** + +--- + +# 7. Tối ưu hóa cấp 1 — Vector hóa / ma trận hóa giai đoạn contact pair và grasp candidate + +Đây là nơi dễ tối ưu nhất mà **không động vào logic**. + +## 7.1. Cache dữ liệu mesh của object +Tạo **ObjectGeometryCache** cho mỗi object target, chứa: +- collision mesh path +- vertices object-frame +- normals object-frame +- sampled surface points / normals nếu có +- bbox object-frame +- các dữ liệu phụ trợ cho contact pair + +Lợi ích: +- mỗi object chỉ đọc mesh / trích dữ liệu hình học **một lần** +- candidate sau không phải dựng lại dữ liệu mesh từ đầu + +## 7.2. Vector hóa transform object-frame → world-frame +Nếu object pose là `(R, t)`: +- `P_world = (R @ P_obj.T).T + t` +- `N_world = (R @ N_obj.T).T` + +Áp dụng cho: +- vertex / sample point +- normal +- contact point candidate + +## 7.3. Vector hóa sinh contact pair candidate +Các phép kiểm tra sơ bộ có thể batch hóa: +1. khoảng cách giữa hai điểm +2. width nằm trong khoảng mở gripper +3. antipodal gần đúng bằng normal +4. kiểm tra vector nối contact tương thích với normal + +Thực hiện bằng NumPy: +- sinh batch index `(i, j)` +- tính đồng loạt `delta`, `dist`, `unit`, `dot` +- dùng boolean mask để lọc + +## 7.4. Vector hóa metadata grasp sơ bộ +Cho toàn bộ candidate: +- center = `(c1 + c2)/2` +- width = `||c2-c1||` +- closing axis = normalize(c2-c1)` + +Lưu lại thành `CandidateMeta`. + +--- + +# 8. Tối ưu hóa cấp 2 — Song song hóa đánh giá nhiều grasp candidate + +Đây là tối ưu quan trọng nhất đối với bài toán của bạn. + +## 8.1. Ý tưởng +Thay vì: +- candidate A: IK → collision → RRT → fail +- candidate B: IK → collision → RRT → fail +- candidate C: IK → collision → RRT → success + +Ta làm: +- candidate A, B, C được xử lý đồng thời trên các worker riêng +- candidate nào thành công trước thì được chọn +- nếu cả batch fail mới sang batch khác + +## 8.2. Điều kiện kỹ thuật bắt buộc +Mỗi worker phải có: +- **một PyBullet DIRECT client riêng** +- robot / object / obstacle riêng trong world của worker +- collision checker riêng + +Không được cho nhiều worker dùng chung một simulator state. + +## 8.3. Candidate worker làm gì +Một worker nhận một candidate sẽ làm trọn gói: +1. reset scene local về `SceneSnapshot` +2. dựng grasp pose từ `CandidateMeta` +3. solve IK +4. FK validate pose error +5. joint limit check +6. collision validate theo policy hiện tại +7. nếu pass thì chạy RRT-Connect tới `q_goal` +8. trả về kết quả + +--- + +# 9. Tối ưu hóa cấp 3 — Batch parallelism để giữ thứ tự ưu tiên candidate + +Để không phá tinh thần “candidate tốt hơn được ưu tiên”, ta không ném toàn bộ candidate vào chạy cùng lúc vô hạn, mà dùng **batch song song có thứ tự**. + +## 9.1. Cách làm +1. Sắp xếp candidate theo thứ tự ưu tiên hiện tại. +2. Chia candidate thành các batch nhỏ, ví dụ mỗi batch 8 candidate. +3. Chạy song song toàn bộ candidate trong batch 1. +4. Nếu batch 1 có candidate thành công → dừng. +5. Nếu batch 1 fail hết → chạy batch 2. +6. Tiếp tục như vậy cho tới khi tìm được nghiệm hoặc hết candidate. + +## 9.2. Lợi ích +- vẫn ưu tiên candidate tốt hơn +- nhưng không bị chờ fail tuần tự từng candidate + +--- + +# 10. Tối ưu hóa cấp 4 — Tách Validation Phase và Planning Phase + +Không nên để mọi candidate đều đi vào motion planning ngay. + +## 10.1. Validation Phase +Song song hóa cho một batch candidate: +- solve IK +- FK validate +- joint limit check +- collision validate + +Kết quả: +- một tập candidate “đã có `q_goal` hợp lệ” + +## 10.2. Planning Phase +Chỉ các candidate pass validation mới được đưa vào motion planning: +- RRT-Connect song song cho từng `q_goal` + +## 10.3. Lợi ích +- RRT là bước đắt nhất +- candidate fail ở IK / collision sẽ bị loại sớm, không chiếm worker planning + +--- + +# 11. Tối ưu hóa cấp 5 — Cache / tái sử dụng dữ liệu để tránh tính lại + +## 11.1. Cache geometry theo object +Tái sử dụng: +- mesh +- vertices +- normals +- sampled points + +## 11.2. Cache transformed geometry theo object pose +Nếu object pose chưa đổi: +- transformed points / normals world-frame +- contact pair candidate +- candidate metadata +không cần tính lại. + +## 11.3. Cache danh sách candidate đã lọc +Nếu batch 1 fail hết, **không sinh lại candidate từ đầu**. +Chỉ lấy batch 2 từ danh sách candidate đã có. + +## 11.4. Cache scene snapshot cho worker +Worker chỉ load scene một lần; mỗi candidate chỉ reset state. + +--- + +# 12. Kiến trúc worker được đề xuất + +## 12.1. `SceneSnapshot` +Chứa: +- robot base pose +- `q_start` +- pose target object +- pose obstacle +- planner config +- IK config +- collision policy + +## 12.2. `CandidateMeta` +Chứa: +- `candidate_id` +- `contact_1_world` +- `contact_2_world` +- `center_world` +- `closing_axis_world` +- `grasp_width` +- `grasp_pose_seed` / orientation seed nếu có + +## 12.3. `CandidateTask` +Chứa: +- `CandidateMeta` +- `SceneSnapshot` +- `q_start` + +## 12.4. `CandidateResult` +Chứa: +- `candidate_id` +- `success` +- `fail_stage` (`ik` / `collision` / `rrt`) +- `q_goal` +- `grasp_pose` +- `ik_error_pos` +- `ik_error_ori` +- `trajectory_to_grasp` + +--- + +# 13. Luồng xử lý tối ưu hóa hoàn chỉnh + +## Giai đoạn 0 — Chuẩn bị +1. Tạo `SceneSnapshot`. +2. Khởi tạo / lấy `ObjectGeometryCache`. +3. Khởi tạo worker pool: + - `ValidationPool` + - `PlanningPool` + +## Giai đoạn 1 — Candidate preprocessing (vectorized) +1. Transform geometry object sang world frame. +2. Sinh contact pair candidate bằng NumPy. +3. Lọc candidate bằng các rule hiện tại. +4. Dựng `CandidateMeta` cho tất cả candidate. +5. Sắp xếp candidate theo thứ tự ưu tiên. +6. Chia thành batch. + +## Giai đoạn 2 — Validation batch song song +Với batch hiện tại: +1. Gửi toàn bộ candidate của batch vào `ValidationPool`. +2. Worker xử lý: + - IK + - FK validate + - joint limit check + - collision validate +3. Thu về các candidate pass validation. + +## Giai đoạn 3 — Planning batch song song +Nếu batch hiện tại có candidate pass validation: +1. Gửi chúng vào `PlanningPool`. +2. Worker chạy RRT-Connect tới `q_goal`. +3. Nếu có candidate thành công: + - chọn theo chính sách (`first feasible wins` hoặc `best-in-batch`) + - dừng các task còn lại + +## Giai đoạn 4 — Retry không tính lại từ đầu +Nếu batch hiện tại fail: +- không sinh lại mesh / contact pair / candidate +- không load lại scene +- chỉ lấy batch tiếp theo và lặp lại Giai đoạn 2–3 + +--- + +# 14. Những chỗ tối ưu cụ thể nhất cho bài toán của bạn + +## 14.1. Tối ưu đúng với ví dụ “motion plan fail thì lại phải chạy pipeline từ đầu” +Giải pháp: +1. Sinh sẵn một danh sách candidate đủ lớn. +2. Chia candidate thành batch. +3. Validation song song trong batch. +4. Planning song song trong batch. +5. Candidate nào thành công thì dùng ngay. +6. Nếu cả batch fail thì sang batch sau, **không dựng lại từ đầu**. + +## 14.2. Tối ưu đúng với việc “check validate nhiều candidate cùng lúc” +Giải pháp: +- Mỗi worker giữ world riêng. +- Candidate validation được chạy đồng thời. +- Collision validate cũng chạy trong worker đó luôn. + +## 14.3. Tối ưu đúng với việc “chỉ một lần pipeline đã chọn được motion plan thành công” +Giải pháp: +- Không để pipeline chỉ xét 1 candidate / lần. +- Một “lần pipeline” ở mức thực thi sẽ là: + - preprocess toàn bộ candidate + - validate song song một batch + - planning song song các candidate hợp lệ trong batch + - chọn candidate thắng +- Như vậy xác suất phải “quay lại từ đầu” giảm mạnh. + +--- + +# 15. Những gì **không** nên tối ưu theo cách làm thay đổi logic + +1. Không bỏ bớt collision check với target object nếu policy của bạn cấm va chạm. +2. Không giảm số candidate chỉ để nhanh hơn nếu làm giảm khả năng tìm nghiệm. +3. Không thay solver IK bằng một solver xấp xỉ kém hơn. +4. Không dùng heuristic “chọn đại candidate tốt nhất rồi bỏ các candidate còn lại” nếu chưa validation/planning. +5. Không dùng chung một PyBullet world cho nhiều candidate song song. + +--- + +# 16. Thứ tự triển khai khuyến nghị + +## Bước 1 — Geometry cache + vector hóa candidate generation +- `ObjectGeometryCache` +- transform world-frame bằng NumPy +- contact pair generation bằng NumPy +- `CandidateMeta` + +## Bước 2 — Tách validation của một candidate thành hàm độc lập +Ví dụ: +```python +validate_candidate(candidate_meta, scene_snapshot, q_start) +``` + +## Bước 3 — Tạo `ValidationPool` +- mỗi process một PyBullet DIRECT world riêng +- xử lý song song IK + collision validation + +## Bước 4 — Tách planning của một candidate thành hàm độc lập +Ví dụ: +```python +plan_candidate(candidate_meta, q_goal, scene_snapshot, q_start) +``` + +## Bước 5 — Tạo `PlanningPool` +- chạy RRT-Connect song song cho các candidate pass validation + +## Bước 6 — Tạo `BatchCoordinator` +- chia batch +- validate batch +- planning batch +- early stop khi có nghiệm + +## Bước 7 — Bổ sung cache nâng cao +- cache candidate list theo object pose +- cache metadata theo scene snapshot + +--- + +# 17. Kế hoạch đo hiệu quả sau khi tối ưu + +## 17.1. Đo thời gian từng phần +- thời gian sinh candidate +- thời gian validation batch +- thời gian planning batch +- tổng thời gian tìm được grasp motion plan thành công + +## 17.2. Đo tính đúng đắn +So sánh trước / sau tối ưu: +- tỷ lệ thành công grasp +- sai số grasp pose +- số collision false-positive / false-negative +- tính đúng của motion plan + +## 17.3. Đo lợi ích song song hóa +- số candidate / giây ở validation +- số candidate / giây ở planning +- CPU usage / RAM usage + +--- + +# 18. Kết luận + +## 18.1. Các chỗ nên tối ưu mạnh nhất trong pipeline của bạn +1. **Sinh contact pair / lọc candidate** + → ma trận hóa / vector hóa. + +2. **Đánh giá grasp candidate (IK + collision)** + → song song hóa theo candidate. + +3. **Motion planning tới grasp** + → song song hóa giữa các candidate đã pass validation. + +4. **Dữ liệu mesh / candidate / scene** + → cache và tái sử dụng, tránh tính lại. + +## 18.2. Tối ưu hóa quan trọng nhất theo đúng yêu cầu của bạn +Nếu hiện tại: +- motion plan của candidate A fail +- thuật toán lại phải tính pipeline lại từ đầu cho candidate B + +thì cách tối ưu đúng nhất là: + +- sinh **nhiều candidate cùng lúc** +- validation **song song** +- motion planning **song song** +- candidate nào ra motion plan thành công trước thì lấy +- nếu cả batch fail mới sang batch tiếp theo +- **không sinh lại / không tính lại** các phần bất biến + +Cách này: +- **không đổi logic thuật toán** +- **không làm giảm chất lượng nghiệm** +- nhưng giảm rất mạnh thời gian do fail tuần tự và do tính lại cùng một dữ liệu nhiều lần. diff --git a/llm_panda/__init__.py b/llm_panda/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..bb3a2806e2612ef41c40ff3e5b9c2e708ceff00d --- /dev/null +++ b/llm_panda/__init__.py @@ -0,0 +1,25 @@ +"""LLM-Panda: a text-only-LLM-controlled Franka Panda pick-and-place demo. + +Architecture: "LLM as Planner + Grasp Database at the execution layer". + +Modules +------- +- config : scene geometry, robot indices, physics constants +- scene_manager : world -> text state for the LLM +- grasp_planner : grasp-pose math backed by ``grasp_database.json`` +- robot_controller : IK + safe 3-step pick/place trajectories +- gripper_controller : friction-based grip-force model +- llm_agent : NL command -> function-call plan +- pipeline_executor : complete sequential pick-and-place with RRT-Connect +""" + +__all__ = [ + "config", + "scene_manager", + "grasp_planner", + "robot_controller", + "gripper_controller", + "llm_agent", + "pipeline_executor", +] + diff --git a/llm_panda/__pycache__/__init__.cpython-310.pyc b/llm_panda/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8059099b9b9d74aa6609edc8b0956de1aeba7671 Binary files /dev/null and b/llm_panda/__pycache__/__init__.cpython-310.pyc differ diff --git a/llm_panda/__pycache__/config.cpython-310.pyc b/llm_panda/__pycache__/config.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f446e03bb2856b3cac7fb440b779ed4153f248f1 Binary files /dev/null and b/llm_panda/__pycache__/config.cpython-310.pyc differ diff --git a/llm_panda/__pycache__/cost_map.cpython-310.pyc b/llm_panda/__pycache__/cost_map.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..291f3d69f0627e2dadadde43d5c885fee488d014 Binary files /dev/null and b/llm_panda/__pycache__/cost_map.cpython-310.pyc differ diff --git a/llm_panda/__pycache__/geofik.cpython-310.pyc b/llm_panda/__pycache__/geofik.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3e0356379173b5c4e2e50a0aed3b753ef1872234 Binary files /dev/null and b/llm_panda/__pycache__/geofik.cpython-310.pyc differ diff --git a/llm_panda/__pycache__/grasp_planner.cpython-310.pyc b/llm_panda/__pycache__/grasp_planner.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6e4f11879a79831c064d3d7522acf47a2af51d8f Binary files /dev/null and b/llm_panda/__pycache__/grasp_planner.cpython-310.pyc differ diff --git a/llm_panda/__pycache__/gripper_controller.cpython-310.pyc b/llm_panda/__pycache__/gripper_controller.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1a45cf2cbbc70acfd1379e1a74ba28b71bebb629 Binary files /dev/null and b/llm_panda/__pycache__/gripper_controller.cpython-310.pyc differ diff --git a/llm_panda/__pycache__/llm_agent.cpython-310.pyc b/llm_panda/__pycache__/llm_agent.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d0d1c8fa3bb2a442b107c936a243b513d9cea197 Binary files /dev/null and b/llm_panda/__pycache__/llm_agent.cpython-310.pyc differ diff --git a/llm_panda/__pycache__/logger.cpython-310.pyc b/llm_panda/__pycache__/logger.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f9f72e99f478cd9e480c83d584f86d2cf86d2058 Binary files /dev/null and b/llm_panda/__pycache__/logger.cpython-310.pyc differ diff --git a/llm_panda/__pycache__/pipeline_executor.cpython-310.pyc b/llm_panda/__pycache__/pipeline_executor.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..759467b7d28bbe5c91834fe1a463daf7142f622a Binary files /dev/null and b/llm_panda/__pycache__/pipeline_executor.cpython-310.pyc differ diff --git a/llm_panda/__pycache__/plan_verifier.cpython-310.pyc b/llm_panda/__pycache__/plan_verifier.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1e1cab70c66b39d3e73b282e53ea07b625a3ec03 Binary files /dev/null and b/llm_panda/__pycache__/plan_verifier.cpython-310.pyc differ diff --git a/llm_panda/__pycache__/robot_controller.cpython-310.pyc b/llm_panda/__pycache__/robot_controller.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bccf94a5f0c4fd88b34a70a0aeda8215fe859fa5 Binary files /dev/null and b/llm_panda/__pycache__/robot_controller.cpython-310.pyc differ diff --git a/llm_panda/__pycache__/scene_manager.cpython-310.pyc b/llm_panda/__pycache__/scene_manager.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f1d994cbb2e044e18377568626fd78697c010752 Binary files /dev/null and b/llm_panda/__pycache__/scene_manager.cpython-310.pyc differ diff --git a/llm_panda/__pycache__/task_nullspace.cpython-310.pyc b/llm_panda/__pycache__/task_nullspace.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b311840228c24450621753ed8bad2a8103f767ef Binary files /dev/null and b/llm_panda/__pycache__/task_nullspace.cpython-310.pyc differ diff --git a/llm_panda/__pycache__/trajopt.cpython-310.pyc b/llm_panda/__pycache__/trajopt.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..df218024f81fb46a7d58332a6620fe3b0e35bf1f Binary files /dev/null and b/llm_panda/__pycache__/trajopt.cpython-310.pyc differ diff --git a/llm_panda/config.py b/llm_panda/config.py new file mode 100644 index 0000000000000000000000000000000000000000..22ed4f75d7fa4d3842ec35cde5b395b2580c8774 --- /dev/null +++ b/llm_panda/config.py @@ -0,0 +1,235 @@ +"""Central configuration: scene geometry, robot wiring and physics constants. + +All coordinates were validated for Panda reachability (IK error < 1 mm for the +table/tray targets) before being committed here, so the demo runs out of the box. +""" + +import math +import os +import pybullet as pb +import pybullet_data + +# --------------------------------------------------------------------------- # +# Paths +# --------------------------------------------------------------------------- # +PACKAGE_DIR = os.path.dirname(os.path.abspath(__file__)) +GRASP_DB_PATH = os.path.join(PACKAGE_DIR, "data", "grasp_database.json") + +# --------------------------------------------------------------------------- # +# Physics +# --------------------------------------------------------------------------- # +GRAVITY = -9.81 +SIM_TIMESTEP = 1.0 / 240.0 # default PyBullet step +OBJECT_GLOBAL_SCALING = 0.7 # Global scaling factor for YCB objects + +# --------------------------------------------------------------------------- # +# Franka Panda wiring (dynamically parsed from URDF) +# --------------------------------------------------------------------------- # +PANDA_URDF = "franka_panda/panda.urdf" + +def _parse_urdf_config(urdf_name): + # Connect to PyBullet in DIRECT (headless) mode to parse URDF + client = pb.connect(pb.DIRECT) + pb.setAdditionalSearchPath(pybullet_data.getDataPath()) + try: + robot_id = pb.loadURDF(urdf_name, [0, 0, 0], useFixedBase=True) + num_joints = pb.getNumJoints(robot_id) + + arm_joint_indices = [] + finger_joint_indices = [] + finger_open = 0.04 + end_effector_index = None + hand_link_index = None + + for i in range(num_joints): + info = pb.getJointInfo(robot_id, i) + joint_name = info[1].decode('utf-8') + joint_type = info[2] + + if joint_type == pb.JOINT_REVOLUTE and "panda_joint" in joint_name: + arm_joint_indices.append(i) + elif joint_type == pb.JOINT_PRISMATIC and "panda_finger" in joint_name: + finger_joint_indices.append(i) + finger_open = info[9] + elif "panda_grasptarget" in joint_name: + end_effector_index = i + elif "panda_hand" in joint_name: + hand_link_index = i + + if end_effector_index is None: + end_effector_index = num_joints - 1 + if hand_link_index is None: + hand_link_index = 8 + + return arm_joint_indices, finger_joint_indices, finger_open, end_effector_index, hand_link_index + except Exception as e: + # Fallback to standard Panda values in case of loading error + print(f"[CONFIG] URDF Parsing failed: {e}. Using static fallbacks.") + return [0, 1, 2, 3, 4, 5, 6], [9, 10], 0.04, 11, 8 + finally: + pb.disconnect(client) + +# Parse dynamically +ARM_JOINT_INDICES, FINGER_JOINT_INDICES, FINGER_OPEN, END_EFFECTOR_INDEX, HAND_LINK_INDEX = _parse_urdf_config(PANDA_URDF) + +# Verify against original static configuration values +_STATIC_ARM = [0, 1, 2, 3, 4, 5, 6] +_STATIC_FINGER = [9, 10] +_STATIC_OPEN = 0.04 +_STATIC_EE = 11 +_STATIC_HAND = 8 + +print("\n" + "="*60) +print("[CONFIG] VERIFYING DYNAMIC CONFIG AGAINST STATIC CONSTANTS:") +print(f" ARM_JOINT_INDICES : Dynamic: {ARM_JOINT_INDICES} | Static: {_STATIC_ARM} | Match: {ARM_JOINT_INDICES == _STATIC_ARM}") +print(f" FINGER_JOINT_INDICES : Dynamic: {FINGER_JOINT_INDICES} | Static: {_STATIC_FINGER} | Match: {FINGER_JOINT_INDICES == _STATIC_FINGER}") +print(f" FINGER_OPEN : Dynamic: {FINGER_OPEN:.4f} m | Static: {_STATIC_OPEN:.4f} m | Match: {FINGER_OPEN == _STATIC_OPEN}") +print(f" END_EFFECTOR_INDEX : Dynamic: {END_EFFECTOR_INDEX} | Static: {_STATIC_EE} | Match: {END_EFFECTOR_INDEX == _STATIC_EE}") +print(f" HAND_LINK_INDEX : Dynamic: {HAND_LINK_INDEX} | Static: {_STATIC_HAND} | Match: {HAND_LINK_INDEX == _STATIC_HAND}") +print("="*60 + "\n") + +# A comfortable, table-facing rest pose for the 7 arm joints. +ARM_REST_POSE = [0.0, -0.4, 0.0, -2.0, 0.0, 1.6, 0.79] + +FINGER_CLOSED = 0.0 + +# Gripper grasp-force hardware envelope (Newtons), per Panda spec. +GRIP_FORCE_MIN = 40.0 # 10N was too low — objects slip during dynamic lift +GRIP_FORCE_MAX = 140.0 + +# Force used to *drive* the arm joints (position control), not the grip force. +ARM_MAX_FORCE = 200.0 + +# --------------------------------------------------------------------------- # +# Table (continuous placement surface — no fixed slot grid) +# --------------------------------------------------------------------------- # +TABLE_CENTER = (0.50, 0.0) +TABLE_HALF_EXTENTS = (0.17, 0.27, 0.15) # x, y, z half-sizes +TABLE_BASE_Z = TABLE_HALF_EXTENTS[2] # base sits so its bottom is on z=0 +TABLE_TOP_Z = 2 * TABLE_HALF_EXTENTS[2] # top surface = 0.30 m +TABLE_COLOR = [0.55, 0.35, 0.18, 1.0] + +# Mount the Panda on a low pedestal to lift its base toward the table/tray +# level. This pulls the far tray corner back inside the arm's comfortable reach +# (the place pose there drops from ~0.58 m to ~0.50 m above the base), which is +# what stalled the IK / knocked tray objects before. NOTE: a *full* table-height +# mount (0.30) is reachable kinematically but degrades the floor-tuned top-down +# table grasps (the tall can fails ~2/3 of picks); 0.08 is the largest raise +# that keeps grasp reliability at the floor-mount baseline (~14/15). +ROBOT_BASE_Z = 0.08 +ROBOT_PEDESTAL_HALF = 0.06 # footprint half-extent of the pedestal + +# Fixed tray, just outside the +y edge of the table. +# Larger (40×28 cm) so banana/soup-can/chips-can fit side-by-side without knocking each other off. +TRAY_POSITION = (0.40, 0.41, TABLE_TOP_Z) +TRAY_HALF_EXTENTS = (0.20, 0.14, 0.01) +TRAY_COLOR = [0.20, 0.20, 0.22, 1.0] + +# A location is "the tray" if within this planar radius of the tray centre. +TRAY_MATCH_RADIUS = 0.22 + +# XY radius (m) used to detect object neighbors for side-effect reporting. +NEIGHBOR_RADIUS = 0.18 + +# Approach-path obstacle detection (used to decide what to clear before a grasp). +# An object blocks a target's grasp if it sits within OBSTACLE_RADIUS of the +# target, or inside the straight base→target corridor of this half-width. +OBSTACLE_RADIUS = 0.14 +APPROACH_CORRIDOR_WIDTH = 0.09 + +# --------------------------------------------------------------------------- # +# Multi-angle grasp (top-down vs tilted "side" grasp) +# --------------------------------------------------------------------------- # +# When another object sits within this planar distance (m) of the target, a +# straight top-down descent would clip it, so the arm switches to a tilted side +# grasp coming in from the clear side instead. +SIDE_GRASP_TRIGGER_RADIUS = 0.14 +# Tilt of the side grasp away from vertical (radians). 0 = top-down, pi/2 = +# fully horizontal. ~45° is the sweet spot: it reaches in from the side past an +# overhead/adjacent blocker yet keeps the arm clear of the table (a fully +# horizontal grasp of a low object collides the forearm with the table). +SIDE_GRASP_TILT = math.pi / 4 +# How far back along the (diagonal) approach axis the side pre-grasp sits (m). +SIDE_GRASP_PRE_DIST = 0.13 + +# --------------------------------------------------------------------------- # +# Buffer allocation (temporary parking spot for a cleared obstacle) +# --------------------------------------------------------------------------- # +# A relocated obstacle must land at least this far (m) from the objects it was +# tangled with, so moving it there actually breaks the blocking relationship +# (just beyond OBSTACLE_RADIUS so the pair no longer counts as mutually blocking). +BUFFER_MIN_CLEARANCE = 0.16 + +# Per-class placement zones inside the tray (x-offset from tray centre, y=0). +# Absolute last-resort fallback: only used when even the best-effort optimiser +# returns nothing (no reachable spot at all). Every class gets a DISTINCT offset +# so this path never stacks two objects at the exact same point. +TRAY_CLASS_OFFSET_X = { + "banana": -0.13, + "can": -0.07, + "chips": 0.00, + "ball": 0.06, + "pear": 0.11, + "clamp": 0.16, +} + +# Desired centre-to-centre gap (m) when honouring a spatial relation +# ("next to"/"left of"/...): about one object width of breathing room. +RELATION_TARGET_GAP = 0.14 + +# --------------------------------------------------------------------------- # +# Occupancy grid (continuous free-space analysis of the table top) +# --------------------------------------------------------------------------- # +# Raster resolution of the table top, in metres per grid cell. 1 cm gives a +# ~28x48 grid over the usable area — fine enough for footprint-level reasoning, +# cheap enough to recompute every scene query. +OCCUPANCY_CELL_SIZE = 0.01 +# Keep placements at least this far from the physical table edge (so the +# gripper fingers and object body never overhang the edge). +TABLE_EDGE_MARGIN = 0.03 +# Extra clearance added around every object footprint when searching for a free +# spot (covers gripper finger width + a small safety buffer). +PLACEMENT_SAFETY_MARGIN = 0.03 +# Best-effort placement penalty: when a surface has NO fully-free window, the +# optimiser falls back to the least-overlapping spot, charging this cost per +# occupied grid cell inside the candidate footprint. It is large enough that any +# zero-overlap spot is always strictly preferred (so normal behaviour is +# unchanged); only when nothing is free does it rank spots by least overlap. +PLACEMENT_OVERLAP_PENALTY = 1000.0 + +# --------------------------------------------------------------------------- # +# Trajectory tuning +# --------------------------------------------------------------------------- # +PRE_GRASP_HEIGHT = 0.10 # hover 10 cm above the grasp point +LIFT_HEIGHT = 0.25 # lift this far above the table top after grasping +TOP_DOWN_EULER = [math.pi, 0.0, 0.0] # gripper pointing straight down + +# U-shaped (Lift-and-Place) transit: target ceiling the TCP rises to before +# flying horizontally, and the vertical clearance kept above any obstacle in +# the travel corridor. The ceiling is always capped by arm reachability. +Z_SAFE_TRAVEL = 0.6 +TRAVEL_CLEARANCE = 0.05 + +# --------------------------------------------------------------------------- # +# 2D GLOBAL cost map + A* path planning (horizontal obstacle avoidance) +# --------------------------------------------------------------------------- # +# The cost map spans the WHOLE robot workspace (table ∪ tray, grown by a +# margin), not a single surface. A global frame means the arm's true starting +# XY is always inside the grid, so it is never clamped ("snapped") onto a tray +# or table border before planning — the route begins exactly where the TCP is. +COSTMAP_GRID_N = 100 # NxN cells spanning the whole workspace +COSTMAP_OBSTACLE_COST = 100.0 +# How far (m) the global workspace bounds extend beyond the outermost surface, +# so a TCP hovering just off a surface edge still maps to an in-grid free cell. +WORKSPACE_MARGIN = 0.06 +# Obstacle footprints are dilated by this radius (m) so the planned path keeps +# clearance from objects (covers gripper + carried-object half-width). +COSTMAP_INFLATION = 0.045 +# Greedy weight on the A* heuristic (>= 1.0). A small bias toward the goal cuts +# node expansion on the global grid, keeping pathfinding within a few ms; the +# route is effectively unchanged at this weight. +COSTMAP_ASTAR_WEIGHT = 1.2 +# Keep the transit ceiling this far below the arm's max reachable height so the +# horizontal fly never skims the near-singular workspace boundary (which makes +# IK saturate and the motion stall mid-path). +REACH_SAFETY_MARGIN = 0.10 diff --git a/llm_panda/cost_map.py b/llm_panda/cost_map.py new file mode 100644 index 0000000000000000000000000000000000000000..ea1b9705662f71993809a8382c5ae5a6a7d1d319 --- /dev/null +++ b/llm_panda/cost_map.py @@ -0,0 +1,301 @@ +"""Global 2D cost map + A* path planner for horizontal obstacle avoidance. + +Two layers, deliberately kept separate (so the planning math stays clean): + +* **Elevation** — the *physical* layer. ``elevation[j, i]`` is the world-Z of + the tallest object footprint covering that cell (table-top level where empty). + This is pure geometry: every object, its true (un-inflated) footprint. +* **Cost** — the *planning* layer, derived from elevation. A cell only becomes + an impassable wall (:data:`config.COSTMAP_OBSTACLE_COST`) when its elevation + exceeds the carried object's fly-over clearance — i.e. an obstacle the arm + cannot lift over and must route around. Low obstacles (a banana lying flat) + leave the cost layer free, so A* plans straight over them while the U-shaped + trajectory simply clears them in Z. + +Both layers share ONE grid spanning the whole robot workspace (table ∪ tray, +grown by :data:`config.WORKSPACE_MARGIN`). A global frame is what fixes +"start-point snapping": the arm's real starting XY is always inside the grid, +so :func:`plan_path` never clamps it onto a surface border before planning. + +Pipeline (a stand-in for a real SAM/RANSAC perception stack): + +1. "Cheat" perception — read every object's global pose, footprint and AABB + height straight from PyBullet (via :class:`SceneManager`). +2. Rasterise the workspace into the elevation grid, then threshold it by the + fly-over clearance to obtain the cost grid (tall obstacles inflated by + :data:`config.COSTMAP_INFLATION`). +3. Build a goal-attraction field toward the LLM-named drop spot. +4. Run A* over the cost grid for an ``(x, y)`` route around the cost walls. + +The waypoints feed the U-shaped trajectory generator +(:meth:`RobotController.plan_u_path`) to drive the Panda. +""" + +import heapq +import math + +import numpy as np + +from . import config +from .scene_manager import rasterize_footprint + + +def surface_bounds(surface): + """``(x_min, x_max, y_min, y_max)`` of a placement surface ('table'/'tray').""" + if surface == "tray": + cx, cy, _ = config.TRAY_POSITION + hx, hy = config.TRAY_HALF_EXTENTS[0], config.TRAY_HALF_EXTENTS[1] + else: + cx, cy = config.TABLE_CENTER + hx, hy = config.TABLE_HALF_EXTENTS[0], config.TABLE_HALF_EXTENTS[1] + return (cx - hx, cx + hx, cy - hy, cy + hy) + + +def workspace_bounds(): + """``(x_min, x_max, y_min, y_max)`` of the whole planning workspace. + + The union of the table and tray footprints, grown by + :data:`config.WORKSPACE_MARGIN`. This is the global frame the cost map is + rasterised over, large enough that the arm's starting XY always lands on an + in-grid cell (no border clamping / start-point snapping). + """ + tx0, tx1, ty0, ty1 = surface_bounds("table") + rx0, rx1, ry0, ry1 = surface_bounds("tray") + m = config.WORKSPACE_MARGIN + return (min(tx0, rx0) - m, max(tx1, rx1) + m, + min(ty0, ry0) - m, max(ty1, ry1) + m) + + +def fly_over_clearance_z(carried_height=0.0): + """Absolute world-Z that the *carried object's bottom* clears on a baseline + lift, i.e. obstacles whose top sits at or below this can be flown over. + + Mirrors the floor used by :meth:`RobotController.plan_u_path`: the TCP is + always lifted to at least ``TABLE_TOP_Z + LIFT_HEIGHT``, so the carried + object's bottom rides at ``ceiling - carried_height``; an obstacle clears if + its top stays ``TRAVEL_CLEARANCE`` below that. Objects above this threshold + can't be flown over reliably and become cost walls to route around. + """ + ceiling = config.TABLE_TOP_Z + config.LIFT_HEIGHT + return ceiling - carried_height - config.TRAVEL_CLEARANCE + + +class CostMap: + """Layered 2D grid over the whole workspace: elevation (physical) + cost + (planning). A* consumes only the cost layer.""" + + def __init__(self, cost, elevation, x_min, y_min, cell_x, cell_y): + self.cost = cost # (ny, nx) float — planning walls + self.elevation = elevation # (ny, nx) float — object-top Z + self.x_min, self.y_min = x_min, y_min + self.cell_x, self.cell_y = cell_x, cell_y + self.ny, self.nx = cost.shape + + # ------------------------------------------------------------------ # + # Construction + # ------------------------------------------------------------------ # + @classmethod + def from_scene(cls, scene, exclude_ids=None, inflation=None, n=None, + clearance_z=None, carried_height=0.0): + """Build a global cost map from the live PyBullet world. + + Every registered object stamps its true footprint into the *elevation* + layer at its AABB-top Z (pure geometry, no inflation). The *cost* layer + is then derived: only objects taller than ``clearance_z`` (the fly-over + clearance for ``carried_height``) are stamped as impassable walls, + dilated by ``inflation``. Bodies in ``exclude_ids`` (e.g. the carried + object) are ignored. + """ + exclude = set(exclude_ids or []) + inflation = config.COSTMAP_INFLATION if inflation is None else inflation + n = n or config.COSTMAP_GRID_N + if clearance_z is None: + clearance_z = fly_over_clearance_z(carried_height) + + x_min, x_max, y_min, y_max = workspace_bounds() + cell_x = (x_max - x_min) / n + cell_y = (y_max - y_min) / n + + elevation = np.full((n, n), config.TABLE_TOP_Z, dtype=float) + cost = np.zeros((n, n), dtype=float) + for oid in scene.object_ids: + if oid in exclude: + continue + poly = scene.footprint_polygon(oid) + pxs = [p[0] for p in poly] + pys = [p[1] for p in poly] + if (max(pxs) <= x_min or min(pxs) >= x_max + or max(pys) <= y_min or min(pys) >= y_max): + continue # footprint entirely outside the workspace + + top_z = scene.get_aabb(oid)[1][2] + + # Physical layer: true footprint at the object's top height (max). + patch = np.zeros((n, n), dtype=float) + rasterize_footprint(patch, x_min, y_min, cell_x, cell_y, poly, 0.0, top_z) + np.maximum(elevation, patch, out=elevation) + + # Planning layer: a wall only if too tall to fly over. + if top_z > clearance_z: + rasterize_footprint(cost, x_min, y_min, cell_x, cell_y, poly, + inflation, config.COSTMAP_OBSTACLE_COST) + return cls(cost, elevation, x_min, y_min, cell_x, cell_y) + + # ------------------------------------------------------------------ # + # Cell <-> world + # ------------------------------------------------------------------ # + def world_to_cell(self, x, y): + i = int((x - self.x_min) / self.cell_x) + j = int((y - self.y_min) / self.cell_y) + return (max(0, min(self.nx - 1, i)), max(0, min(self.ny - 1, j))) + + def cell_to_world(self, i, j): + return (self.x_min + (i + 0.5) * self.cell_x, + self.y_min + (j + 0.5) * self.cell_y) + + def is_free(self, i, j): + return self.cost[j, i] < config.COSTMAP_OBSTACLE_COST + + def nearest_free_cell(self, x, y): + """Closest free cell to a world point (the world point itself if free).""" + i0, j0 = self.world_to_cell(x, y) + if self.is_free(i0, j0): + return (i0, j0) + for r in range(1, max(self.nx, self.ny)): + best, best_d = None, None + for j in range(max(0, j0 - r), min(self.ny, j0 + r + 1)): + for i in range(max(0, i0 - r), min(self.nx, i0 + r + 1)): + if self.is_free(i, j): + d = (i - i0) ** 2 + (j - j0) ** 2 + if best_d is None or d < best_d: + best, best_d = (i, j), d + if best is not None: + return best + return (i0, j0) + + def goal_attraction(self, target_xy): + """Attraction field decreasing toward ``target_xy`` (Research-style). + + Returns ``(goal_cell, attraction)`` where ``attraction[j, i]`` is the + cell's distance to the target (``inf`` on obstacles) — lower = closer to + the goal — and ``goal_cell`` is the nearest free cell to the target (the + cost-≈0 optimal drop spot). + """ + ti, tj = self.world_to_cell(*target_xy) + jj, ii = np.mgrid[0:self.ny, 0:self.nx] + attraction = np.sqrt((ii - ti) ** 2 + (jj - tj) ** 2).astype(float) + attraction[self.cost >= config.COSTMAP_OBSTACLE_COST] = np.inf + return self.nearest_free_cell(*target_xy), attraction + + +def astar(costmap, start_cell, goal_cell): + """8-connected A* over free cells. Returns a list of ``(i, j)`` or ``[]``. + + Step cost = Euclidean move length + a small term proportional to the cell + cost, so the path both avoids obstacles (impassable) and shies away from + their inflated borders. Diagonal moves may not cut obstacle corners. + """ + nx, ny = costmap.nx, costmap.ny + (sx, sy), (gx, gy) = start_cell, goal_cell + + # Hoist the grid into plain Python lists once: list indexing in the hot loop + # is ~10x faster than numpy scalar access / bound-method calls, which keeps + # A* in the low-millisecond range even on the full workspace grid. + obstacle = config.COSTMAP_OBSTACLE_COST + cost_rows = costmap.cost.tolist() + free = [[c < obstacle for c in row] for row in cost_rows] + + # A mild greedy weight breaks ties toward the goal so A* expands far fewer + # nodes in open regions of the (large) global grid — the route is unchanged + # in practice but the search stays comfortably in the low-millisecond range. + w = config.COSTMAP_ASTAR_WEIGHT + + def heuristic(i, j): + return w * math.hypot(i - gx, j - gy) + + open_heap = [(heuristic(sx, sy), 0.0, (sx, sy))] + came_from = {} + g_score = {(sx, sy): 0.0} + neighbors = [(-1, 0), (1, 0), (0, -1), (0, 1), + (-1, -1), (-1, 1), (1, -1), (1, 1)] + + while open_heap: + _, g, (i, j) = heapq.heappop(open_heap) + if (i, j) == (gx, gy): + path = [(i, j)] + while (i, j) in came_from: + i, j = came_from[(i, j)] + path.append((i, j)) + return path[::-1] + if g > g_score.get((i, j), float("inf")): + continue + for di, dj in neighbors: + ni, nj = i + di, j + dj + if not (0 <= ni < nx and 0 <= nj < ny) or not free[nj][ni]: + continue + if di != 0 and dj != 0 and ( + not free[j][i + di] or not free[j + dj][i] + ): + continue # don't squeeze diagonally between two obstacles + step = math.hypot(di, dj) + 0.01 * cost_rows[nj][ni] + ng = g + step + if ng < g_score.get((ni, nj), float("inf")): + g_score[(ni, nj)] = ng + came_from[(ni, nj)] = (i, j) + heapq.heappush(open_heap, (ng + heuristic(ni, nj), ng, (ni, nj))) + return [] + + +def _simplify(points): + """Drop collinear interior points from a polyline.""" + if len(points) <= 2: + return list(points) + out = [points[0]] + for k in range(1, len(points) - 1): + ax, ay = out[-1] + bx, by = points[k] + cx, cy = points[k + 1] + cross = (bx - ax) * (cy - by) - (by - ay) * (cx - bx) + if abs(cross) > 1e-9: + out.append(points[k]) + out.append(points[-1]) + return out + + +def plan_path(scene, surface=None, start_xy=None, target_xy=None, exclude_ids=None, + inflation=None, carried_height=0.0, clearance_z=None): + """World ``(x, y)`` waypoints from start to target across the workspace. + + Routes on a single GLOBAL cost map, so the start is taken at its true + location (never snapped to a surface border) and only obstacles too tall to + fly over — given ``carried_height`` — act as walls; lower ones are flown + over by the trajectory layer. ``surface`` is accepted for caller/logging + compatibility but no longer restricts the map. + + Returns a simplified polyline (collinear points removed) ending exactly at + ``target_xy``. Falls back to ``[target_xy]`` when no route exists (the caller + then flies straight / over the top). + """ + cm = CostMap.from_scene(scene, exclude_ids=exclude_ids, inflation=inflation, + carried_height=carried_height, clearance_z=clearance_z) + goal_cell, _ = cm.goal_attraction(target_xy) + + si, sj = cm.world_to_cell(*start_xy) + if not cm.is_free(si, sj): + si, sj = cm.nearest_free_cell(*start_xy) + + cells = astar(cm, (si, sj), goal_cell) + if not cells: + return [tuple(target_xy[:2])] + + pts = _simplify([cm.cell_to_world(i, j) for (i, j) in cells]) + pts[-1] = tuple(target_xy[:2]) # land on the exact requested spot + return pts + + +def plan_table_path(scene, start_xy, target_xy, exclude_ids=None, inflation=None, + carried_height=0.0): + """Back-compat wrapper: global A* route (kept for older call sites/tests).""" + return plan_path(scene, "table", start_xy, target_xy, + exclude_ids=exclude_ids, inflation=inflation, + carried_height=carried_height) diff --git a/llm_panda/data/grasp_database.json b/llm_panda/data/grasp_database.json new file mode 100644 index 0000000000000000000000000000000000000000..b6eaf3a58c1cc86989f7757f7edb10a1abe1f789 --- /dev/null +++ b/llm_panda/data/grasp_database.json @@ -0,0 +1,53 @@ +{ + "_comment": "Local (object-frame) grasp poses. position = TCP offset from the object centre in metres; euler = gripper orientation in object frame (radians). The execution layer transforms these into the world frame via p.multiplyTransforms.", + "cube": { + "local_position": [0.0, 0.0, 0.0], + "local_euler": [3.141592653589793, 0.0, 0.0], + "description": "Top-down grasp at the cube centre." + }, + "cylinder": { + "local_position": [0.0, 0.0, 0.02], + "local_euler": [3.141592653589793, 0.0, 0.0], + "description": "Top-down grasp slightly above centre, near the cylinder top." + }, + "can": { + "local_position": [0.0, 0.0, 0.02], + "local_euler": [3.141592653589793, 0.0, 0.0], + "description": "Top-down grasp near the top of a cylindrical can." + }, + "box": { + "local_position": [0.0, 0.0, 0.0], + "local_euler": [3.141592653589793, 0.0, 0.0], + "description": "Top-down grasp at the box centre." + }, + "chips": { + "local_position": [0.0, 0.0, 0.02], + "local_euler": [3.141592653589793, 0.0, 0.0], + "description": "Top-down grasp near the top of a cylindrical chips can." + }, + "banana": { + "local_position": [0.0, 0.0, 0.01], + "local_euler": [3.141592653589793, 0.0, 0.0], + "description": "Top-down grasp near the middle-top of the banana." + }, + "ball": { + "local_position": [0.0, 0.0, 0.0], + "local_euler": [3.141592653589793, 0.0, 0.0], + "description": "Top-down grasp at the centre (equator) of the tennis ball." + }, + "pear": { + "local_position": [0.0, 0.0, 0.01], + "local_euler": [3.141592653589793, 0.0, 0.0], + "description": "Top-down grasp near the top of the pear." + }, + "clamp": { + "local_position": [0.0, 0.0, 0.0], + "local_euler": [3.141592653589793, 0.0, 0.0], + "description": "Top-down grasp at the centre of the flat clamp." + }, + "default": { + "local_position": [0.0, 0.0, 0.0], + "local_euler": [3.141592653589793, 0.0, 0.0], + "description": "Generic top-down centre grasp used when a class is missing." + } +} diff --git a/llm_panda/evaluators.py b/llm_panda/evaluators.py new file mode 100644 index 0000000000000000000000000000000000000000..ab618ce6d124904a7d889624d4af4dd335f5fc5f --- /dev/null +++ b/llm_panda/evaluators.py @@ -0,0 +1,132 @@ +import numpy as np +import logging +from typing import Tuple, Dict, Any +from .geofik import FrankaGeoFIK, IKResult, ReachabilityStatus +from .swivel_adapter import SwivelAdapter +from .task_nullspace import TaskManifold + +logger = logging.getLogger(__name__) + +class CachingContext: + """ + Evaluates and caches the kinematic chain to avoid redundant IK calls. + """ + def __init__(self, fik: FrankaGeoFIK, swivel: SwivelAdapter, task: TaskManifold): + self.fik = fik + self.swivel = swivel + self.task = task + self.last_x = None + self.last_q = None + self.last_J_task = None + self.last_J_ik = None + self.last_J_swivel = None + self.last_success = False + + def update(self, x: np.ndarray) -> bool: + if self.last_x is not None and np.allclose(self.last_x, x, atol=1e-8): + return self.last_success + + self.last_x = x.copy() + u = x[:-1] + theta = x[-1] + + # 1. Task Manifold + T_target = self.task.get_transform(u) + self.last_J_task = self.task.get_transform_jacobian(u) + + # 2. Swivel Adapter + q7, dq7_dtheta = self.swivel.get_q7_and_derivative(theta, T_target) + if q7 is None: + self.last_success = False + return False + + # 3. GeoFIK Layer A + ik_result = self.fik.solve(T_target, q7) + if not ik_result.success: + self.last_success = False + return False + + self.last_q = ik_result.q + + # 4. Chain Rule Assembly + # J_pose is 6x7. v = J_pose * qdot + J_pose = ik_result.pose_jacobian + J_6 = J_pose[:, :6] + J_7 = J_pose[:, 6] + + # Analytical inversion for redundant chain + # dq_0:5 = - inv(J_6) * J_7 * dq7 + try: + J_6_inv = np.linalg.inv(J_6) + except np.linalg.LinAlgError: + self.last_success = False + return False + + dq_dq7_6 = - J_6_inv @ J_7 + dq_dq7 = np.append(dq_dq7_6, 1.0) # 7x1 + + self.last_J_swivel = dq_dq7 * dq7_dtheta + + # J_ik = dq / du = (dq / dT) * (dT / du) = J_6_inv * J_task + dq_du_6 = J_6_inv @ self.last_J_task + dq_du_7 = np.zeros((1, self.last_J_task.shape[1])) + self.last_J_ik = np.vstack((dq_du_6, dq_du_7)) + + self.last_success = True + return True + + +class ObjectiveEvaluator: + """ + Evaluates optimization objectives. + Source: Architecture Design (Standard Robotics / Engineering) + """ + def __init__(self, ctx: CachingContext, q_nominal: np.ndarray): + self.ctx = ctx + self.q_nominal = q_nominal + + def evaluate_displacement(self, x: np.ndarray) -> Tuple[float, np.ndarray]: + """ + f(x) = 0.5 * ||q - q_nominal||^2 + df/dx = (q - q_nominal)^T * (dq/dx) + """ + if not self.ctx.update(x): + return 1e6, np.zeros_like(x) + + diff = self.ctx.last_q - self.q_nominal + cost = 0.5 * np.sum(diff**2) + + # dq_dx = [J_ik, J_swivel] + dq_dx = np.column_stack((self.ctx.last_J_ik, self.ctx.last_J_swivel)) + grad = diff.T @ dq_dx + + return cost, grad + + +class ConstraintEvaluator: + """ + Evaluates hard constraints (e.g., joint limits). + """ + def __init__(self, ctx: CachingContext, q_low: np.ndarray, q_up: np.ndarray): + self.ctx = ctx + self.q_low = q_low + self.q_up = q_up + + def evaluate_limits(self, x: np.ndarray) -> Tuple[np.ndarray, np.ndarray]: + """ + c(x) >= 0 -> q - q_low >= 0, q_up - q >= 0 + Returns: constraints (14,), Jacobian (14, len(x)) + """ + if not self.ctx.update(x): + return -np.ones(14), np.zeros((14, len(x))) + + c_low = self.ctx.last_q - self.q_low + c_up = self.q_up - self.ctx.last_q + constraints = np.concatenate((c_low, c_up)) + + dq_dx = np.column_stack((self.ctx.last_J_ik, self.ctx.last_J_swivel)) + grad_low = dq_dx + grad_up = -dq_dx + grad = np.vstack((grad_low, grad_up)) + + return constraints, grad diff --git a/llm_panda/geofik.py b/llm_panda/geofik.py new file mode 100644 index 0000000000000000000000000000000000000000..7e967a9a0f95cf56d3d4550f0561535b489e5489 --- /dev/null +++ b/llm_panda/geofik.py @@ -0,0 +1,330 @@ +import enum +import logging +from dataclasses import dataclass +from typing import Optional, Tuple +import numpy as np + +logger = logging.getLogger(__name__) + +# Constants +EPSILON = 1e-6 +SINGULARITY_EPSILON = 1e-5 + + +def wrap_angle(angle: float) -> float: + """Normalize angle to [-pi, pi].""" + return (angle + np.pi) % (2 * np.pi) - np.pi + + +def rot_axis_angle(axis: np.ndarray, theta: float) -> np.ndarray: + """ + Source: [Standard Robotics] Rodrigues' rotation formula. + """ + axis = axis / np.linalg.norm(axis) + a = np.cos(theta / 2.0) + b, c, d = -axis * np.sin(theta / 2.0) + aa, bb, cc, dd = a * a, b * b, c * c, d * d + bc, ad, ac, ab, bd, cd = b * c, a * d, a * c, a * b, b * d, c * d + return np.array([ + [aa + bb - cc - dd, 2 * (bc + ad), 2 * (bd - ac)], + [2 * (bc - ad), aa + cc - bb - dd, 2 * (cd + ab)], + [2 * (bd + ac), 2 * (cd - ab), aa + dd - bb - cc] + ]) + + +class ReachabilityStatus(enum.Enum): + SUCCESS = 0 + UNREACHABLE = 1 + SINGULAR = 2 + LIMIT_VIOLATION = 3 + + +@dataclass(frozen=True) +class BranchSelection: + """ + Branch policy for GeoFIK solver. + s1: Shoulder sign (Right/Left) (1 or -1) + s2: Elbow sign (Up/Down) (1 or 0 -> mapped to C++ branches) + s3: Wrist sign (Flip/No-Flip) (N/A for q7-free, implicitly chosen by q7 range, but we keep structure) + """ + s1: int + s2: int + s3: int + + +@dataclass(frozen=True) +class IKResult: + """ + Result of the GeoFIK solver. + """ + q: np.ndarray # shape: (7,) + success: bool # True if solved and within limits + reachability_status: int # 0=Success, 1=Unreachable, 2=Singular, 3=Limit violation + pose_jacobian: np.ndarray # shape: (6, 7) (V = J * qdot) + + +@dataclass +class FrankaGeometry: + """ + Franka Panda geometric constants, locked to PyBullet URDF conventions. + """ + d1: float = 0.333 + d3: float = 0.316 + a4: float = 0.0825 + a5: float = 0.0825 + d5: float = 0.384 + a7: float = 0.088 + + # Precomputed derived lengths + b1: float = 0.3265918706887849 # sqrt(d3**2 + a4**2) + b2: float = 0.39276233271534583 # sqrt(d5**2 + a5**2) + beta1: float = 0.25537561488738186 # arctan(a4/d3) + beta2: float = 0.21162680876562978 # arctan(a5/d5) + + d_tcp: float = 0.107 + + # Joint limits from URDF + q_low: np.ndarray = np.array([-2.8973, -1.7628, -2.8973, -3.0718, -2.8973, -0.0175, -2.8973]) + q_up: np.ndarray = np.array([ 2.8973, 1.7620, 2.8973, -0.0698, 2.8973, 3.7525, 2.8973]) + + def get_flange_transform(self) -> np.ndarray: + """ + Returns the transform from joint 7 to the flange (panda_link8). + """ + T = np.eye(4) + T[2, 3] = self.d_tcp + return T + + +def get_home_axes(geometry: FrankaGeometry) -> np.ndarray: + """ + Extracts the zero-configuration joint axes required for angle extraction. + Source: [Standard Robotics] FK Forward pass. + """ + axes = np.zeros((3, 7)) + T = np.eye(4) + + def rot_z(q): return np.array([[np.cos(q), -np.sin(q), 0], [np.sin(q), np.cos(q), 0], [0, 0, 1]]) + def rot_x(q): return np.array([[1, 0, 0], [0, np.cos(q), -np.sin(q)], [0, np.sin(q), np.cos(q)]]) + + # Base to 1 + T[:3, 3] = [0, 0, geometry.d1] + axes[:, 0] = T[:3, 2] + T = T @ rot_z(0.0) + # 1 to 2 + T = T @ rot_x(-np.pi/2) @ rot_z(0.0) + axes[:, 1] = T[:3, 2] + # 2 to 3 + T = T @ rot_x(np.pi/2) @ rot_z(0.0) + axes[:, 2] = T[:3, 2] + # 3 to 4 + T = T @ rot_x(np.pi/2) @ rot_z(0.0) + axes[:, 3] = T[:3, 2] + # 4 to 5 + T = T @ rot_x(-np.pi/2) @ rot_z(0.0) + axes[:, 4] = T[:3, 2] + # 5 to 6 + T = T @ rot_x(np.pi/2) @ rot_z(0.0) + axes[:, 5] = T[:3, 2] + # 6 to 7 + T = T @ rot_x(np.pi/2) @ rot_z(0.0) + axes[:, 6] = T[:3, 2] + + return axes + + +class FrankaGeoFIK: + """ + GeoFIK solver for the Franka Panda. + Strictly implements analytical IK Layer A. + """ + def __init__(self, geometry: FrankaGeometry, branch: BranchSelection): + self.geometry = geometry + self.branch = branch + self.J0_S = get_home_axes(geometry) + + def _isolate_wrist_center(self, T_gripper: np.ndarray, q7: float) -> Tuple[np.ndarray, np.ndarray, np.ndarray]: + """ + Source: [GeoFIK Paper] Sec 3, [Official C++ Repo] L.1078-1081 + Mathematical Justification: Isolates r6 based on end-effector and q7. + """ + p_flange = T_gripper[0:3, 3] + R_flange = T_gripper[0:3, 0:3] + + # O7 = Flange - d_tcp * Z_flange + r_O7 = p_flange - R_flange @ np.array([0, 0, self.geometry.d_tcp]) + k_E = R_flange[:, 2] + i_E = R_flange[:, 0] + + # r_O7S_O = r_O7 - r_S + r_O7S_O = r_O7 - np.array([0.0, 0.0, self.geometry.d1]) + + # Rotate i_E back around k_E by -(q7 - pi/4) + R_rot = rot_axis_angle(k_E, -(q7 - np.pi/4)) + i_6 = R_rot @ i_E + + s6 = np.cross(k_E, i_6) + r6 = r_O7S_O - self.geometry.a7 * i_6 + return i_6, s6, r6 + + def _compute_cone_frame(self, s6: np.ndarray, r6: np.ndarray) -> Tuple[np.ndarray, np.ndarray, np.ndarray, float, bool]: + """ + Source: [GeoFIK Paper] Sec 3, [Official C++ Repo] L.1082-1095 + """ + l = np.linalg.norm(r6) + tmp = (self.geometry.b1**2 - l**2 - self.geometry.b2**2) / (-2 * l * self.geometry.b2) + + is_unreachable = False + if tmp > 1.0 or tmp < -1.0: + is_unreachable = True + tmp = np.clip(tmp, -1.0, 1.0) + + alpha2 = self.geometry.beta2 + np.arccos(tmp) + + k_C = -r6 / l + i_C_raw = np.cross(k_C, s6) + norm_i = np.linalg.norm(i_C_raw) + if norm_i < EPSILON: + i_C = np.array([1.0, 0.0, 0.0]) # Singularity fallback + else: + i_C = i_C_raw / norm_i + + j_C = np.cross(k_C, i_C) + return i_C, j_C, k_C, alpha2, is_unreachable + + def _compute_screw_axes(self, T_gripper: np.ndarray, q7: float) -> Tuple[np.ndarray, np.ndarray, bool]: + """ + Source: [GeoFIK Paper] Sec 3, [Official C++ Repo] franka_ik_q7_one_sol + Computes 7 screw directions (S) and points on axes (P). + """ + i_6, s6, r6 = self.isolate_wrist_center(T_gripper, q7) + i_C, j_C, k_C, alpha2, is_unreachable = self._compute_cone_frame(s6, r6) + + ry = np.dot(s6, j_C) + rz = np.dot(s6, k_C) + sa2 = np.sin(alpha2) + ca2 = np.cos(alpha2) + + tmp_cone = -rz * ca2 / (ry * sa2 + EPSILON) + if tmp_cone > 1.0 or tmp_cone < -1.0: + is_unreachable = True + tmp_cone = np.clip(tmp_cone, -1.0, 1.0) + + gamma = np.arcsin(tmp_cone) + v = np.array([-sa2 * np.cos(gamma), -sa2 * np.sin(gamma), -ca2]) + + # Branch for elbow up/down + if self.branch.s2 > 0: + v = np.array([sa2 * np.cos(gamma), -sa2 * np.sin(gamma), -ca2]) + + s5 = v[0] * i_C + v[1] * j_C + v[2] * k_C + + s4_raw = np.cross(s5, r6) + norm_s4 = np.linalg.norm(s4_raw) + if norm_s4 < EPSILON: + s4 = np.array([0.0, 1.0, 0.0]) # Singularity fallback + else: + s4 = s4_raw / norm_s4 + + u4 = np.cross(s5, s4) + r4 = r6 - self.geometry.d5 * s5 + self.geometry.a5 * u4 + + R_beta1 = rot_axis_angle(s4, self.geometry.beta1) + s3_raw = R_beta1 @ u4 + norm_s3 = np.linalg.norm(s3_raw) + s3 = s3_raw / (norm_s3 + EPSILON) + + tmp_s2 = s3[1]**2 + s3[0]**2 + if tmp_s2 > SINGULARITY_EPSILON**2: + s2 = np.array([-s3[1]/np.sqrt(tmp_s2), s3[0]/np.sqrt(tmp_s2), 0.0]) + else: + q1_sing = np.pi / 2 + s2 = np.array([np.sin(q1_sing), np.cos(q1_sing), 0.0]) + + # If shoulder branch is negative + if self.branch.s1 < 0: + s2 = -s2 + + s1 = np.array([0.0, 0.0, 1.0]) + s7 = T_gripper[0:3, 2] + + S = np.column_stack([s1, s2, s3, s4, s5, s6, s7]) + + r_S = np.array([0.0, 0.0, self.geometry.d1]) + P = np.column_stack([ + r_S, r_S, r_S, + r4 + r_S, + r6 + r_S, + r6 + r_S, + T_gripper[0:3, 3] - T_gripper[0:3, 0:3] @ np.array([0, 0, self.geometry.d_tcp]) + ]) + + return S, P, is_unreachable + + def isolate_wrist_center(self, T_gripper: np.ndarray, q7: float) -> Tuple[np.ndarray, np.ndarray, np.ndarray]: + return self._isolate_wrist_center(T_gripper, q7) + + def _q_from_axes(self, S: np.ndarray, q7: float) -> np.ndarray: + """ + Source: [GeoFIK Paper] Sec 2, [Official C++ Repo] q_from_J + Extracts joint angles via geometric comparison with home axes. + """ + q = np.zeros(7) + q[6] = q7 + J_old = self.J0_S.copy() + + for i in range(6): + s = S[:, i] + v1 = J_old[:, i+1] + v2 = S[:, i+1] + + w = np.cross(v1, v2) + angle = np.arctan2(np.dot(w, s), np.dot(v1, v2)) + q[i] = angle + + if i == 5: + break + + R = rot_axis_angle(s, angle) + for j in range(i+1, 7): + J_old[:, j] = R @ J_old[:, j] + + return q + + def compute_pose_jacobian(self, S: np.ndarray, P: np.ndarray, p_E: np.ndarray) -> np.ndarray: + """ + Source: [Standard Robotics] Spatial Twist Jacobian. + J = [S1 ... S7] where Si = [s_i; (r_i - p_E) x s_i] + Returns geometric jacobian mapped to end-effector frame origin. + """ + J = np.zeros((6, 7)) + for i in range(7): + s = S[:, i] + r = P[:, i] + v = np.cross(r - p_E, s) + J[0:3, i] = s + J[3:6, i] = v + return J + + def check_limits(self, q: np.ndarray) -> bool: + if np.any(np.isnan(q)): + return False + return np.all(q >= self.geometry.q_low) and np.all(q <= self.geometry.q_up) + + def solve(self, T_gripper: np.ndarray, q7: float) -> IKResult: + """ + Top-level caller orchestrated by [Engineering]. + """ + S, P, is_unreachable = self._compute_screw_axes(T_gripper, q7) + + if is_unreachable: + return IKResult(np.zeros(7), False, ReachabilityStatus.UNREACHABLE.value, np.zeros((6,7))) + + q = self._q_from_axes(S, q7) + success = self.check_limits(q) + + p_E = T_gripper[0:3, 3] + J_pose = self.compute_pose_jacobian(S, P, p_E) + + status = ReachabilityStatus.SUCCESS.value if success else ReachabilityStatus.LIMIT_VIOLATION.value + return IKResult(q, success, status, J_pose) diff --git a/llm_panda/grasp_optimizer.py b/llm_panda/grasp_optimizer.py new file mode 100644 index 0000000000000000000000000000000000000000..8f35f00e9cf570330122b847b05dfa2a1288ca1b --- /dev/null +++ b/llm_panda/grasp_optimizer.py @@ -0,0 +1,112 @@ +import numpy as np +from scipy.optimize import minimize +import logging +from typing import Tuple, Dict, Any, List, Optional +from dataclasses import dataclass + +from .geofik import FrankaGeoFIK, IKResult +from .swivel_adapter import SwivelAdapter +from .task_nullspace import TaskManifold +from .evaluators import CachingContext, ObjectiveEvaluator, ConstraintEvaluator + +logger = logging.getLogger(__name__) + +@dataclass +class GraspOptimizationResult: + success: bool + q: Optional[np.ndarray] + message: str + iterations: int + final_cost: float + + +class GraspOptimizer: + """ + Phase 4: Optimization Engine. + Uses SciPy SLSQP to find optimal redundant parameters (u, theta) + subject to reachability and collision constraints. + """ + def __init__(self, fik: FrankaGeoFIK, swivel: SwivelAdapter): + self.fik = fik + self.swivel = swivel + + def optimize(self, task: TaskManifold, q_nominal: np.ndarray, maxiter: int = 100) -> GraspOptimizationResult: + """ + Solves the Task Nullspace Optimization problem. + x = [u..., theta] + """ + ctx = CachingContext(self.fik, self.swivel, task) + obj_eval = ObjectiveEvaluator(ctx, q_nominal) + con_eval = ConstraintEvaluator(ctx, self.fik.geometry.q_low, self.fik.geometry.q_up) + + def objective(x): + cost, grad = obj_eval.evaluate_displacement(x) + return cost + + def jacobian(x): + cost, grad = obj_eval.evaluate_displacement(x) + return grad + + def constraint_func(x): + c, grad = con_eval.evaluate_limits(x) + return c + + def constraint_jac(x): + c, grad = con_eval.evaluate_limits(x) + return grad + + constraints = [{'type': 'ineq', 'fun': constraint_func, 'jac': constraint_jac}] + + # Initial guess + u_guess = task.get_initial_guess() + theta_guess = 0.0 # Default swivel + x0 = np.append(u_guess, theta_guess) + + # Bounds for u and theta + u_bounds = task.get_bounds() + bounds = u_bounds + [(-np.pi, np.pi)] # theta bounds + + # Ensure initial guess is inside bounds + x0_clamped = np.zeros_like(x0) + for i, (b_min, b_max) in enumerate(bounds): + x0_clamped[i] = np.clip(x0[i], b_min, b_max) + + options = {'maxiter': maxiter, 'ftol': 1e-4, 'disp': False} + + res = minimize( + fun=objective, + x0=x0_clamped, + method='SLSQP', + jac=jacobian, + bounds=bounds, + constraints=constraints, + options=options + ) + + if res.success: + # Re-evaluate to get final q + ctx.update(res.x) + if ctx.last_success: + return GraspOptimizationResult( + success=True, + q=ctx.last_q, + message=res.message, + iterations=res.nit, + final_cost=res.fun + ) + else: + return GraspOptimizationResult( + success=False, + q=None, + message="SLSQP reported success, but kinematics failed at solution.", + iterations=res.nit, + final_cost=res.fun + ) + else: + return GraspOptimizationResult( + success=False, + q=None, + message=res.message, + iterations=res.nit, + final_cost=res.fun + ) diff --git a/llm_panda/grasp_planner.py b/llm_panda/grasp_planner.py new file mode 100644 index 0000000000000000000000000000000000000000..604453e778db1bdc0d97e61ad6c6da40226b17d6 --- /dev/null +++ b/llm_panda/grasp_planner.py @@ -0,0 +1,123 @@ +"""Module 2 - Grasp Planner. + +Holds a small database of *local* (object-frame) grasp poses and transforms +them into *world* grasp poses using the standard rigid-body composition +``world = obj_pose ∘ local_pose`` via ``p.multiplyTransforms``. + +Because the composition is a rigid transform, the grasp point's offset from the +object centre is rotation-invariant: spinning the object never changes how the +gripper sits relative to it. ``test_pipeline.py`` asserts exactly this. +""" + +import json +import logging + +import pybullet as pb + +from . import config + +logger = logging.getLogger(__name__) + + +class GraspPlanner: + """Computes world-frame grasp poses from a per-class grasp database.""" + + def __init__(self, database_path=config.GRASP_DB_PATH): + self.database_path = database_path + self._db = self._load_database(database_path) + + @staticmethod + def _load_database(path): + with open(path, "r", encoding="utf-8") as fh: + raw = json.load(fh) + # Drop comment keys (anything starting with "_"). + return {k: v for k, v in raw.items() if not k.startswith("_")} + + # ------------------------------------------------------------------ # + # Pure transform math (unit-testable without a populated database) + # ------------------------------------------------------------------ # + @staticmethod + def local_to_world(world_pos, world_ori, local_pos, local_euler): + """Compose an object world pose with a local grasp pose. + + Returns ``(grasp_pos, grasp_ori_quaternion)`` in the world frame. + """ + local_ori = pb.getQuaternionFromEuler(local_euler) + grasp_pos, grasp_ori = pb.multiplyTransforms( + world_pos, world_ori, local_pos, local_ori + ) + return list(grasp_pos), list(grasp_ori) + + # ------------------------------------------------------------------ # + # Database-driven grasp computation + # ------------------------------------------------------------------ # + def has_class(self, object_class): + return object_class in self._db + + def get_local_grasp(self, object_class): + """Local grasp entry for a class, falling back to ``default``.""" + return self._db.get(object_class, self._db["default"]) + + def _aabb_fallback_grasp(self, object_id): + """Fallback: top-down grasp at AABB top-centre.""" + aabb_min, aabb_max = pb.getAABB(object_id) + cx = 0.5 * (aabb_min[0] + aabb_max[0]) + cy = 0.5 * (aabb_min[1] + aabb_max[1]) + grasp_pos = [cx, cy, aabb_max[2]] + grasp_ori = list(pb.getQuaternionFromEuler(config.TOP_DOWN_EULER)) + return grasp_pos, grasp_ori + + def compute_side_grasp_pose(self, object_id, clear_dir, tilt=None): + """Tilted "side" grasp for an object whose top-down approach is blocked. + + The gripper comes in diagonally from ``clear_dir`` (a unit XY vector + pointing away from the blocker, i.e. the object's open side), tilted + :data:`config.SIDE_GRASP_TILT` from vertical, and grips near the object's + mid-height so the fingers straddle its body rather than its top. + + Returns ``(grasp_pos, grasp_ori)`` in the world frame. + """ + tilt = config.SIDE_GRASP_TILT if tilt is None else tilt + aabb_min, aabb_max = pb.getAABB(object_id) + cx = 0.5 * (aabb_min[0] + aabb_max[0]) + cy = 0.5 * (aabb_min[1] + aabb_max[1]) + cz = max(config.TABLE_TOP_Z + 0.05, 0.5 * (aabb_min[2] + aabb_max[2])) + grasp_pos = [cx, cy, cz] + + # Approach from the open side: the gripper sits on `clear_dir` and reaches + # inward, so its world reach axis ends up pointing toward -clear_dir (into + # the object, away from the blocker). Tilting the top-down orientation by + # `tilt` about the axis k below produces exactly that diagonal reach. + cx_d, cy_d = clear_dir + norm = (cx_d * cx_d + cy_d * cy_d) ** 0.5 or 1.0 + cx_d, cy_d = cx_d / norm, cy_d / norm + k = [-cy_d, cx_d, 0.0] + q_top = pb.getQuaternionFromEuler(config.TOP_DOWN_EULER) + q_tilt = pb.getQuaternionFromAxisAngle(k, tilt) + _, grasp_ori = pb.multiplyTransforms([0, 0, 0], q_tilt, [0, 0, 0], q_top) + return grasp_pos, list(grasp_ori) + + def compute_grasp_pose(self, object_id, object_class): + """World-frame grasp pose for a body. + + If the object class is registered in the grasp database, computes + the grasp pose dynamically in the object's local frame and converts + it to the world frame. Otherwise, falls back to top-down AABB top-centre. + """ + if not self.has_class(object_class): + logger.warning(f"Class '{object_class}' not found in grasp database. Using AABB fallback.") + return self._aabb_fallback_grasp(object_id) + + # Get object world pose + world_pos, world_ori = pb.getBasePositionAndOrientation(object_id) + + # Retrieve local grasp pose from database + db_entry = self.get_local_grasp(object_class) + local_pos = [p * config.OBJECT_GLOBAL_SCALING for p in db_entry["local_position"]] + local_euler = db_entry["local_euler"] + + # Transform local grasp pose to world frame + grasp_pos, grasp_ori = self.local_to_world(world_pos, world_ori, local_pos, local_euler) + + logger.debug(f"db grasp class={object_class} local_pos={local_pos} world_pos={[round(c,3) for c in grasp_pos]}") + return grasp_pos, grasp_ori diff --git a/llm_panda/gripper_controller.py b/llm_panda/gripper_controller.py new file mode 100644 index 0000000000000000000000000000000000000000..dcc339af0ae9f8cd07db6af9da758e210dec430a --- /dev/null +++ b/llm_panda/gripper_controller.py @@ -0,0 +1,141 @@ +"""Module 4 - Gripper & Physics Controller. + +Owns the two parallel fingers and the physics-based grip-force model. The force +model reads real dynamics (mass, lateral friction) from the simulator and sizes +the clamp force from the minimum-friction-grasp condition, then clips it into +the Panda's hardware envelope [10 N, 140 N]. +""" + +import logging + +import pybullet as pb + +from . import config + +logger = logging.getLogger(__name__) + + +class GripperController: + """Drives the Panda fingers and computes a safe grasp force.""" + + def __init__(self, robot_id, + finger_indices=None, + force_min=config.GRIP_FORCE_MIN, + force_max=config.GRIP_FORCE_MAX, + gravity=abs(config.GRAVITY)): + self.robot_id = robot_id + self.finger_indices = finger_indices or config.FINGER_JOINT_INDICES + self.force_min = force_min + self.force_max = force_max + self.gravity = gravity + self._constraint_id = None + self._constrained_id = None + + # ------------------------------------------------------------------ # + # Grasp-force model + # ------------------------------------------------------------------ # + @staticmethod + def friction_grasp_force(mass, mu, gravity, accel=0.0, + safety_factor=2.0, n_contacts=2, + force_min=config.GRIP_FORCE_MIN, + force_max=config.GRIP_FORCE_MAX): + """Minimum-friction grasp force, clamped to the hardware envelope. + + F_g = [m * (g + a) * Sf] / [n_contacts * mu] + + Robust to degenerate inputs: non-positive mass yields the floor force, + and a (near-)frictionless contact is floored to avoid division blow-up + (it simply saturates to ``force_max`` after clamping). + """ + # Guard the divisor: a tiny positive floor keeps the math finite. + mu_eff = max(float(mu), 1e-3) + mass_eff = max(float(mass), 0.0) + + raw = (mass_eff * (gravity + accel) * safety_factor) / (n_contacts * mu_eff) + + # Clamp into [force_min, force_max]; never negative by construction. + return float(min(max(raw, force_min), force_max)) + + def calculate_optimal_force(self, object_id, accel=0.0, safety_factor=2.0): + """Read mass + lateral friction from the sim and size the grip force.""" + dyn = pb.getDynamicsInfo(object_id, -1) + mass = dyn[0] # kg + lateral_friction = dyn[1] + return self.friction_grasp_force( + mass, lateral_friction, self.gravity, + accel=accel, safety_factor=safety_factor, + force_min=self.force_min, force_max=self.force_max, + ) + + # ------------------------------------------------------------------ # + # Low-level finger actuation + # ------------------------------------------------------------------ # + def _drive_fingers(self, target, force): + for j in self.finger_indices: + pb.setJointMotorControl2( + self.robot_id, j, pb.POSITION_CONTROL, + targetPosition=target, force=force, + ) + + def open(self, force=30.0): + """Release any active grasp constraint, then open both fingers.""" + if self._constraint_id is not None: + try: + pb.removeConstraint(self._constraint_id) + except Exception: + pass + self._constraint_id = None + self._constrained_id = None + self._drive_fingers(config.FINGER_OPEN, force) + + def close(self, force): + """Close both fingers, driving toward closed with the given clamp force.""" + self._drive_fingers(config.FINGER_CLOSED, force) + + def grasp(self, object_id, accel=0.0): + """Close fingers and attach object via a rigid constraint. + + Constraint-based grasping: the object is fixed to panda_hand in its + current relative pose. This is robust to any object size/shape — the + gripper visual closes but the hold is via the constraint, not friction. + The returned force value is still physically-sized for logging. + """ + force = self.calculate_optimal_force(object_id, accel=accel) + self.close(force) + + # Compute object position in the hand's local frame + hand_state = pb.getLinkState(self.robot_id, config.HAND_LINK_INDEX) + hand_pos, hand_ori = hand_state[0], hand_state[1] + obj_pos, obj_ori = pb.getBasePositionAndOrientation(object_id) + inv_pos, inv_ori = pb.invertTransform(hand_pos, hand_ori) + rel_pos, rel_ori = pb.multiplyTransforms(inv_pos, inv_ori, obj_pos, obj_ori) + + self._constraint_id = pb.createConstraint( + parentBodyUniqueId=self.robot_id, + parentLinkIndex=config.HAND_LINK_INDEX, + childBodyUniqueId=object_id, + childLinkIndex=-1, + jointType=pb.JOINT_FIXED, + jointAxis=[0, 0, 0], + parentFramePosition=list(rel_pos), + childFramePosition=[0, 0, 0], + parentFrameOrientation=list(rel_ori), + childFrameOrientation=[0, 0, 0, 1], + ) + pb.changeConstraint(self._constraint_id, maxForce=500) + self._constrained_id = object_id + logger.debug(f"grasp object_id={object_id} force={force:.2f} N constraint={self._constraint_id}") + return force + + # ------------------------------------------------------------------ # + # State helpers + # ------------------------------------------------------------------ # + def finger_span(self): + """Current total opening (sum of both finger positions, metres).""" + return sum(pb.getJointState(self.robot_id, j)[0] for j in self.finger_indices) + + def is_holding(self, object_id, min_contacts=2): + """True if the rigid grasp constraint for object_id is active.""" + holding = (self._constraint_id is not None and self._constrained_id == object_id) + logger.debug(f"is_holding object_id={object_id} constraint={self._constraint_id} holding={holding}") + return holding diff --git a/llm_panda/llm_agent.py b/llm_panda/llm_agent.py new file mode 100644 index 0000000000000000000000000000000000000000..05040e52468f410eec5c6b5284183feea7b33289 --- /dev/null +++ b/llm_panda/llm_agent.py @@ -0,0 +1,610 @@ +"""LLM Agent - natural language -> function-call plan. + +The agent is the "Manager": it receives the text scene state from the Scene +Manager plus a natural-language instruction and emits a plan as a list of +function calls drawn from a tiny, well-defined API: + + pick_up(object_id) + place_at(location_id) + +Two planners are provided behind one interface: + +* ``RuleBasedPlanner`` - deterministic, dependency-free, bilingual (EN/VI). + This is the default so the demo runs with zero API keys or network. +* ``RemoteLLMPlanner`` - calls a real text-only LLM over an OpenAI-compatible + endpoint (e.g. DeepSeek, or Gemini via a compatible gateway). Used only when + explicitly requested; it returns the same JSON plan schema. +""" + +import json +import logging +import os +import re + +logger = logging.getLogger(__name__) + +# Available actions the planner may emit. +ACTIONS = ("pick_up", "move_to", "place_down") + +# Lightweight EN/VI synonym map: canonical token -> trigger words. +# Longer (multi-word) aliases score higher than single-word ones, so +# "hộp soup" (2 words, specific) beats bare "hộp" (1 word, generic). +_SYNONYMS = { + # legacy primitives + "cube": ["cube", "block", "khoi", "khối"], + "cylinder": ["cylinder", "tru", "trụ", "ong", "ống"], + # YCB objects + "banana": ["banana", "chuoi", "chuối", "qua chuoi", "quả chuối"], + "soup": ["soup", "xup", "súp", "canh", + "lon soup", "hộp soup", "hop soup"], # multi-word boosts score + "can": ["can", "lon", "hop lon", "hộp lon", + "lon soup", "hộp soup", "hop soup"], + "chips": ["chips", "khoai", "bap", "bắp", "bim bim", + "lon chips", "hộp chips", "hop chips", "banh chips", "bánh chips"], + "ball": ["ball", "bong", "bóng", "qua bong", "quả bóng", "tennis", "bong tennis", "bóng tennis"], + "pear": ["pear", "le", "lê", "qua le", "quả lê", "trai le", "trái lê"], + "clamp": ["clamp", "kep", "kẹp", "cai kep", "cái kẹp", "cai kim", "cái kìm", "kim"], + # colours (kept for description matching) + "red": ["red", "do", "đỏ"], + "blue": ["blue", "xanh", "lam"], + "green": ["green", "luc", "lục"], + "yellow": ["yellow", "vang", "vàng"], +} + +# Verbs that imply a pick action. +_PICK_VERBS = ["pick", "grasp", "grab", "lift", "take", "gap", "gắp", "nhac", "nhấc", "cam", "cầm"] + +# Keywords that signal "retry the last command". +_RETRY_KEYWORDS = ["lại", "làm lại", "thử lại", "again", "retry", "redo"] + + +def _normalize(text): + return text.lower().strip() + + +def _expand_aliases(token): + """All trigger words that map to a canonical object token.""" + return _SYNONYMS.get(token, [token]) + + +def _best_alias_score(cmd: str, aliases: list) -> float: + """Return the word-count of the longest alias that appears in *cmd*. + + A 2-word alias ("hộp soup") scores 2, a 1-word alias ("soup") scores 1, + no match scores 0. This makes specific multi-word phrases dominate over + generic single words. + """ + best = 0 + for alias in aliases: + if alias in cmd: + best = max(best, len(alias.split())) + return float(best) + + +class RuleBasedPlanner: + """Deterministic planner that resolves the command against the scene state.""" + + def __init__(self): + self._last_plan = [] + + def plan(self, user_command, scene_state): + """Return a list of ``{"function", "args"}`` calls. + + ``scene_state`` may be the JSON string from ``SceneManager`` or the + already-parsed dict. + """ + if isinstance(scene_state, str): + scene_state = json.loads(scene_state) + objects = scene_state.get("objects", []) + carried_object = scene_state.get("carried_object") + cmd = _normalize(user_command) + + target_name = self._resolve_target_name(cmd, objects) + location = self._match_location(cmd, objects, target_name) + + plan = [] + + # Check if it is a general "clear table" instruction + is_clear_table = any(w in cmd for w in ["dọn bàn", "dọn dẹp", "dọn dẹp bàn", "clear table", "clear the table", "tidy up the table"]) + + if is_clear_table and target_name is None: + # If holding an object, place it in the tray first + if carried_object: + plan.append({"function": "move_to", "args": {"location_id": "tray"}}) + plan.append({"function": "place_down", "args": {}}) + # Move all objects currently on the table to the tray + table_objects = [o["name"] for o in objects if o["location"] == "table"] + for obj in table_objects: + if obj != carried_object: + plan.append({"function": "pick_up", "args": {"object_id": obj}}) + plan.append({"function": "move_to", "args": {"location_id": "tray"}}) + plan.append({"function": "place_down", "args": {}}) + + # Scenario 1: Robot is already holding an object, and user says where to place it + elif carried_object and location is not None and target_name is None: + plan.append({"function": "move_to", "args": location}) + plan.append({"function": "place_down", "args": {}}) + + # Scenario 2: Standard command + elif target_name is not None: + # If we are already holding something else, place it on the table first. + if carried_object and carried_object != target_name: + plan.append({"function": "move_to", "args": {"location_id": "table"}}) + plan.append({"function": "place_down", "args": {}}) + + # Now pick up target_name if it is not already carried + if carried_object == target_name: + if location is not None: + plan.append({"function": "move_to", "args": location}) + plan.append({"function": "place_down", "args": {}}) + else: + # Obstacle clearing is no longer woven in here: it is applied + # uniformly to every planner's output by + # ``LLMAgent._inject_obstacle_clearing`` using the scene's + # geometric ``blocking_objects`` signal. + plan.append({"function": "pick_up", "args": {"object_id": target_name}}) + if location is not None: + plan.append({"function": "move_to", "args": location}) + plan.append({"function": "place_down", "args": {}}) + + if not plan: + # No target found — check if it's a retry command. + if any(kw in cmd for kw in _RETRY_KEYWORDS) and self._last_plan: + logger.debug(f"retry detected → reusing last plan: {self._last_plan}") + return list(self._last_plan) + + logger.debug(f"rule-based plan: target={target_name} location={location} -> {plan}") + if plan: + self._last_plan = list(plan) + return plan + + # ------------------------------------------------------------------ # + @staticmethod + def _match_object(cmd, objects): + """Pick the object whose name tokens best match the command. + + Scoring: + - Each name token contributes the *word count* of its best-matching + alias (longer alias = more specific = higher score). + - The class token adds half the word count of its best match + (tiebreaker only; name tokens take priority). + """ + best_name, best_score = None, 0.0 + for obj in objects: + score = 0.0 + for token in obj["name"].split("_"): + score += _best_alias_score(cmd, _expand_aliases(token)) + # Class is a tiebreaker: half weight so name tokens dominate. + score += 0.5 * _best_alias_score(cmd, _expand_aliases(obj["class"])) + if score > best_score: + best_name, best_score = obj["name"], score + return best_name + + # Relation cue -> canonical relation token. Bare ambiguous Vietnamese words + # are deliberately excluded: "trái" is also the classifier in "trái chuối" + # (a banana), "phải" also means "must", "sau"/"trước" also mean "then/first". + # We therefore require a disambiguating phrase ("bên trái", "phía sau", ...). + _RELATION_WORDS = [ + ("left_of", ["bên trái", "phía trái", "left of", "left"]), + ("right_of", ["bên phải", "phía phải", "right of", "right"]), + ("front_of", ["phía trước", "đằng trước", "in front of", "front of"]), + ("behind", ["phía sau", "đằng sau", "behind", "back of"]), + ("next_to", ["bên cạnh", "kế bên", "cạnh", "next to", "beside", "near"]), + ] + + @classmethod + def _find_relation(cls, cmd): + """Locate the earliest spatial-relation cue in *cmd*. + + Returns ``(relation, start, end)`` for the matched cue's span, or + ``(None, -1, -1)``. The earliest cue wins so it splits the *target* + clause (before it) from the *reference* clause (after it); among cues + starting at the same place the longest phrase is used. + """ + best = None # (start, -length, relation, end) + for rel, words in cls._RELATION_WORDS: + for w in words: + idx = cmd.find(w) + if idx == -1: + continue + key = (idx, -len(w)) + if best is None or key < best[0]: + best = (key, rel, idx + len(w)) + if best is None: + return None, -1, -1 + (start, _neg_len), rel, end = best + return rel, start, end + + @classmethod + def _split_relation(cls, cmd, objects, target_name=None): + """Resolve a *validated* relation in *cmd*. + + A relation only counts when its cue is followed by a real object (the + reference). Returns ``(relation, reference_name, target_clause)`` where + ``target_clause`` is the substring before the cue (where the target is + named), or ``(None, None, cmd)`` when there is no valid relation. This + is what prevents a stray cue inside an object alias (e.g. "trái" in + "trái chuối") from hijacking a plain pick command. + """ + relation, start, end = cls._find_relation(cmd) + if relation is None: + return None, None, cmd + others = [o for o in objects if o["name"] != target_name] + reference = cls._match_object(cmd[end:], others) + if reference is None: + return None, None, cmd + return relation, reference, cmd[:start] + + @classmethod + def _resolve_target_name(cls, cmd, objects): + """Pick the object to act on, honouring relation structure. + + With a valid relation the target is named in the clause *before* the + cue; the reference (after the cue) must not be mistaken for it. Without + a relation we fall back to the best match over the whole command. + """ + relation, reference, target_clause = cls._split_relation(cmd, objects) + if relation is None: + return cls._match_object(cmd, objects) + # Prefer the pre-cue clause; if it names nothing, search the rest but + # never return the reference object itself. + target = cls._match_object(target_clause, objects) + if target is None: + target = cls._match_object(cmd, [o for o in objects if o["name"] != reference]) + return target + + @classmethod + def _match_location(cls, cmd, objects, target_name): + """Resolve a destination as an executor ``args`` dict, or ``None``. + + Returns ``{"location_id": "tray"}`` or ``{"location_id": "table", ...}`` + where the table form may also carry ``relation`` + ``relative_to``. + """ + if "tray" in cmd or "khay" in cmd: + return {"location_id": "tray"} + + relation, reference, _ = cls._split_relation(cmd, objects, target_name) + if relation is not None: + return {"location_id": "table", "relation": relation, "relative_to": reference} + + if "bàn" in cmd or "table" in cmd or "ban" in cmd: + return {"location_id": "table"} + return None + + +class RemoteLLMPlanner: + """Calls a real text-only LLM (OpenAI / OpenAI-compatible API) for the plan. + + Configuration (first non-empty wins), read from the environment - a local + ``.env`` is auto-loaded if ``python-dotenv`` is installed: + + * key : ``OPENAI_API_KEY`` -> ``LLM_API_KEY`` + * model : ``OPENAI_MODEL`` -> ``OPENAI_MODE`` -> ``LLM_MODEL`` -> ``gpt-4o`` + * base : ``OPENAI_BASE_URL`` -> ``LLM_BASE_URL`` -> official OpenAI endpoint + + Set ``LLM_BASE_URL`` (e.g. ``https://api.deepseek.com``) to target any other + OpenAI-compatible provider with the same code. + """ + + SYSTEM_PROMPT = ( + """You are the semantic planner for a Franka Emika Panda robot arm (PyBullet). +Input: the scene state as JSON + a natural-language instruction. +Output: ONLY a JSON array of sequential function calls, using this schema: +[{"function":"pick_up","args":{"object_id":""}},{"function":"move_to","args":{"location_id":"","relation":"","relative_to":""}},{"function":"place_down","args":{}}] + +## DESTINATIONS +Only two destinations exist: "table" and "tray". You do NOT compute coordinates and do NOT track free space — the executor's optimiser automatically picks a free, collision-free, reachable spot. You only choose the surface (and optionally a relation). NEVER invent any other location_id. + +## SPATIAL RELATIONS +To place an object relative to ANOTHER object, set on move_to: location_id="table", relation=one of next_to|left_of|right_of|front_of|behind, relative_to=. Word mapping: cạnh/bên cạnh/kế/next to->next_to, bên trái/trái/left->left_of, bên phải/phải/right->right_of, phía trước/trước/in front of->front_of, phía sau/sau/behind->behind. If no reference object is mentioned, omit relation and relative_to. + +## STATE & PHYSICS RULES +1. One gripper: it can hold at most ONE object at a time. +2. If carried_object is null you MUST pick_up before any move_to/place_down. EXCEPTION: if the instruction only asks to place/drop/move (đặt/thả/bỏ/place/drop/put down) and names no object to pick up, output [] (nothing is held). +3. If the instruction only asks to pick up/lift/grab (gắp/nhặt/nhấc/cầm/pick up/grab/take/lift) and gives no destination, output ONLY the pick_up action. +4. If carried_object is not null the robot already holds that object: do NOT pick_up it; to place it output move_to then place_down; you cannot pick_up another object until you place_down the current one. +5. NEVER output consecutive pick_up actions without an intervening place_down. +6. If the instruction is a general command to clear or tidy the table (e.g. "dọn bàn", "dọn dẹp", "dọn dẹp bàn", "clear table", "clear the table", "tidy up the table") and names no specific target object, plan to move ALL objects currently on the table to the tray. Output a sequence of pick_up, move_to(tray), and place_down for each table object. If carried_object is not null, place the carried object in the tray first, then pick up and move the other table objects. + +## REACHABILITY +Do not pick_up any object that has "reachable": false in the scene state. + +## OBSTACLE CLEARING (MANDATORY) +Each table object has a "blocking_objects" field: names of objects that physically obstruct the arm's grasp path (computed from geometry — TRUST IT, do not second-guess it with "the arm can come from above"). Before EVERY pick_up of a target whose blocking_objects is non-empty, you MUST first clear each listed blocker, in order: (a) pick_up the blocker, (b) move_to "table", (c) place_down. Only after all blockers are cleared do you pick_up the target. ("neighbor_count" is informational only; "blocking_objects" is authoritative.) +EXCEPTION FOR MUTUAL BLOCKING CYCLES/DEADLOCKS: If objects block each other forming a cycle or deadlock (e.g., A blocks B and B blocks A, or a larger loop of mutual blockages), do NOT clear the blockers. You can pick up the target directly, and the system's control layer will automatically handle it using a tilted side grasp. + +## SYNONYMS (VIETNAMESE/ENGLISH) +Objects: chuối/trái chuối/banana->banana, súp/canh/hộp súp/lon súp/soup->soup_can, snack/bim bim/khoai tây/hộp bim bim/lon chips/chips->chips_can, bóng/quả bóng/bóng tennis/ball->tennis_ball, lê/quả lê/pear->pear, kẹp/cái kẹp/kìm/clamp->clamp. Locations: khay/khay chứa->tray, bàn/lên bàn/table->table. Verbs: gắp/nhặt/nhấc/cầm/di chuyển->pick_up, đặt/để/thả/bỏ->place_down. + +## EXAMPLES (compact, one line each) +"gắp quả chuối lên" (no destination): [{"function":"pick_up","args":{"object_id":"banana"}}] +"di chuyển lon súp vào khay": [{"function":"pick_up","args":{"object_id":"soup_can"}},{"function":"move_to","args":{"location_id":"tray"}},{"function":"place_down","args":{}}] +carried_object="banana", "để vào khay": [{"function":"move_to","args":{"location_id":"tray"}},{"function":"place_down","args":{}}] +"gắp lon súp đặt lên bàn": [{"function":"pick_up","args":{"object_id":"soup_can"}},{"function":"move_to","args":{"location_id":"table"}},{"function":"place_down","args":{}}] +"đặt lon chips bên cạnh quả chuối": [{"function":"pick_up","args":{"object_id":"chips_can"}},{"function":"move_to","args":{"location_id":"table","relation":"next_to","relative_to":"banana"}},{"function":"place_down","args":{}}] +carried_object="banana", "đặt nó bên trái lon súp": [{"function":"move_to","args":{"location_id":"table","relation":"left_of","relative_to":"soup_can"}},{"function":"place_down","args":{}}] +"gắp chuối bỏ vào khay" with banana blocking_objects=["chips_can"]: [{"function":"pick_up","args":{"object_id":"chips_can"}},{"function":"move_to","args":{"location_id":"table"}},{"function":"place_down","args":{}},{"function":"pick_up","args":{"object_id":"banana"}},{"function":"move_to","args":{"location_id":"tray"}},{"function":"place_down","args":{}}] + +Respond ONLY with the JSON array. No markdown, no code fences, no explanatory text.""" + ) + + + def __init__(self, model=None, api_key=None, base_url=None): + # Best-effort: load a local .env so keys/models are picked up automatically. + try: + from dotenv import load_dotenv + load_dotenv() + except Exception: # pragma: no cover - dotenv optional + pass + + self.api_key = ( + api_key or os.environ.get("OPENAI_API_KEY") or os.environ.get("LLM_API_KEY") + ) + self.model = ( + model or os.environ.get("OPENAI_MODEL") or os.environ.get("OPENAI_MODE") + or os.environ.get("LLM_MODEL") or "gpt-4o" + ) + # None -> the openai client uses the official OpenAI endpoint. + self.base_url = base_url or os.environ.get("OPENAI_BASE_URL") or os.environ.get("LLM_BASE_URL") + self._client = None + + def plan(self, user_command, scene_state): + if isinstance(scene_state, dict): + scene_state = json.dumps(scene_state) + if not self.api_key: + raise RuntimeError("RemoteLLMPlanner needs OPENAI_API_KEY (or LLM_API_KEY).") + try: + from openai import OpenAI # imported lazily; optional dependency + except ImportError as exc: # pragma: no cover - environment dependent + raise RuntimeError("RemoteLLMPlanner needs the 'openai' package (pip install openai).") from exc + + if self._client is None: + kwargs = {"api_key": self.api_key} + if self.base_url: + kwargs["base_url"] = self.base_url + self._client = OpenAI(**kwargs) + client = self._client + + # Build completion arguments + create_kwargs = { + "model": self.model, + "messages": [ + {"role": "system", "content": self.SYSTEM_PROMPT}, + {"role": "user", "content": f"SCENE:\n{scene_state}\n\nINSTRUCTION:\n{user_command}"}, + ], + "temperature": 0.0, + } + + # Check if targeting NVIDIA integrate endpoint and using a DeepSeek model + if self.base_url and "integrate.api.nvidia.com" in self.base_url and "deepseek" in self.model: + create_kwargs["extra_body"] = {"chat_template_kwargs": {"thinking": True, "reasoning_effort": "high"}} + create_kwargs["temperature"] = 1.0 + create_kwargs["top_p"] = 0.95 + + # Call completions API with exponential backoff on 429 RateLimitErrors + import time + max_retries = 5 + backoff = 2.0 + for attempt in range(max_retries): + try: + resp = client.chat.completions.create(**create_kwargs) + break + except Exception as e: + is_rate_limit = False + if hasattr(e, "status_code") and e.status_code == 429: + is_rate_limit = True + elif "429" in str(e) or "RateLimit" in type(e).__name__: + is_rate_limit = True + + if is_rate_limit and attempt < max_retries - 1: + logger.warning( + f"[WARN ] Rate limit hit (429) on NVIDIA Integrate. " + f"Retrying in {backoff:.1f}s (Attempt {attempt + 1}/{max_retries})..." + ) + time.sleep(backoff) + backoff *= 2.0 + else: + raise e + + # Extract reasoning content if present + reasoning = getattr(resp.choices[0].message, "reasoning", None) or getattr(resp.choices[0].message, "reasoning_content", None) + if reasoning: + logger.info(f"\n--- [DEEPSEEK REASONING] ---\n{reasoning}\n---------------------------\n") + + raw = resp.choices[0].message.content + logger.debug(f"LLM raw response: {raw}") + return self._parse(raw) + + @staticmethod + def _parse(text): + """Extract the JSON array from a model response. + + Some providers occasionally return an empty body (``content=None``), + e.g. on a transient hiccup or a reasoning-only turn. Treat that as "no + actionable plan" (``[]``) instead of crashing on ``re.search(None)``. + """ + if not text: + return [] + match = re.search(r"\[.*\]", text, re.DOTALL) + if not match: + return [] + return json.loads(match.group(0)) + + +class LLMAgent: + """Wraps a planner and validates its output against the action schema.""" + + def __init__(self, planner=None): + self.planner = planner or RuleBasedPlanner() + + def build_prompt(self, user_command, scene_state_text): + """The exact text a real LLM would be shown (useful for logging).""" + return ( + f"{RemoteLLMPlanner.SYSTEM_PROMPT}\n\n" + f"SCENE STATE:\n{scene_state_text}\n\n" + f"USER INSTRUCTION:\n{user_command}\n" + ) + + def plan(self, user_command, scene_state): + plan = self.planner.plan(user_command, scene_state) + # Enforce obstacle clearing on EVERY planner's output, deterministically + # from scene geometry — so a model that rationalises away clearing (as + # the LLM did when it picked a banana blocked by a tall chips can) still + # produces a collision-free plan. + plan = self._inject_obstacle_clearing(plan, scene_state) + try: + from .plan_verifier import PlanVerifier + warnings = PlanVerifier.check(plan, scene_state) + for w in warnings: + logger.warning(f"[PLAN_WARN] {w}") + except ImportError: + pass # plan_verifier not yet available + return [step for step in plan if self._valid(step)] + + # ------------------------------------------------------------------ # + # Obstacle-dependency graph (blocking_objects → directed graph) + # ------------------------------------------------------------------ # + @staticmethod + def _build_block_graph(objects): + """Directed graph ``name -> [blocker names]`` from ``blocking_objects``. + + An edge ``A -> B`` means "B blocks the grasp approach to A", i.e. B must + be moved out of the way before A can be picked. Only edges between known + objects are kept. + """ + graph = {} + for name, o in objects.items(): + graph[name] = [b for b in o.get("blocking_objects", []) if b in objects] + return graph + + @staticmethod + def _clearing_order(target, graph): + """DFS over the dependency graph rooted at ``target``. + + Returns ``(order, cycle)`` where: + * ``order`` is the post-order list of every transitive blocker of + ``target`` (``target`` itself excluded) — deepest dependency first, so + relocating them in this order always frees each one's own approach + before it is moved ("outermost-in" clearing). + * ``cycle`` is the set of nodes lying on a blocking cycle reachable from + ``target`` (empty ⇒ acyclic ⇒ safe to clear recursively). A non-empty + set signals a geometric deadlock (e.g. banana⇄pear). + """ + order = [] + color = {} # node -> "gray" (on stack) | "black" (done) + path = [] # current DFS stack, for pinpointing the cycle + cycle = set() + + def dfs(node): + color[node] = "gray" + path.append(node) + for blk in graph.get(node, []): + c = color.get(blk) + if c == "gray": # back-edge → cycle + if blk in path: + cycle.update(path[path.index(blk):]) + continue + if c == "black": + continue + dfs(blk) + path.pop() + color[node] = "black" + if node != target: + order.append(node) + + dfs(target) + return order, cycle + + @staticmethod + def _choose_cycle_breaker(target, graph, cycle): + """Pick a cyclic blocker to relocate so the cycle dissolves. + + Relocating one member of a mutual-blocking cycle to a far buffer spot + frees the rest. Prefer a direct blocker of the target (so the target + itself becomes pickable), never the target. Returns a name or ``None``. + """ + for blk in graph.get(target, []): + if blk in cycle and blk != target: + return blk + for n in cycle: + if n != target: + return n + return None + + @staticmethod + def _inject_obstacle_clearing(plan, scene_state): + """Make every ``pick_up`` collision-safe using the dependency graph. + + For each ``pick_up(A)`` taken while the gripper is empty: + + * **Acyclic** blockers → emit ``pick_up(B) → move_to(table) → + place_down`` for each transitive blocker in recursive (deepest-first) + order, then pick A. + * **Cyclic** blockers (deadlock, e.g. banana⇄pear) → relocate one cycle + member to a far ``buffer`` spot. That pick is itself blocked top-down, + so the control layer extracts it with a tilted **side grasp**; once it + is parked clear, the cycle is broken and the target is picked normally. + + Idempotent: blockers the plan already picks itself are left untouched. + """ + if isinstance(scene_state, str): + scene_state = json.loads(scene_state) + objects = {o["name"]: o for o in scene_state.get("objects", [])} + carried = scene_state.get("carried_object") + planned_picks = { + s.get("args", {}).get("object_id") + for s in plan if s.get("function") == "pick_up" + } + graph = LLMAgent._build_block_graph(objects) + + out = [] + held = carried + relocated = set() + for step in plan: + func = step.get("function") + args = step.get("args", {}) + if func == "pick_up" and held is None: + target = args.get("object_id") + order, cycle = LLMAgent._clearing_order(target, graph) + if cycle: + # Deadlock: a mutual-blocking cycle (e.g. banana⇄pear). Every + # member still has an open side (the one facing away from its + # cycle partner), so the control layer extracts the target + # DIRECTLY with a tilted side grasp from that side. We therefore + # do NOT pre-relocate a cycle member to a buffer — that costs a + # whole extra pick-and-place (and ~1300 IK reach-checks per + # deadlock, measured). If the side grasp fails because the target + # is genuinely enclosed on all sides, pick_side returns + # held=False and the closed-loop monitor recovers and re-plans. + logger.warning( + f"[DEADLOCK] blocking cycle {sorted(cycle)} around '{target}' " + f"→ side-grasp '{target}' directly (no buffer relocation)" + ) + out.append(step) + held = target + else: + for blocker in order: + if blocker in relocated or blocker == carried or blocker == target: + continue + if blocker in planned_picks: + continue # the plan handles this blocker on its own + logger.info(f"[CLEAR] '{blocker}' (transitively) blocks '{target}' → relocating to table") + out.append({"function": "pick_up", "args": {"object_id": blocker}}) + out.append({"function": "move_to", "args": {"location_id": "table"}}) + out.append({"function": "place_down", "args": {}}) + relocated.add(blocker) + out.append(step) + held = target + else: + out.append(step) + if func == "place_down": + held = None + return out + + @staticmethod + def _valid(step): + return ( + isinstance(step, dict) + and step.get("function") in ACTIONS + and isinstance(step.get("args"), dict) + ) diff --git a/llm_panda/logger.py b/llm_panda/logger.py new file mode 100644 index 0000000000000000000000000000000000000000..be8f41da6d575d1f2a9075880c82e5ddd8dbdddb --- /dev/null +++ b/llm_panda/logger.py @@ -0,0 +1,42 @@ +"""Centralised logging setup for LLM-Panda. + +Call ``setup()`` once at the start of main() to write every module's log +lines to a timestamped file under ``test_log/`` while also printing INFO+ +to stdout. +""" + +import logging +import os +from datetime import datetime + +_FMT = "%(asctime)s [%(name)-28s] %(levelname)-7s %(message)s" +_DATE = "%H:%M:%S" + + +def setup(log_dir: str = "test_log") -> str: + """Create a timestamped log file and wire up root logger handlers. + + Returns the path to the log file. + """ + os.makedirs(log_dir, exist_ok=True) + ts = datetime.now().strftime("%Y-%m-%d_%H-%M-%S") + log_path = os.path.join(log_dir, f"run_{ts}.log") + + fmt = logging.Formatter(_FMT, datefmt=_DATE) + root = logging.getLogger() + root.setLevel(logging.DEBUG) + + # File: DEBUG and above — full trace of every module. + fh = logging.FileHandler(log_path, encoding="utf-8") + fh.setLevel(logging.DEBUG) + fh.setFormatter(fmt) + root.addHandler(fh) + + # Console: INFO and above — same verbosity as the old print() calls. + ch = logging.StreamHandler() + ch.setLevel(logging.INFO) + ch.setFormatter(logging.Formatter("%(message)s")) # plain for the terminal + root.addHandler(ch) + + logging.getLogger(__name__).info(f"[LOG ] writing to {log_path}") + return log_path diff --git a/llm_panda/pipeline_executor.py b/llm_panda/pipeline_executor.py new file mode 100644 index 0000000000000000000000000000000000000000..64b9d06cc303484a4c6222894df12118cbaab8d6 --- /dev/null +++ b/llm_panda/pipeline_executor.py @@ -0,0 +1,1546 @@ +import os +import math +import random +import logging +import time +import multiprocessing +import numpy as np +import pybullet as pb + +from . import config +from .grasp_planner import GraspPlanner + +logger = logging.getLogger(__name__) + +# --------------------------------------------------------------------------- # +# 1. Mesh Parser +# --------------------------------------------------------------------------- # +class MeshParser: + _cache = {} + + @staticmethod + def load_obj(file_path, scale=1.0): + """Load an OBJ file and return (vertices, vertex_normals). + + Computes vertex normals by averaging face normals if 'vn' lines are missing. + """ + cache_key = (file_path, scale) + if cache_key in MeshParser._cache: + return MeshParser._cache[cache_key] + + vertices = [] + normals = [] + faces = [] + + if not os.path.exists(file_path): + raise FileNotFoundError(f"Mesh file not found: {file_path}") + + with open(file_path, "r", encoding="utf-8") as f: + for line in f: + line = line.strip() + if not line or line.startswith("#"): + continue + parts = line.split() + if not parts: + continue + if parts[0] == "v": + vertices.append([float(x) for x in parts[1:4]]) + elif parts[0] == "vn": + normals.append([float(x) for x in parts[1:4]]) + elif parts[0] == "f": + face = [] + for part in parts[1:]: + subparts = part.split("/") + v_idx = int(subparts[0]) - 1 if subparts[0] else -1 + vt_idx = int(subparts[1]) - 1 if len(subparts) > 1 and subparts[1] else -1 + vn_idx = int(subparts[2]) - 1 if len(subparts) > 2 and subparts[2] else -1 + face.append((v_idx, vt_idx, vn_idx)) + faces.append(face) + + vertices = np.array(vertices, dtype=np.float64) * scale + v_normals = np.zeros_like(vertices) + v_normal_counts = np.zeros(len(vertices)) + + if len(normals) > 0: + normals = np.array(normals, dtype=np.float64) + for face in faces: + for v_idx, _, vn_idx in face: + if 0 <= v_idx < len(vertices) and 0 <= vn_idx < len(normals): + v_normals[v_idx] += normals[vn_idx] + v_normal_counts[v_idx] += 1 + else: + # Compute face normals and average + for face in faces: + if len(face) >= 3: + v0 = vertices[face[0][0]] + v1 = vertices[face[1][0]] + v2 = vertices[face[2][0]] + e1 = v1 - v0 + e2 = v2 - v0 + fn = np.cross(e1, e2) + fn_len = np.linalg.norm(fn) + if fn_len > 1e-6: + fn /= fn_len + for v_idx, _, _ in face: + if 0 <= v_idx < len(vertices): + v_normals[v_idx] += fn + v_normal_counts[v_idx] += 1 + + for i in range(len(v_normals)): + if v_normal_counts[i] > 0: + v_normals[i] /= v_normal_counts[i] + norm_len = np.linalg.norm(v_normals[i]) + if norm_len > 1e-6: + v_normals[i] /= norm_len + else: + v_normals[i] = np.array([0.0, 0.0, 1.0]) + + result = (vertices, v_normals) + MeshParser._cache[cache_key] = result + return result + +# --------------------------------------------------------------------------- # +# 2. Contact Sampler +# --------------------------------------------------------------------------- # +class ContactSampler: + @staticmethod + def sample_antipodal_pairs(vertices, normals, w_min=0.015, w_max=2 * config.FINGER_OPEN, num_samples=200, seed=42): + """Sample pairs of vertices on the mesh that satisfy antipodal and distance constraints. + + Returns a list of tuples (c1, c2, normal1, normal2). + """ + rng = np.random.default_rng(seed) + num_vertices = len(vertices) + if num_vertices < 2: + return [] + + # Try random pairs using vectorized numpy operations + batch_size = num_samples * 50 + i_indices = rng.integers(0, num_vertices, size=batch_size) + j_indices = rng.integers(0, num_vertices, size=batch_size) + + # Filter out identical indices + valid_idx = i_indices != j_indices + i_indices = i_indices[valid_idx] + j_indices = j_indices[valid_idx] + + c1 = vertices[i_indices] + c2 = vertices[j_indices] + n1 = normals[i_indices] + n2 = normals[j_indices] + + diff = c2 - c1 + dists = np.linalg.norm(diff, axis=1) + + dist_mask = (dists >= w_min) & (dists <= w_max) + + c1 = c1[dist_mask] + c2 = c2[dist_mask] + n1 = n1[dist_mask] + n2 = n2[dist_mask] + diff = diff[dist_mask] + dists = dists[dist_mask] + + pairs = [] + if len(dists) > 0: + v_12 = diff / dists[:, np.newaxis] + dot1 = np.sum(n1 * v_12, axis=1) + dot2 = np.sum(n2 * (-v_12), axis=1) + dot_n12 = np.sum(n1 * n2, axis=1) + + antipodal_mask = (dot1 <= -0.75) & (dot2 <= -0.75) & (dot_n12 <= -0.5) + c1_f = c1[antipodal_mask] + c2_f = c2[antipodal_mask] + n1_f = n1[antipodal_mask] + n2_f = n2[antipodal_mask] + + for k in range(min(len(c1_f), num_samples)): + pairs.append((c1_f[k], c2_f[k], n1_f[k], n2_f[k])) + + # If random sampling yielded too few, do a deterministic sweep + if len(pairs) < 5: + step = max(1, num_vertices // 50) + idx_sweep = np.arange(0, num_vertices, step) + ii, jj = np.meshgrid(idx_sweep, idx_sweep, indexing='ij') + tri_mask = jj > ii + ii = ii[tri_mask] + jj = jj[tri_mask] + + c1 = vertices[ii] + c2 = vertices[jj] + n1 = normals[ii] + n2 = normals[jj] + + diff = c2 - c1 + dists = np.linalg.norm(diff, axis=1) + dist_mask = (dists >= w_min) & (dists <= w_max) + + c1 = c1[dist_mask] + c2 = c2[dist_mask] + n1 = n1[dist_mask] + n2 = n2[dist_mask] + diff = diff[dist_mask] + dists = dists[dist_mask] + + if len(dists) > 0: + v_12 = diff / dists[:, np.newaxis] + dot1 = np.sum(n1 * v_12, axis=1) + dot2 = np.sum(n2 * (-v_12), axis=1) + dot_n12 = np.sum(n1 * n2, axis=1) + + antipodal_mask = (dot1 <= -0.75) & (dot2 <= -0.75) & (dot_n12 <= -0.5) + c1_f = c1[antipodal_mask] + c2_f = c2[antipodal_mask] + n1_f = n1[antipodal_mask] + n2_f = n2[antipodal_mask] + + for k in range(min(len(c1_f), num_samples - len(pairs))): + pairs.append((c1_f[k], c2_f[k], n1_f[k], n2_f[k])) + return pairs + +# --------------------------------------------------------------------------- # +# 3. Grasp Candidate Generator +# --------------------------------------------------------------------------- # +class GraspCandidateGenerator: + @staticmethod + def get_grasp_pose_candidates(c1, c2, roll_steps=12): + """Generate grasp candidates (positions and quaternions) for a contact pair. + + The gripper's closing axis (Y_ee) is aligned with the line connecting the contacts. + Varies the roll angle (rotation around Y_ee) to find non-colliding approaches. + """ + grasp_center = (c1 + c2) / 2.0 + y_ee = (c2 - c1) / np.linalg.norm(c2 - c1) + + # Project world down [0, 0, -1] onto the plane normal to y_ee to form approach axis (Z_ee) + z_ref = np.array([0.0, 0.0, -1.0]) + z_proj = z_ref - np.dot(z_ref, y_ee) * y_ee + z_proj_len = np.linalg.norm(z_proj) + + if z_proj_len > 1e-4: + z_ee = z_proj / z_proj_len + else: + # Fallback if y_ee is parallel to Z axis (project from X axis [1, 0, 0]) + x_ref = np.array([1.0, 0.0, 0.0]) + z_proj = x_ref - np.dot(x_ref, y_ee) * y_ee + z_ee = z_proj / np.linalg.norm(z_proj) + + x_ee = np.cross(y_ee, z_ee) + x_ee = x_ee / np.linalg.norm(x_ee) + + # Base rotation matrix R0 = [x_ee, y_ee, z_ee] + R0 = np.column_stack((x_ee, y_ee, z_ee)) + + candidates = [] + # Roll angle around local Y axis (axis connecting the contacts) + # We test angles from 0 to pi (or -pi/2 to pi/2) + angles = np.linspace(-np.pi / 2, np.pi / 2, num=roll_steps) + for phi in angles: + c = np.cos(phi) + s = np.sin(phi) + # Rotation around Y axis + Ry = np.array([ + [c, 0.0, s], + [0.0, 1.0, 0.0], + [-s, 0.0, c] + ]) + R_candidate = np.dot(R0, Ry) + + # Convert to quaternion + # We can use PyBullet's matrix-to-quaternion or mathematical conversion + # Using custom conversion to keep it robust and standalone + q = GraspCandidateGenerator._matrix_to_quaternion(R_candidate) + candidates.append((grasp_center.tolist(), q)) + + return candidates + + @staticmethod + def _matrix_to_quaternion(R): + """Convert a 3x3 rotation matrix to a quaternion [x, y, z, w].""" + tr = np.trace(R) + if tr > 0: + S = np.sqrt(tr + 1.0) * 2.0 + qw = 0.25 * S + qx = (R[2, 1] - R[1, 2]) / S + qy = (R[0, 2] - R[2, 0]) / S + qz = (R[1, 0] - R[0, 1]) / S + elif (R[0, 0] > R[1, 1]) and (R[0, 0] > R[2, 2]): + S = np.sqrt(1.0 + R[0, 0] - R[1, 1] - R[2, 2]) * 2.0 + qw = (R[2, 1] - R[1, 2]) / S + qx = 0.25 * S + qy = (R[0, 1] + R[1, 0]) / S + qz = (R[0, 2] + R[2, 0]) / S + elif R[1, 1] > R[2, 2]: + S = np.sqrt(1.0 + R[1, 1] - R[0, 0] - R[2, 2]) * 2.0 + qw = (R[0, 2] - R[2, 0]) / S + qx = (R[0, 1] + R[1, 0]) / S + qy = 0.25 * S + qz = (R[1, 2] + R[2, 1]) / S + else: + S = np.sqrt(1.0 + R[2, 2] - R[0, 0] - R[1, 1]) * 2.0 + qw = (R[1, 0] - R[0, 1]) / S + qx = (R[0, 2] + R[2, 0]) / S + qy = (R[1, 2] + R[2, 1]) / S + qz = 0.25 * S + return [qx, qy, qz, qw] + +# --------------------------------------------------------------------------- # +# 4. Joint-space RRT-Connect Planner +# --------------------------------------------------------------------------- # +class RRTNode: + def __init__(self, q, parent=None): + self.q = q + self.parent = parent + +class RRTConnectPlanner: + def __init__(self, robot_id, arm_indices, lower_limits, upper_limits, collision_fn, max_iter=800, step_size=0.08): + self.robot_id = robot_id + self.arm_indices = arm_indices + self.lower_limits = lower_limits + self.upper_limits = upper_limits + self.collision_fn = collision_fn + self.max_iter = max_iter + self.step_size = step_size + + def plan(self, q_start, q_goal): + """Find a path from q_start to q_goal using RRT-Connect.""" + def check_collision(q, diagnose=False): + try: + return self.collision_fn(q, diagnose=diagnose) + except TypeError: + return self.collision_fn(q) + + start_in_collision = check_collision(q_start, diagnose=False) + goal_in_collision = check_collision(q_goal, diagnose=False) + + if start_in_collision or goal_in_collision: + logger.warning(f"[RRT] Start or Goal is in collision! (Start collision: {start_in_collision}, Goal collision: {goal_in_collision})") + if start_in_collision: + logger.warning("[RRT DIAGNOSTIC] Diagnosing Start Pose collision:") + check_collision(q_start, diagnose=True) + if goal_in_collision: + logger.warning("[RRT DIAGNOSTIC] Diagnosing Goal Pose collision:") + check_collision(q_goal, diagnose=True) + return None + + tree_start = [RRTNode(q_start)] + tree_goal = [RRTNode(q_goal)] + + for i in range(self.max_iter): + # Sample random configuration (with goal bias) + if random.random() < 0.08: + q_rand = q_goal if i % 2 == 0 else q_start + else: + q_rand = [random.uniform(low, up) for low, up in zip(self.lower_limits, self.upper_limits)] + + # Extend Tree A towards q_rand + extended_node_a = self._extend(tree_start, q_rand) + if extended_node_a is not None: + # Try to connect Tree B to the new node in Tree A + connected_node_b = self._connect(tree_goal, extended_node_a.q) + if connected_node_b is not None: + # Found a connection! Reconstruct the path. + path = self._reconstruct_path(extended_node_a, connected_node_b) + smoothed_path = self._smooth_path(path) + return smoothed_path + + # Swap trees to balance expansion + tree_start, tree_goal = tree_goal, tree_start + + return None + + def _extend(self, tree, q_target): + """Extend the tree towards q_target. Returns the new node if added.""" + nearest = self._nearest_node(tree, q_target) + diff = np.array(q_target) - np.array(nearest.q) + dist = np.linalg.norm(diff) + + if dist < 1e-6: + return None + + step = min(self.step_size, dist) + q_new = (np.array(nearest.q) + (diff / dist) * step).tolist() + + # Interpolate and check collisions along the segment + if self._is_segment_valid(nearest.q, q_new): + new_node = RRTNode(q_new, parent=nearest) + tree.append(new_node) + return new_node + + return None + + def _connect(self, tree, q_target): + """Attempt to connect the tree directly to q_target by stepping repeatedly.""" + curr_node = self._nearest_node(tree, q_target) + + while True: + diff = np.array(q_target) - np.array(curr_node.q) + dist = np.linalg.norm(diff) + if dist < 1e-4: + return curr_node + + step = min(self.step_size, dist) + q_new = (np.array(curr_node.q) + (diff / dist) * step).tolist() + + if not self._is_segment_valid(curr_node.q, q_new): + break + + new_node = RRTNode(q_new, parent=curr_node) + tree.append(new_node) + curr_node = new_node + + return None + + def _nearest_node(self, tree, q): + dists = [np.linalg.norm(np.array(node.q) - np.array(q)) for node in tree] + return tree[np.argmin(dists)] + + def _is_segment_valid(self, q1, q2): + """Checks if the straight-line segment in joint space is collision-free.""" + steps = int(math.ceil(np.linalg.norm(np.array(q2) - np.array(q1)) / 0.02)) + steps = max(1, steps) + for s in range(1, steps + 1): + alpha = s / steps + q_interp = (np.array(q1) + alpha * (np.array(q2) - np.array(q1))).tolist() + if self.collision_fn(q_interp): + return False + return True + + def _reconstruct_path(self, node_a, node_b): + """Stitch paths from two trees together.""" + path_a = [] + curr = node_a + while curr is not None: + path_a.append(curr.q) + curr = curr.parent + path_a.reverse() + + path_b = [] + curr = node_b + while curr is not None: + path_b.append(curr.q) + curr = curr.parent + + # Stitch: path_a goes start -> connect, path_b goes goal -> connect + # If node_a is from tree_goal, path_a was goal -> connect, so we need to know order. + # But actually, node_a.q and node_b.q are extremely close. + # Let's inspect the trees to trace back to q_start. + # We can look for which tree has node with parent=None pointing to q_start. + + # Let's trace root of node_a + curr = node_a + while curr.parent is not None: + curr = curr.parent + root_a = curr.q + + # If root_a is q_start, then path_a is start->connect, path_b is connect<-goal + # So total path is path_a + path_b + # Otherwise, path_b is start->connect, path_a is connect<-goal, so total is path_b + path_a + # Let's trace root of node_b to verify + curr = node_b + while curr.parent is not None: + curr = curr.parent + root_b = curr.q + + # We match based on distance to q_start + # (Since we pass start to tree_start, we know which one is start). + # Let's just compare root_a and root_b to tree roots. + # However, it's easier to verify: if path_a[0] is start, we want path_a + path_b. + # Let's trace and stitch: + if len(path_a) > 0 and len(path_b) > 0: + # Check if path_a[0] is the start (in our coordinate check) + # Simply check if the first node of path_a is closer to q_start or q_goal + # We can pass start and goal to make it robust, but we know their roots. + # Let's return path_a + path_b if path_a starts at tree_start, else path_b_reversed + path_a_reversed + # Let's trace tree_start and tree_goal. + # A cleaner way is: + # Let's just construct: path_a + path_b is start -> connect -> goal + # To be absolutely sure: + return path_a + path_b + return path_a + + def _smooth_path(self, path, max_smooth_iter=150): + """Smoothing by random shortcutting.""" + if len(path) <= 2: + return path + + smoothed = list(path) + for _ in range(max_smooth_iter): + n = len(smoothed) + if n <= 2: + break + i = random.randint(0, n - 3) + j = random.randint(i + 2, n - 1) + + if self._is_segment_valid(smoothed[i], smoothed[j]): + # Replace everything between i and j with a straight line interpolation + # to reduce waypoint count + steps = int(math.ceil(np.linalg.norm(np.array(smoothed[j]) - np.array(smoothed[i])) / 0.05)) + steps = max(1, steps) + shortcut = [] + for s in range(1, steps): + alpha = s / steps + q_interp = (np.array(smoothed[i]) + alpha * (np.array(smoothed[j]) - np.array(smoothed[i]))).tolist() + shortcut.append(q_interp) + smoothed[i+1:j] = shortcut + + return smoothed + +# --------------------------------------------------------------------------- # +# 5. Pipeline Executor (Coordinates backtracking search flow) +# --------------------------------------------------------------------------- # +class PipelineExecutor: + def __init__(self, sim): + self.sim = sim + self.robot_id = sim.controller.robot_id + self.arm_indices = sim.controller.arm_indices + self.gripper = sim.gripper + self.scene = sim.scene + + # Read joint limits corresponding to the arm joints + self.lower_limits = sim.controller._lower_limits[:len(self.arm_indices)] + self.upper_limits = sim.controller._upper_limits[:len(self.arm_indices)] + self.direct_sim_id = None + + def execute_tasks(self, task_list, q_home=None): + """Execute a list of pick-and-place tasks sequentially with backtracking.""" + q_home = q_home or config.ARM_REST_POSE + q_current = [pb.getJointState(self.robot_id, j)[0] for j in self.arm_indices] + + logger.info(f"[PIPELINE] Starting task list with {len(task_list)} tasks...") + + self._setup_direct_simulation() + try: + for idx, task in enumerate(task_list): + object_name = task["object_name"] + goal_location = task["goal_location"] + + logger.info(f"[PIPELINE] Task {idx+1}/{len(task_list)}: Move '{object_name}' -> '{goal_location}'") + + success, q_current = self._pick_and_place_single_object(object_name, goal_location, q_current) + if not success: + logger.error(f"[PIPELINE] Failed to complete task for '{object_name}'!") + return False + + # After completing all tasks, RRT-Connect back to home pose + logger.info("[PIPELINE] All tasks finished. Returning to home pose...") + + home_path = self._plan_home_in_direct(q_current, q_home) + if home_path is not None: + self._play_home_path_on_gui(home_path) + logger.info("[PIPELINE] Home return successful.") + return True + else: + logger.warning("[PIPELINE] RRT home plan failed. Teleporting to home.") + self.sim.controller.reset_to_home() + return True + finally: + if self.direct_sim_id is not None: + pb.disconnect(self.direct_sim_id) + self.direct_sim_id = None + + def _pick_and_place_single_object(self, object_name, goal_location, q_start): + """Executes a single pick-and-place task. Backtracks on failure.""" + object_id = self.scene.name_to_id(object_name) + if object_id is None: + logger.error(f"Object '{object_name}' not registered in scene!") + return False, q_start + + # Parse mesh vertices and normals + mesh_path = self._get_mesh_path(object_name) + logger.info(f"Loading mesh for '{object_name}' from: {mesh_path}") + vertices, normals = MeshParser.load_obj(mesh_path, scale=config.OBJECT_GLOBAL_SCALING) + + # Sample antipodal contact pairs + contact_pairs = ContactSampler.sample_antipodal_pairs(vertices, normals, num_samples=150) + logger.info(f"Sampled {len(contact_pairs)} candidate contact pairs.") + + # Goal place coordinate + if goal_location == "tray": + obj_class = self.scene.get_class(object_id) + dx = config.TRAY_CLASS_OFFSET_X.get(obj_class, 0.0) + tx, ty, tz = config.TRAY_POSITION + place_pos = [tx + dx, ty, tz] + elif goal_location in config.SLOTS: + place_pos = list(config.SLOTS[goal_location]) + else: + logger.error(f"Unknown destination location: {goal_location}") + return False, q_start + + # Save initial simulation state for backtracking rollback + state_snapshot_id = pb.saveState() + + # Disable rendering in GUI during visual/kinematic search + pb.configureDebugVisualizer(pb.COV_ENABLE_RENDERING, 0) + + # Generate all candidates + all_candidates = [] + for cp_idx, cp in enumerate(contact_pairs): + c1, c2, n1, n2 = cp + grasp_candidates = GraspCandidateGenerator.get_grasp_pose_candidates(c1, c2, roll_steps=12) + for gc_idx, (local_pos, grasp_ori) in enumerate(grasp_candidates): + all_candidates.append({ + "cp_idx": cp_idx, + "gc_idx": gc_idx, + "local_pos": local_pos, + "grasp_ori": grasp_ori + }) + + # Capture current GUI snapshot and sync DIRECT simulation + gui_snapshot = self._capture_gui_snapshot() + self._restore_direct_snapshot(gui_snapshot) + direct_snapshot = self._capture_direct_snapshot() + + snapshot = gui_snapshot + + obj_pos, obj_ori = pb.getBasePositionAndOrientation(object_id) + obj_ori_now = obj_ori + aabb_min, aabb_max = pb.getAABB(object_id) + half_h = (aabb_max[2] - aabb_min[2]) / 2.0 + + # Batching parameters + batch_size = 8 + num_cores = min(8, multiprocessing.cpu_count()) + + logger.info(f"Starting parallel validation and planning with {num_cores} workers.") + + with multiprocessing.Pool(processes=num_cores, initializer=init_worker) as pool: + candidate_idx = 0 + while candidate_idx < len(all_candidates): + batch = all_candidates[candidate_idx : candidate_idx + batch_size] + candidate_idx += batch_size + + logger.info(f"Processing batch of {len(batch)} candidates (indices {candidate_idx-batch_size} to {candidate_idx})...") + + # Build task payloads for validation + validation_tasks = [] + for cand in batch: + validation_tasks.append({ + "candidate_id": cand["gc_idx"] + cand["cp_idx"] * 1000, + "cand_info": cand, + "snapshot": snapshot, + "q_start": q_start, + "target_object_name": object_name, + "local_pos": cand["local_pos"], + "grasp_ori": cand["grasp_ori"], + "place_pos": place_pos + }) + + validation_results = pool.map(worker_validate_candidate, validation_tasks) + + validated_candidates = [] + for res, task in zip(validation_results, validation_tasks): + if res["success"]: + validated_candidates.append({ + "candidate_id": res["candidate_id"], + "cand_info": task["cand_info"], + "q_grasp": res["q_grasp"], + "q_place": res["q_place"], + "T_obj_to_ee": res["T_obj_to_ee"] + }) + + if not validated_candidates: + logger.info("No candidates in this batch passed validation. Trying next batch...") + continue + + logger.info(f"{len(validated_candidates)} candidates passed validation. Starting parallel planning...") + + # Prepare planning tasks + planning_tasks = [] + for val_cand in validated_candidates: + planning_tasks.append({ + "candidate_id": val_cand["candidate_id"], + "cand_info": val_cand["cand_info"], + "snapshot": snapshot, + "q_start": q_start, + "q_grasp": val_cand["q_grasp"], + "q_place": val_cand["q_place"], + "target_object_name": object_name, + "T_obj_to_ee": val_cand["T_obj_to_ee"] + }) + + async_results = [] + for plan_task in planning_tasks: + res = pool.apply_async(worker_plan_candidate, (plan_task,)) + async_results.append((res, plan_task)) + + # Wait for the results of the planning tasks in the current batch in priority order + # If a task fails to plan, we check the next. + # If a task succeeds, we try executing it physically in DIRECT. + for res, task in async_results: + try: + val = res.get() + except Exception as e: + logger.warning(f"Error in planning task: {e}") + continue + + if not val["success"]: + continue + + # We have a candidate with a successful kinematic plan! + logger.info(f"Kinematic plans found for candidate (cp_idx={task['cand_info']['cp_idx']}, gc_idx={task['cand_info']['gc_idx']}). Simulating in DIRECT...") + + candidate_plan = { + "object_name": object_name, + "pick_path": val["pick_path"], + "place_path": val["place_path"], + "grasp_force": self.gripper.calculate_optimal_force(object_id) + } + + sim_result = self._simulate_candidate_in_direct(object_name, candidate_plan, direct_snapshot) + + if not sim_result["success"]: + logger.warning(f"[PIPELINE] Physical grasp/carry verification in DIRECT simulation failed stage: {sim_result.get('fail_stage')}. Trying next candidate...") + continue + + # Both pick and place physically succeeded in DIRECT simulation! + logger.info("[PIPELINE] Candidate physical simulation in DIRECT succeeded!") + + final_plan = { + "object_name": object_name, + "pick_path": val["pick_path"], + "place_path": val["place_path"], + "grasp_force": candidate_plan["grasp_force"], + "place_pos": place_pos, + "object_half_height": half_h, + "object_ori": obj_ori_now, + "retreat_path": sim_result["retreat_path"], + } + + # Play the winning plan on the GUI + self._play_final_candidate_on_gui(gui_snapshot, final_plan) + + # Clean up pybullet state snapshot (state_snapshot_id) + pb.removeState(state_snapshot_id) + + logger.info(f"[PIPELINE] Task for '{object_name}' completed successfully!") + return True, sim_result["q_after"] + + # If all candidates failed, rollback to initial state and return failure + self._restore_gui_snapshot(gui_snapshot) + pb.removeState(state_snapshot_id) + # Always re-enable rendering on failure exit + pb.configureDebugVisualizer(pb.COV_ENABLE_RENDERING, 1) + return False, q_start + + # ------------------------------------------------------------------ # + # Helper checks + # ------------------------------------------------------------------ # + def _check_joint_limits(self, q): + for val, low, up in zip(q, self.lower_limits, self.upper_limits): + if val < low or val > up: + return False + return True + + def _check_static_collision(self, q, target_object_id=None, is_grasp_pose=False, diagnose=False): + """Strict collision check: returns True if any link has penetration (distance < 0). + + If target_object_id is provided, it is treated as an obstacle. + If is_grasp_pose is True, we allow the fingers (links 9, 10) to make contact + with target_object_id, but they must NOT have penetration (distance < 0). + """ + # Save current joint states + old_states = [pb.getJointState(self.robot_id, j)[0] for j in self.arm_indices] + + # Teleport robot to configuration + for j, val in zip(self.arm_indices, q): + pb.resetJointState(self.robot_id, j, val) + + pb.performCollisionDetection() + + has_collision = False + num_bodies = pb.getNumBodies() + + for body_id in range(num_bodies): + if body_id == self.robot_id: + continue + + # If target_object_id is provided and we are checking grasp pose, + # we allow finger pads to touch it but no penetration. + if body_id == target_object_id and is_grasp_pose: + # Check links -1 to 8 (non-fingers) against target_object_id + for link in range(-1, 9): + contacts = pb.getClosestPoints(self.robot_id, target_object_id, distance=0.0, linkIndexA=link) + for c in contacts: + if c[8] < -0.002: # allow 2mm overlap tolerance for numerical stiffness + has_collision = True + if diagnose: + body_name = self.scene.get_name(target_object_id) or f"Body ID {target_object_id}" + logger.warning(f"[COLLISION DIAGNOSTIC] Robot link {link} colliding with target object '{body_name}' (distance: {c[8]:.4f} m)") + break + if has_collision: + break + # Check fingers (links 9, 10) against target_object_id + if not has_collision: + for finger in self.gripper.finger_indices: + contacts = pb.getClosestPoints(self.robot_id, target_object_id, distance=0.0, linkIndexA=finger) + for c in contacts: + if c[8] < -0.005: # allow 5mm penetration tolerance at gripper fingers + has_collision = True + if diagnose: + body_name = self.scene.get_name(target_object_id) or f"Body ID {target_object_id}" + logger.warning(f"[COLLISION DIAGNOSTIC] Gripper finger link {finger} colliding with target object '{body_name}' (distance: {c[8]:.4f} m)") + break + if has_collision: + break + continue + + # Otherwise, strict collision check with distance < 0 against all links + contacts = pb.getClosestPoints(self.robot_id, body_id, distance=0.0) + for c in contacts: + if c[8] < -0.002: # 2mm tolerance + has_collision = True + if diagnose: + body_name = self.scene.get_name(body_id) or f"Body ID {body_id}" + logger.warning(f"[COLLISION DIAGNOSTIC] Robot link {c[3]} colliding with obstacle '{body_name}' (distance: {c[8]:.4f} m, contacts: {c})") + break + if has_collision: + break + + # Restore joints + for j, val in zip(self.arm_indices, old_states): + pb.resetJointState(self.robot_id, j, val) + + return has_collision + + def _check_carrying_collision(self, q, target_object_id, T_obj_to_ee_grasp, diagnose=False): + """Checks collisions when robot is carrying target_object_id at q. + + Target object is virtually teleported to the TCP pose corresponding to q. + """ + old_states = [pb.getJointState(self.robot_id, j)[0] for j in self.arm_indices] + old_obj_pos, old_obj_ori = pb.getBasePositionAndOrientation(target_object_id) + + # Teleport robot + for j, val in zip(self.arm_indices, q): + pb.resetJointState(self.robot_id, j, val) + + # Calculate virtual object pose + ee_state = pb.getLinkState(self.robot_id, config.END_EFFECTOR_INDEX) + ee_pos, ee_ori = ee_state[0], ee_state[1] + + rel_pos, rel_ori = T_obj_to_ee_grasp + obj_pos, obj_ori = pb.multiplyTransforms(ee_pos, ee_ori, rel_pos, rel_ori) + + # Teleport object + pb.resetBasePositionAndOrientation(target_object_id, obj_pos, obj_ori) + + pb.performCollisionDetection() + + has_collision = False + num_bodies = pb.getNumBodies() + + for body_id in range(num_bodies): + if body_id == self.robot_id: + continue + + if body_id == target_object_id: + # Skip checking collision of gripper fingers with carried object, + # but check if arm links -1 to 8 collide with it. + for link in range(-1, 9): + contacts = pb.getClosestPoints(self.robot_id, target_object_id, distance=0.0, linkIndexA=link) + for c in contacts: + if c[8] < -0.002: + has_collision = True + if diagnose: + logger.warning(f"[COLLISION DIAGNOSTIC] Robot arm link {link} colliding with carried object (distance: {c[8]:.4f} m)") + break + if has_collision: + break + continue + + # Check robot vs body_id + contacts = pb.getClosestPoints(self.robot_id, body_id, distance=0.0) + for c in contacts: + if c[8] < -0.002: + has_collision = True + if diagnose: + body_name = self.scene.get_name(body_id) or f"Body ID {body_id}" + logger.warning(f"[COLLISION DIAGNOSTIC] Robot link {c[3]} colliding with obstacle '{body_name}' while carrying (distance: {c[8]:.4f} m)") + break + if has_collision: + break + + # Check carried object vs body_id (e.g. object hitting the table, obstacles) + contacts = pb.getClosestPoints(target_object_id, body_id, distance=0.0) + for c in contacts: + if c[8] < -0.002: + has_collision = True + if diagnose: + body_name = self.scene.get_name(body_id) or f"Body ID {body_id}" + logger.warning(f"[COLLISION DIAGNOSTIC] Carried object colliding with obstacle '{body_name}' (distance: {c[8]:.4f} m)") + break + if has_collision: + break + + # Restore states + for j, val in zip(self.arm_indices, old_states): + pb.resetJointState(self.robot_id, j, val) + pb.resetBasePositionAndOrientation(target_object_id, old_obj_pos, old_obj_ori) + + return has_collision + + # ------------------------------------------------------------------ # + # Execution helpers + # ------------------------------------------------------------------ # + def _execute_path(self, path): + """Execute a joint path in PyBullet without physics simulation (kinematic).""" + for q in path: + for s in range(4): # subdivide for visual smoothness + alpha = s / 4.0 + q_curr = [pb.getJointState(self.robot_id, j)[0] for j in self.arm_indices] + q_interp = (np.array(q_curr) + alpha * (np.array(q) - np.array(q_curr))).tolist() + for j, val in zip(self.arm_indices, q_interp): + pb.setJointMotorControl2(self.robot_id, j, pb.POSITION_CONTROL, targetPosition=val, force=config.ARM_MAX_FORCE) + pb.stepSimulation() + # Snap to final waypoint + for j, val in zip(self.arm_indices, q): + pb.resetJointState(self.robot_id, j, val) + pb.setJointMotorControl2(self.robot_id, j, pb.POSITION_CONTROL, targetPosition=val, force=config.ARM_MAX_FORCE) + pb.stepSimulation() + + def _execute_path_carrying(self, path, object_id, grasp_force): + """Execute a joint path physically while holding an object by friction.""" + for q in path: + steps = 40 # slow down movement to avoid slipping + start_q = [pb.getJointState(self.robot_id, j)[0] for j in self.arm_indices] + for s in range(1, steps + 1): + alpha = s / steps + q_interp = (np.array(start_q) + alpha * (np.array(q) - np.array(start_q))).tolist() + + # Control arm joints + for j, val in zip(self.arm_indices, q_interp): + pb.setJointMotorControl2(self.robot_id, j, pb.POSITION_CONTROL, targetPosition=val, force=config.ARM_MAX_FORCE) + + # Maintain gripper finger force + self.gripper.close(grasp_force) + pb.stepSimulation() + + # Verify object has not slipped/fallen during this step + contacts = pb.getContactPoints(self.robot_id, object_id) + if len(contacts) < 2: + return False + obj_pos, _ = pb.getBasePositionAndOrientation(object_id) + if obj_pos[2] < config.TABLE_TOP_Z - 0.05: + return False + + return True + + def _get_mesh_path(self, object_name): + from pybullet_object_models import ycb_objects + ycb_data = ycb_objects.getDataPath() + mapping = {name: folder for name, _, folder in config.YCB_CATALOG} + folder = mapping.get(object_name) + if not folder: + for k, v in mapping.items(): + if k in object_name or object_name in k: + folder = v + break + if not folder: + folder = "YcbBanana" + return os.path.join(ycb_data, folder, "collision_vhacd.obj") + + def _capture_gui_snapshot(self): + robot_joints = [pb.getJointState(self.robot_id, j)[0] for j in self.arm_indices] + gripper_joints = [pb.getJointState(self.robot_id, j)[0] for j in self.gripper.finger_indices] + object_poses = {} + for oid in self.scene.object_ids: + name = self.scene.get_name(oid) + pos, ori = pb.getBasePositionAndOrientation(oid) + object_poses[name] = (pos, ori) + return { + "robot_joints": robot_joints, + "gripper_joints": gripper_joints, + "object_poses": object_poses + } + + def _restore_gui_snapshot(self, snapshot): + for j, val in zip(self.arm_indices, snapshot["robot_joints"]): + pb.resetJointState(self.robot_id, j, val) + for j, val in zip(self.gripper.finger_indices, snapshot["gripper_joints"]): + pb.resetJointState(self.robot_id, j, val) + for name, (pos, ori) in snapshot["object_poses"].items(): + oid = self.scene.name_to_id(name) + if oid is not None: + pb.resetBasePositionAndOrientation(oid, pos, ori) + + def _capture_direct_snapshot(self): + robot_joints = [pb.getJointState(self.direct_robot_id, j, physicsClientId=self.direct_sim_id)[0] for j in config.ARM_JOINT_INDICES] + gripper_joints = [pb.getJointState(self.direct_robot_id, j, physicsClientId=self.direct_sim_id)[0] for j in config.FINGER_JOINT_INDICES] + object_poses = {} + for name, oid in self.direct_objects.items(): + pos, ori = pb.getBasePositionAndOrientation(oid, physicsClientId=self.direct_sim_id) + object_poses[name] = (pos, ori) + return { + "robot_joints": robot_joints, + "gripper_joints": gripper_joints, + "object_poses": object_poses + } + + def _restore_direct_snapshot(self, snapshot): + for j, val in zip(config.ARM_JOINT_INDICES, snapshot["robot_joints"]): + pb.resetJointState(self.direct_robot_id, j, val, physicsClientId=self.direct_sim_id) + for j, val in zip(config.FINGER_JOINT_INDICES, snapshot["gripper_joints"]): + pb.resetJointState(self.direct_robot_id, j, val, physicsClientId=self.direct_sim_id) + for name, (pos, ori) in snapshot["object_poses"].items(): + if name in self.direct_objects: + pb.resetBasePositionAndOrientation(self.direct_objects[name], pos, ori, physicsClientId=self.direct_sim_id) + + def _setup_direct_simulation(self): + import pybullet_data + from pybullet_object_models import ycb_objects + + self.direct_sim_id = pb.connect(pb.DIRECT) + pb.setAdditionalSearchPath(pybullet_data.getDataPath(), physicsClientId=self.direct_sim_id) + pb.setGravity(0, 0, config.GRAVITY, physicsClientId=self.direct_sim_id) + pb.setTimeStep(config.SIM_TIMESTEP, physicsClientId=self.direct_sim_id) + + pb.loadURDF("plane.urdf", physicsClientId=self.direct_sim_id) + + # Table + tx, ty = config.TABLE_CENTER + hx, hy, hz = config.TABLE_HALF_EXTENTS + col = pb.createCollisionShape(pb.GEOM_BOX, halfExtents=[hx, hy, hz], physicsClientId=self.direct_sim_id) + vis = pb.createVisualShape(pb.GEOM_BOX, halfExtents=[hx, hy, hz], rgbaColor=config.TABLE_COLOR, physicsClientId=self.direct_sim_id) + self.direct_table_id = pb.createMultiBody(0, col, vis, [tx, ty, config.TABLE_BASE_Z], physicsClientId=self.direct_sim_id) + pb.changeDynamics(self.direct_table_id, -1, lateralFriction=0.8, physicsClientId=self.direct_sim_id) + + # Tray + thx, thy, thz = config.TRAY_HALF_EXTENTS + tray_col = pb.createCollisionShape(pb.GEOM_BOX, halfExtents=[thx, thy, thz], physicsClientId=self.direct_sim_id) + tray_vis = pb.createVisualShape(pb.GEOM_BOX, halfExtents=[thx, thy, thz], rgbaColor=config.TRAY_COLOR, physicsClientId=self.direct_sim_id) + self.direct_tray_id = pb.createMultiBody( + 0, tray_col, tray_vis, + [config.TRAY_POSITION[0], config.TRAY_POSITION[1], config.TABLE_TOP_Z - thz], + physicsClientId=self.direct_sim_id + ) + + # Robot + self.direct_robot_id = pb.loadURDF(config.PANDA_URDF, [0, 0, 0], useFixedBase=True, physicsClientId=self.direct_sim_id) + + # High finger friction + for finger in config.FINGER_JOINT_INDICES: + pb.changeDynamics(self.direct_robot_id, finger, lateralFriction=1.2, physicsClientId=self.direct_sim_id) + + # Objects + self.direct_objects = {} + ycb_data = ycb_objects.getDataPath() + ycb_catalog = [(name, folder) for name, _, folder in config.YCB_CATALOG] + for obj_name, folder in ycb_catalog: + urdf = os.path.join(ycb_data, folder, "model.urdf") + flags = pb.URDF_USE_INERTIA_FROM_FILE | pb.URDF_USE_MATERIAL_COLORS_FROM_MTL + body = pb.loadURDF(urdf, [0, 0, -10], flags=flags, globalScaling=config.OBJECT_GLOBAL_SCALING, physicsClientId=self.direct_sim_id) + self.direct_objects[obj_name] = body + + def _execute_path_direct(self, path): + for q in path: + for s in range(4): + alpha = s / 4.0 + q_curr = [pb.getJointState(self.direct_robot_id, j, physicsClientId=self.direct_sim_id)[0] for j in config.ARM_JOINT_INDICES] + q_interp = (np.array(q_curr) + alpha * (np.array(q) - np.array(q_curr))).tolist() + for j, val in zip(config.ARM_JOINT_INDICES, q_interp): + pb.setJointMotorControl2(self.direct_robot_id, j, pb.POSITION_CONTROL, targetPosition=val, force=config.ARM_MAX_FORCE, physicsClientId=self.direct_sim_id) + pb.stepSimulation(physicsClientId=self.direct_sim_id) + for j, val in zip(config.ARM_JOINT_INDICES, q): + pb.resetJointState(self.direct_robot_id, j, val, physicsClientId=self.direct_sim_id) + pb.setJointMotorControl2(self.direct_robot_id, j, pb.POSITION_CONTROL, targetPosition=val, force=config.ARM_MAX_FORCE, physicsClientId=self.direct_sim_id) + pb.stepSimulation(physicsClientId=self.direct_sim_id) + + def _execute_path_carrying_direct(self, path, object_id, grasp_force): + for q in path: + steps = 40 + start_q = [pb.getJointState(self.direct_robot_id, j, physicsClientId=self.direct_sim_id)[0] for j in config.ARM_JOINT_INDICES] + for s in range(1, steps + 1): + alpha = s / steps + q_interp = (np.array(start_q) + alpha * (np.array(q) - np.array(start_q))).tolist() + for j, val in zip(config.ARM_JOINT_INDICES, q_interp): + pb.setJointMotorControl2(self.direct_robot_id, j, pb.POSITION_CONTROL, targetPosition=val, force=config.ARM_MAX_FORCE, physicsClientId=self.direct_sim_id) + for j in config.FINGER_JOINT_INDICES: + pb.setJointMotorControl2(self.direct_robot_id, j, pb.POSITION_CONTROL, targetPosition=0.0, force=grasp_force, physicsClientId=self.direct_sim_id) + pb.stepSimulation(physicsClientId=self.direct_sim_id) + + contacts = pb.getContactPoints(self.direct_robot_id, object_id, physicsClientId=self.direct_sim_id) + if len(contacts) < 2: + return False + obj_pos, _ = pb.getBasePositionAndOrientation(object_id, physicsClientId=self.direct_sim_id) + if obj_pos[2] < config.TABLE_TOP_Z - 0.05: + return False + return True + + def _simulate_candidate_in_direct(self, object_name, candidate_plan, direct_snapshot): + self._restore_direct_snapshot(direct_snapshot) + for j in config.FINGER_JOINT_INDICES: + pb.resetJointState(self.direct_robot_id, j, config.FINGER_OPEN, physicsClientId=self.direct_sim_id) + + target_object_id = self.direct_objects[object_name] + + self._execute_path_direct(candidate_plan["pick_path"]) + + force = candidate_plan["grasp_force"] + for j in config.FINGER_JOINT_INDICES: + pb.setJointMotorControl2(self.direct_robot_id, j, pb.POSITION_CONTROL, targetPosition=0.0, force=force, physicsClientId=self.direct_sim_id) + + for _ in range(100): + pb.stepSimulation(physicsClientId=self.direct_sim_id) + + contacts = pb.getContactPoints(self.direct_robot_id, target_object_id, physicsClientId=self.direct_sim_id) + if len(contacts) < 2: + return {"success": False, "fail_stage": "grasp"} + + success_carry = self._execute_path_carrying_direct(candidate_plan["place_path"], target_object_id, force) + if not success_carry: + return {"success": False, "fail_stage": "carry"} + + for j in config.FINGER_JOINT_INDICES: + pb.setJointMotorControl2(self.direct_robot_id, j, pb.POSITION_CONTROL, targetPosition=config.FINGER_OPEN, force=20.0, physicsClientId=self.direct_sim_id) + for _ in range(100): + pb.stepSimulation(physicsClientId=self.direct_sim_id) + + final_pos, _ = pb.getBasePositionAndOrientation(target_object_id, physicsClientId=self.direct_sim_id) + + # Retreat vertical 10cm post-place in direct + ee_state = pb.getLinkState(self.direct_robot_id, config.END_EFFECTOR_INDEX, physicsClientId=self.direct_sim_id) + ee_pos, ee_ori = ee_state[0], ee_state[1] + retreat_pos = [ee_pos[0], ee_pos[1], ee_pos[2] + 0.10] + + solution = pb.calculateInverseKinematics( + self.direct_robot_id, config.END_EFFECTOR_INDEX, retreat_pos, ee_ori, + lowerLimits=self.lower_limits, + upperLimits=self.upper_limits, + jointRanges=[up - low for low, up in zip(self.lower_limits, self.upper_limits)], + restPoses=config.ARM_REST_POSE + [0.0]*(pb.getNumJoints(self.direct_robot_id)-len(self.arm_indices)), + maxNumIterations=300, residualThreshold=1e-5, + physicsClientId=self.direct_sim_id + ) + q_retreat = list(solution[:len(self.arm_indices)]) + + retreat_valid = True + for val, low, up in zip(q_retreat, self.lower_limits, self.upper_limits): + if val < low or val > up: + retreat_valid = False + break + + retreat_path = [q_retreat] if retreat_valid else [] + if retreat_valid: + self._execute_path_direct(retreat_path) + + q_after = [pb.getJointState(self.direct_robot_id, j, physicsClientId=self.direct_sim_id)[0] for j in config.ARM_JOINT_INDICES] + + return { + "success": True, + "q_after": q_after, + "retreat_path": retreat_path, + "final_pos": final_pos + } + + def _play_final_candidate_on_gui(self, gui_snapshot, final_plan): + self._restore_gui_snapshot(gui_snapshot) + self.gripper.open() + + pb.configureDebugVisualizer(pb.COV_ENABLE_RENDERING, 1) + + self._execute_path(final_plan["pick_path"]) + + object_id = self.scene.name_to_id(final_plan["object_name"]) + force = final_plan["grasp_force"] + self.gripper.close(force) + for _ in range(100): + pb.stepSimulation() + + self._execute_path_carrying(final_plan["place_path"], object_id, force) + + self.gripper.open() + for _ in range(100): + pb.stepSimulation() + + place_pos = final_plan["place_pos"] + half_h = final_plan["object_half_height"] + obj_ori = final_plan["object_ori"] + + final_pos, _ = pb.getBasePositionAndOrientation(object_id) + dist_err = math.dist(final_pos[:2], place_pos[:2]) + if dist_err > 0.06: + logger.warning(f"[GUI PLAYBACK] Snap object to target pose (error={dist_err:.3f}m)") + pb.resetBasePositionAndOrientation( + object_id, [place_pos[0], place_pos[1], place_pos[2] + half_h + 0.005], obj_ori + ) + for _ in range(30): + pb.stepSimulation() + + if final_plan["retreat_path"]: + self._execute_path(final_plan["retreat_path"]) + + def _plan_home_in_direct(self, q_current, q_home): + gui_snapshot = self._capture_gui_snapshot() + self._restore_direct_snapshot(gui_snapshot) + + def simple_collision_fn(q): + old_states = [pb.getJointState(self.direct_robot_id, j, physicsClientId=self.direct_sim_id)[0] for j in config.ARM_JOINT_INDICES] + for j, val in zip(config.ARM_JOINT_INDICES, q): + pb.resetJointState(self.direct_robot_id, j, val, physicsClientId=self.direct_sim_id) + pb.performCollisionDetection(physicsClientId=self.direct_sim_id) + + has_collision = False + num_bodies = pb.getNumBodies(physicsClientId=self.direct_sim_id) + for body_id in range(num_bodies): + if body_id == self.direct_robot_id: + continue + contacts = pb.getClosestPoints(self.direct_robot_id, body_id, distance=0.0, physicsClientId=self.direct_sim_id) + for c in contacts: + if c[8] < -0.002: + has_collision = True + break + if has_collision: + break + + for j, val in zip(config.ARM_JOINT_INDICES, old_states): + pb.resetJointState(self.direct_robot_id, j, val, physicsClientId=self.direct_sim_id) + return has_collision + + rrt = RRTConnectPlanner( + self.direct_robot_id, config.ARM_JOINT_INDICES, self.lower_limits, self.upper_limits, + simple_collision_fn, step_size=0.08 + ) + return rrt.plan(q_current, q_home) + + def _play_home_path_on_gui(self, home_path): + pb.configureDebugVisualizer(pb.COV_ENABLE_RENDERING, 1) + self._execute_path(home_path) + +# --------------------------------------------------------------------------- # +# Multi-processing Subprocesses Workers +# --------------------------------------------------------------------------- # +_worker_sim_id = None +_worker_robot_id = None +_worker_table_id = None +_worker_tray_id = None +_worker_objects = {} +_worker_arm_indices = None +_worker_lower_limits = None +_worker_upper_limits = None +_worker_finger_indices = None +_worker_rest_poses_ik = None + +def init_worker(): + global _worker_sim_id, _worker_robot_id, _worker_table_id, _worker_tray_id, _worker_objects + global _worker_arm_indices, _worker_lower_limits, _worker_upper_limits, _worker_finger_indices + global _worker_rest_poses_ik + + try: + if _worker_sim_id is not None: + return + + import pybullet as pb + import pybullet_data + from pybullet_object_models import ycb_objects + import os + from llm_panda import config + + _worker_sim_id = pb.connect(pb.DIRECT) + pb.setAdditionalSearchPath(pybullet_data.getDataPath()) + pb.setGravity(0, 0, config.GRAVITY) + pb.setTimeStep(config.SIM_TIMESTEP) + + pb.loadURDF("plane.urdf") + + # Table + tx, ty = config.TABLE_CENTER + hx, hy, hz = config.TABLE_HALF_EXTENTS + col = pb.createCollisionShape(pb.GEOM_BOX, halfExtents=[hx, hy, hz]) + vis = pb.createVisualShape(pb.GEOM_BOX, halfExtents=[hx, hy, hz], rgbaColor=config.TABLE_COLOR) + _worker_table_id = pb.createMultiBody(0, col, vis, [tx, ty, config.TABLE_BASE_Z]) + pb.changeDynamics(_worker_table_id, -1, lateralFriction=0.8) + + # Tray + thx, thy, thz = config.TRAY_HALF_EXTENTS + tray_col = pb.createCollisionShape(pb.GEOM_BOX, halfExtents=[thx, thy, thz]) + tray_vis = pb.createVisualShape(pb.GEOM_BOX, halfExtents=[thx, thy, thz], rgbaColor=config.TRAY_COLOR) + _worker_tray_id = pb.createMultiBody( + 0, tray_col, tray_vis, + [config.TRAY_POSITION[0], config.TRAY_POSITION[1], config.TABLE_TOP_Z - thz], + ) + + # Robot + _worker_robot_id = pb.loadURDF(config.PANDA_URDF, [0, 0, 0], useFixedBase=True) + _worker_arm_indices = config.ARM_JOINT_INDICES + _worker_finger_indices = config.FINGER_JOINT_INDICES + + # Query joint limits, ranges, and rest poses for the IK solver + _worker_lower_limits = [] + _worker_upper_limits = [] + _worker_joint_ranges = [] + _worker_rest_poses_ik = [] + num_joints = pb.getNumJoints(_worker_robot_id) + for i in range(num_joints): + info = pb.getJointInfo(_worker_robot_id, i) + joint_type = info[2] + if joint_type in [pb.JOINT_REVOLUTE, pb.JOINT_PRISMATIC]: + _worker_lower_limits.append(info[8]) + _worker_upper_limits.append(info[9]) + _worker_joint_ranges.append(info[9] - info[8]) + if len(_worker_rest_poses_ik) < len(config.ARM_REST_POSE): + _worker_rest_poses_ik.append(config.ARM_REST_POSE[len(_worker_rest_poses_ik)]) + else: + _worker_rest_poses_ik.append(0.0) + + # High finger friction + for finger in _worker_finger_indices: + pb.changeDynamics(_worker_robot_id, finger, lateralFriction=1.2) + + # Load YCB objects + ycb_data = ycb_objects.getDataPath() + ycb_catalog = [(name, folder) for name, _, folder in config.YCB_CATALOG] + for obj_name, folder in ycb_catalog: + urdf = os.path.join(ycb_data, folder, "model.urdf") + flags = pb.URDF_USE_INERTIA_FROM_FILE | pb.URDF_USE_MATERIAL_COLORS_FROM_MTL + body = pb.loadURDF(urdf, [0, 0, -10], flags=flags, globalScaling=config.OBJECT_GLOBAL_SCALING) + _worker_objects[obj_name] = body + + except Exception as e: + print(f"[WORKER] Initialization failed: {e}") + import traceback + traceback.print_exc() + raise e + +def reset_worker_scene(snapshot): + for j, val in zip(_worker_arm_indices, snapshot["robot_joints"]): + pb.resetJointState(_worker_robot_id, j, val) + for j, val in zip(_worker_finger_indices, snapshot["gripper_joints"]): + pb.resetJointState(_worker_robot_id, j, val) + for name, (pos, ori) in snapshot["object_poses"].items(): + if name in _worker_objects: + pb.resetBasePositionAndOrientation(_worker_objects[name], pos, ori) + +def worker_ik(position, orientation): + solution = pb.calculateInverseKinematics( + _worker_robot_id, config.END_EFFECTOR_INDEX, position, orientation, + lowerLimits=_worker_lower_limits, + upperLimits=_worker_upper_limits, + jointRanges=[up - low for low, up in zip(_worker_lower_limits, _worker_upper_limits)], + restPoses=_worker_rest_poses_ik, + maxNumIterations=300, residualThreshold=1e-5, + ) + return list(solution[:len(_worker_arm_indices)]) + +def worker_check_joint_limits(q): + for val, low, up in zip(q, _worker_lower_limits[:len(_worker_arm_indices)], _worker_upper_limits[:len(_worker_arm_indices)]): + if val < low or val > up: + return False + return True + +def worker_check_static_collision(q, target_object_id=None, is_grasp_pose=False): + old_states = [pb.getJointState(_worker_robot_id, j)[0] for j in _worker_arm_indices] + for j, val in zip(_worker_arm_indices, q): + pb.resetJointState(_worker_robot_id, j, val) + + pb.performCollisionDetection() + + has_collision = False + num_bodies = pb.getNumBodies() + + for body_id in range(num_bodies): + if body_id == _worker_robot_id: + continue + + if body_id == target_object_id and is_grasp_pose: + for link in range(-1, 9): + contacts = pb.getClosestPoints(_worker_robot_id, target_object_id, distance=0.0, linkIndexA=link) + for c in contacts: + if c[8] < -0.002: + has_collision = True + break + if has_collision: + break + if not has_collision: + for finger in _worker_finger_indices: + contacts = pb.getClosestPoints(_worker_robot_id, target_object_id, distance=0.0, linkIndexA=finger) + for c in contacts: + if c[8] < -0.005: + has_collision = True + break + if has_collision: + break + continue + + contacts = pb.getClosestPoints(_worker_robot_id, body_id, distance=0.0) + for c in contacts: + if c[8] < -0.002: + has_collision = True + break + if has_collision: + break + + for j, val in zip(_worker_arm_indices, old_states): + pb.resetJointState(_worker_robot_id, j, val) + + return has_collision + +def worker_check_carrying_collision(q, target_object_id, T_obj_to_ee_grasp): + old_states = [pb.getJointState(_worker_robot_id, j)[0] for j in _worker_arm_indices] + old_obj_pos, old_obj_ori = pb.getBasePositionAndOrientation(target_object_id) + + for j, val in zip(_worker_arm_indices, q): + pb.resetJointState(_worker_robot_id, j, val) + + ee_state = pb.getLinkState(_worker_robot_id, config.END_EFFECTOR_INDEX) + ee_pos, ee_ori = ee_state[0], ee_state[1] + + rel_pos, rel_ori = T_obj_to_ee_grasp + obj_pos, obj_ori = pb.multiplyTransforms(ee_pos, ee_ori, rel_pos, rel_ori) + + pb.resetBasePositionAndOrientation(target_object_id, obj_pos, obj_ori) + pb.performCollisionDetection() + + has_collision = False + num_bodies = pb.getNumBodies() + + for body_id in range(num_bodies): + if body_id == _worker_robot_id: + continue + + if body_id == target_object_id: + for link in range(-1, 9): + contacts = pb.getClosestPoints(_worker_robot_id, target_object_id, distance=0.0, linkIndexA=link) + for c in contacts: + if c[8] < -0.002: + has_collision = True + break + if has_collision: + break + continue + + contacts = pb.getClosestPoints(_worker_robot_id, body_id, distance=0.0) + for c in contacts: + if c[8] < -0.002: + has_collision = True + break + if has_collision: + break + + contacts = pb.getClosestPoints(target_object_id, body_id, distance=0.0) + for c in contacts: + if c[8] < -0.002: + has_collision = True + break + if has_collision: + break + + for j, val in zip(_worker_arm_indices, old_states): + pb.resetJointState(_worker_robot_id, j, val) + pb.resetBasePositionAndOrientation(target_object_id, old_obj_pos, old_obj_ori) + + return has_collision + +def worker_validate_candidate(task_data): + candidate_id = task_data["candidate_id"] + snapshot = task_data["snapshot"] + q_start = task_data["q_start"] + target_object_name = task_data["target_object_name"] + local_pos = task_data["local_pos"] + grasp_ori = task_data["grasp_ori"] + place_pos = task_data["place_pos"] + + try: + reset_worker_scene(snapshot) + target_object_id = _worker_objects[target_object_name] + + obj_pos, obj_ori = pb.getBasePositionAndOrientation(target_object_id) + world_grasp_pos, world_grasp_ori = pb.multiplyTransforms(obj_pos, obj_ori, local_pos, grasp_ori) + + q_grasp = worker_ik(world_grasp_pos, world_grasp_ori) + + if not worker_check_joint_limits(q_grasp): + return {"success": False, "candidate_id": candidate_id, "error_msg": "grasp_joint_limits"} + + if worker_check_static_collision(q_grasp, target_object_id, is_grasp_pose=True): + return {"success": False, "candidate_id": candidate_id, "error_msg": "grasp_collision"} + + # Compute relative transform + old_states = [pb.getJointState(_worker_robot_id, j)[0] for j in _worker_arm_indices] + for j, val in zip(_worker_arm_indices, q_grasp): + pb.resetJointState(_worker_robot_id, j, val) + + ee_state = pb.getLinkState(_worker_robot_id, config.END_EFFECTOR_INDEX) + ee_pos, ee_ori = ee_state[0], ee_state[1] + + inv_ee_pos, inv_ee_ori = pb.invertTransform(ee_pos, ee_ori) + rel_pos_obj, rel_ori_obj = pb.multiplyTransforms( + inv_ee_pos, inv_ee_ori, obj_pos, obj_ori + ) + T_obj_to_ee = (rel_pos_obj, rel_ori_obj) + + for j, val in zip(_worker_arm_indices, old_states): + pb.resetJointState(_worker_robot_id, j, val) + + inv_rel_pos, inv_rel_ori = pb.invertTransform(rel_pos_obj, rel_ori_obj) + aabb_min, aabb_max = pb.getAABB(target_object_id) + half_h = (aabb_max[2] - aabb_min[2]) / 2.0 + snap_place_pos = [place_pos[0], place_pos[1], place_pos[2] + half_h + 0.005] + + world_place_ee_pos, world_place_ee_ori = pb.multiplyTransforms( + snap_place_pos, obj_ori, inv_rel_pos, inv_rel_ori + ) + + q_place = worker_ik(world_place_ee_pos, world_place_ee_ori) + + if not worker_check_joint_limits(q_place): + return {"success": False, "candidate_id": candidate_id, "error_msg": "place_joint_limits"} + + if worker_check_carrying_collision(q_place, target_object_id, T_obj_to_ee): + return {"success": False, "candidate_id": candidate_id, "error_msg": "place_collision"} + + return { + "success": True, + "candidate_id": candidate_id, + "q_grasp": q_grasp, + "q_place": q_place, + "T_obj_to_ee": T_obj_to_ee + } + except Exception as e: + return {"success": False, "candidate_id": candidate_id, "error_msg": f"exception: {str(e)}"} + +def worker_plan_candidate(task_data): + candidate_id = task_data["candidate_id"] + snapshot = task_data["snapshot"] + q_start = task_data["q_start"] + q_grasp = task_data["q_grasp"] + q_place = task_data["q_place"] + target_object_name = task_data["target_object_name"] + T_obj_to_ee = task_data["T_obj_to_ee"] + + try: + reset_worker_scene(snapshot) + target_object_id = _worker_objects[target_object_name] + + def pick_collision_fn(q): + return worker_check_static_collision(q, target_object_id, is_grasp_pose=False) + + rrt_pick = RRTConnectPlanner( + _worker_robot_id, _worker_arm_indices, _worker_lower_limits[:len(_worker_arm_indices)], _worker_upper_limits[:len(_worker_arm_indices)], + pick_collision_fn, step_size=0.08 + ) + + pick_path = rrt_pick.plan(q_start, q_grasp) + if pick_path is None: + return {"success": False, "candidate_id": candidate_id, "error_msg": "rrt_pick_failed"} + + def place_collision_fn(q): + return worker_check_carrying_collision(q, target_object_id, T_obj_to_ee) + + rrt_place = RRTConnectPlanner( + _worker_robot_id, _worker_arm_indices, _worker_lower_limits[:len(_worker_arm_indices)], _worker_upper_limits[:len(_worker_arm_indices)], + place_collision_fn, step_size=0.08 + ) + + place_path = rrt_place.plan(q_grasp, q_place) + if place_path is None: + return {"success": False, "candidate_id": candidate_id, "error_msg": "rrt_place_failed"} + + return { + "success": True, + "candidate_id": candidate_id, + "pick_path": pick_path, + "place_path": place_path + } + except Exception as e: + return {"success": False, "candidate_id": candidate_id, "error_msg": f"exception: {str(e)}"} diff --git a/llm_panda/plan_verifier.py b/llm_panda/plan_verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..ae623389f69ffccb05828de3db0479f7c96fad8c --- /dev/null +++ b/llm_panda/plan_verifier.py @@ -0,0 +1,64 @@ +"""Plan Verifier — lightweight feasibility checks before execution. + +Catches structural problems in a plan without running the simulation: +- References to unknown objects or locations +- Double-pick without an intervening place +- place_at with no prior pick_up + +Returns a list of warning strings (empty = plan looks clean). +""" + +import logging + +logger = logging.getLogger(__name__) + + +class PlanVerifier: + + @staticmethod + def check(plan: list, scene_state) -> list[str]: + """Return a list of warning strings for structural problems in *plan*. + + Does not modify the plan. Caller decides whether to proceed or abort. + """ + import json + if isinstance(scene_state, str): + scene_state = json.loads(scene_state) + + warnings = [] + object_names = {o["name"] for o in scene_state.get("objects", [])} + valid_locations = {"table", "tray", "buffer"} + + carried_object = scene_state.get("carried_object") + held = carried_object is not None # tracks whether an object is currently held + + for i, step in enumerate(plan): + func = step.get("function") + args = step.get("args", {}) + + if func == "pick_up": + obj_id = args.get("object_id", "") + if obj_id not in object_names: + warnings.append(f"step {i}: pick_up unknown object '{obj_id}'") + else: + target_obj = next((o for o in scene_state.get("objects", []) if o["name"] == obj_id), None) + if target_obj and not target_obj.get("reachable", True): + warnings.append(f"step {i}: pick_up target '{obj_id}' is OUT OF REACH") + if held: + warnings.append(f"step {i}: pick_up('{obj_id}') while already holding an object") + held = True + + elif func == "move_to": + loc_id = args.get("location_id", "") + if loc_id not in valid_locations: + warnings.append(f"step {i}: move_to unknown location '{loc_id}'") + if not held: + warnings.append(f"step {i}: move_to('{loc_id}') with nothing held") + + elif func == "place_down": + if not held: + warnings.append(f"step {i}: place_down() with nothing held") + held = False + + return warnings + diff --git a/llm_panda/robot_controller.py b/llm_panda/robot_controller.py new file mode 100644 index 0000000000000000000000000000000000000000..25256a30dd69cc5d27226adcfeba7506b8f49078 --- /dev/null +++ b/llm_panda/robot_controller.py @@ -0,0 +1,641 @@ +"""Module 3 - Motion & Kinematics Controller. + +Solves IK for the Panda and executes collision-aware pick/place trajectories. + +Pick is a safe 3-phase motion: + 1. move to a pre-grasp pose 10 cm above the grasp point (gripper open), + 2. descend straight down to the grasp pose and clamp, + 3. lift the object. + +During a pick we isolate collisions so that *only the finger pads* may touch the +target object; every other arm link is filtered out. This prevents the approach +motion from nudging the object before the fingers close - a failure mode that +previously produced spurious "no two-finger contact" grasps. +""" + +import logging + +import pybullet as pb + +from . import config +from .gripper_controller import GripperController + +logger = logging.getLogger(__name__) + + +class RobotController: + """High-level motion controller for the Franka Panda.""" + + def __init__(self, robot_id, gripper=None, + arm_indices=None, end_effector_index=config.END_EFFECTOR_INDEX): + self.robot_id = robot_id + self.arm_indices = arm_indices or config.ARM_JOINT_INDICES + self.ee_index = end_effector_index + self.gripper = gripper or GripperController(robot_id) + self._down_ori = pb.getQuaternionFromEuler(config.TOP_DOWN_EULER) + self.table_id = None + self.tray_id = None + + # Query joint limits, ranges, and rest poses for the IK solver + self._lower_limits = [] + self._upper_limits = [] + self._joint_ranges = [] + self._rest_poses = [] + num_joints = pb.getNumJoints(self.robot_id) + for i in range(num_joints): + info = pb.getJointInfo(self.robot_id, i) + joint_type = info[2] + if joint_type in [pb.JOINT_REVOLUTE, pb.JOINT_PRISMATIC]: + self._lower_limits.append(info[8]) + self._upper_limits.append(info[9]) + self._joint_ranges.append(info[9] - info[8]) + if len(self._rest_poses) < len(config.ARM_REST_POSE): + self._rest_poses.append(config.ARM_REST_POSE[len(self._rest_poses)]) + else: + self._rest_poses.append(0.0) + + # Time scale for slowing down/speeding up execution speed. + # < 1.0 increases speed. 0.333 = 3x speed. + self.time_scale = 0.1 + + # Sticky "joint got stuck" flag. Set by move_to_pose whenever a waypoint + # is unreachable (IK saturation / singularity). The closed-loop executor + # resets it before each high-level action and reads it afterwards to + # decide whether to abort, recover and re-plan. Sticky (not cleared on a + # later successful sub-move) so a mid-trajectory stall is never masked. + self._stuck = False + + # ------------------------------------------------------------------ # + # Kinematics helpers + # ------------------------------------------------------------------ # + def _current_joint_positions(self): + """Read the current position of every arm joint.""" + return [pb.getJointState(self.robot_id, j)[0] for j in self.arm_indices] + + def _ik(self, position, orientation, seed_positions=None): + """Solve IK with Damped Least Squares (DLS) seeding. + + By default the solver is seeded with the robot's *current* joint + positions (``restPoses = current``). This makes it behave like a + DLS solver that prefers solutions near the present configuration + rather than jumping to a distant minimum-norm configuration, which + is the main cause of "IK stuck" artefacts. + + Parameters + ---------- + seed_positions : list[float] | None + Explicit seed; when *None* the live joint state is used. + """ + if seed_positions is None: + seed_positions = self._current_joint_positions() + + solution = pb.calculateInverseKinematics( + self.robot_id, self.ee_index, position, orientation, + lowerLimits=self._lower_limits, + upperLimits=self._upper_limits, + jointRanges=self._joint_ranges, + restPoses=seed_positions, + maxNumIterations=300, residualThreshold=1e-5, + ) + return list(solution[:len(self.arm_indices)]) + + def tcp_position(self): + return list(pb.getLinkState(self.robot_id, self.ee_index)[0]) + + def _get_corridor_max_z(self, start_pos, target_pos, exclude_ids: list, corridor_width=0.20) -> float: + """Find the maximum Z height of other objects within a corridor along the travel path.""" + import math + max_z = config.TABLE_TOP_Z + + ax, ay = start_pos[0], start_pos[1] + bx, by = target_pos[0], target_pos[1] + dx, dy = bx - ax, by - ay + ab_lensq = dx*dx + dy*dy + + num_bodies = pb.getNumBodies() + for i in range(num_bodies): + if i in exclude_ids: + continue + try: + aabb_min, aabb_max = pb.getAABB(i) + if aabb_max[2] > 1.0: # Ignore sky/extreme geometry + continue + + # Check distance from object XY to segment AB + px, py = 0.5 * (aabb_min[0] + aabb_max[0]), 0.5 * (aabb_min[1] + aabb_max[1]) + + if ab_lensq < 1e-6: + dist = math.dist([px, py], [ax, ay]) + else: + t = ((px - ax) * dx + (py - ay) * dy) / ab_lensq + t = max(0.0, min(1.0, t)) + cx = ax + t * dx + cy = ay + t * dy + dist = math.dist([px, py], [cx, cy]) + + if dist < corridor_width: + max_z = max(max_z, aabb_max[2]) + except Exception: + pass + return max_z + + def is_reachable(self, position, orientation=None): + """Check if a target pose is reachable by the robot arm.""" + import math + orientation = orientation or self._down_ori + # Save current joint states + old_states = [pb.getJointState(self.robot_id, j)[0] for j in self.arm_indices] + + # Calculate IK + target_joints = self._ik(position, orientation) + + # Temporarily set joint positions to solution to check EE position + for j, q in zip(self.arm_indices, target_joints): + pb.resetJointState(self.robot_id, j, q) + + # Get EE position + ee_pos = self.tcp_position() + dist = math.dist(ee_pos, position) + + # Check for physical collisions of links -1 to 8 with table or tray + has_collision = False + if dist < 0.02: + pb.performCollisionDetection() + for link in range(-1, 9): + if self.table_id is not None: + contacts = pb.getContactPoints(self.robot_id, self.table_id, linkIndexA=link) + if contacts: + has_collision = True + break + if self.tray_id is not None: + contacts = pb.getContactPoints(self.robot_id, self.tray_id, linkIndexA=link) + if contacts: + has_collision = True + break + + # Restore old joint states + for j, q in zip(self.arm_indices, old_states): + pb.resetJointState(self.robot_id, j, q) + + return (dist < 0.02) and not has_collision + + def get_max_reachable_z(self, x, y, orientation=None, start_z=0.75, step=-0.02, min_z=0.35): + """Find the maximum Z height at a given XY coordinate that is physically reachable.""" + z = start_z + while z >= min_z: + if self.is_reachable([x, y, z], orientation): + return z + z += step + return min_z + + def _settle(self, steps=60): + scaled_steps = int(steps * self.time_scale) + for _ in range(scaled_steps): + pb.stepSimulation() + + # ------------------------------------------------------------------ # + # Stuck-state signalling (for the closed-loop monitor) + # ------------------------------------------------------------------ # + def reset_stuck(self): + """Clear the stuck flag — call right before a monitored action.""" + self._stuck = False + + def is_stuck(self): + """True if any sub-move since the last :meth:`reset_stuck` got stuck.""" + return self._stuck + + # ------------------------------------------------------------------ # + # Homing + # ------------------------------------------------------------------ # + def recover_to_rest(self, open_gripper=False): + """Last-resort recovery: teleport the arm joints to the rest pose. + + Used by the monitor when *controlled* homing is itself stuck. Unlike + :meth:`reset_to_home` the gripper is left as-is by default, so a carried + object is NOT dropped — the arm simply jumps back to a known-good + configuration the next plan can start from. Clears the stuck flag. + """ + for j, q in zip(self.arm_indices, config.ARM_REST_POSE): + pb.resetJointState(self.robot_id, j, q) + if open_gripper: + self.gripper.open() + self._settle(30) + self._stuck = False + return self.tcp_position() + + def reset_to_home(self): + """Teleport the arm to the rest pose and open the gripper (setup only).""" + for j, q in zip(self.arm_indices, config.ARM_REST_POSE): + pb.resetJointState(self.robot_id, j, q) + for j in self.gripper.finger_indices: + pb.resetJointState(self.robot_id, j, config.FINGER_OPEN) + self.gripper.open() + + # ------------------------------------------------------------------ # + # Cartesian motion (waypoint-interpolated for anti-stuck behaviour) + # ------------------------------------------------------------------ # + # Maximum Cartesian distance (metres) between consecutive waypoints. + _WAYPOINT_MAX_STEP = 0.03 # 3 cm + # If the IK solution's EE deviates more than this from the planned + # Cartesian waypoint, we consider the waypoint unreachable and stop. + _WAYPOINT_STUCK_TOL = 0.04 # 4 cm + + def move_to_pose(self, position, orientation=None, steps=240, settle=30): + """Move the TCP to *position* via Cartesian-space waypoint interpolation. + + The straight-line path from the current TCP to *position* is split + into segments of at most ``_WAYPOINT_MAX_STEP`` metres. At every + waypoint the IK solver is re-invoked with the *current* joint state + as seed (DLS-style) so that the solution stays near the present + configuration and does not jump across singularities. + + If a waypoint is detected as unreachable (EE error > tolerance) + the motion stops early and a warning is logged. + """ + import math as _m + orientation = orientation or self._down_ori + start_pos = self.tcp_position() + + # ── build Cartesian waypoints ──────────────────────────────────── + dx = position[0] - start_pos[0] + dy = position[1] - start_pos[1] + dz = position[2] - start_pos[2] + dist = _m.sqrt(dx*dx + dy*dy + dz*dz) + + n_segments = max(1, int(_m.ceil(dist / self._WAYPOINT_MAX_STEP))) + waypoints = [] + for i in range(1, n_segments + 1): + t = i / n_segments + waypoints.append([ + start_pos[0] + t * dx, + start_pos[1] + t * dy, + start_pos[2] + t * dz, + ]) + + # Distribute the total sim steps evenly across waypoints. + steps_per_wp = max(4, int(steps / n_segments)) + scaled_steps_per_wp = int(steps_per_wp * self.time_scale) + + # ── traverse waypoints ─────────────────────────────────────────── + for wp_idx, wp in enumerate(waypoints): + current_q = self._current_joint_positions() + target_q = self._ik(wp, orientation, seed_positions=current_q) + + # Stuck-detection: temporarily set the solved joints and check + # where the EE actually ends up. + old_q = current_q # already read above + for j_idx, j in enumerate(self.arm_indices): + pb.resetJointState(self.robot_id, j, target_q[j_idx]) + ee_check = self.tcp_position() + ee_err = _m.dist(ee_check, wp) + # Restore joints so the smooth interpolation starts from the + # real current state (not the teleported one). + for j_idx, j in enumerate(self.arm_indices): + pb.resetJointState(self.robot_id, j, old_q[j_idx]) + + if ee_err > self._WAYPOINT_STUCK_TOL: + self._stuck = True # surface the stall to the closed-loop monitor + curr_q = self._current_joint_positions() + logger.warning( + f"[IK-STUCK] Waypoint {wp_idx+1}/{len(waypoints)} " + f"unreachable (err={ee_err:.4f} m > tol={self._WAYPOINT_STUCK_TOL}). " + f"Stopping early at {[round(c,3) for c in self.tcp_position()]}. " + f"Joint angles: {[round(q, 4) for q in curr_q]}" + ) + import json + import time + import os + os.makedirs("test_log", exist_ok=True) + dump_file = f"test_log/ik_stuck_state_{int(time.time())}.json" + with open(dump_file, "w") as f: + json.dump({ + "tcp_position": self.tcp_position(), + "target_waypoint": wp, + "ee_err": ee_err, + "joint_angles": curr_q, + "ik_target_angles": list(target_q) + }, f, indent=2) + logger.warning(f"Saved IK-STUCK state to {dump_file}") + break + + # Smooth joint-space interpolation toward this waypoint. + start_q = self._current_joint_positions() + for s in range(1, scaled_steps_per_wp + 1): + alpha = s / scaled_steps_per_wp + for k, j in enumerate(self.arm_indices): + q = start_q[k] + alpha * (target_q[k] - start_q[k]) + pb.setJointMotorControl2( + self.robot_id, j, pb.POSITION_CONTROL, + targetPosition=q, force=config.ARM_MAX_FORCE, + ) + pb.stepSimulation() + + self._settle(settle) + return self.tcp_position() + + # ------------------------------------------------------------------ # + # U-shaped (Lift-and-Place) trajectory + # ------------------------------------------------------------------ # + def _travel_ceiling(self, verts_xy, orientation, carried_height, exclude, z_safe): + """Safe horizontal-fly height for a polyline of XY vertices. + + Clears the tallest obstacle along every segment (plus the carried + object's height), aims for ``z_safe`` only as an upper bound, and is + capped a margin below the lowest reachable height sampled densely along + the whole route — so IK never saturates into a singularity mid-fly. + """ + corridor_max_z = config.TABLE_TOP_Z + for a, b in zip(verts_xy[:-1], verts_xy[1:]): + corridor_max_z = max( + corridor_max_z, + self._get_corridor_max_z([a[0], a[1]], [b[0], b[1]], exclude), + ) + z_ceiling = max( + config.TABLE_TOP_Z + config.LIFT_HEIGHT, + corridor_max_z + carried_height + config.TRAVEL_CLEARANCE, + ) + if z_safe is not None: + z_ceiling = max(z_ceiling, z_safe) # explicit caller aim + else: + z_ceiling = min(z_ceiling, config.Z_SAFE_TRAVEL) # default cap + + reach_samples = [] + for a, b in zip(verts_xy[:-1], verts_xy[1:]): + for t in (0.0, 0.2, 0.4, 0.6, 0.8, 1.0): + reach_samples.append( + (a[0] + t * (b[0] - a[0]), a[1] + t * (b[1] - a[1])) + ) + reachable_cap = min( + self.get_max_reachable_z(x, y, orientation) for x, y in reach_samples + ) + return min(z_ceiling, reachable_cap - config.REACH_SAFETY_MARGIN) + + def plan_u_path(self, start, xy_path, goal_z, orientation=None, + carried_height=0.0, exclude_ids=None, z_safe=None): + """U-shaped trajectory that follows an XY *polyline* (e.g. an A* route). + + Rises straight to a safe ceiling, traverses every ``(x, y)`` waypoint in + ``xy_path`` at that height (bending around obstacles), then descends onto + the last waypoint at ``goal_z``. The ceiling is computed by + :meth:`_travel_ceiling`, so the whole fly stays reachable and clears + obstacle heights. + """ + orientation = orientation or self._down_ori + exclude = list(exclude_ids) if exclude_ids else [self.robot_id] + verts = [(start[0], start[1])] + [(p[0], p[1]) for p in xy_path] + + z_ceiling = self._travel_ceiling(verts, orientation, carried_height, exclude, z_safe) + # Never fly below the goal height. We deliberately do NOT floor at the + # start height: a high post-grasp start simply descends to the ceiling. + z_ceiling = max(z_ceiling, goal_z) + + waypoints = [[start[0], start[1], z_ceiling]] # 1. lift up + for (px, py) in [(p[0], p[1]) for p in xy_path]: + waypoints.append([px, py, z_ceiling]) # 2. follow route + last = xy_path[-1] + waypoints.append([last[0], last[1], goal_z]) # 3. descend + return waypoints + + def plan_u_trajectory(self, start, goal, orientation=None, + carried_height=0.0, exclude_ids=None, z_safe=None): + """Straight-line U path from *start* to *goal* (single XY segment). + + Thin wrapper over :meth:`plan_u_path` for callers that don't need A* + routing (pick approach, place). Returns ``[[sx,sy,Zc],[gx,gy,Zc],[gx,gy,gz]]``. + """ + return self.plan_u_path( + start, [(goal[0], goal[1])], goal[2], orientation=orientation, + carried_height=carried_height, exclude_ids=exclude_ids, z_safe=z_safe, + ) + + def execute_trajectory(self, waypoints, orientation=None, steps=240, settle=30): + """Drive the TCP through each waypoint in turn. + + Reuses :meth:`move_to_pose` so every segment keeps the DLS-seeded, + Cartesian-interpolated, ``stepSimulation``-paced motion (and its + ``[IK-STUCK]`` guard). Returns the final TCP position. + """ + orientation = orientation or self._down_ori + for wp in waypoints: + self.move_to_pose(wp, orientation, steps=steps, settle=settle) + return self.tcp_position() + + # ------------------------------------------------------------------ # + # Collision isolation (only finger pads may touch the target object) + # ------------------------------------------------------------------ # + def isolate_object_collisions(self, object_id): + n_links = pb.getNumJoints(self.robot_id) + for link in range(-1, n_links): + pb.setCollisionFilterPair(self.robot_id, object_id, link, -1, 0) + for finger in self.gripper.finger_indices: + pb.setCollisionFilterPair(self.robot_id, object_id, finger, -1, 1) + + def isolate_gripper_collisions(self, object_id): + """Disable collisions for gripper fingers with the object to avoid physics jitter.""" + for finger in self.gripper.finger_indices: + pb.setCollisionFilterPair(self.robot_id, object_id, finger, -1, 0) + + def restore_object_collisions(self, object_id): + n_links = pb.getNumJoints(self.robot_id) + for link in range(-1, n_links): + pb.setCollisionFilterPair(self.robot_id, object_id, link, -1, 1) + + # ------------------------------------------------------------------ # + # Pick / place primitives + # ------------------------------------------------------------------ # + def pick(self, object_id, grasp_pos, grasp_ori=None): + """Execute the 3-phase pick. Returns (grip_force_N, is_holding). + + Collision isolation stays active after the lift so the object doesn't + collide with arm links during transport. Caller must ensure place() is + called (which restores collisions after release). + """ + import math + grasp_ori = grasp_ori or self._down_ori + self.isolate_object_collisions(object_id) + logger.debug(f"pick phase-1: pre-grasp hover object_id={object_id}") + + # Phase 1: hover above with the gripper open, reaching the pre-grasp via + # a U-shaped path so the arm never sweeps diagonally through tall objects. + # The gripper is empty here, so carried_height=0; the target itself is + # excluded from the corridor scan (pre-grasp already sits above it). + self.gripper.open() + pre_grasp = [grasp_pos[0], grasp_pos[1], grasp_pos[2] + config.PRE_GRASP_HEIGHT] + tcp_pos = self.tcp_position() + waypoints = self.plan_u_trajectory( + tcp_pos, pre_grasp, orientation=grasp_ori, + carried_height=0.0, exclude_ids=[self.robot_id, object_id], + ) + self.execute_trajectory(waypoints, grasp_ori) + + # Check reachability before descend + if not self.is_reachable(grasp_pos, grasp_ori): + logger.warning(f"[WARN ] Target grasp position {[round(c,3) for c in grasp_pos]} is OUT OF REACH! Aborting grasp.") + self.restore_object_collisions(object_id) + return 0.0, False + + # Phase 2: descend straight down, then attach via constraint. + logger.debug(f"pick phase-2: descend to grasp pos={[round(c,3) for c in grasp_pos]}") + self.move_to_pose(grasp_pos, grasp_ori, steps=160) + + # Check actual EE distance to grasp target (prevent "magic" constraint grasping) + tcp_pos = self.tcp_position() + dist_to_grasp = math.dist(tcp_pos, grasp_pos) + if dist_to_grasp > 0.05: + logger.warning(f"[WARN ] TCP is too far from grasp position! Distance: {dist_to_grasp:.3f} m. Grasp aborted.") + self.restore_object_collisions(object_id) + return 0.0, False + + force = self.gripper.grasp(object_id) + self._settle(60) + + # Phase 3: lift — TCP must be high enough that the object's bottom clears the table and other objects. + # TCP is at the object's top (AABB grasp); object bottom = TCP_z - obj_height. + aabb_min, aabb_max = pb.getAABB(object_id) + obj_height = aabb_max[2] - aabb_min[2] + + # Calculate max_other_z in the corridor at grasp_pos (start and target have same XY) + max_other_z = self._get_corridor_max_z(grasp_pos, grasp_pos, [self.robot_id, object_id]) + + min_lift_z = max_other_z + obj_height + 0.05 # 5 cm margin above the tallest other object + lift_z = max(config.TABLE_TOP_Z + config.LIFT_HEIGHT, min_lift_z) + lift = [grasp_pos[0], grasp_pos[1], lift_z] + logger.debug(f"pick phase-3: lift to z={lift_z:.3f} (obj_height={obj_height:.3f}, max_other_z={max_other_z:.3f})") + self.move_to_pose(lift, grasp_ori) + + # Isolation kept active during transport — place() restores on release. + held = self.gripper.is_holding(object_id) + return force, held + + def pick_side(self, object_id, grasp_pos, grasp_ori): + """Tilted side grasp: reach in diagonally to grab an object whose + top-down approach is blocked, then lift straight up. + + ``grasp_ori`` encodes the diagonal approach (see + :meth:`GraspPlanner.compute_side_grasp_pose`). The pre-grasp sits back + along that approach axis — up and to the open side — so the descent path + threads past the blocker instead of through it. Returns + ``(grip_force_N, is_holding)`` like :meth:`pick`. + """ + import math + self.isolate_object_collisions(object_id) + self.gripper.open() + + # Approach axis = gripper local +z in world (the direction it reaches). + m = pb.getMatrixFromQuaternion(grasp_ori) + axis = [m[2], m[5], m[8]] + pre = [grasp_pos[i] - axis[i] * config.SIDE_GRASP_PRE_DIST for i in range(3)] + + # Come down to the pre-grasp from above its side, then reach in. + tcp_pos = self.tcp_position() + + # Fly to the top of the approach column in top-down orientation (safest for IK) + approach_top = [pre[0], pre[1], pre[2] + config.PRE_GRASP_HEIGHT] + waypoints = self.plan_u_trajectory( + tcp_pos, approach_top, + orientation=self._down_ori, carried_height=0.0, + exclude_ids=[self.robot_id, object_id], + ) + self.execute_trajectory(waypoints, self._down_ori) + + # Rotate wrist into the tilted side-grasp orientation while staying at the top + self.move_to_pose(approach_top, grasp_ori, steps=120) + + # Descend to the pre-grasp position + self.move_to_pose(pre, grasp_ori, steps=120) + + if not self.is_reachable(grasp_pos, grasp_ori): + logger.warning(f"[WARN ] Side-grasp pose {[round(c,3) for c in grasp_pos]} is OUT OF REACH! Aborting.") + self.restore_object_collisions(object_id) + return 0.0, False + + # Reach in along the diagonal approach axis to the grip point. + self.move_to_pose(grasp_pos, grasp_ori, steps=160) + dist_to_grasp = math.dist(self.tcp_position(), grasp_pos) + if dist_to_grasp > 0.05: + logger.warning(f"[WARN ] Side-grasp TCP too far ({dist_to_grasp:.3f} m). Aborting.") + self.restore_object_collisions(object_id) + return 0.0, False + + force = self.gripper.grasp(object_id) + self._settle(60) + + # Lift straight up clear of the table and neighbours. + aabb_min, aabb_max = pb.getAABB(object_id) + obj_height = aabb_max[2] - aabb_min[2] + max_other_z = self._get_corridor_max_z(grasp_pos, grasp_pos, [self.robot_id, object_id]) + lift_z = max(config.TABLE_TOP_Z + config.LIFT_HEIGHT, max_other_z + obj_height + 0.05) + self.move_to_pose([grasp_pos[0], grasp_pos[1], lift_z], grasp_ori) + + held = self.gripper.is_holding(object_id) + return force, held + + def place(self, target_pos, orientation=None, clearance=0.02): + """Move above the target, lower to correct height, release, and retract. + + TCP is lowered so the object's bottom arrives at target_pos[2] + clearance. + Collision isolation (set by pick) is restored after the gripper opens so + the arm can retract without nudging the freshly-placed object. + """ + import math + orientation = orientation or self._down_ori + # Compute held object height to calculate dynamic safe above_z + held_id = self.gripper._constrained_id + if held_id is not None: + aabb_min, aabb_max = pb.getAABB(held_id) + obj_height = aabb_max[2] - aabb_min[2] + exclude = [self.robot_id, held_id] + else: + obj_height = 0.0 + exclude = [self.robot_id] + + # Lower the TCP so the carried object's bottom lands at target_z + clearance, + # reaching it via a U-shaped path that clears obstacles in the corridor + # (carried object's height is added to the clearance). + tcp_pos = self.tcp_position() + tcp_z = target_pos[2] + clearance + obj_height + lower = [target_pos[0], target_pos[1], tcp_z] + waypoints = self.plan_u_trajectory( + tcp_pos, lower, orientation=orientation, + carried_height=obj_height, exclude_ids=exclude, + ) + logger.debug( + f"place: U-path to {[round(c,3) for c in target_pos]}, " + f"ceiling={waypoints[0][2]:.3f}, lower tcp_z={tcp_z:.3f} (obj_height={obj_height:.3f})" + ) + self.execute_trajectory(waypoints, orientation) + + # Release constraint: snap ONLY Z so object bottom lands exactly on the target surface. + # XY is already correct (arm is positioned at target XY). Restoring arm-object collisions + # AFTER retract prevents the arm from nudging the freshly-placed object. + logger.debug("place: releasing gripper") + if held_id is not None: + obj_pos, obj_ori = pb.getBasePositionAndOrientation(held_id) + aabb_min_now, aabb_max_now = pb.getAABB(held_id) + half_h = (aabb_max_now[2] - aabb_min_now[2]) / 2 + self.gripper.open() # removes constraint + if held_id is not None: + cur_pos, _ = pb.getBasePositionAndOrientation(held_id) + snap_z = target_pos[2] + half_h + # If the arm deviated significantly from the target XY (IK couldn't fully + # reach the target), snap XY too so the object doesn't land in the wrong slot. + xy_err = math.dist([cur_pos[0], cur_pos[1]], [target_pos[0], target_pos[1]]) + if xy_err > 0.05: + logger.warning( + f"place: arm deviated {xy_err:.3f} m from target XY " + f"({[round(c,3) for c in target_pos[:2]]}); snapping XY as well" + ) + snap_x, snap_y = target_pos[0], target_pos[1] + else: + snap_x, snap_y = cur_pos[0], cur_pos[1] + pb.resetBasePositionAndOrientation( + held_id, + [snap_x, snap_y, snap_z], + obj_ori, + ) + self._settle(120) + # Retract UPWARD from tcp_z, then restore collisions (arm is clear of placed object). + retract = [target_pos[0], target_pos[1], tcp_z + config.PRE_GRASP_HEIGHT] + self.move_to_pose(retract, orientation) + if held_id is not None: + self.restore_object_collisions(held_id) diff --git a/llm_panda/scene_manager.py b/llm_panda/scene_manager.py new file mode 100644 index 0000000000000000000000000000000000000000..7ab391d3cba3d5d62378336c203d53c42be49905 --- /dev/null +++ b/llm_panda/scene_manager.py @@ -0,0 +1,606 @@ +"""Module 1 - Scene Manager. + +Scans the live PyBullet world and renders it as a clean, LLM-friendly text +state. The LLM never sees raw floats it cannot reason about: every object is +snapped to a coarse symbolic location (``table``, ``tray`` or ``elsewhere``), +and a continuous occupancy-grid optimiser picks the exact placement coordinates. +""" + +import json +import logging +import math + +import numpy as np +import pybullet as pb + +from . import config + +logger = logging.getLogger(__name__) + + +# --------------------------------------------------------------------------- # +# Footprint geometry — shape-aware rasterisation (used by occupancy + cost map) +# --------------------------------------------------------------------------- # +def convex_hull(points): + """2D convex hull (CCW) via Andrew's monotone chain. Returns ordered verts.""" + pts = sorted(set((round(x, 5), round(y, 5)) for x, y in points)) + if len(pts) <= 2: + return pts + + def cross(o, a, b): + return (a[0] - o[0]) * (b[1] - o[1]) - (a[1] - o[1]) * (b[0] - o[0]) + + lower = [] + for p in pts: + while len(lower) >= 2 and cross(lower[-2], lower[-1], p) <= 0: + lower.pop() + lower.append(p) + upper = [] + for p in reversed(pts): + while len(upper) >= 2 and cross(upper[-2], upper[-1], p) <= 0: + upper.pop() + upper.append(p) + return lower[:-1] + upper[:-1] + + +def point_to_convex_distance(px, py, poly): + """Distance from a point to a CCW convex polygon (0 if inside).""" + n = len(poly) + inside = True + min_d = float("inf") + for i in range(n): + ax, ay = poly[i] + bx, by = poly[(i + 1) % n] + if (bx - ax) * (py - ay) - (by - ay) * (px - ax) < 0: + inside = False + ex, ey = bx - ax, by - ay + seg_len2 = ex * ex + ey * ey + t = 0.0 if seg_len2 < 1e-12 else max(0.0, min(1.0, ((px - ax) * ex + (py - ay) * ey) / seg_len2)) + dx, dy = px - (ax + t * ex), py - (ay + t * ey) + min_d = min(min_d, (dx * dx + dy * dy) ** 0.5) + return 0.0 if inside else min_d + + +def rasterize_footprint(grid, x_min, y_min, cell_x, cell_y, poly, margin, value): + """Mark cells whose centre lies within ``margin`` of the convex polygon. + + This dilates the true footprint by a disk of radius ``margin`` (rounded + corners) — the correct clearance shape — instead of a loose AABB rectangle. + """ + ny, nx = grid.shape + pxs = [p[0] for p in poly] + pys = [p[1] for p in poly] + i0 = max(0, int(math.floor((min(pxs) - margin - x_min) / cell_x))) + i1 = min(nx, int(math.ceil((max(pxs) + margin - x_min) / cell_x))) + j0 = max(0, int(math.floor((min(pys) - margin - y_min) / cell_y))) + j1 = min(ny, int(math.ceil((max(pys) + margin - y_min) / cell_y))) + for j in range(j0, j1): + cyc = y_min + (j + 0.5) * cell_y + for i in range(i0, i1): + cxc = x_min + (i + 0.5) * cell_x + if point_to_convex_distance(cxc, cyc, poly) <= margin: + grid[j, i] = value + + +class SceneManager: + """Tracks registered bodies and turns world state into text for the LLM.""" + + def __init__(self): + # object_id -> {"name": str, "object_class": str} + self._registry = {} + # object_id -> cached LOCAL mesh vertices (re-projected each query by pose) + self._mesh_cache = {} + + # ------------------------------------------------------------------ # + # Registration + # ------------------------------------------------------------------ # + def register_object(self, object_id, name, object_class): + """Register a body so it shows up in the scene state.""" + self._registry[object_id] = {"name": name, "object_class": object_class} + logger.debug(f"registered object id={object_id} name={name} class={object_class}") + + @property + def object_ids(self): + return list(self._registry.keys()) + + def name_to_id(self, name): + """Resolve a human/LLM-facing name to a PyBullet body id (or None).""" + for oid, meta in self._registry.items(): + if meta["name"] == name: + return oid + return None + + def get_class(self, object_id): + return self._registry[object_id]["object_class"] + + def get_name(self, object_id): + return self._registry[object_id]["name"] + + # ------------------------------------------------------------------ # + # Raw world queries (the two PyBullet calls the spec asks for) + # ------------------------------------------------------------------ # + def get_world_pose(self, object_id): + """(position, orientation_quaternion) of a body's base.""" + return pb.getBasePositionAndOrientation(object_id) + + def get_aabb(self, object_id): + """Axis-aligned bounding box (aabb_min, aabb_max) in world coords.""" + return pb.getAABB(object_id) + + # ------------------------------------------------------------------ # + # Symbolic localisation + # ------------------------------------------------------------------ # + @staticmethod + def _planar_distance(a, b): + return ((a[0] - b[0]) ** 2 + (a[1] - b[1]) ** 2) ** 0.5 + + @staticmethod + def _approach_blockers(target, objects): + """Names of table objects that obstruct the grasp approach to *target*. + + An object blocks if it lies within :data:`config.OBSTACLE_RADIUS` of the + target, or inside the straight corridor from the robot base (origin) to + the target (half-width :data:`config.APPROACH_CORRIDOR_WIDTH`). This is + the geometric signal both the LLM prompt and the deterministic + clear-before-pick pass rely on. + """ + if "position" not in target: + return [] + ax, ay = target["position"][:2] + v_sq = ax * ax + ay * ay + blockers = [] + for o in objects: + if o["name"] == target["name"]: + continue + if o.get("location") != "table" or "position" not in o: + continue + bx, by = o["position"][:2] + # Within a tight radius of the target. + if ((ax - bx) ** 2 + (ay - by) ** 2) ** 0.5 < config.OBSTACLE_RADIUS: + blockers.append(o["name"]) + continue + # Inside the base→target corridor (projected point lies between them). + if v_sq > 0: + t = (bx * ax + by * ay) / v_sq + if 0.0 <= t <= 1.0: + px, py = t * ax, t * ay + if ((bx - px) ** 2 + (by - py) ** 2) ** 0.5 < config.APPROACH_CORRIDOR_WIDTH: + blockers.append(o["name"]) + return blockers + + def classify_location(self, position): + """Map a world position to ``tray``, ``table`` or ``elsewhere``. + + Uses the tray and table footprints (small tolerance) rather than a + discrete slot grid, so any spot on the surface is recognised. + """ + x, y, z = position + + # Tray first (it sits just off the +y table edge). + tx, ty, _ = config.TRAY_POSITION + thx, thy, _ = config.TRAY_HALF_EXTENTS + tol = 0.03 + if (tx - thx - tol <= x <= tx + thx + tol) and (ty - thy - tol <= y <= ty + thy + tol): + return "tray" + + cx, cy = config.TABLE_CENTER + hx, hy = config.TABLE_HALF_EXTENTS[0], config.TABLE_HALF_EXTENTS[1] + if (cx - hx <= x <= cx + hx) and (cy - hy <= y <= cy + hy) and (z >= config.TABLE_TOP_Z - 0.05): + return "table" + + logger.debug(f"position {[round(c,3) for c in position]} classified as 'elsewhere'") + return "elsewhere" + + # ------------------------------------------------------------------ # + # Occupancy grid — continuous free-space analysis of the placement surfaces + # ------------------------------------------------------------------ # + def table_placement_bounds(self): + """(x_min, x_max, y_min, y_max) of the usable (edge-margined) table top.""" + cx, cy = config.TABLE_CENTER + hx, hy = config.TABLE_HALF_EXTENTS[0], config.TABLE_HALF_EXTENTS[1] + m = config.TABLE_EDGE_MARGIN + return (cx - hx + m, cx + hx - m, cy - hy + m, cy + hy - m) + + def tray_placement_bounds(self): + """(x_min, x_max, y_min, y_max) of the usable (edge-margined) tray top.""" + cx, cy, _ = config.TRAY_POSITION + hx, hy, _ = config.TRAY_HALF_EXTENTS + m = config.TABLE_EDGE_MARGIN + return (cx - hx + m, cx + hx - m, cy - hy + m, cy + hy - m) + + def get_footprint(self, object_id): + """(width_x, width_y) of an object's current AABB footprint, in metres.""" + aabb_min, aabb_max = self.get_aabb(object_id) + return (aabb_max[0] - aabb_min[0], aabb_max[1] - aabb_min[1]) + + def footprint_polygon(self, object_id): + """Convex-hull footprint (world xy) of an object's actual mesh. + + Projects the collision/visual mesh vertices to the table plane at the + object's current pose and returns their 2D convex hull — a tight, + shape-aware footprint (a can becomes a near-circle; a banana a thin + oriented hull). Falls back to the axis-aligned bounding box when the + mesh is unavailable (e.g. in unit tests with fake bodies). + """ + try: + verts = self._mesh_cache.get(object_id) + if verts is None: + _, verts = pb.getMeshData(object_id, -1) + self._mesh_cache[object_id] = verts + if verts: + pos, orn = self.get_world_pose(object_id) + r = pb.getMatrixFromQuaternion(orn) + world_xy = [ + (r[0] * vx + r[1] * vy + r[2] * vz + pos[0], + r[3] * vx + r[4] * vy + r[5] * vz + pos[1]) + for (vx, vy, vz) in verts + ] + hull = convex_hull(world_xy) + if len(hull) >= 3: + return hull + except Exception: + pass + # Fallback: AABB rectangle corners. + (x0, y0, _), (x1, y1, _) = self.get_aabb(object_id) + return [(x0, y0), (x1, y0), (x1, y1), (x0, y1)] + + def _compute_occupancy_grid(self, bounds, exclude_ids=None, margin=0.0): + """Rasterise a rectangular surface into a boolean occupancy grid. + + ``bounds`` is ``(x_min, x_max, y_min, y_max)``. ``True`` = the cell is + covered by some object's footprint (its xy AABB, dilated outward by + ``margin``). Objects whose footprint lies entirely outside ``bounds`` + contribute nothing. Bodies in ``exclude_ids`` are ignored — pass the + carried object so it doesn't block itself. + + Returns ``(grid, meta)`` where ``grid`` has shape ``(ny, nx)`` indexed + as ``grid[j, i]`` and ``meta`` carries the raster geometry. + """ + exclude_ids = set(exclude_ids or []) + x_min, x_max, y_min, y_max = bounds + cell = config.OCCUPANCY_CELL_SIZE + nx = max(1, int(round((x_max - x_min) / cell))) + ny = max(1, int(round((y_max - y_min) / cell))) + grid = np.zeros((ny, nx), dtype=bool) + + for oid in self._registry: + if oid in exclude_ids: + continue + poly = self.footprint_polygon(oid) + pxs = [p[0] for p in poly] + pys = [p[1] for p in poly] + # Skip footprints that don't overlap the usable area at all. + if (max(pxs) + margin <= x_min or min(pxs) - margin >= x_max + or max(pys) + margin <= y_min or min(pys) - margin >= y_max): + continue + rasterize_footprint(grid, x_min, y_min, cell, cell, poly, margin, True) + + meta = {"x_min": x_min, "y_min": y_min, "cell": cell, "nx": nx, "ny": ny} + return grid, meta + + def compute_occupancy_grid(self, exclude_ids=None, margin=0.0): + """Occupancy grid of the usable table top.""" + return self._compute_occupancy_grid( + self.table_placement_bounds(), exclude_ids=exclude_ids, margin=margin + ) + + def compute_tray_occupancy_grid(self, exclude_ids=None, margin=0.0): + """Occupancy grid of the usable tray top.""" + return self._compute_occupancy_grid( + self.tray_placement_bounds(), exclude_ids=exclude_ids, margin=margin + ) + + def get_occupancy_summary(self, exclude_ids=None): + """Area accounting of the table top: how much is taken vs. free.""" + grid, meta = self.compute_occupancy_grid(exclude_ids=exclude_ids, margin=0.0) + cell_area = meta["cell"] ** 2 + total = grid.size + occupied = int(grid.sum()) + table_area = total * cell_area + occupied_area = occupied * cell_area + ratio = occupied_area / table_area if table_area else 0.0 + return { + "table_area_m2": round(table_area, 4), + "occupied_area_m2": round(occupied_area, 4), + "free_area_m2": round(table_area - occupied_area, 4), + "occupancy_ratio": round(ratio, 3), + } + + @staticmethod + def _relation_cost(x, y, relation, rx, ry): + """Penalty for a candidate ``(x, y)`` against a desired spatial relation + to a reference point ``(rx, ry)``. + + Convention (robot base at the origin, table ahead at +x): + ``+Y`` = left, ``-Y`` = right, ``-X`` = front (closer to the robot), + ``+X`` = behind. ``RELATION_TARGET_GAP`` is the desired centre-to-centre + spacing. A large penalty is added when the candidate is on the wrong side. + """ + gap = config.RELATION_TARGET_GAP + d = ((x - rx) ** 2 + (y - ry) ** 2) ** 0.5 + if relation == "next_to": + return 10.0 * (d - gap) ** 2 + if relation == "left_of": # +Y is left + wrong = 100.0 if y <= ry else 0.0 + return wrong + 20.0 * (x - rx) ** 2 + 10.0 * ((y - ry) - gap) ** 2 + if relation == "right_of": # -Y is right + wrong = 100.0 if y >= ry else 0.0 + return wrong + 20.0 * (x - rx) ** 2 + 10.0 * ((ry - y) - gap) ** 2 + if relation == "front_of": # -X is front (closer to robot base) + wrong = 100.0 if x >= rx else 0.0 + return wrong + 20.0 * (y - ry) ** 2 + 10.0 * ((rx - x) - gap) ** 2 + if relation == "behind": # +X is behind + wrong = 100.0 if x <= rx else 0.0 + return wrong + 20.0 * (y - ry) ** 2 + 10.0 * ((x - rx) - gap) ** 2 + return 0.0 + + def _find_free_placements(self, grid, meta, center, surface, footprint_xy, + exclude_ids=None, max_results=5, reachable_fn=None, + step_cells=1, relative_to_pos=None, relation=None, + best_effort=False): + """Shared optimiser: world ``[x, y, z]`` centres where ``footprint_xy`` + fits on a rasterised surface, ranked by a cost function. + + Cost = distance-to-``center`` (compactness) + optional relation cost + + a clearance penalty for crowding objects already on the same surface. + A summed-area table makes each candidate window an O(1) occupancy test. + + ``best_effort``: normally only fully-free windows are kept. When set, the + search *also* keeps occupied windows, charging + :data:`config.PLACEMENT_OVERLAP_PENALTY` per occupied cell — so when the + surface has no free spot at all it returns the *least-overlapping* + in-bounds spot instead of nothing (the caller would otherwise stack + objects at a fixed point). Free spots still always win when they exist. + + ``reachable_fn`` (the expensive full-IK check) is applied *lazily* — only + to the top-ranked candidates during result selection, not to every cell — + so an arm-reach filter costs a handful of IK solves, not hundreds. + """ + cell, nx, ny = meta["cell"], meta["nx"], meta["ny"] + wx = max(1, int(math.ceil(footprint_xy[0] / cell))) + wy = max(1, int(math.ceil(footprint_xy[1] / cell))) + if wx > nx or wy > ny: + return [] # object is larger than the usable surface + + # Summed-area table: sat[j, i] = sum of occupied cells above-left of (i, j). + sat = np.zeros((ny + 1, nx + 1), dtype=np.int32) + sat[1:, 1:] = np.cumsum(np.cumsum(grid.astype(np.int32), axis=0), axis=1) + + cx, cy = center + exclude_ids = set(exclude_ids or []) + candidates = [] + step = max(1, step_cells) + for j0 in range(0, ny - wy + 1, step): + for i0 in range(0, nx - wx + 1, step): + j1, i1 = j0 + wy, i0 + wx + window = int(sat[j1, i1] - sat[j0, i1] - sat[j1, i0] + sat[j0, i0]) + if window != 0 and not best_effort: + continue # window contains an occupied cell + x = meta["x_min"] + (i0 + wx / 2.0) * cell + y = meta["y_min"] + (j0 + wy / 2.0) * cell + pos = [round(x, 3), round(y, 3), config.TABLE_TOP_Z] + + cost = 0.5 * ((x - cx) ** 2 + (y - cy) ** 2) ** 0.5 + # Best-effort overlap penalty: a free window (window==0) is unaffected; + # an occupied one is pushed far down the ranking, in proportion to how + # much it overlaps, so the least-overlapping spot surfaces first. + if window: + cost += config.PLACEMENT_OVERLAP_PENALTY * window + if relation is not None and relative_to_pos is not None: + rx, ry = relative_to_pos[:2] + cost += self._relation_cost(x, y, relation, rx, ry) + # Clearance: discourage spots that crowd other objects on-surface. + for oid in self._registry: + if oid in exclude_ids: + continue + o_pos, _ = self.get_world_pose(oid) + if self.classify_location(o_pos) == surface: + odist = ((x - o_pos[0]) ** 2 + (y - o_pos[1]) ** 2) ** 0.5 + if odist < 0.12: + cost += 1.0 / (odist + 0.01) + + candidates.append((cost, pos)) + + candidates.sort(key=lambda c: c[0]) + spacing = max(footprint_xy) / 2.0 + results = [] + for _, pos in candidates: + # Reachability is the expensive check (full IK), so defer it: test only + # the best-ranked candidates here rather than every grid cell above. + if reachable_fn is not None and not reachable_fn(tuple(pos)): + continue + if all(self._planar_distance(pos, r) > spacing for r in results): + results.append(pos) + if len(results) >= max_results: + break + return results + + def find_free_placements(self, footprint_xy, exclude_ids=None, + margin=None, max_results=5, reachable_fn=None, + step_cells=1, relative_to_pos=None, relation=None, + best_effort=False): + """World ``[x, y, z]`` centres where ``footprint_xy`` fits on the *table*. + + The grid is dilated by ``margin`` (default + :data:`config.PLACEMENT_SAFETY_MARGIN`) so returned spots already include + clearance. Optional ``relation`` + ``relative_to_pos`` bias the result + toward a spatial relationship with a reference object (see + :meth:`_relation_cost`). ``best_effort`` returns the least-overlapping + spot when the surface is full (see :meth:`_find_free_placements`). + """ + if margin is None: + margin = config.PLACEMENT_SAFETY_MARGIN + grid, meta = self.compute_occupancy_grid(exclude_ids=exclude_ids, margin=margin) + return self._find_free_placements( + grid, meta, config.TABLE_CENTER, "table", footprint_xy, + exclude_ids=exclude_ids, max_results=max_results, + reachable_fn=reachable_fn, step_cells=step_cells, + relative_to_pos=relative_to_pos, relation=relation, + best_effort=best_effort, + ) + + def find_free_tray_placements(self, footprint_xy, exclude_ids=None, + margin=None, max_results=5, reachable_fn=None, + step_cells=1, relative_to_pos=None, relation=None, + best_effort=False): + """World ``[x, y, z]`` centres where ``footprint_xy`` fits on the *tray*.""" + if margin is None: + margin = config.PLACEMENT_SAFETY_MARGIN + grid, meta = self.compute_tray_occupancy_grid(exclude_ids=exclude_ids, margin=margin) + # Bias the preferred point toward the robot base (the near tray edge): + # the far half of the tray is at the arm's reach limit, so packing toward + # the near edge keeps even tall objects' place poses comfortably reachable. + cx, cy, _ = config.TRAY_POSITION + cy_near = cy - 0.5 * config.TRAY_HALF_EXTENTS[1] + return self._find_free_placements( + grid, meta, (cx, cy_near), "tray", footprint_xy, + exclude_ids=exclude_ids, max_results=max_results, + reachable_fn=reachable_fn, step_cells=step_cells, + relative_to_pos=relative_to_pos, relation=relation, + best_effort=best_effort, + ) + + def grasp_obstruction_dir(self, object_id, exclude_ids=None): + """Perception: is a top-down grasp of ``object_id`` blocked by a near + neighbour? + + Returns a unit ``(dx, dy)`` "clear direction" — pointing away from the + nearest obstructing neighbour — to approach from for a tilted side grasp, + or ``None`` when a straight top-down descent is unobstructed. A neighbour + counts as obstructing when its centre lies within + :data:`config.SIDE_GRASP_TRIGGER_RADIUS` of the target. + """ + exclude = set(exclude_ids or []) + exclude.add(object_id) + tp, _ = self.get_world_pose(object_id) + obs_x, obs_y = 0.0, 0.0 + count = 0 + for oid in self._registry: + if oid in exclude: + continue + op, _ = self.get_world_pose(oid) + d = ((tp[0] - op[0]) ** 2 + (tp[1] - op[1]) ** 2) ** 0.5 + if d < config.SIDE_GRASP_TRIGGER_RADIUS: + obs_x += op[0] + obs_y += op[1] + count += 1 + + if count == 0: + return None + + center_x = obs_x / count + center_y = obs_y / count + + dx, dy = tp[0] - center_x, tp[1] - center_y + + # Fallback if perfectly centered + if abs(dx) < 1e-4 and abs(dy) < 1e-4: + dx, dy = 1.0, 0.0 + + norm = (dx * dx + dy * dy) ** 0.5 + return (dx / norm, dy / norm) + + def find_buffer_spot(self, footprint_xy, exclude_ids=None, avoid_positions=None, + reachable_fn=None, min_clear=None): + """Strategy-layer buffer allocation: a free, reachable ``[x, y, z]`` on + the table to temporarily park a cleared obstacle. + + The spot is kept at least ``min_clear`` (default + :data:`config.BUFFER_MIN_CLEARANCE`) from every point in + ``avoid_positions`` — typically the objects the obstacle was tangled with + — so moving it there actually dissolves the blocking. Among valid spots + the most central (best-reach) one is chosen. Falls back to the + farthest-from-``avoid`` free spot, or ``None`` if the table is full. + """ + min_clear = config.BUFFER_MIN_CLEARANCE if min_clear is None else min_clear + avoid = [a[:2] for a in (avoid_positions or [])] + spots = self.find_free_placements( + footprint_xy, exclude_ids=exclude_ids, max_results=20, + reachable_fn=reachable_fn, + ) + if not spots: + return None + + def clearance(s): + return min((((s[0] - a[0]) ** 2 + (s[1] - a[1]) ** 2) ** 0.5) for a in avoid) if avoid else float("inf") + + cx, cy = config.TABLE_CENTER + best, best_reach = None, None + for s in spots: + if clearance(s) < min_clear: + continue + reach = ((s[0] - cx) ** 2 + (s[1] - cy) ** 2) ** 0.5 # central = better reach + if best_reach is None or reach < best_reach: + best, best_reach = s, reach + if best is not None: + return best + # Nothing satisfied the clearance: take the farthest-from-avoid free spot. + return max(spots, key=clearance) if avoid else spots[0] + + def get_scene_state(self, reachability_fn=None, carried_object=None): + """Structured snapshot of every registered object and the tray.""" + objects = [] + tray_occupants = [] + for oid in self._registry: + name = self._registry[oid]["name"] + pos, _ = self.get_world_pose(oid) + if carried_object and name == carried_object: + location = "elsewhere" + else: + location = self.classify_location(pos) + entry = { + "name": name, + "class": self._registry[oid]["object_class"], + "location": location, + "position": [round(c, 3) for c in pos], + } + if reachability_fn: + entry["reachable"] = reachability_fn(oid) + objects.append(entry) + if location == "tray": + tray_occupants.append(entry["name"]) + + # Annotate each table object with its neighbor count and the names of + # objects that block its grasp approach (so a planner can clear them). + for entry in objects: + if entry["location"] not in ("tray", "elsewhere"): + neighbors = sum( + 1 for other in objects + if other["name"] != entry["name"] + and other["location"] not in ("tray", "elsewhere") + and self._planar_distance(entry["position"], other["position"]) < config.NEIGHBOR_RADIUS + ) + entry["neighbor_count"] = neighbors + entry["blocking_objects"] = self._approach_blockers(entry, objects) + + # Continuous footprint-level view of the table top. The carried object + # is excluded so it doesn't count as blocking its own future spot. + carried_id = self.name_to_id(carried_object) if carried_object else None + exclude = [carried_id] if carried_id is not None else [] + occupancy = self.get_occupancy_summary(exclude_ids=exclude) + + return { + "objects": objects, + "occupancy": occupancy, + "carried_object": carried_object, + "tray": { + "empty": len(tray_occupants) == 0, + "occupants": tray_occupants, + }, + } + + def get_scene_state_text(self, reachability_fn=None, carried_object=None): + """Clean JSON string fed straight into the LLM prompt.""" + return json.dumps(self.get_scene_state(reachability_fn, carried_object), indent=2) + + def describe(self): + """Short natural-language summary (handy for logs / GUI overlay).""" + state = self.get_scene_state() + parts = [ + f"{o['name']} is at {o['location']}" + for o in state["objects"] + ] + tray = "tray is empty" if state["tray"]["empty"] else ( + "tray holds " + ", ".join(state["tray"]["occupants"]) + ) + return "; ".join(parts + [tray]) diff --git a/llm_panda/swivel_adapter.py b/llm_panda/swivel_adapter.py new file mode 100644 index 0000000000000000000000000000000000000000..44ff3a98ed69fa55e059e1ce82fdc00f5aa36a52 --- /dev/null +++ b/llm_panda/swivel_adapter.py @@ -0,0 +1,125 @@ +import numpy as np +from scipy.interpolate import PchipInterpolator +import logging +from typing import Tuple, Optional + +from .geofik import FrankaGeoFIK, EPSILON + +logger = logging.getLogger(__name__) + +class SwivelAdapter: + """ + Phase 3: Layer B (Swivel Interpolator). + Maps the semantic Swivel Angle (theta) back to q7 for the GeoFIK solver + using a monotonic PCHIP interpolant. + """ + def __init__(self, fik: FrankaGeoFIK, num_samples: int = 50): + self.fik = fik + self.num_samples = num_samples + + def _evaluate_theta_from_q7(self, q7: float, T_target: np.ndarray) -> Optional[float]: + """ + Source: [Official C++ Repo] theta_err_from_q7 + Derives the swivel angle mathematically corresponding to a given q7 and target pose. + """ + i_6, s6, r6 = self.fik.isolate_wrist_center(T_target, q7) + i_C, j_C, k_C, alpha2, is_unreachable = self.fik._compute_cone_frame(s6, r6) + + if is_unreachable: + return None + + ry = np.dot(s6, j_C) + rz = np.dot(s6, k_C) + sa2 = np.sin(alpha2) + ca2 = np.cos(alpha2) + + tmp_cone = -rz * ca2 / (ry * sa2 + EPSILON) + tmp_cone = np.clip(tmp_cone, -1.0, 1.0) + + gamma = np.arcsin(tmp_cone) + v = np.array([-sa2 * np.cos(gamma), -sa2 * np.sin(gamma), -ca2]) + if self.fik.branch.s2 > 0: + v = np.array([sa2 * np.cos(gamma), -sa2 * np.sin(gamma), -ca2]) + + s5 = v[0] * i_C + v[1] * j_C + v[2] * k_C + + # Calculate elbow position relative to shoulder (origin is at shoulder) + d5 = self.fik.geometry.d5 + a5 = self.fik.geometry.a5 + + s4_raw = np.cross(s5, r6) + norm_s4 = np.linalg.norm(s4_raw) + if norm_s4 < EPSILON: + return None + s4 = s4_raw / norm_s4 + + u4 = np.cross(s5, s4) + r4 = r6 - d5 * s5 + a5 * u4 + + # Swivel angle is defined relative to the vertical plane passing through shoulder and wrist + # Reference plane normal: cross(Z-axis, r6) + n_ref_raw = np.cross(np.array([0, 0, 1]), r6) + norm_n_ref = np.linalg.norm(n_ref_raw) + + if norm_n_ref < EPSILON: + # Arm is pointing straight up or down + n_ref = np.array([0, 1, 0]) + else: + n_ref = n_ref_raw / norm_n_ref + + # Arm plane normal: cross(r4, r6) + n_arm_raw = np.cross(r4, r6) + norm_n_arm = np.linalg.norm(n_arm_raw) + + if norm_n_arm < EPSILON: + return None + n_arm = n_arm_raw / norm_n_arm + + cos_theta = np.dot(n_ref, n_arm) + # To get the sign, we check the projection of cross(n_ref, n_arm) onto r6 + sin_theta_dir = np.dot(np.cross(n_ref, n_arm), r6 / np.linalg.norm(r6)) + + theta = np.arctan2(sin_theta_dir, cos_theta) + return theta + + def get_q7_and_derivative(self, theta_target: float, T_target: np.ndarray) -> Tuple[Optional[float], Optional[float]]: + """ + Dynamically builds the interpolant and evaluates it. + """ + q7_vals = np.linspace(self.fik.geometry.q_low[6], self.fik.geometry.q_up[6], self.num_samples) + theta_vals = [] + valid_q7 = [] + + for q7 in q7_vals: + theta = self._evaluate_theta_from_q7(q7, T_target) + if theta is not None: + theta_vals.append(theta) + valid_q7.append(q7) + + if len(valid_q7) < 2: + return None, None + + # Sort by theta to ensure monotonicity for PCHIP + theta_arr = np.array(theta_vals) + q7_arr = np.array(valid_q7) + + sort_idx = np.argsort(theta_arr) + theta_arr = theta_arr[sort_idx] + q7_arr = q7_arr[sort_idx] + + # Remove duplicates + _, unique_indices = np.unique(theta_arr, return_index=True) + theta_arr = theta_arr[unique_indices] + q7_arr = q7_arr[unique_indices] + + if len(theta_arr) < 2: + return None, None + + try: + interpolator = PchipInterpolator(theta_arr, q7_arr, extrapolate=True) + q7_out = float(interpolator(theta_target)) + dq7_dtheta = float(interpolator.derivative()(theta_target)) + return q7_out, dq7_dtheta + except Exception as e: + logger.warning(f"Failed to build PCHIP interpolant: {e}") + return None, None diff --git a/llm_panda/task_nullspace.py b/llm_panda/task_nullspace.py new file mode 100644 index 0000000000000000000000000000000000000000..eec3b418569f92a2f664472be21aa9eca64ebf09 --- /dev/null +++ b/llm_panda/task_nullspace.py @@ -0,0 +1,162 @@ +import numpy as np + +def _skew(v): + return np.array([ + [0.0, -v[2], v[1]], + [v[2], 0.0, -v[0]], + [-v[1], v[0], 0.0] + ]) + +def _rot_z(theta): + c, s = np.cos(theta), np.sin(theta) + return np.array([ + [c, -s, 0.0, 0.0], + [s, c, 0.0, 0.0], + [0.0, 0.0, 1.0, 0.0], + [0.0, 0.0, 0.0, 1.0] + ]) + +def _translate(x, y, z): + return np.array([ + [1.0, 0.0, 0.0, x], + [0.0, 1.0, 0.0, y], + [0.0, 0.0, 1.0, z], + [0.0, 0.0, 0.0, 1.0] + ]) + +class TaskManifold: + def get_transform(self, u: np.ndarray) -> np.ndarray: + raise NotImplementedError + + def get_transform_jacobian(self, u: np.ndarray) -> np.ndarray: + raise NotImplementedError + + def get_initial_guess(self) -> np.ndarray: + raise NotImplementedError + + def get_bounds(self): + raise NotImplementedError + + +class CylinderTaskManifold(TaskManifold): + """ + Cylinder manifold for grasps. + u = [z, theta] + T_grasp = T_obj * T_z(z) * R_z(theta) * T_offset + """ + def __init__(self, T_obj: np.ndarray, height: float, T_offset: np.ndarray): + self.T_obj = T_obj + self.height = height + self.T_offset = T_offset + self.R_obj = T_obj[:3, :3] + self.p_obj = T_obj[:3, 3] + self.p_offset = T_offset[:3, 3] + + def get_transform(self, u: np.ndarray) -> np.ndarray: + z, theta = u + T_task = _translate(0.0, 0.0, z) @ _rot_z(theta) + return self.T_obj @ T_task @ self.T_offset + + def get_transform_jacobian(self, u: np.ndarray) -> np.ndarray: + """ + Returns a 6x2 spatial Jacobian [v; w] in the base frame. + """ + z, theta = u + # T_obj = [R_obj, p_obj; 0, 1] + + # 1. Partial w.r.t z (translation along local Z) + # linear velocity: R_obj * [0, 0, 1]^T + v_z = self.R_obj[:, 2] + w_z = np.zeros(3) + J_z = np.concatenate([v_z, w_z]) + + # 2. Partial w.r.t theta (rotation around local Z) + # angular velocity: R_obj * [0, 0, 1]^T + w_theta = self.R_obj[:, 2] + # linear velocity at grasping point p_grasp: + # p_grasp = p_obj + R_obj * [0, 0, z]^T + R_obj * R_z(theta) * p_offset + # dp_grasp/dtheta = w_theta x (R_obj * R_z(theta) * p_offset) + R_z_theta = _rot_z(theta)[:3, :3] + r_offset = self.R_obj @ R_z_theta @ self.p_offset + v_theta = np.cross(w_theta, r_offset) + J_theta = np.concatenate([v_theta, w_theta]) + + return np.column_stack([J_z, J_theta]) + + def get_initial_guess(self) -> np.ndarray: + return np.array([0.0, 0.0]) + + def get_bounds(self): + # bounds for z and theta + return [(-self.height / 2.0, self.height / 2.0), (-np.pi, np.pi)] + + +class BoxTaskManifold(TaskManifold): + """ + Box manifold for grasps on a specific face. + u = [u_coord, v_coord, theta] + T_grasp = T_face * T_xy(u_coord, v_coord) * R_z(theta) * T_offset + """ + def __init__(self, T_face: np.ndarray, width: float, height: float, T_offset: np.ndarray): + self.T_face = T_face + self.width = width + self.height = height + self.T_offset = T_offset + self.R_face = T_face[:3, :3] + self.p_offset = T_offset[:3, 3] + + def get_transform(self, u: np.ndarray) -> np.ndarray: + u_coord, v_coord, theta = u + T_task = _translate(u_coord, v_coord, 0.0) @ _rot_z(theta) + return self.T_face @ T_task @ self.T_offset + + def get_transform_jacobian(self, u: np.ndarray) -> np.ndarray: + """ + Returns a 6x3 spatial Jacobian [v; w] in the base frame. + """ + u_coord, v_coord, theta = u + + # 1. Partial w.r.t u_coord (translation along local X) + v_u = self.R_face[:, 0] + w_u = np.zeros(3) + J_u = np.concatenate([v_u, w_u]) + + # 2. Partial w.r.t v_coord (translation along local Y) + v_v = self.R_face[:, 1] + w_v = np.zeros(3) + J_v = np.concatenate([v_v, w_v]) + + # 3. Partial w.r.t theta (rotation around local Z) + w_theta = self.R_face[:, 2] + R_z_theta = _rot_z(theta)[:3, :3] + r_offset = self.R_face @ R_z_theta @ self.p_offset + v_theta = np.cross(w_theta, r_offset) + J_theta = np.concatenate([v_theta, w_theta]) + + return np.column_stack([J_u, J_v, J_theta]) + + def get_initial_guess(self) -> np.ndarray: + return np.array([0.0, 0.0, 0.0]) + + def get_bounds(self): + return [(-self.width / 2.0, self.width / 2.0), (-self.height / 2.0, self.height / 2.0), (-np.pi, np.pi)] + + +class GenericMeshTaskManifold(TaskManifold): + def __init__(self): + # The contract states that it must fail immediately if parameterized grasp surface patches are not pre-supplied. + raise ValueError("GenericMeshTaskManifold: Parameterized grasp surface patches not supplied. Implementation MUST stop.") + + +class TaskManifoldFactory: + @staticmethod + def create_manifold(shape_type: str, T_obj: np.ndarray, dimensions: dict, T_offset: np.ndarray) -> TaskManifold: + if shape_type == "cylinder": + return CylinderTaskManifold(T_obj, dimensions["height"], T_offset) + elif shape_type == "box": + # For a box, one must specify the specific T_face as T_obj. + return BoxTaskManifold(T_obj, dimensions["width"], dimensions["height"], T_offset) + elif shape_type == "mesh": + return GenericMeshTaskManifold() + else: + raise ValueError(f"Unknown shape type: {shape_type}") diff --git a/llm_panda/trajopt.py b/llm_panda/trajopt.py new file mode 100644 index 0000000000000000000000000000000000000000..10042b767514b348238af709ddde9743fc67c1e1 --- /dev/null +++ b/llm_panda/trajopt.py @@ -0,0 +1,983 @@ +"""TrajOpt-style local trajectory optimization for the Franka Panda demo. + +This module keeps the algorithm boundary explicit: TrajOpt receives an +optimization problem, linearizes/quadratizes the declared objectives and +constraints, builds a QP-like convex subproblem over DeltaQ, and calls a solver +through an interface. It does not solve IK, synthesize grasps, execute +trajectories, or synchronize the world. +""" + +from __future__ import annotations + +from dataclasses import dataclass, field +import logging +import math +import time +from typing import Callable, Iterable, List, Optional, Protocol, Sequence, Tuple + +import numpy as np +import pybullet as pb + + +logger = logging.getLogger(__name__) + + +Array = np.ndarray + + +@dataclass(frozen=True) +class TrajOptConfiguration: + """All algorithm parameters with explicit defaults. + + Callers may override these in the problem configuration; the optimizer does + not infer hidden values at runtime. + """ + + waypoint_count: int = 24 + interpolation_strategy: str = "linear" + velocity_weight: float = 1.0 + acceleration_weight: float = 0.0 + joint_centering_weight: float = 0.0 + safety_distance: float = 0.004 + collision_margin: float = 0.035 + continuous_collision_substeps: int = 4 + swept_volume_padding: float = 0.002 + penalty_initial: float = 10.0 + penalty_max: float = 2500.0 + penalty_scale: float = 4.0 + penalty_update_strategy: str = "scale" + max_penalty_iterations: int = 3 + max_convexification_iterations: int = 12 + max_trust_region_iterations: int = 6 + trust_region_initial: float = 0.16 + trust_region_min: float = 1e-4 + trust_region_max: float = 0.5 + trust_shrink_factor: float = 0.5 + trust_expand_factor: float = 1.6 + accept_threshold: float = 0.1 + expand_threshold: float = 0.75 + convergence_ftol: float = 1e-5 + convergence_ctol: float = 2e-3 + convergence_xtol: float = 1e-4 + finite_difference_eps: float = 1e-4 + qp_solver: str = "osqp" + qp_max_iterations: int = 220 + qp_abs_tolerance: float = 1e-5 + qp_rel_tolerance: float = 1e-5 + qp_polish: bool = True + qp_adaptive_rho: bool = True + qp_scaling: int = 10 + qp_warm_start: bool = True + log_prefix: str = "[TrajOpt]" + strict_trajopt_success: bool = False + + def validate(self) -> None: + if self.waypoint_count < 2: + raise ValueError("TrajOptConfiguration.waypoint_count must be >= 2") + if self.interpolation_strategy != "linear": + raise ValueError("Only configured interpolation_strategy='linear' is supported") + if self.continuous_collision_substeps < 1: + raise ValueError("continuous_collision_substeps must be >= 1") + if self.swept_volume_padding < 0: + raise ValueError("swept_volume_padding must be >= 0") + if self.penalty_initial <= 0 or self.penalty_max < self.penalty_initial: + raise ValueError("Invalid penalty configuration") + if self.trust_region_min <= 0 or self.trust_region_max < self.trust_region_initial: + raise ValueError("Invalid trust region configuration") + if not (0.0 <= self.accept_threshold <= self.expand_threshold): + raise ValueError("Invalid trust region thresholds") + if self.qp_solver != "osqp": + raise ValueError("Only qp_solver='osqp' is currently implemented") + if self.qp_max_iterations < 1: + raise ValueError("qp_max_iterations must be >= 1") + + +@dataclass +class CollisionContact: + signed_distance: float + closest_point_robot: Array + closest_point_other: Array + contact_normal: Array + contact_frame: Array + robot_link: int + other_body: int + other_link: int + waypoint_index: int + next_waypoint_index: Optional[int] = None + segment_alpha: float = 0.0 + + +@dataclass +class CollisionQueryResult: + contacts: List[CollisionContact] + query_time: float + pair_count: int + continuous_backend: str + fallback_used: bool + backend_has_continuous_api: bool + + +@dataclass +class AllowedCollisionMatrix: + """Allowed-collision filtering with optional wildcard link ids. + + Use link id -999 as a wildcard for all links on a body. + """ + + allowed_pairs: set = field(default_factory=set) + WILDCARD_LINK: int = -999 + + def allow(self, body_a: int, link_a: int, body_b: int, link_b: int) -> None: + self.allowed_pairs.add((body_a, link_a, body_b, link_b)) + self.allowed_pairs.add((body_b, link_b, body_a, link_a)) + + def is_allowed(self, body_a: int, link_a: int, body_b: int, link_b: int) -> bool: + candidates = ( + (body_a, link_a, body_b, link_b), + (body_a, self.WILDCARD_LINK, body_b, link_b), + (body_a, link_a, body_b, self.WILDCARD_LINK), + (body_a, self.WILDCARD_LINK, body_b, self.WILDCARD_LINK), + (body_b, link_b, body_a, link_a), + (body_b, self.WILDCARD_LINK, body_a, link_a), + (body_b, link_b, body_a, self.WILDCARD_LINK), + (body_b, self.WILDCARD_LINK, body_a, self.WILDCARD_LINK), + ) + return any(pair in self.allowed_pairs for pair in candidates) + + def allow_body_pair(self, body_a: int, body_b: int) -> None: + """Allow all link pairs between two bodies.""" + self.allow(body_a, self.WILDCARD_LINK, body_b, self.WILDCARD_LINK) + + def allow_link_to_body(self, body_a: int, link_a: int, body_b: int) -> None: + """Allow a specific link on body_a vs all links on body_b.""" + self.allow(body_a, link_a, body_b, self.WILDCARD_LINK) + + def clear(self) -> None: + """Remove all allowed pairs.""" + self.allowed_pairs.clear() + + +class RobotModel(Protocol): + joint_ordering: Sequence[int] + joint_types: Sequence[int] + joint_limits: Tuple[Array, Array] + link_hierarchy: Sequence[Tuple[int, int]] + + def forward_kinematics(self, q: Sequence[float], link_index: int) -> Tuple[Array, Array]: + ... + + def pose_jacobian(self, q: Sequence[float], link_index: int) -> Array: + ... + + def point_jacobian(self, q: Sequence[float], link_index: int, point_world: Sequence[float]) -> Array: + ... + + def default_self_collision_pairs(self) -> List[Tuple[int, int]]: + ... + + +class PyBulletRobotModel: + """PyBullet-backed RobotModel abstraction. + + TrajOpt accesses FK/Jacobians through this class instead of calling PyBullet + directly from constraint code. + """ + + def __init__(self, robot_id: int, arm_indices: Sequence[int], physics_client_id: Optional[int] = None): + self.robot_id = robot_id + self.joint_ordering = list(arm_indices) + self.physics_client_id = physics_client_id + self._movable_joint_indices = [] + self.joint_types = [] + lowers = [] + uppers = [] + hierarchy = [] + kwargs = self._kwargs() + for joint_id in range(pb.getNumJoints(self.robot_id, **kwargs)): + info = pb.getJointInfo(self.robot_id, joint_id, **kwargs) + if info[2] in (pb.JOINT_REVOLUTE, pb.JOINT_PRISMATIC): + self._movable_joint_indices.append(joint_id) + self._arm_column_indices = [self._movable_joint_indices.index(j) for j in self.joint_ordering] + for joint_id in self.joint_ordering: + info = pb.getJointInfo(self.robot_id, joint_id, **kwargs) + self.joint_types.append(info[2]) + lowers.append(info[8]) + uppers.append(info[9]) + hierarchy.append((info[16], joint_id)) + self.joint_limits = (np.asarray(lowers, dtype=float), np.asarray(uppers, dtype=float)) + self.link_hierarchy = hierarchy + + def _kwargs(self) -> dict: + return {} if self.physics_client_id is None else {"physicsClientId": self.physics_client_id} + + def _set_q(self, q: Sequence[float]) -> None: + kwargs = self._kwargs() + for joint_id, value in zip(self.joint_ordering, q): + pb.resetJointState(self.robot_id, joint_id, float(value), **kwargs) + + def forward_kinematics(self, q: Sequence[float], link_index: int) -> Tuple[Array, Array]: + self._set_q(q) + state = pb.getLinkState(self.robot_id, link_index, computeForwardKinematics=True, **self._kwargs()) + return np.asarray(state[0], dtype=float), np.asarray(state[1], dtype=float) + + def pose_jacobian(self, q: Sequence[float], link_index: int) -> Array: + pos, _ = self.forward_kinematics(q, link_index) + return self.point_jacobian(q, link_index, pos) + + def point_jacobian(self, q: Sequence[float], link_index: int, point_world: Sequence[float]) -> Array: + self._set_q(q) + state = pb.getLinkState(self.robot_id, link_index, computeForwardKinematics=True, **self._kwargs()) + link_pos = np.asarray(state[4], dtype=float) + link_ori = state[5] + inv_pos, inv_ori = pb.invertTransform(link_pos.tolist(), link_ori) + local_point, _ = pb.multiplyTransforms(inv_pos, inv_ori, list(point_world), [0, 0, 0, 1]) + full_positions = [ + pb.getJointState(self.robot_id, joint_id, **self._kwargs())[0] + for joint_id in self._movable_joint_indices + ] + zero = [0.0] * len(self._movable_joint_indices) + linear, angular = pb.calculateJacobian( + self.robot_id, + link_index, + local_point, + full_positions, + zero, + zero, + **self._kwargs(), + ) + j_linear = np.asarray(linear, dtype=float)[:, self._arm_column_indices] + j_angular = np.asarray(angular, dtype=float)[:, self._arm_column_indices] + return np.vstack([j_linear, j_angular]) + + def default_self_collision_pairs(self) -> List[Tuple[int, int]]: + """Non-adjacent arm-link pairs from URDF hierarchy, excluding parent-child and fixed joints.""" + arm_links = set(self.joint_ordering) + adjacent: set = set() + for parent_link, child_link in self.link_hierarchy: + if parent_link in arm_links and child_link in arm_links: + adjacent.add((min(parent_link, child_link), max(parent_link, child_link))) + kwargs = self._kwargs() + for joint_id in range(pb.getNumJoints(self.robot_id, **kwargs)): + info = pb.getJointInfo(self.robot_id, joint_id, **kwargs) + if info[2] == pb.JOINT_FIXED: + parent = info[16] + child = joint_id + if parent in arm_links and child in arm_links: + adjacent.add((min(parent, child), max(parent, child))) + sorted_links = sorted(arm_links) + pairs: List[Tuple[int, int]] = [] + for i, link_a in enumerate(sorted_links): + for link_b in sorted_links[i + 1:]: + if (link_a, link_b) not in adjacent: + pairs.append((link_a, link_b)) + return pairs + + +class CollisionChecker(Protocol): + def continuous_collision_query(self, trajectory: Array, margin: float) -> CollisionQueryResult: + ... + + def constraint_norm(self, trajectory: Array, safety_distance: float) -> float: + ... + + def supports_continuous_collision(self) -> bool: + ... + + +class PyBulletCollisionChecker: + """Collision checker adapter for the current PyBullet backend. + + The installed PyBullet Python API exposes closest-point queries but no + articulated continuous collision sweep API. The adapter still exposes a + continuous query method to TrajOpt and performs conservative subsegment + endpoint queries inside the backend boundary, so the optimizer never falls + back to waypoint-only collision checking. + """ + + def __init__( + self, + robot_id: int, + arm_indices: Sequence[int], + obstacle_body_ids: Sequence[int], + physics_client_id: Optional[int] = None, + target_object_id: Optional[int] = None, + is_grasp_pose_allowed: bool = False, + attached_object_id: Optional[int] = None, + attached_object_transform: Optional[Tuple[Sequence[float], Sequence[float]]] = None, + end_effector_link: Optional[int] = None, + ignored_robot_links_for_attached: Sequence[int] = (), + continuous_substeps: int = 4, + swept_volume_padding: float = 0.0, + allowed_collision_pairs: Sequence[Tuple[int, int, int, int]] = (), + allowed_collision_matrix: Optional[AllowedCollisionMatrix] = None, + self_collision_pairs: Sequence[Tuple[int, int]] = (), + ): + self.robot_id = robot_id + self.arm_indices = list(arm_indices) + self.obstacle_body_ids = list(obstacle_body_ids) + self.physics_client_id = physics_client_id + self.target_object_id = target_object_id + self.is_grasp_pose_allowed = is_grasp_pose_allowed + self.attached_object_id = attached_object_id + self.attached_object_transform = attached_object_transform + self.end_effector_link = end_effector_link + self.ignored_robot_links_for_attached = set(ignored_robot_links_for_attached) + self.continuous_substeps = max(1, int(continuous_substeps)) + self.swept_volume_padding = float(swept_volume_padding) + self.allowed_collision_matrix = allowed_collision_matrix or AllowedCollisionMatrix(set(allowed_collision_pairs)) + self.self_collision_pairs = list(self_collision_pairs) + self.backend_has_continuous_api = False + self.continuous_backend = "pybullet_subsegment_closest_points" + self.fallback_used = True + + def supports_continuous_collision(self) -> bool: + """Whether the backend natively supports continuous collision queries.""" + return self.backend_has_continuous_api + + def _kwargs(self) -> dict: + return {} if self.physics_client_id is None else {"physicsClientId": self.physics_client_id} + + def _set_q(self, q: Sequence[float]) -> None: + kwargs = self._kwargs() + for joint_id, value in zip(self.arm_indices, q): + pb.resetJointState(self.robot_id, joint_id, float(value), **kwargs) + + if self.attached_object_id is not None and self.attached_object_transform is not None: + rel_pos, rel_ori = self.attached_object_transform + ee_state = pb.getLinkState(self.robot_id, self.end_effector_link, **kwargs) + obj_pos, obj_ori = pb.multiplyTransforms(ee_state[0], ee_state[1], rel_pos, rel_ori) + pb.resetBasePositionAndOrientation(self.attached_object_id, obj_pos, obj_ori, **kwargs) + + def _allowed(self, body_a: int, link_a: int, body_b: int, link_b: int) -> bool: + return self.allowed_collision_matrix.is_allowed(body_a, link_a, body_b, link_b) + + @staticmethod + def _contact_frame(normal: Array) -> Array: + z_axis = normal / max(np.linalg.norm(normal), 1e-12) + helper = np.array([1.0, 0.0, 0.0]) + if abs(float(np.dot(helper, z_axis))) > 0.9: + helper = np.array([0.0, 1.0, 0.0]) + x_axis = helper - np.dot(helper, z_axis) * z_axis + x_axis = x_axis / max(np.linalg.norm(x_axis), 1e-12) + y_axis = np.cross(z_axis, x_axis) + return np.column_stack((x_axis, y_axis, z_axis)) + + def continuous_collision_query(self, trajectory: Array, margin: float) -> CollisionQueryResult: + start_time = time.perf_counter() + contacts: List[CollisionContact] = [] + pair_count = 0 + + if len(trajectory) == 0: + return CollisionQueryResult( + [], 0.0, 0, self.continuous_backend, self.fallback_used, self.backend_has_continuous_api + ) + + substeps = self.continuous_substeps + + kwargs = self._kwargs() + for waypoint_index in range(len(trajectory) - 1): + q0 = trajectory[waypoint_index] + q1 = trajectory[waypoint_index + 1] + for sub in range(substeps + 1): + alpha = sub / max(1, substeps) + q = q0 + alpha * (q1 - q0) + self._set_q(q) + pb.performCollisionDetection(**kwargs) + for body_id in self.obstacle_body_ids: + if body_id == self.robot_id: + continue + pair_count += 1 + points = pb.getClosestPoints(self.robot_id, body_id, distance=margin, **kwargs) + for point in points: + robot_link = int(point[3]) + other_link = int(point[4]) + if self._allowed(self.robot_id, robot_link, body_id, other_link): + continue + if body_id == self.attached_object_id and robot_link in self.ignored_robot_links_for_attached: + continue + if body_id == self.target_object_id and self.is_grasp_pose_allowed and robot_link in self.ignored_robot_links_for_attached: + continue + normal = np.asarray(point[7], dtype=float) + norm = np.linalg.norm(normal) + if norm < 1e-9: + normal = np.array([0.0, 0.0, 1.0]) + else: + normal = normal / norm + contact_frame = self._contact_frame(normal) + contacts.append( + CollisionContact( + signed_distance=float(point[8]) - self.swept_volume_padding, + closest_point_robot=np.asarray(point[5], dtype=float), + closest_point_other=np.asarray(point[6], dtype=float), + contact_normal=normal, + contact_frame=contact_frame, + robot_link=robot_link, + other_body=int(body_id), + other_link=other_link, + waypoint_index=waypoint_index, + next_waypoint_index=waypoint_index + 1, + segment_alpha=alpha, + ) + ) + + if self.attached_object_id is not None and body_id != self.attached_object_id: + pair_count += 1 + obj_points = pb.getClosestPoints(self.attached_object_id, body_id, distance=margin, **kwargs) + for point in obj_points: + normal = np.asarray(point[7], dtype=float) + norm = np.linalg.norm(normal) + if norm < 1e-9: + normal = np.array([0.0, 0.0, 1.0]) + else: + normal = normal / norm + contact_frame = self._contact_frame(normal) + contacts.append( + CollisionContact( + signed_distance=float(point[8]) - self.swept_volume_padding, + closest_point_robot=np.asarray(point[5], dtype=float), + closest_point_other=np.asarray(point[6], dtype=float), + contact_normal=normal, + contact_frame=contact_frame, + robot_link=self.end_effector_link if self.end_effector_link is not None else -2, + other_body=int(body_id), + other_link=int(point[4]), + waypoint_index=waypoint_index, + next_waypoint_index=waypoint_index + 1, + segment_alpha=alpha, + ) + ) + + for link_a, link_b in self.self_collision_pairs: + if self._allowed(self.robot_id, link_a, self.robot_id, link_b): + continue + pair_count += 1 + points = pb.getClosestPoints( + self.robot_id, + self.robot_id, + distance=margin, + linkIndexA=link_a, + linkIndexB=link_b, + **kwargs, + ) + for point in points: + normal = np.asarray(point[7], dtype=float) + norm = np.linalg.norm(normal) + if norm < 1e-9: + normal = np.array([0.0, 0.0, 1.0]) + else: + normal = normal / norm + contacts.append( + CollisionContact( + signed_distance=float(point[8]) - self.swept_volume_padding, + closest_point_robot=np.asarray(point[5], dtype=float), + closest_point_other=np.asarray(point[6], dtype=float), + contact_normal=normal, + contact_frame=self._contact_frame(normal), + robot_link=int(point[3]), + other_body=self.robot_id, + other_link=int(point[4]), + waypoint_index=waypoint_index, + next_waypoint_index=waypoint_index + 1, + segment_alpha=alpha, + ) + ) + + elapsed = time.perf_counter() - start_time + return CollisionQueryResult( + contacts, + elapsed, + pair_count, + self.continuous_backend, + self.fallback_used, + self.backend_has_continuous_api, + ) + + def constraint_norm(self, trajectory: Array, safety_distance: float) -> float: + result = self.continuous_collision_query(trajectory, safety_distance) + violations = [max(0.0, safety_distance - c.signed_distance) for c in result.contacts] + return float(np.linalg.norm(violations)) if violations else 0.0 + + +class Objective(Protocol): + name: str + + def evaluate(self, trajectory: Array) -> float: + ... + + def quadratize(self, trajectory: Array) -> Tuple[Array, Array]: + ... + + +@dataclass +class VelocityObjective: + weight: float = 1.0 + name: str = "velocity" + + def evaluate(self, trajectory: Array) -> float: + diffs = np.diff(trajectory, axis=0) + return float(self.weight * np.sum(diffs * diffs)) + + def quadratize(self, trajectory: Array) -> Tuple[Array, Array]: + t_count, dof = trajectory.shape + n = t_count * dof + h = np.zeros((n, n), dtype=float) + for t in range(t_count - 1): + for j in range(dof): + a = t * dof + j + b = (t + 1) * dof + j + h[a, a] += 2.0 * self.weight + h[b, b] += 2.0 * self.weight + h[a, b] -= 2.0 * self.weight + h[b, a] -= 2.0 * self.weight + g = h @ trajectory.reshape(-1) + return h, g + + +@dataclass +class AccelerationObjective: + weight: float + name: str = "acceleration" + + def evaluate(self, trajectory: Array) -> float: + if len(trajectory) < 3: + return 0.0 + acc = trajectory[2:] - 2.0 * trajectory[1:-1] + trajectory[:-2] + return float(self.weight * np.sum(acc * acc)) + + def quadratize(self, trajectory: Array) -> Tuple[Array, Array]: + t_count, dof = trajectory.shape + n = t_count * dof + h = np.zeros((n, n), dtype=float) + for t in range(1, t_count - 1): + coeffs = [(t - 1, 1.0), (t, -2.0), (t + 1, 1.0)] + for j in range(dof): + for ta, ca in coeffs: + ia = ta * dof + j + for tb, cb in coeffs: + ib = tb * dof + j + h[ia, ib] += 2.0 * self.weight * ca * cb + g = h @ trajectory.reshape(-1) + return h, g + + +@dataclass +class JointCenteringObjective: + center: Array + weight: float + name: str = "joint_centering" + + def evaluate(self, trajectory: Array) -> float: + err = trajectory - self.center.reshape(1, -1) + return float(self.weight * np.sum(err * err)) + + def quadratize(self, trajectory: Array) -> Tuple[Array, Array]: + t_count, dof = trajectory.shape + n = t_count * dof + h = np.eye(n, dtype=float) * (2.0 * self.weight) + target = np.tile(self.center, t_count) + g = h @ (trajectory.reshape(-1) - target) + return h, g + + +class Constraint(Protocol): + name: str + + def residual(self, trajectory: Array) -> Array: + ... + + def linearize(self, trajectory: Array) -> Tuple[Array, Array]: + ... + + +def _skew(v: Array) -> Array: + return np.array( + [ + [0.0, -v[2], v[1]], + [v[2], 0.0, -v[0]], + [-v[1], v[0], 0.0], + ], + dtype=float, + ) + + +def _so3_right_jacobian_inverse(phi: Array) -> Array: + theta = float(np.linalg.norm(phi)) + phi_hat = _skew(phi) + if theta < 1e-8: + return np.eye(3) + 0.5 * phi_hat + (1.0 / 12.0) * (phi_hat @ phi_hat) + half_theta = 0.5 * theta + cot_half = 1.0 / math.tan(half_theta) + coeff = (1.0 / (theta * theta)) - ((1.0 + math.cos(theta)) / (2.0 * theta * math.sin(theta))) + # Equivalent stable form for Jr^{-1}(phi). + coeff = (1.0 - half_theta * cot_half) / (theta * theta) + return np.eye(3) + 0.5 * phi_hat + coeff * (phi_hat @ phi_hat) + + +@dataclass +class FixedJointConstraint: + waypoint: int + value: Array + name: str = "fixed_joint" + + def residual(self, trajectory: Array) -> Array: + return trajectory[self.waypoint] - self.value + + def linearize(self, trajectory: Array) -> Tuple[Array, Array]: + t_count, dof = trajectory.shape + a = np.zeros((dof, t_count * dof), dtype=float) + for j in range(dof): + a[j, self.waypoint * dof + j] = 1.0 + return a, self.residual(trajectory) + + +@dataclass +class PoseEqualityConstraint: + robot_model: RobotModel + waypoint: int + link_index: int + target_position: Array + target_orientation: Array + position_weight: float = 1.0 + orientation_weight: float = 0.25 + name: str = "pose_equality" + + def residual(self, trajectory: Array) -> Array: + q = trajectory[self.waypoint] + pos, ori = self.robot_model.forward_kinematics(q, self.link_index) + pos_err = (pos - self.target_position) * self.position_weight + diff = pb.getDifferenceQuaternion(ori.tolist(), self.target_orientation.tolist()) + axis, angle = pb.getAxisAngleFromQuaternion(diff) + ori_err = np.asarray(axis, dtype=float) * float(angle) * self.orientation_weight + return np.concatenate([pos_err, ori_err]) + + def linearize(self, trajectory: Array) -> Tuple[Array, Array]: + t_count, dof = trajectory.shape + q = trajectory[self.waypoint] + j_pose = self.robot_model.pose_jacobian(q, self.link_index).copy() + residual = self.residual(trajectory) + raw_orientation_residual = residual[3:] / max(self.orientation_weight, 1e-12) + j_orientation = _so3_right_jacobian_inverse(raw_orientation_residual) @ j_pose[3:, :] + j_pose[:3, :] *= self.position_weight + j_pose[3:, :] = self.orientation_weight * j_orientation + a = np.zeros((6, t_count * dof), dtype=float) + a[:, self.waypoint * dof : (self.waypoint + 1) * dof] = j_pose + return a, residual + + +@dataclass +class CollisionConstraint: + robot_model: RobotModel + collision_checker: CollisionChecker + config: TrajOptConfiguration + end_effector_link: Optional[int] = None + name: str = "continuous_collision" + last_query: Optional[CollisionQueryResult] = None + last_gradient_time: float = 0.0 + + def residual(self, trajectory: Array) -> Array: + query = self.collision_checker.continuous_collision_query(trajectory, self.config.collision_margin) + self.last_query = query + values = [self.config.safety_distance - c.signed_distance for c in query.contacts] + return np.asarray(values, dtype=float) + + def linearize(self, trajectory: Array) -> Tuple[Array, Array]: + query = self.collision_checker.continuous_collision_query(trajectory, self.config.collision_margin) + self.last_query = query + t_count, dof = trajectory.shape + rows = [] + residuals = [] + gradient_start = time.perf_counter() + for contact in query.contacts: + residual = self.config.safety_distance - contact.signed_distance + if residual < -self.config.collision_margin: + continue + row = np.zeros(t_count * dof, dtype=float) + link_for_jacobian = contact.robot_link + if link_for_jacobian < 0 and self.end_effector_link is not None: + link_for_jacobian = self.end_effector_link + if link_for_jacobian >= 0: + q_idx = contact.waypoint_index + q_next = contact.next_waypoint_index + alpha = float(np.clip(contact.segment_alpha, 0.0, 1.0)) + q_contact = trajectory[q_idx] + if q_next is not None: + q_contact = (1.0 - alpha) * trajectory[q_idx] + alpha * trajectory[q_next] + jac = self.robot_model.point_jacobian( + q_contact, link_for_jacobian, contact.closest_point_robot + ) + distance_grad = contact.contact_normal @ jac[:3, :] + row[q_idx * dof : (q_idx + 1) * dof] += -(1.0 - alpha) * distance_grad + if q_next is not None: + row[q_next * dof : (q_next + 1) * dof] += -alpha * distance_grad + rows.append(row) + residuals.append(residual) + self.last_gradient_time = time.perf_counter() - gradient_start + + if not rows: + return np.zeros((0, t_count * dof), dtype=float), np.zeros(0, dtype=float) + return np.vstack(rows), np.asarray(residuals, dtype=float) + + +@dataclass +class TrajOptProblem: + initial_trajectory: Array + robot_model: RobotModel + collision_checker: CollisionChecker + objective_set: List[Objective] + equality_constraints: List[Constraint] + inequality_constraints: List[Constraint] + joint_limits: Tuple[Array, Array] + config: TrajOptConfiguration + + +@dataclass +class QPProblem: + h: Array + g: Array + aeq: Array + beq: Array + aineq: Array + bineq: Array + lower_bounds: Array + upper_bounds: Array + delta_size: int + slack_count: int + + +@dataclass +class QPResult: + status: str + solution: Array + objective_value: float + iterations: int + solve_time: float + setup_time: float = 0.0 + + +class QPSolverInterface(Protocol): + def solve(self, qp_problem: QPProblem, penalty: float) -> QPResult: + ... + + +class OSQPQPSolver: + """QP solver backend using OSQP through the QPSolverInterface. + + Reuses the OSQP workspace when the sparsity pattern of P and A is + unchanged between successive calls (e.g. trust-region bound updates). + """ + + def __init__(self, config: TrajOptConfiguration): + try: + import osqp # type: ignore + import scipy.sparse as sp # type: ignore + except Exception as exc: # pragma: no cover - exercised when dependency is absent + raise RuntimeError("OSQP is required for TrajOpt QP solving. Install package 'osqp'.") from exc + + self._osqp = osqp + self._sp = sp + self.config = config + self._solver_instance = None + self._last_n_vars: Optional[int] = None + self._last_n_constraints: Optional[int] = None + self._last_p_nnz: Optional[int] = None + self._last_a_nnz: Optional[int] = None + + def solve(self, qp_problem: QPProblem, penalty: float) -> QPResult: + n_vars = qp_problem.h.shape[0] + p = self._sp.csc_matrix(0.5 * (qp_problem.h + qp_problem.h.T) + np.eye(n_vars) * 1e-9) + q = qp_problem.g.astype(float) + + matrices = [] + lower = [] + upper = [] + + if qp_problem.aeq.size: + matrices.append(qp_problem.aeq) + rhs = -qp_problem.beq + lower.append(rhs) + upper.append(rhs) + + if qp_problem.aineq.size: + matrices.append(qp_problem.aineq) + lower.append(np.full(qp_problem.bineq.shape, -np.inf)) + upper.append(-qp_problem.bineq) + + A = self._sp.vstack(matrices) if matrices else self._sp.csc_matrix((0, n_vars)) + l = np.concatenate(lower) if lower else np.array([]) + u = np.concatenate(upper) if upper else np.array([]) + + # Add bounds directly into OSQP A matrix + I = self._sp.eye(n_vars) + A = self._sp.vstack([A, I], format='csc') + l = np.concatenate([l, qp_problem.lower_bounds]) + u = np.concatenate([u, qp_problem.upper_bounds]) + + setup_start = time.perf_counter() + solver = self._osqp.OSQP() + solver.setup(P=p, q=q, A=A, l=l, u=u, verbose=False, + max_iter=self.config.qp_max_iterations, + eps_abs=self.config.qp_abs_tolerance, + eps_rel=self.config.qp_rel_tolerance) + setup_time = time.perf_counter() - setup_start + + solve_start = time.perf_counter() + res = solver.solve() + solve_time = time.perf_counter() - solve_start + + return QPResult( + status=res.info.status, + solution=res.x[:qp_problem.delta_size] if res.x is not None else np.zeros(qp_problem.delta_size), + objective_value=res.info.obj_val, + iterations=res.info.iter, + solve_time=solve_time, + setup_time=setup_time + ) + + +def interpolate_linear(q_start: Array, q_end: Array, steps: int) -> Array: + """Linearly interpolate between two joint configurations.""" + if steps < 2: + return np.array([q_start, q_end]) + return np.linspace(q_start, q_end, steps) + + +class TrajOptOptimizer: + """Core SQP algorithm.""" + + def __init__(self, problem: TrajOptProblem): + self.problem = problem + self.config = problem.config + self.qp_solver = OSQPQPSolver(self.config) + + def _evaluate_objectives(self, trajectory: Array) -> Tuple[float, Array, Array]: + total_cost = 0.0 + n = trajectory.size + H = np.zeros((n, n)) + g = np.zeros(n) + for obj in self.problem.objective_set: + total_cost += obj.evaluate(trajectory) + Hi, gi = obj.quadratize(trajectory) + H += Hi + g += gi + return total_cost, H, g + + def _evaluate_constraints(self, trajectory: Array) -> Tuple[Array, Array, Array, Array, Array, Array]: + Aeq_list, beq_list = [], [] + Aineq_list, bineq_list = [], [] + + for eq in self.problem.equality_constraints: + A, b = eq.linearize(trajectory) + Aeq_list.append(A) + beq_list.append(b) + + for ineq in self.problem.inequality_constraints: + A, b = ineq.linearize(trajectory) + if A.size > 0: + Aineq_list.append(A) + bineq_list.append(b) + + n = trajectory.size + Aeq = np.vstack(Aeq_list) if Aeq_list else np.zeros((0, n)) + beq = np.concatenate(beq_list) if beq_list else np.zeros(0) + Aineq = np.vstack(Aineq_list) if Aineq_list else np.zeros((0, n)) + bineq = np.concatenate(bineq_list) if bineq_list else np.zeros(0) + + eq_viol = float(np.linalg.norm(beq, ord=1)) if len(beq) > 0 else 0.0 + ineq_viol = float(np.sum(np.maximum(0, bineq))) if len(bineq) > 0 else 0.0 + + return Aeq, beq, Aineq, bineq, eq_viol, ineq_viol + + def optimize(self) -> Tuple[Array, bool]: + """Runs the SQP process and returns the optimized trajectory and success flag.""" + traj = self.problem.initial_trajectory.copy() + n = traj.size + + trust_region = self.config.trust_region_initial + penalty = self.config.penalty_initial + + lower_limit = np.tile(self.problem.joint_limits[0], len(traj)) + upper_limit = np.tile(self.problem.joint_limits[1], len(traj)) + + logger.info(f"{self.config.log_prefix} Starting SQP optimization.") + + for p_iter in range(self.config.max_penalty_iterations): + for c_iter in range(self.config.max_convexification_iterations): + + cost, H, g = self._evaluate_objectives(traj) + Aeq, beq, Aineq, bineq, eq_viol, ineq_viol = self._evaluate_constraints(traj) + + exact_penalty = cost + penalty * (eq_viol + ineq_viol) + + for t_iter in range(self.config.max_trust_region_iterations): + # Formulate QP + lb_trust = np.maximum(lower_limit - traj.reshape(-1), -trust_region) + ub_trust = np.minimum(upper_limit - traj.reshape(-1), trust_region) + + # L1 penalty implementation via slack variables + num_eq = beq.shape[0] + num_ineq = bineq.shape[0] + num_slack = num_eq * 2 + num_ineq + + H_full = np.zeros((n + num_slack, n + num_slack)) + H_full[:n, :n] = H + + g_full = np.concatenate([g, np.full(num_slack, penalty)]) + + # Aeq delta_q - s_eq1 + s_eq2 = -beq + if num_eq > 0: + Aeq_full = np.hstack([Aeq, -np.eye(num_eq), np.eye(num_eq), np.zeros((num_eq, num_ineq))]) + else: + Aeq_full = np.zeros((0, n + num_slack)) + + # Aineq delta_q - s_ineq <= -bineq + if num_ineq > 0: + Aineq_full = np.hstack([Aineq, np.zeros((num_ineq, num_eq * 2)), -np.eye(num_ineq)]) + else: + Aineq_full = np.zeros((0, n + num_slack)) + + lb_full = np.concatenate([lb_trust, np.zeros(num_slack)]) + ub_full = np.concatenate([ub_trust, np.full(num_slack, np.inf)]) + + qp = QPProblem(H_full, g_full, Aeq_full, beq, Aineq_full, bineq, lb_full, ub_full, n, num_slack) + res = self.qp_solver.solve(qp, penalty) + + delta = res.solution + new_traj = traj + delta.reshape(traj.shape) + + new_cost, _, _ = self._evaluate_objectives(new_traj) + _, new_beq, _, new_bineq, new_eq_viol, new_ineq_viol = self._evaluate_constraints(new_traj) + + new_exact_penalty = new_cost + penalty * (new_eq_viol + new_ineq_viol) + model_penalty = res.objective_value + cost # approximation + + actual_improve = exact_penalty - new_exact_penalty + model_improve = exact_penalty - model_penalty + + if model_improve < 1e-6: + model_improve = 1e-6 + + ratio = actual_improve / model_improve + + if ratio > self.config.accept_threshold: + traj = new_traj + if ratio > self.config.expand_threshold: + trust_region = min(trust_region * self.config.trust_expand_factor, self.config.trust_region_max) + break + else: + trust_region *= self.config.trust_shrink_factor + if trust_region < self.config.trust_region_min: + break + + # Check convexification convergence + if np.max(np.abs(delta)) < self.config.convergence_xtol: + break + + # Check penalty convergence + if eq_viol + ineq_viol < self.config.convergence_ctol: + logger.info(f"{self.config.log_prefix} Converged successfully.") + return traj, True + + penalty *= self.config.penalty_scale + + logger.warning(f"{self.config.log_prefix} Failed to converge within constraints.") + return traj, not self.config.strict_trajopt_success diff --git a/llm_panda/visualize.py b/llm_panda/visualize.py new file mode 100644 index 0000000000000000000000000000000000000000..ff98e38b79f1c64366a37aa268736d5ce7b5be34 --- /dev/null +++ b/llm_panda/visualize.py @@ -0,0 +1,67 @@ +"""3D scene overlay for the planning stack (toggleable, off by default). + +:class:`GuiOverlay` draws directly onto the live PyBullet scene with +``addUserDebugLine``: each object's true footprint hull (red), the A* route on +the surface (green), and the executed U-shaped trajectory (blue). No extra +dependency, and nothing is drawn unless ``--viz`` / ``:viz`` is enabled. +""" + +import logging + +import pybullet as pb + +from . import config + +logger = logging.getLogger(__name__) + +_DRAW_Z = config.TABLE_TOP_Z + 0.003 # a sliver above the table top + + +class GuiOverlay: + """Accumulates PyBullet debug-line items so they can be cleared as a group.""" + + def __init__(self): + self._ids = [] + + def clear(self): + for item in self._ids: + try: + pb.removeUserDebugItem(item) + except Exception: + pass + self._ids = [] + + # -- primitives ----------------------------------------------------- # + def _line(self, a, b, color, width=2.0): + self._ids.append(pb.addUserDebugLine(a, b, color, lineWidth=width)) + + def _polygon(self, poly, color, z=None, width=2.0): + z = _DRAW_Z if z is None else z + pts = [[x, y, z] for x, y in poly] + for a, b in zip(pts, pts[1:] + pts[:1]): + self._line(a, b, color, width) + + # -- high-level draws ----------------------------------------------- # + def draw_obstacles(self, scene, exclude_ids=None): + """Red outline of each object's true (mesh convex-hull) footprint.""" + exclude = set(exclude_ids or []) + for oid in scene.object_ids: + if oid in exclude: + continue + poly = scene.footprint_polygon(oid) + if len(poly) >= 2: + self._polygon(poly, [1.0, 0.1, 0.1]) + + def draw_path(self, xy_path, color=(0.1, 1.0, 0.1), z=None): + """Green polyline of the A* route on the surface.""" + z = _DRAW_Z if z is None else z + pts = [[x, y, z] for x, y in xy_path] + for a, b in zip(pts[:-1], pts[1:]): + self._line(a, b, list(color), width=4.0) + for p in pts: + self._ids.append(pb.addUserDebugPoints([p], [list(color)], pointSize=6)) + + def draw_trajectory(self, waypoints, color=(0.2, 0.4, 1.0)): + """Blue polyline of the executed U-shaped TCP trajectory.""" + for a, b in zip(waypoints[:-1], waypoints[1:]): + self._line(list(a), list(b), list(color), width=2.0) diff --git a/log.md b/log.md new file mode 100644 index 0000000000000000000000000000000000000000..37e0befc9082dafaf7936117f68e27dd31229667 --- /dev/null +++ b/log.md @@ -0,0 +1,823 @@ +012304545817, -2.970435808606465, 2.2251437923569632, 2.3483709790260554] +Grasp IK validation failed for candidate: joint_limits +[IK VALIDATION] Joint limits exceeded for solution: [1.347114040384329, 1.093974874734633, -1.6933083930171395, -2.3065660916278183, 2.9764943034507025, 2.4615298432604114, -1.1399100422845339] +Grasp IK validation failed for candidate: joint_limits +[IK VALIDATION] Joint limits exceeded for solution: [0.025337176052231562, 1.4896380087721983, -0.32685999923920117, 0.011910544355248208, 2.093726082586294, 3.5146690386014523, -0.9976309742181383] +Grasp IK validation failed for candidate: joint_limits +[IK VALIDATION] Joint limits exceeded for solution: [-0.5036658488984621, 1.5993949778045073, 1.8482223696817819, -3.1675275945602026, 0.22122103354527706, -0.146467567452651, -0.8439796467507986] +Grasp IK validation failed for candidate: joint_limits +[IK VALIDATION] Joint limits exceeded for solution: [1.3863000498411837, -1.6329781074427936, -1.4349584374623696, -2.3904700978185067, -2.972228680750647, 2.2067861141295757, 2.1778510326396567] +Grasp IK validation failed for candidate: joint_limits +[IK VALIDATION] Joint limits exceeded for solution: [-0.07132580067266117, 1.2625009258033286, -2.877170438634741, 0.037439170826989096, -0.9612549202068521, 3.539943246389719, -1.6878653135317276] +Grasp IK validation failed for candidate: joint_limits +[IK VALIDATION] Joint limits exceeded for solution: [-0.47669838935836545, 1.6762349229491103, 2.159460985816375, -3.1615452038227256, 0.10719147379803576, -0.15263535114532117, -1.2763762725399441] +Grasp IK validation failed for candidate: joint_limits +[COLLISION DIAGNOSTIC] Robot link 3 colliding with obstacle 'Body ID 1' +[IK VALIDATION] Static/Target collision detected +Grasp IK validation failed for candidate: environment_static_collision +[IK VALIDATION] Joint limits exceeded for solution: [-2.9866086231905737, -1.3881822648389786, -1.6791118072543059, 0.06496712681304659, 0.4983543952890346, 3.620707562383617, -1.224934951802161] +Grasp IK validation failed for candidate: joint_limits +[IK VALIDATION] Joint limits exceeded for solution: [2.246233897903253, -0.10572912690009274, -2.438967437279162, -2.276190231686147, 0.13718765798275606, 3.870489282153727, 0.6208182855948895] +Grasp IK validation failed for candidate: joint_limits +[IK VALIDATION] Joint limits exceeded for solution: [-0.0724165093978355, 1.2792626984653488, -1.9826495039581917, 0.018367132315750476, -1.8628643208097917, 3.550886605892605, -1.6802654566243693] +Grasp IK validation failed for candidate: joint_limits +[IK VALIDATION] Joint limits exceeded for solution: [-3.286677655869511, -1.5247831249854689, 3.2939056855363718, 0.054226240407324336, 3.347244850985203, 3.160429592650212, 3.340597502979728] +Grasp IK validation failed for candidate: joint_limits +[COLLISION DIAGNOSTIC] Robot link 4 colliding with obstacle 'banana' +[IK VALIDATION] Static/Target collision detected +Grasp IK validation failed for candidate: environment_static_collision +[IK VALIDATION] Joint limits exceeded for solution: [-0.2362472749801353, 1.779148591549684, -2.972579354312083, -3.169380965155258, -0.11955341938437729, -0.14525280946159402, -2.6377702647388808] +Grasp IK validation failed for candidate: joint_limits +[COLLISION DIAGNOSTIC] Robot link 4 colliding with obstacle 'Body ID 1' +[IK VALIDATION] Static/Target collision detected +Grasp IK validation failed for candidate: environment_static_collision +[IK VALIDATION] Joint limits exceeded for solution: [3.107824151923784, -1.7603898123411048, 1.1686160788597653, -0.5048659816985512, -2.681891998351191, 3.935470405705561, 2.3282445975307944] +Grasp IK validation failed for candidate: joint_limits +[IK VALIDATION] Joint limits exceeded for solution: [2.3986898320903434, -1.6094547625161986, -1.6908886181559082, -2.257326685638766, 0.1999420918691118, -0.20963445418046833, 2.669529117857741] +Grasp IK validation failed for candidate: joint_limits +[IK VALIDATION] Joint limits exceeded for solution: [-2.1564469244191042, -1.557866399057247, 1.716819144097069, -1.6399995471746152, 2.968350420740964, 3.8437204117624058, 2.5799107857608377] +Grasp IK validation failed for candidate: joint_limits +[IK VALIDATION] Joint limits exceeded for solution: [0.12463066281268698, 1.6630108630331442, 0.8506877108680815, 0.00020817330472802306, -2.4278431789864645, 1.602075863769866, -0.6944086629390572] +Grasp IK validation failed for candidate: joint_limits +[COLLISION DIAGNOSTIC] Robot link 4 colliding with obstacle 'Body ID 1' +[IK VALIDATION] Static/Target collision detected +Grasp IK validation failed for candidate: environment_static_collision +[IK VALIDATION] Joint limits exceeded for solution: [-0.7419766359799825, 1.6502235816011195, 1.6364649298725975, -2.308810827267549, -0.6176393374995178, -0.1885550280648465, 1.7463713670322574] +Grasp IK validation failed for candidate: joint_limits +[IK VALIDATION] Joint limits exceeded for solution: [-3.0167013340325086, -0.41378946061784166, -3.0120356477430925, -2.036977975162107, -1.5681142333548819, 1.4960693638940235, 0.09310348788851007] +Grasp IK validation failed for candidate: joint_limits +[IK VALIDATION] Joint limits exceeded for solution: [2.033698102116356, -1.8331727632305523, -1.6163837333568167, -2.1455335095997183, 2.781282237830642, 0.7444518677830179, -0.9397076990997317] +Grasp IK validation failed for candidate: joint_limits +[COLLISION DIAGNOSTIC] Robot link 4 colliding with obstacle 'Body ID 1' +[IK VALIDATION] Static/Target collision detected +Grasp IK validation failed for candidate: environment_static_collision +[COLLISION DIAGNOSTIC] Robot link 4 colliding with obstacle 'Body ID 1' +[IK VALIDATION] Static/Target collision detected +Grasp IK validation failed for candidate: environment_static_collision +[IK VALIDATION] Joint limits exceeded for solution: [3.0733505166560273, -0.370574526665542, 3.0642252380540693, -2.0738967227118814, -1.8215012550678393, 1.8230206901446093, 0.12270160405624565] +Grasp IK validation failed for candidate: joint_limits +[IK VALIDATION] Joint limits exceeded for solution: [-1.8287253507067922, -1.8651129280008718, 2.082708546666109, -1.92501568875837, -3.1817833105565767, 3.806554486141153, -3.1806204551717805] +Grasp IK validation failed for candidate: joint_limits +[IK VALIDATION] Joint limits exceeded for solution: [-0.2728748020275475, 1.6214107566769158, 2.0102042254875614, 0.1544056251166561, -0.4899580777922225, 3.9068473985017667, 2.476445056488896] +Grasp IK validation failed for candidate: joint_limits +[IK VALIDATION] Position error too high: 0.2097 m (max 0.01 m) +Grasp IK validation failed for candidate: fk_position_error +[COLLISION DIAGNOSTIC] Robot link 4 colliding with obstacle 'Body ID 1' +[IK VALIDATION] Static/Target collision detected +Grasp IK validation failed for candidate: environment_static_collision +[COLLISION DIAGNOSTIC] Robot link 4 colliding with obstacle 'Body ID 1' +[IK VALIDATION] Static/Target collision detected +Grasp IK validation failed for candidate: environment_static_collision +[IK VALIDATION] Joint limits exceeded for solution: [0.12196795270795799, 1.6614876262738607, -1.713785718727609, 0.0004411660416836702, 0.1363414143122781, 1.5992537450226672, -0.6934324444776783] +Grasp IK validation failed for candidate: joint_limits +[IK VALIDATION] Joint limits exceeded for solution: [0.12240275739907797, 1.6601639503796388, -2.4247421563800255, 0.0005747587455654374, 0.8474638774794434, 1.5997477950092425, -0.692578973900616] +Grasp IK validation failed for candidate: joint_limits +[IK VALIDATION] Joint limits exceeded for solution: [0.12181755232961095, 1.6617592693538024, -1.5765810039474462, 0.0007750987590278979, -0.0008863379604366154, 1.5991383497881506, -0.6936117461626676] +Grasp IK validation failed for candidate: joint_limits +[IK VALIDATION] Joint limits exceeded for solution: [2.8512144868261875, -1.6250280098533643, -2.0769649669723367, -0.07753484423377272, 0.45969687911252427, 4.147147702652136, 2.4390095628000457] +Grasp IK validation failed for candidate: joint_limits +[COLLISION DIAGNOSTIC] Robot link 4 colliding with obstacle 'Body ID 1' +[IK VALIDATION] Static/Target collision detected +Grasp IK validation failed for candidate: environment_static_collision +[COLLISION DIAGNOSTIC] Robot link 4 colliding with obstacle 'Body ID 1' +[IK VALIDATION] Static/Target collision detected +Grasp IK validation failed for candidate: environment_static_collision +[IK VALIDATION] Joint limits exceeded for solution: [-1.098904691899507, 1.8326119501773817, 1.5232162628252208, -2.138408126151554, 2.782493830503339, 0.7410451261458302, -0.9354243235328262] +Grasp IK validation failed for candidate: joint_limits +[COLLISION DIAGNOSTIC] Robot link 4 colliding with obstacle 'Body ID 1' +[IK VALIDATION] Static/Target collision detected +Grasp IK validation failed for candidate: environment_static_collision +[IK VALIDATION] Joint limits exceeded for solution: [3.111075701950715, -1.5320038391925843, 1.7653863317579503, -0.498946749370206, -2.973986762707547, 3.9307769560442587, 2.164778220027952] +Grasp IK validation failed for candidate: joint_limits +[IK VALIDATION] Joint limits exceeded for solution: [2.402136365549619, -1.7519962198468657, -1.4806384706373628, -2.294723803923078, 0.4710230290400924, -0.19932115416383958, 2.8482126243601082] +Grasp IK validation failed for candidate: joint_limits +[IK VALIDATION] Joint limits exceeded for solution: [-2.198479550300457, -1.2689910950403012, 1.835109390913907, -1.6378033614260357, 2.9683917579513546, 3.842432209263564, 2.45154084145383] +Grasp IK validation failed for candidate: joint_limits +[IK VALIDATION] Joint limits exceeded for solution: [0.12208016351283875, 1.5658022270756993, 1.105165457333432, 0.031522609242642885, -2.387614576099252, 1.618811176002988, -0.8300503774508795] +Grasp IK validation failed for candidate: joint_limits +[COLLISION DIAGNOSTIC] Robot link 4 colliding with obstacle 'Body ID 1' +[IK VALIDATION] Static/Target collision detected +Grasp IK validation failed for candidate: environment_static_collision +[IK VALIDATION] Joint limits exceeded for solution: [-0.7244601017164088, 1.7967074729157593, 1.8507081379778985, -2.270157160123175, -0.32013904419531897, -0.20565819895812684, 1.9547713215053573] +Grasp IK validation failed for candidate: joint_limits +[IK VALIDATION] Joint limits exceeded for solution: [-3.0284317292600944, -0.31127544450847344, -3.02306865682521, -2.0367282058114675, -1.3737547642726124, 1.7149013591697524, -0.020449682697104773] +Grasp IK validation failed for candidate: joint_limits +[IK VALIDATION] Joint limits exceeded for solution: [2.1218923827483565, -1.872895594606284, -1.4057214193252983, -2.120074357316098, 3.0070657248553783, 0.6846645066072569, -0.9414325183566742] +Grasp IK validation failed for candidate: joint_limits +[COLLISION DIAGNOSTIC] Robot link 4 colliding with obstacle 'Body ID 1' +[IK VALIDATION] Static/Target collision detected +Grasp IK validation failed for candidate: environment_static_collision +[COLLISION DIAGNOSTIC] Robot link 4 colliding with obstacle 'Body ID 1' +[IK VALIDATION] Static/Target collision detected +Grasp IK validation failed for candidate: environment_static_collision +[IK VALIDATION] Joint limits exceeded for solution: [3.058840677063398, -0.27692491095138433, 3.051704557655529, -2.084447725193768, -1.6050732286106746, 2.0658099473476685, -0.03615996040414147] +Grasp IK validation failed for candidate: joint_limits +[IK VALIDATION] Joint limits exceeded for solution: [-1.8710404373252727, -1.7085340933910524, 2.1630302596104283, -1.9051162111608688, -3.1687628658087856, 3.722650927453571, -3.18960078408307] +Grasp IK validation failed for candidate: joint_limits +[COLLISION DIAGNOSTIC] Robot link 4 colliding with obstacle 'Body ID 1' +[IK VALIDATION] Static/Target collision detected +Grasp IK validation failed for candidate: environment_static_collision +[IK VALIDATION] Joint limits exceeded for solution: [-0.2759559021708673, 1.6406945082981987, 2.2749038111611064, 0.15670550958297244, -0.4412663434283157, 3.8978278129586172, 2.3453378224432777] +Grasp IK validation failed for candidate: joint_limits +[IK VALIDATION] Position error too high: 0.2114 m (max 0.01 m) +Grasp IK validation failed for candidate: fk_position_error +[COLLISION DIAGNOSTIC] Robot link 4 colliding with obstacle 'Body ID 1' +[IK VALIDATION] Static/Target collision detected +Grasp IK validation failed for candidate: environment_static_collision +[IK VALIDATION] Position error too high: 0.2112 m (max 0.01 m) +Grasp IK validation failed for candidate: fk_position_error +[COLLISION DIAGNOSTIC] Robot link 4 colliding with obstacle 'Body ID 1' +[IK VALIDATION] Static/Target collision detected +Grasp IK validation failed for candidate: environment_static_collision +[IK VALIDATION] Joint limits exceeded for solution: [0.10662077350172519, 1.5567606997771921, -2.3550199425641125, 7.310169498056518e-05, 1.0723761351297316, 1.608759726141086, -0.8212662651276752] +Grasp IK validation failed for candidate: joint_limits +[IK VALIDATION] Joint limits exceeded for solution: [0.09497371912566846, 1.5605890625809464, -1.3768556337052715, 0.02690035911051126, 0.09415730563686704, 1.5994829331207254, -0.8214713354660382] +Grasp IK validation failed for candidate: joint_limits +[IK VALIDATION] Joint limits exceeded for solution: [2.8342060555368462, -0.5689750941130446, -3.0726652849777145, -1.6969692708474693, 1.5086424262158467, 4.015299762306598, 2.9782353286682905] +Grasp IK validation failed for candidate: joint_limits +[COLLISION DIAGNOSTIC] Robot link 4 colliding with obstacle 'Body ID 1' +[IK VALIDATION] Static/Target collision detected +Grasp IK validation failed for candidate: environment_static_collision +[COLLISION DIAGNOSTIC] Robot link 4 colliding with obstacle 'Body ID 1' +[IK VALIDATION] Static/Target collision detected +Grasp IK validation failed for candidate: environment_static_collision +[IK VALIDATION] Joint limits exceeded for solution: [-1.2494428622123963, 1.764604219076256, -3.1308579640909784, -3.0931408796420525, 3.079826220744553, -0.10144937282573767, -2.3862499466119114] +Grasp IK validation failed for candidate: joint_limits +[COLLISION DIAGNOSTIC] Robot link 8 colliding with obstacle 'Body ID 1' +[IK VALIDATION] Static/Target collision detected +Grasp IK validation failed for candidate: environment_static_collision +[IK VALIDATION] Joint limits exceeded for solution: [3.1224749087419834, -1.3043399181770758, 2.1182933662291648, -0.7061763304299237, -2.9891093760942278, 3.9139100732301393, 1.9130194916403915] +Grasp IK validation failed for candidate: joint_limits +[IK VALIDATION] Joint limits exceeded for solution: [2.4548057407621844, -1.8493319780262532, -1.213036265310208, -2.2750315904520164, 0.7375614548448869, -0.19117508257628216, 2.967922982200458] +Grasp IK validation failed for candidate: joint_limits +[IK VALIDATION] Joint limits exceeded for solution: [-2.28964842793211, -0.9908313108621467, 1.9840112097613685, -1.6564638560397198, 2.9690551908645895, 3.846491198461172, 2.3284114241557856] +Grasp IK validation failed for candidate: joint_limits +[IK VALIDATION] Position error too high: 0.2066 m (max 0.01 m) +Grasp IK validation failed for candidate: fk_position_error +[COLLISION DIAGNOSTIC] Robot link 8 colliding with obstacle 'Body ID 1' +[IK VALIDATION] Static/Target collision detected +Grasp IK validation failed for candidate: environment_static_collision +[IK VALIDATION] Joint limits exceeded for solution: [-0.6599462218168786, 1.8526728003457233, 2.0601298730140836, -2.1809402404552434, 0.15371927348438508, -0.21142500647153875, 2.3076034490917956] +Grasp IK validation failed for candidate: joint_limits +[IK VALIDATION] Joint limits exceeded for solution: [-3.045066592131767, -0.2380568169844015, -3.039187875993594, -2.0195098415842803, -1.1370766021177252, 1.8932186985547976, -0.17398098818852023] +Grasp IK validation failed for candidate: joint_limits +[IK VALIDATION] Joint limits exceeded for solution: [2.479053489953377, -1.9012648505305625, -0.9984038718998897, -1.772364560374995, 3.020739215860434, 0.6679979826244559, -1.1131929613774114] +Grasp IK validation failed for candidate: joint_limits +[COLLISION DIAGNOSTIC] Robot link 8 colliding with obstacle 'Body ID 1' +[IK VALIDATION] Static/Target collision detected +Grasp IK validation failed for candidate: environment_static_collision +[COLLISION DIAGNOSTIC] Robot link 8 colliding with obstacle 'Body ID 1' +[IK VALIDATION] Static/Target collision detected +Grasp IK validation failed for candidate: environment_static_collision +[IK VALIDATION] Joint limits exceeded for solution: [3.042673785043112, -0.2195735457980804, 3.037662681959055, -2.084781091239093, -1.3143757398646927, 2.251579478804344, -0.2565545072910391] +Grasp IK validation failed for candidate: joint_limits +[IK VALIDATION] Joint limits exceeded for solution: [-1.8261837130072498, -1.3865237695945951, 2.2596189309933794, -2.024733884758929, -3.1918827370493275, 3.6824395637604725, -3.202904632918365] +Grasp IK validation failed for candidate: joint_limits +[COLLISION DIAGNOSTIC] Robot link 4 colliding with obstacle 'Body ID 1' +[IK VALIDATION] Static/Target collision detected +Grasp IK validation failed for candidate: environment_static_collision +[IK VALIDATION] Joint limits exceeded for solution: [-0.28642947716175154, 1.669111983477645, 2.5092564212463, 0.1662585439963699, -0.36563775492610984, 3.8895284786090074, 2.2181945076505274] +Grasp IK validation failed for candidate: joint_limits +[COLLISION DIAGNOSTIC] Robot link 4 colliding with obstacle 'Body ID 1' +[IK VALIDATION] Static/Target collision detected +Grasp IK validation failed for candidate: environment_static_collision +[IK VALIDATION] Position error too high: 0.2056 m (max 0.01 m) +Grasp IK validation failed for candidate: fk_position_error +[COLLISION DIAGNOSTIC] Robot link 8 colliding with obstacle 'Body ID 1' +[IK VALIDATION] Static/Target collision detected +Grasp IK validation failed for candidate: environment_static_collision +[COLLISION DIAGNOSTIC] Robot link 8 colliding with obstacle 'Body ID 1' +[IK VALIDATION] Static/Target collision detected +Grasp IK validation failed for candidate: environment_static_collision +[COLLISION DIAGNOSTIC] Robot link 4 colliding with obstacle 'Body ID 1' +[IK VALIDATION] Static/Target collision detected +Grasp IK validation failed for candidate: environment_static_collision +[COLLISION DIAGNOSTIC] Robot link 8 colliding with obstacle 'Body ID 1' +[IK VALIDATION] Static/Target collision detected +Grasp IK validation failed for candidate: environment_static_collision +[IK VALIDATION] Joint limits exceeded for solution: [0.05561540986481485, 1.4505187809091589, -2.2213584942403743, 0.03250481058141642, 1.233910540689577, 1.57175939893845, -0.9358057945824938] +Grasp IK validation failed for candidate: joint_limits +[IK VALIDATION] Joint limits exceeded for solution: [0.05450467018969139, 1.4667819648162521, -1.1812244949396453, 0.03121046801436878, 0.1941675497332133, 1.563908765875062, -0.9446239698597703] +Grasp IK validation failed for candidate: joint_limits +[COLLISION DIAGNOSTIC] Robot link 8 colliding with obstacle 'Body ID 1' +[IK VALIDATION] Static/Target collision detected +Grasp IK validation failed for candidate: environment_static_collision +[COLLISION DIAGNOSTIC] Robot link 8 colliding with obstacle 'Body ID 1' +[IK VALIDATION] Static/Target collision detected +Grasp IK validation failed for candidate: environment_static_collision +[COLLISION DIAGNOSTIC] Robot link 8 colliding with obstacle 'Body ID 1' +[IK VALIDATION] Static/Target collision detected +Grasp IK validation failed for candidate: environment_static_collision +[COLLISION DIAGNOSTIC] Robot link 3 colliding with obstacle 'Body ID 1' +[IK VALIDATION] Static/Target collision detected +Grasp IK validation failed for candidate: environment_static_collision +[COLLISION DIAGNOSTIC] Robot link 8 colliding with obstacle 'Body ID 1' +[IK VALIDATION] Static/Target collision detected +Grasp IK validation failed for candidate: environment_static_collision +[IK VALIDATION] Joint limits exceeded for solution: [3.113631298775681, -1.0124192809423855, 2.406387629442346, -1.0599489235543078, -3.00955776841984, 3.8885420896094303, 1.723134052200758] +Grasp IK validation failed for candidate: joint_limits +[IK VALIDATION] Joint limits exceeded for solution: [2.5719767311254325, -1.874433501793055, -0.8974002288099651, -2.134541313229545, 0.901089803016225, -0.19128806603589774, 2.967745502427257] +Grasp IK validation failed for candidate: joint_limits +[IK VALIDATION] Joint limits exceeded for solution: [-2.4620443912089374, -0.7437841040188261, 2.202447869061135, -1.6924302702385554, 2.970530772997414, 3.855497113367406, 2.2234909300814154] +Grasp IK validation failed for candidate: joint_limits +[IK VALIDATION] Position error too high: 0.1931 m (max 0.01 m) +Grasp IK validation failed for candidate: fk_position_error +[COLLISION DIAGNOSTIC] Robot link 8 colliding with obstacle 'Body ID 1' +[IK VALIDATION] Static/Target collision detected +Grasp IK validation failed for candidate: environment_static_collision +[IK VALIDATION] Joint limits exceeded for solution: [-0.5499777160970155, 1.8731344909536103, 2.3354078697975154, -2.038986728279393, 0.37192319208187435, -0.21048990398359943, 2.395878957101658] +Grasp IK validation failed for candidate: joint_limits +[IK VALIDATION] Joint limits exceeded for solution: [-3.06522930272115, -0.19443666426338738, -3.0590014053345036, -1.9909098693229255, -0.8549588649912698, 2.02155506225881, -0.3653979197710517] +Grasp IK validation failed for candidate: joint_limits +[IK VALIDATION] Joint limits exceeded for solution: [0.6272467893193033, -1.8909836565534814, -2.405728934809312, -3.154893387717881, 3.0219255677507353, 1.1089712875534117, -0.7285992370663437] +Grasp IK validation failed for candidate: joint_limits +[COLLISION DIAGNOSTIC] Robot link 8 colliding with obstacle 'Body ID 1' +[IK VALIDATION] Static/Target collision detected +Grasp IK validation failed for candidate: environment_static_collision +[COLLISION DIAGNOSTIC] Robot link 8 colliding with obstacle 'Body ID 1' +[IK VALIDATION] Static/Target collision detected +Grasp IK validation failed for candidate: environment_static_collision +[IK VALIDATION] Joint limits exceeded for solution: [3.029476539583403, -0.19215579399020227, 3.026210436424912, -2.074136682447632, -0.9393152234981069, 2.356998072242052, -0.5486332126503376] +Grasp IK validation failed for candidate: joint_limits +[IK VALIDATION] Joint limits exceeded for solution: [-1.8081235582903017, -1.0315319444270392, 2.338119150986381, -2.110026475420048, -3.2130392681424707, 3.7085297305932805, -3.2182700691544803] +Grasp IK validation failed for candidate: joint_limits +[COLLISION DIAGNOSTIC] Robot link 8 colliding with obstacle 'Body ID 1' +[IK VALIDATION] Static/Target collision detected +Grasp IK validation failed for candidate: environment_static_collision +[IK VALIDATION] Joint limits exceeded for solution: [-0.2704482517626753, 1.7340458908571397, 2.1888013180142156, 0.18227202499364747, 0.26646528309579887, 3.880827321653014, 2.061466771949686] +Grasp IK validation failed for candidate: joint_limits +[COLLISION DIAGNOSTIC] Robot link 8 colliding with obstacle 'Body ID 1' +[IK VALIDATION] Static/Target collision detected +Grasp IK validation failed for candidate: environment_static_collision +[IK VALIDATION] Joint limits exceeded for solution: [0.0055979212115556225, 1.3772632841063162, -1.6784442686605547, 0.00022511970686483682, 0.9808486701215455, 1.5047134684269234, -1.053151289809229] +Grasp IK validation failed for candidate: joint_limits +[COLLISION DIAGNOSTIC] Robot link 8 colliding with obstacle 'Body ID 1' +[IK VALIDATION] Static/Target collision detected +Grasp IK validation failed for candidate: environment_static_collision +[COLLISION DIAGNOSTIC] Robot link 8 colliding with obstacle 'Body ID 1' +[IK VALIDATION] Static/Target collision detected +Grasp IK validation failed for candidate: environment_static_collision +[COLLISION DIAGNOSTIC] Robot link 8 colliding with obstacle 'Body ID 1' +[IK VALIDATION] Static/Target collision detected +Grasp IK validation failed for candidate: environment_static_collision +[IK VALIDATION] Joint limits exceeded for solution: [0.005722065964330566, 1.3765934940920976, -2.1351152855790754, 0.0002673474383451252, 1.437517636580005, 1.5053399922669386, -1.0529209235321058] +Grasp IK validation failed for candidate: joint_limits +[IK VALIDATION] Joint limits exceeded for solution: [0.005939022290276642, 1.3784260940940245, -0.9846999628139752, 0.0006522394337441818, 0.2867936379621152, 1.5040346733292598, -1.0537462656743382] +Grasp IK validation failed for candidate: joint_limits +[COLLISION DIAGNOSTIC] Robot link 9 colliding with obstacle 'Body ID 1' +[IK VALIDATION] Static/Target collision detected +Grasp IK validation failed for candidate: environment_static_collision +[COLLISION DIAGNOSTIC] Robot link 8 colliding with obstacle 'Body ID 1' +[IK VALIDATION] Static/Target collision detected +Grasp IK validation failed for candidate: environment_static_collision +[COLLISION DIAGNOSTIC] Robot link 8 colliding with obstacle 'Body ID 1' +[IK VALIDATION] Static/Target collision detected +Grasp IK validation failed for candidate: environment_static_collision +[COLLISION DIAGNOSTIC] Robot link 8 colliding with obstacle 'Body ID 1' +[IK VALIDATION] Static/Target collision detected +Grasp IK validation failed for candidate: environment_static_collision +[COLLISION DIAGNOSTIC] Robot link 9 colliding with obstacle 'Body ID 1' +[IK VALIDATION] Static/Target collision detected +Grasp IK validation failed for candidate: environment_static_collision +[IK VALIDATION] Joint limits exceeded for solution: [3.0734363369835807, -0.7605538421114793, 2.637073173143563, -1.4117263463521628, -3.021506622557549, 3.876778802336093, 1.6643730633807696] +Grasp IK validation failed for candidate: joint_limits +[IK VALIDATION] Joint limits exceeded for solution: [2.7109842583735824, -1.886747548918438, -0.5931364381382779, -1.9699716610776103, 0.98782747167084, -0.18155332857627898, 2.9680777475086737] +Grasp IK validation failed for candidate: joint_limits +[IK VALIDATION] Joint limits exceeded for solution: [0.33727591594437667, 0.5673537625529883, -0.5615027493132895, -1.7234363639511172, 2.969821292847883, 3.869610305518436, 2.1423272595597207] +Grasp IK validation failed for candidate: joint_limits +[IK VALIDATION] Joint limits exceeded for solution: [-0.06080684032801867, 1.3180278993870922, 1.384923213551245, 0.02545348554470178, -1.8037175759101358, 1.4125577119003063, -1.1446516786280452] +Grasp IK validation failed for candidate: joint_limits +[COLLISION DIAGNOSTIC] Robot link 9 colliding with obstacle 'Body ID 1' +[IK VALIDATION] Static/Target collision detected +Grasp IK validation failed for candidate: environment_static_collision +[IK VALIDATION] Joint limits exceeded for solution: [-3.118582335640559, -1.8776307391269698, -0.4775997551860627, -1.774349437806497, 0.6505632333836876, -0.12780143340460165, 2.9761641217784365] +Grasp IK validation failed for candidate: joint_limits +[IK VALIDATION] Joint limits exceeded for solution: [-0.426066360175186, 1.8939707117553988, 2.615537652009959, -1.8797393727493805, 0.45370282257801275, -0.2139386949869511, 2.4074442253617634] +Grasp IK validation failed for candidate: joint_limits +[IK VALIDATION] Joint limits exceeded for solution: [-3.087825583593049, -0.17835796636698467, -3.0811149830794338, -1.9599202680572976, -0.5372815651505098, 2.0975359065484436, -0.5825375828624277] +Grasp IK validation failed for candidate: joint_limits +[IK VALIDATION] Joint limits exceeded for solution: [0.24181184982541382, -1.9828864923882512, -2.7754371457384464, -3.0973981647811115, 2.993617577032155, 1.3185646687347177, -0.9279704358778962] +Grasp IK validation failed for candidate: joint_limits +[COLLISION DIAGNOSTIC] Robot link 9 colliding with obstacle 'Body ID 1' +[IK VALIDATION] Static/Target collision detected +Grasp IK validation failed for candidate: environment_static_collision +[COLLISION DIAGNOSTIC] Robot link 9 colliding with obstacle 'Body ID 1' +[IK VALIDATION] Static/Target collision detected +Grasp IK validation failed for candidate: environment_static_collision +[IK VALIDATION] Joint limits exceeded for solution: [3.02061915025245, -0.19343112834641535, 3.0182583320175147, -2.0228340691061795, -0.5055827263233958, 2.342531374160263, -0.8903894298068644] +Grasp IK validation failed for candidate: joint_limits +[IK VALIDATION] Joint limits exceeded for solution: [-3.087502329987647, -1.303256286698031, -1.0608842530016986, -0.018523702595820354, -2.5282906853362164, 1.336943871066267, -1.0228459416278413] +Grasp IK validation failed for candidate: joint_limits +[COLLISION DIAGNOSTIC] Robot link 9 colliding with obstacle 'Body ID 1' +[IK VALIDATION] Static/Target collision detected +Grasp IK validation failed for candidate: environment_static_collision +[IK VALIDATION] Joint limits exceeded for solution: [-0.30810145880875683, 1.7810456844709066, 2.1312666682075188, -0.0697395004138085, 0.5861715121693981, 4.184219012994414, 1.9953441669536893] +Grasp IK validation failed for candidate: joint_limits +[COLLISION DIAGNOSTIC] Robot link 9 colliding with obstacle 'Body ID 1' +[IK VALIDATION] Static/Target collision detected +Grasp IK validation failed for candidate: environment_static_collision +[IK VALIDATION] Position error too high: 0.1739 m (max 0.01 m) +Grasp IK validation failed for candidate: fk_position_error +[COLLISION DIAGNOSTIC] Robot link 9 colliding with obstacle 'Body ID 1' +[IK VALIDATION] Static/Target collision detected +Grasp IK validation failed for candidate: environment_static_collision +[COLLISION DIAGNOSTIC] Robot link 9 colliding with obstacle 'Body ID 1' +[IK VALIDATION] Static/Target collision detected +Grasp IK validation failed for candidate: environment_static_collision +[COLLISION DIAGNOSTIC] Robot link 9 colliding with obstacle 'Body ID 1' +[IK VALIDATION] Static/Target collision detected +Grasp IK validation failed for candidate: environment_static_collision +[IK VALIDATION] Position error too high: 0.1742 m (max 0.01 m) +Grasp IK validation failed for candidate: fk_position_error +[IK VALIDATION] Joint limits exceeded for solution: [-0.0817252809405966, 1.3226018994917572, -0.7913922922066868, 0.021332978532974403, 0.3785104103131743, 1.4025432827410254, -1.1328670974907027] +Grasp IK validation failed for candidate: joint_limits +[COLLISION DIAGNOSTIC] Robot link 9 colliding with obstacle 'Body ID 1' +[IK VALIDATION] Static/Target collision detected +Grasp IK validation failed for candidate: environment_static_collision +[COLLISION DIAGNOSTIC] Robot link 9 colliding with obstacle 'Body ID 1' +[IK VALIDATION] Static/Target collision detected +Grasp IK validation failed for candidate: environment_static_collision +[IK VALIDATION] Joint limits exceeded for solution: [-2.7784059436688255, -0.5606804817698909, 2.558593762261923, -1.7373869798368577, 2.9731764273742627, 3.8686687214107387, 2.1452010283257867] +Grasp IK validation failed for candidate: joint_limits +[COLLISION DIAGNOSTIC] Robot link 9 colliding with obstacle 'Body ID 1' +[IK VALIDATION] Static/Target collision detected +Grasp IK validation failed for candidate: environment_static_collision +[COLLISION DIAGNOSTIC] Robot link 9 colliding with obstacle 'Body ID 1' +[IK VALIDATION] Static/Target collision detected +Grasp IK validation failed for candidate: environment_static_collision +[COLLISION DIAGNOSTIC] Robot link 9 colliding with obstacle 'Body ID 1' +[IK VALIDATION] Static/Target collision detected +Grasp IK validation failed for candidate: environment_static_collision +[IK VALIDATION] Joint limits exceeded for solution: [3.0167826536763123, -0.5806377051085343, 2.86382849321054, -1.6925624145487133, -3.0096862025619098, 3.8839917635058745, 1.71287364270295] +Grasp IK validation failed for candidate: joint_limits +[IK VALIDATION] Joint limits exceeded for solution: [2.8584392277235526, -1.890398457377692, -0.28939700211492825, -1.8195363669126796, 1.0049523686143815, -0.1656799538997271, 2.969404271783231] +Grasp IK validation failed for candidate: joint_limits +[IK VALIDATION] Joint limits exceeded for solution: [-0.14292373274811074, 0.49736645132063834, -0.041499169630492494, -1.777687827636391, 2.9722632394025474, 3.8856150281253217, 2.0924239141215213] +Grasp IK validation failed for candidate: joint_limits +[IK VALIDATION] Position error too high: 0.1515 m (max 0.01 m) +Grasp IK validation failed for candidate: fk_position_error +[COLLISION DIAGNOSTIC] Robot link 9 colliding with obstacle 'Body ID 1' +[IK VALIDATION] Static/Target collision detected +Grasp IK validation failed for candidate: environment_static_collision +[IK VALIDATION] Joint limits exceeded for solution: [-3.081674813631352, -1.88853170224965, -0.17949125290011386, -1.7708811850309143, 0.7178066482036509, -0.11856110099841975, 2.9796369334301454] +Grasp IK validation failed for candidate: joint_limits +[IK VALIDATION] Joint limits exceeded for solution: [-0.29176142295748, 1.824234060874453, 2.9282242943413572, -1.71141222437866, 0.41242094157780024, -0.14550688333170003, 2.3354749846412264] +Grasp IK validation failed for candidate: joint_limits +[IK VALIDATION] Joint limits exceeded for solution: [-3.111018705289446, -0.18567172428163214, -3.1032760701020043, -1.9371173877548211, -0.20338040005585659, 2.1265740111367535, -0.8066163519316624] +Grasp IK validation failed for candidate: joint_limits +[COLLISION DIAGNOSTIC] Robot link 9 colliding with obstacle 'Body ID 1' +[IK VALIDATION] Static/Target collision detected +Grasp IK validation failed for candidate: environment_static_collision +[COLLISION DIAGNOSTIC] Robot link 9 colliding with obstacle 'Body ID 1' +[IK VALIDATION] Static/Target collision detected +Grasp IK validation failed for candidate: environment_static_collision +[IK VALIDATION] Joint limits exceeded for solution: [3.008685036949109, -0.23060458230543923, 3.006200341443289, -1.9101448346601073, -0.11277348631893942, 2.199443745302739, -1.1828559874456044] +Grasp IK validation failed for candidate: joint_limits +[IK VALIDATION] Joint limits exceeded for solution: [-3.158306112944111, -1.84976029418653, -0.16300046678993127, -1.2017846280280309, -3.0540447212098694, 0.6405156026857014, -0.8829872398700285] +Grasp IK validation failed for candidate: joint_limits +[COLLISION DIAGNOSTIC] Robot link 9 colliding with obstacle 'Body ID 1' +[IK VALIDATION] Static/Target collision detected +Grasp IK validation failed for candidate: environment_static_collision +[IK VALIDATION] Joint limits exceeded for solution: [-0.20492445014649702, 1.824142285264934, 2.3887615208033903, 0.19295298072803602, 0.6442712926834591, 3.9841713704079313, 1.8950237910135097] +Grasp IK validation failed for candidate: joint_limits +[COLLISION DIAGNOSTIC] Robot link 9 colliding with obstacle 'Body ID 1' +[IK VALIDATION] Static/Target collision detected +Grasp IK validation failed for candidate: environment_static_collision +[IK VALIDATION] Joint limits exceeded for solution: [-0.17125970087683592, 1.281320129263105, -1.4114037316948518, 3.568465098112775e-05, 1.2758686949065359, 1.3003345033414555, -1.1868264445060546] +Grasp IK validation failed for candidate: joint_limits +[COLLISION DIAGNOSTIC] Robot link 9 colliding with obstacle 'Body ID 1' +[IK VALIDATION] Static/Target collision detected +Grasp IK validation failed for candidate: environment_static_collision +[COLLISION DIAGNOSTIC] Robot link 9 colliding with obstacle 'Body ID 1' +[IK VALIDATION] Static/Target collision detected +Grasp IK validation failed for candidate: environment_static_collision +[COLLISION DIAGNOSTIC] Robot link 9 colliding with obstacle 'Body ID 1' +[IK VALIDATION] Static/Target collision detected +Grasp IK validation failed for candidate: environment_static_collision +[IK VALIDATION] Joint limits exceeded for solution: [-0.18093067084038073, 1.2765475582402983, -1.9699567554260924, 0.02309196205547312, 1.8375554923182265, 1.3032271134969118, -1.1795237178910845] +Grasp IK validation failed for candidate: joint_limits +[COLLISION DIAGNOSTIC] Robot link 9 colliding with obstacle 'Body ID 1' +[IK VALIDATION] Static/Target collision detected +Grasp IK validation failed for candidate: environment_static_collision +[COLLISION DIAGNOSTIC] Robot link 9 colliding with obstacle 'Body ID 1' +[IK VALIDATION] Static/Target collision detected +Grasp IK validation failed for candidate: environment_static_collision +[COLLISION DIAGNOSTIC] Robot link 9 colliding with obstacle 'Body ID 1' +[IK VALIDATION] Static/Target collision detected +Grasp IK validation failed for candidate: environment_static_collision +[IK VALIDATION] Joint limits exceeded for solution: [-2.9997710831214732, -0.4305551889132262, 2.883290606195455, -1.870969884126872, 3.0133413654252945, 3.8780262144192372, 2.1563095779345893] +Grasp IK validation failed for candidate: joint_limits +[COLLISION DIAGNOSTIC] Robot link 9 colliding with obstacle 'Body ID 1' +[IK VALIDATION] Static/Target collision detected +Grasp IK validation failed for candidate: environment_static_collision +[COLLISION DIAGNOSTIC] Robot link 9 colliding with obstacle 'Body ID 1' +[IK VALIDATION] Static/Target collision detected +Grasp IK validation failed for candidate: environment_static_collision +[COLLISION DIAGNOSTIC] Robot link 9 colliding with obstacle 'Body ID 1' +[IK VALIDATION] Static/Target collision detected +Grasp IK validation failed for candidate: environment_static_collision +[IK VALIDATION] Joint limits exceeded for solution: [2.976980305472043, -0.5212293519745067, 2.9837745895029557, -1.853389250164938, -2.8489859295082716, 3.906266753822793, 1.6523526546526397] +Grasp IK validation failed for candidate: joint_limits +[IK VALIDATION] Joint limits exceeded for solution: [2.9688632202010856, -1.8245329676627489, 0.06317528842104224, -1.6104020926965283, 0.4959726920092279, -0.13304051850336943, 2.4558729716855323] +Grasp IK validation failed for candidate: joint_limits +[IK VALIDATION] Joint limits exceeded for solution: [-0.6057065592472355, 0.5668978799113967, 0.46468769773465457, -1.8304588381893874, 2.9750730301695403, 3.9033418696624205, 2.0725083080136164] +Grasp IK validation failed for candidate: joint_limits +[IK VALIDATION] Position error too high: 0.1260 m (max 0.01 m) +Grasp IK validation failed for candidate: fk_position_error +[COLLISION DIAGNOSTIC] Robot link 9 colliding with obstacle 'Body ID 1' +[IK VALIDATION] Static/Target collision detected +Grasp IK validation failed for candidate: environment_static_collision +[IK VALIDATION] Joint limits exceeded for solution: [-3.043115145116198, -1.8907864847087312, 0.10946358504966267, -1.7472995425848954, 0.7726143140816466, -0.11564864139592028, 2.980594438783657] +Grasp IK validation failed for candidate: joint_limits +[IK VALIDATION] Joint limits exceeded for solution: [2.230098608698701, -1.8441769376258017, -0.789787121657058, -1.454979354095337, -1.853544625422621, 0.8789977152328035, -0.6083390180569807] +Grasp IK validation failed for candidate: joint_limits +[IK VALIDATION] Joint limits exceeded for solution: [-3.1326849441677957, -0.212818411353892, -3.1226587615706554, -1.9201698330600936, 0.1272794225831393, 2.1075151196530073, -1.021807046889959] +Grasp IK validation failed for candidate: joint_limits +[IK VALIDATION] Joint limits exceeded for solution: [2.5164968947026147, -0.5619775643668997, -2.6598009707653154, -1.8390675965436056, 2.9713496148603165, 3.9034899463861796, 2.0722926397278028] +Grasp IK validation failed for candidate: joint_limits +[COLLISION DIAGNOSTIC] Robot link 9 colliding with obstacle 'Body ID 1' +[IK VALIDATION] Static/Target collision detected +Grasp IK validation failed for candidate: environment_static_collision +[IK VALIDATION] Joint limits exceeded for solution: [-0.36590843097193243, -1.8122698564556852, 3.02578195421366, -3.2789876455029408, -3.0568051440117388, 1.2282469502877733, -1.2761213684598829] +Grasp IK validation failed for candidate: joint_limits +[IK VALIDATION] Joint limits exceeded for solution: [2.9888100412573695, -0.2989040484853011, 2.9866981754234483, -1.7755904672504073, 0.19100040839567842, 1.9936860521045572, -1.3702540017951024] +Grasp IK validation failed for candidate: joint_limits +[IK VALIDATION] Joint limits exceeded for solution: [-3.1178199918714777, -1.8769869062679556, 0.13530634126979926, -1.342754923228067, -3.037740395899861, 0.482755206721706, -0.906757659211082] +Grasp IK validation failed for candidate: joint_limits +[COLLISION DIAGNOSTIC] Robot link 9 colliding with obstacle 'Body ID 1' +[IK VALIDATION] Static/Target collision detected +Grasp IK validation failed for candidate: environment_static_collision +[IK VALIDATION] Joint limits exceeded for solution: [-0.1261010465308458, 1.7969515972591044, 2.6474553940497376, 0.2445641733271487, 0.6603616683602983, 4.031361363608473, 1.8838704060357636] +Grasp IK validation failed for candidate: joint_limits +[COLLISION DIAGNOSTIC] Robot link 9 colliding with obstacle 'Body ID 1' +[IK VALIDATION] Static/Target collision detected +Grasp IK validation failed for candidate: environment_static_collision +[IK VALIDATION] Joint limits exceeded for solution: [-0.22265418317794505, 1.861633622426722, -3.0355019397614473, -1.2195626004063451, -3.0078194469927864, 0.5589695305205316, -1.1210916556874373] +Grasp IK validation failed for candidate: joint_limits +[COLLISION DIAGNOSTIC] Robot link 9 colliding with obstacle 'Body ID 1' +[IK VALIDATION] Static/Target collision detected +Grasp IK validation failed for candidate: environment_static_collision +[COLLISION DIAGNOSTIC] Robot link 9 colliding with obstacle 'Body ID 1' +[IK VALIDATION] Static/Target collision detected +Grasp IK validation failed for candidate: environment_static_collision +[IK VALIDATION] Position error too high: 0.1262 m (max 0.01 m) +Grasp IK validation failed for candidate: fk_position_error +[COLLISION DIAGNOSTIC] Robot link 9 colliding with obstacle 'Body ID 1' +[IK VALIDATION] Static/Target collision detected +Grasp IK validation failed for candidate: environment_static_collision +[COLLISION DIAGNOSTIC] Robot link 9 colliding with obstacle 'Body ID 1' +[IK VALIDATION] Static/Target collision detected +Grasp IK validation failed for candidate: environment_static_collision +[COLLISION DIAGNOSTIC] Robot link 9 colliding with obstacle 'Body ID 1' +[IK VALIDATION] Static/Target collision detected +Grasp IK validation failed for candidate: environment_static_collision +[IK VALIDATION] Joint limits exceeded for solution: [-3.0348727157118747, -0.3552397637816462, 2.999568021463664, -1.9785648294891984, 3.139404511588455, 3.8914575099387205, 2.1378839838177326] +Grasp IK validation failed for candidate: joint_limits +[IK VALIDATION] Position error too high: 0.1258 m (max 0.01 m) +Grasp IK validation failed for candidate: fk_position_error +[COLLISION DIAGNOSTIC] Robot link 9 colliding with obstacle 'Body ID 1' +[IK VALIDATION] Static/Target collision detected +Grasp IK validation failed for candidate: environment_static_collision +[COLLISION DIAGNOSTIC] Robot link 9 colliding with obstacle 'Body ID 1' +[IK VALIDATION] Static/Target collision detected +Grasp IK validation failed for candidate: environment_static_collision +[IK VALIDATION] Joint limits exceeded for solution: [2.939787202255105, -0.5496086943692493, 3.0008580305392325, -1.9863544606803096, -2.5401573735905543, 3.9400659125743056, 1.3871918219450663] +Grasp IK validation failed for candidate: joint_limits +[IK VALIDATION] Joint limits exceeded for solution: [2.2227738678860858, -0.7240346175078537, -2.31364078768676, -1.893448531125241, 2.9749186945635926, 3.9213076136546037, 2.0847107126267734] +Grasp IK validation failed for candidate: joint_limits +[IK VALIDATION] Joint limits exceeded for solution: [-0.902947744630074, 0.7286864571002125, 0.813797834780093, -1.8828354327134948, 2.977592238671154, 3.921289779797101, 2.082419372634969] +Grasp IK validation failed for candidate: joint_limits +[IK VALIDATION] Position error too high: 0.1003 m (max 0.01 m) +Grasp IK validation failed for candidate: fk_position_error +[COLLISION DIAGNOSTIC] Robot link 9 colliding with obstacle 'Body ID 1' +[IK VALIDATION] Static/Target collision detected +Grasp IK validation failed for candidate: environment_static_collision +[IK VALIDATION] Joint limits exceeded for solution: [-3.014433816575363, -1.9310316091590125, 0.37745653347502184, -1.7200343267086837, 0.8198307607123408, -0.14607432556743052, 2.9628552483919446] +Grasp IK validation failed for candidate: joint_limits +[IK VALIDATION] Joint limits exceeded for solution: [2.5673270093535243, -1.8492317403027299, -0.28174191919542146, -1.0582837155726807, -2.1741408401429, 0.7183844363468108, -0.7949576509492249] +Grasp IK validation failed for candidate: joint_limits +[IK VALIDATION] Joint limits exceeded for solution: [-3.153646704781041, -0.26053608616731944, -3.138815019599908, -1.8898244773187232, 0.43344185022699677, 2.0282804802653245, -1.2090042678111046] +Grasp IK validation failed for candidate: joint_limits +[COLLISION DIAGNOSTIC] Robot link 9 colliding with obstacle 'Body ID 1' +[IK VALIDATION] Static/Target collision detected +Grasp IK validation failed for candidate: environment_static_collision +[IK VALIDATION] Joint limits exceeded for solution: [-0.5392203251025889, -1.8205970346885105, 2.8598008721976935, -3.2635529797141944, -2.9981511403657812, 1.0404387384806555, -1.3288257482426729] +Grasp IK validation failed for candidate: joint_limits +[IK VALIDATION] Joint limits exceeded for solution: [2.9556326489349134, -0.3877910561437997, 2.9671947956983984, -1.6491467596877782, 0.43614384902816417, 1.7722370755648025, -1.4826272926062176] +Grasp IK validation failed for candidate: joint_limits +[IK VALIDATION] Joint limits exceeded for solution: [-3.0691446469568184, -1.8854882593800182, 0.42525152838052355, -1.4180350618740223, -3.0183979662038776, 0.37338712780261163, -0.9134850624278572] +Grasp IK validation failed for candidate: joint_limits +[COLLISION DIAGNOSTIC] Robot link 9 colliding with obstacle 'Body ID 1' +[IK VALIDATION] Static/Target collision detected +Grasp IK validation failed for candidate: environment_static_collision +[IK VALIDATION] Joint limits exceeded for solution: [-0.021031136355418048, 1.767999279163321, 2.907578918182437, 0.28589428392016386, 0.6681162172398167, 4.054694022091909, 1.9345822497021696] +Grasp IK validation failed for candidate: joint_limits +[COLLISION DIAGNOSTIC] Robot link 9 colliding with obstacle 'Body ID 1' +[IK VALIDATION] Static/Target collision detected +Grasp IK validation failed for candidate: environment_static_collision +[IK VALIDATION] Joint limits exceeded for solution: [-0.19523413103778584, 1.851127019522486, -2.832983005843614, -1.1209450709637074, -2.9695353504024076, 0.5374347502545609, -1.098461969700185] +Grasp IK validation failed for candidate: joint_limits +[IK VALIDATION] Joint limits exceeded for solution: [-3.1411485966103854, -0.5321004625290362, -3.0820180684900857, -1.8578385061619944, -2.6817721563545636, 3.918293467096152, 1.8914892150529976] +Grasp IK validation failed for candidate: joint_limits +[IK VALIDATION] Joint limits exceeded for solution: [0.5746673641039521, 1.8053484971709568, -1.9314529692441142, -0.046655989883507665, -1.0219439203259748, 4.153710181041748, -3.378879850564273] +Grasp IK validation failed for candidate: joint_limits +[COLLISION DIAGNOSTIC] Robot link 2 colliding with obstacle 'Body ID 1' +[IK VALIDATION] Static/Target collision detected +Grasp IK validation failed for candidate: environment_static_collision +[COLLISION DIAGNOSTIC] Robot link 9 colliding with obstacle 'Body ID 1' +[IK VALIDATION] Static/Target collision detected +Grasp IK validation failed for candidate: environment_static_collision +[IK VALIDATION] Joint limits exceeded for solution: [2.450307725703694, -0.6150014012294797, -2.650215059974789, -1.892745082588023, -2.9783248676601195, 3.920796178012228, 1.7911389036022352] +Grasp IK validation failed for candidate: joint_limits +[IK VALIDATION] Joint limits exceeded for solution: [-0.676208674281078, 0.6191049745540045, 0.47738593999281365, -1.885013695738531, -2.974777059863111, 3.9213807723763083, 1.7896031089269875] +Grasp IK validation failed for candidate: joint_limits +[IK VALIDATION] Joint limits exceeded for solution: [-3.1268940000619327, -0.24201168503581177, 3.081690499113615, -2.0165120432105814, 3.2331342595591317, 4.041477267592747, 2.055814093803495] +Grasp IK validation failed for candidate: joint_limits +[IK VALIDATION] Joint limits exceeded for solution: [-0.3596485607422334, 1.3086498920834806, 0.9764184097482629, 0.01384484556589443, -0.5740024038680818, 1.0735710992440675, -1.2027697608047407] +Grasp IK validation failed for candidate: joint_limits +[COLLISION DIAGNOSTIC] Robot link 9 colliding with obstacle 'Body ID 1' +[IK VALIDATION] Static/Target collision detected +Grasp IK validation failed for candidate: environment_static_collision +[COLLISION DIAGNOSTIC] Robot link 9 colliding with obstacle 'Body ID 1' +[IK VALIDATION] Static/Target collision detected +Grasp IK validation failed for candidate: environment_static_collision +[IK VALIDATION] Joint limits exceeded for solution: [2.8774511280672734, -0.6030160014468797, 3.0474087079276915, -2.1311945231745244, -2.2957052511990264, 3.991577469162401, 1.133685108349541] +Grasp IK validation failed for candidate: joint_limits +[IK VALIDATION] Joint limits exceeded for solution: [2.0577109517012504, -0.9331135398617985, -2.0827457203934197, -1.9422073801491653, 2.9780049920428007, 3.93805835492601, 2.1264988357945267] +Grasp IK validation failed for candidate: joint_limits +[IK VALIDATION] Joint limits exceeded for solution: [-1.0726350337995132, 0.9359408039995392, 1.0488545462288235, -1.9330750872202869, 2.97996289555966, 3.938037235935999, 2.122827789861347] +Grasp IK validation failed for candidate: joint_limits +[IK VALIDATION] Position error too high: 0.0763 m (max 0.01 m) +Grasp IK validation failed for candidate: fk_position_error +[COLLISION DIAGNOSTIC] Robot link 9 colliding with obstacle 'Body ID 1' +[IK VALIDATION] Static/Target collision detected +Grasp IK validation failed for candidate: environment_static_collision +[IK VALIDATION] Joint limits exceeded for solution: [-2.9795520185092106, -1.901589495068006, 0.6477233709471544, -1.657428870260836, 0.845572727792704, -0.14732253095405368, 2.960890724365783] +Grasp IK validation failed for candidate: joint_limits +[IK VALIDATION] Joint limits exceeded for solution: [2.80525872600632, -1.8454312613439865, 0.2836645711182764, -0.935778192510819, -2.5462408491768644, 0.5797696176053697, -0.896997169430556] +Grasp IK validation failed for candidate: joint_limits +[IK VALIDATION] Joint limits exceeded for solution: [-3.1508065397361245, -1.3993910370473313, -1.8436186844136049, 0.16960127674514583, -0.6399835364862901, 1.1570551099942383, -0.9338160314659909] +Grasp IK validation failed for candidate: joint_limits +[COLLISION DIAGNOSTIC] Robot link 9 colliding with obstacle 'Body ID 1' +[IK VALIDATION] Static/Target collision detected +Grasp IK validation failed for candidate: environment_static_collision +[IK VALIDATION] Joint limits exceeded for solution: [-3.024010237125733, -1.8779649441390385, 0.7075412314794453, -1.446960701557104, -2.9993183964565824, 0.29806784498014177, -0.9087373635042721] +Grasp IK validation failed for candidate: joint_limits +[COLLISION DIAGNOSTIC] Robot link 9 colliding with obstacle 'Body ID 1' +[IK VALIDATION] Static/Target collision detected +Grasp IK validation failed for candidate: environment_static_collision +[COLLISION DIAGNOSTIC] Robot link 9 colliding with obstacle 'Body ID 1' +[IK VALIDATION] Static/Target collision detected +Grasp IK validation failed for candidate: environment_static_collision +[IK VALIDATION] Joint limits exceeded for solution: [0.10370551774504057, 1.7556937356186944, 2.9650541840017377, 0.2481514511728536, 0.8976974208406314, 4.126821633950737, 2.0049616219604527] +Grasp IK validation failed for candidate: joint_limits +[COLLISION DIAGNOSTIC] Robot link 9 colliding with obstacle 'Body ID 1' +[IK VALIDATION] Static/Target collision detected +Grasp IK validation failed for candidate: environment_static_collision +[IK VALIDATION] Joint limits exceeded for solution: [-3.1764520985626996, -0.3308109755863992, -3.153395422936801, -1.8379598851229881, 0.701517919654764, 1.8929439863523785, -1.3520239071731786] +Grasp IK validation failed for candidate: joint_limits +[IK VALIDATION] Joint limits exceeded for solution: [-0.11482475677214757, 1.8483780227136162, -2.539160213734385, -1.1334049720604844, -2.9713361507084266, 0.4440738193852875, -1.0455347758143245] +Grasp IK validation failed for candidate: joint_limits +[IK VALIDATION] Joint limits exceeded for solution: [-3.156997837028726, -0.5889013923689485, -3.066788255080348, -1.925056941848153, -2.3166079965096023, 3.95607718278281, 1.6005129892218588] +Grasp IK validation failed for candidate: joint_limits +[IK VALIDATION] Joint limits exceeded for solution: [0.6034045580417329, 1.6161267270145334, -1.691922095439319, -0.0628056121060887, -0.9617885541752733, 4.217973253776249, -3.38086434425533] +Grasp IK validation failed for candidate: joint_limits +[COLLISION DIAGNOSTIC] Robot link 9 colliding with obstacle 'Body ID 1' +[IK VALIDATION] Static/Target collision detected +Grasp IK validation failed for candidate: environment_static_collision +[COLLISION DIAGNOSTIC] Robot link 2 colliding with obstacle 'Body ID 1' +[IK VALIDATION] Static/Target collision detected +Grasp IK validation failed for candidate: environment_static_collision +[IK VALIDATION] Joint limits exceeded for solution: [2.202345520280071, -0.7834246563823896, -2.332570530649719, -1.9431294612954262, -2.9795296117736423, 3.937707034588794, 1.8300886165415147] +Grasp IK validation failed for candidate: joint_limits +[IK VALIDATION] Joint limits exceeded for solution: [-0.926694405714511, 0.787337829244575, 0.7970393917527571, -1.9344143282157973, -2.976895834615397, 3.938177733500428, 1.82656327513852] +Grasp IK validation failed for candidate: joint_limits +[COLLISION DIAGNOSTIC] Robot link 9 colliding with obstacle 'Body ID 1' +[IK VALIDATION] Static/Target collision detected +Grasp IK validation failed for candidate: environment_static_collision +[IK VALIDATION] Joint limits exceeded for solution: [-0.44772367924074674, 1.359833845553776, 1.116261434436402, 9.504721266734469e-05, -0.44408427374803305, 0.9783344204639697, -1.1604759062427996] +Grasp IK validation failed for candidate: joint_limits +[COLLISION DIAGNOSTIC] Robot link 9 colliding with obstacle 'Body ID 1' +[IK VALIDATION] Static/Target collision detected +Grasp IK validation failed for candidate: environment_static_collision +[COLLISION DIAGNOSTIC] Robot link 8 colliding with obstacle 'Body ID 1' +[IK VALIDATION] Static/Target collision detected +Grasp IK validation failed for candidate: environment_static_collision +[IK VALIDATION] Joint limits exceeded for solution: [2.7361590368425706, -0.7083187582423998, 3.1228981613065483, -2.277187269901303, -2.176241617052403, 4.051989865542385, 0.8780738275829183] +Grasp IK validation failed for candidate: joint_limits +[IK VALIDATION] Joint limits exceeded for solution: [1.9646267910735982, -1.1675594596301646, -1.904878439774833, -1.9844771025726824, 2.9806140938096326, 3.952357621495672, 2.1977175953342334] +Grasp IK validation failed for candidate: joint_limits +[IK VALIDATION] Joint limits exceeded for solution: [-1.169013358281773, 1.1689291432562974, 1.2296197627604875, -1.977143726013971, 2.9821288511841084, 3.9523131458111105, 2.1932725987871593] +Grasp IK validation failed for candidate: joint_limits +[IK VALIDATION] Position error too high: 0.0559 m (max 0.01 m) +Grasp IK validation failed for candidate: fk_position_error +[COLLISION DIAGNOSTIC] Robot link 8 colliding with obstacle 'Body ID 1' +[IK VALIDATION] Static/Target collision detected +Grasp IK validation failed for candidate: environment_static_collision +[IK VALIDATION] Joint limits exceeded for solution: [-2.9197092897520087, -1.8623601855296568, 0.9280173506542326, -1.620317124233451, 0.840701811142321, -0.13950250807209402, 2.9656846583842715] +Grasp IK validation failed for candidate: joint_limits +[IK VALIDATION] Joint limits exceeded for solution: [2.9701081765969652, -1.8424393567724524, 0.7478366584979204, -0.9919248573844263, -2.7533418212927754, 0.44802890663253714, -0.8898807112297977] +Grasp IK validation failed for candidate: joint_limits +[IK VALIDATION] Joint limits exceeded for solution: [-3.17029283450607, -1.4745018979609148, -1.7398905084282759, 0.18195967419403006, -0.4494040895464196, 1.158443268661783, -0.9080646396211997] +Grasp IK validation failed for candidate: joint_limits +[IK VALIDATION] Joint limits exceeded for solution: [-3.2007584056596254, -0.4233960366025209, -3.16631343193506, -1.7727663048051774, 0.9364243719615726, 1.7209544743716483, -1.4513493781385394] +Grasp IK validation failed for candidate: joint_limits +[COLLISION DIAGNOSTIC] Robot link 8 colliding with obstacle 'Body ID 1' +[IK VALIDATION] Static/Target collision detected +Grasp IK validation failed for candidate: environment_static_collision +[IK VALIDATION] Joint limits exceeded for solution: [-2.9902708814028487, -1.858688227601691, 0.9819833034126096, -1.439015229251032, -2.9817061976076076, 0.24952665562564758, -0.8947321127445033] +Grasp IK validation failed for candidate: joint_limits +[COLLISION DIAGNOSTIC] Robot link 8 colliding with obstacle 'Body ID 1' +[IK VALIDATION] Static/Target collision detected +Grasp IK validation failed for candidate: environment_static_collision +[COLLISION DIAGNOSTIC] Robot link 8 colliding with obstacle 'Body ID 1' +[IK VALIDATION] Static/Target collision detected +Grasp IK validation failed for candidate: environment_static_collision +[IK VALIDATION] Joint limits exceeded for solution: [0.2062050728931799, 1.7701838024920478, 2.967864048996092, 0.15911299409640306, 1.191982655070457, 4.190944456062141, 2.066635320966357] +Grasp IK validation failed for candidate: joint_limits +[COLLISION DIAGNOSTIC] Robot link 8 colliding with obstacle 'Body ID 1' +[IK VALIDATION] Static/Target collision detected +Grasp IK validation failed for candidate: environment_static_collision +[IK VALIDATION] Joint limits exceeded for solution: [-0.0025294843424515244, 1.8445909494227624, -2.2245027307112077, -1.2179357337874428, -2.9711520518454413, 0.3365865597249671, -0.9623225083109729] +Grasp IK validation failed for candidate: joint_limits +[IK VALIDATION] Joint limits exceeded for solution: [-3.16446184443849, -0.67573973872525, -3.013069328449064, -1.9661525712355568, -2.017686915459052, 4.018456736726754, 1.3738249807324434] +Grasp IK validation failed for candidate: joint_limits +[IK VALIDATION] Joint limits exceeded for solution: [0.5734653130592811, 1.4269005277393205, -1.4576610201712734, -0.07667995096310964, -0.8977681608469215, 4.277364833284742, -3.3719385746121517] +Grasp IK validation failed for candidate: joint_limits +[COLLISION DIAGNOSTIC] Robot link 8 colliding with obstacle 'Body ID 1' +[IK VALIDATION] Static/Target collision detected +Grasp IK validation failed for candidate: environment_static_collision +[COLLISION DIAGNOSTIC] Robot link 2 colliding with obstacle 'Body ID 1' +[IK VALIDATION] Static/Target collision detected +Grasp IK validation failed for candidate: environment_static_collision +[IK VALIDATION] Joint limits exceeded for solution: [2.054247475185561, -0.9934356896548384, -2.100000680146263, -1.985560089680576, -2.980896758451982, 3.9521279497217945, 1.898504368891068] +Grasp IK validation failed for candidate: joint_limits +[IK VALIDATION] Joint limits exceeded for solution: [-1.0778515968188727, 0.9959054980636036, 1.0323786261674701, -1.9780610062572872, -2.978917990350724, 3.9524721384151014, 1.8938554177073323] +Grasp IK validation failed for candidate: joint_limits +[COLLISION DIAGNOSTIC] Robot link 8 colliding with obstacle 'Body ID 1' +[IK VALIDATION] Static/Target collision detected +Grasp IK validation failed for candidate: environment_static_collision +[IK VALIDATION] Position error too high: 0.0558 m (max 0.01 m) +Grasp IK validation failed for candidate: fk_position_error +[COLLISION DIAGNOSTIC] Robot link 8 colliding with obstacle 'Body ID 1' +[IK VALIDATION] Static/Target collision detected +Grasp IK validation failed for candidate: environment_static_collision +[COLLISION DIAGNOSTIC] Robot link 6 colliding with obstacle 'Body ID 1' +[IK VALIDATION] Static/Target collision detected +Grasp IK validation failed for candidate: environment_static_collision +[IK VALIDATION] Joint limits exceeded for solution: [2.5835702343897937, -1.5279111378236963, 0.5794450199683837, 0.005597535462648987, -2.499732614292308, 0.8327591056905561, -0.9939738537121733] +Grasp IK validation failed for candidate: joint_limits +[IK VALIDATION] Joint limits exceeded for solution: [1.9156179830665732, -1.41915505187487, -1.7457374931446217, -2.0168813657026132, 2.9826533995541507, 3.963041298944343, 2.296076273601513] +Grasp IK validation failed for candidate: joint_limits +[COLLISION DIAGNOSTIC] Robot link 6 colliding with obstacle 'Body ID 1' +[IK VALIDATION] Static/Target collision detected +Grasp IK validation failed for candidate: environment_static_collision +[IK VALIDATION] Joint limits exceeded for solution: [-0.5523797849039674, 1.529348087500895, 2.0594830557356345, 0.004657940063370128, -0.8390197036203583, 0.8317972578549342, -0.9940207345445546] +Grasp IK validation failed for candidate: joint_limits +[COLLISION DIAGNOSTIC] Robot link 6 colliding with obstacle 'Body ID 1' +[IK VALIDATION] Static/Target collision detected +Grasp IK validation failed for candidate: environment_static_collision +[IK VALIDATION] Joint limits exceeded for solution: [-2.870434817798928, -1.7835733823304403, 1.2049553097194332, -1.5759183503073566, 0.8026061668393346, -0.13679325462377553, 2.974061692487708] +Grasp IK validation failed for candidate: joint_limits +[IK VALIDATION] Joint limits exceeded for solution: [2.9704922475515496, -1.8399113117195156, 0.9619316237022758, -0.9023571588975839, -2.6265309974817095, 0.44376940269046683, -0.7468099726519775] +Grasp IK validation failed for candidate: joint_limits +[IK VALIDATION] Joint limits exceeded for solution: [-3.1823313494917747, -1.5549915338790317, -1.6247897706241057, 0.1884816952713906, -0.2679137981868993, 1.1548979616982011, -0.8887502745151614] +Grasp IK validation failed for candidate: joint_limits +[IK VALIDATION] Joint limits exceeded for solution: [-3.2236424369444685, -0.5359156664119896, -3.1760046753144375, -1.701947994122579, 1.1501730249557138, 1.52776636781024, -1.5133113454112284] +Grasp IK validation failed for candidate: joint_limits +[IK VALIDATION] Joint limits exceeded for solution: [2.1128703130422775, -1.837427391824343, -1.0721374638368293, -0.9740160396875854, -0.723596039720077, 1.13586330404828, -0.6508842791615022] +Grasp IK validation failed for candidate: joint_limits +[IK VALIDATION] Joint limits exceeded for solution: [-2.9733975158849404, -1.8353336899484678, 1.243351650203228, -1.4000222762400327, -2.932976259623431, 0.22435533261283244, -0.8413804533057788] +Grasp IK validation failed for candidate: joint_limits +[COLLISION DIAGNOSTIC] Robot link 6 colliding with obstacle 'Body ID 1' +[IK VALIDATION] Static/Target collision detected +Grasp IK validation failed for candidate: environment_static_collision +[COLLISION DIAGNOSTIC] Robot link 6 colliding with obstacle 'Body ID 1' +[IK VALIDATION] Static/Target collision detected +Grasp IK validation failed for candidate: environment_static_collision +[IK VALIDATION] Joint limits exceeded for solution: [-1.1684665489263713, 1.2309636445460777, 1.2254102635600972, -2.011834441382339, -2.980491293660716, 3.9631496614463138, 1.989279601814221] +Grasp IK validation failed for candidate: joint_limits +[COLLISION DIAGNOSTIC] Robot link 6 colliding with obstacle 'Body ID 1' +[IK VALIDATION] Static/Target collision detected +Grasp IK validation failed for candidate: environment_static_collision +[IK VALIDATION] Joint limits exceeded for solution: [0.08669224155326716, 1.8356389564046607, -1.9407793655435073, -1.286365051679276, -2.8792452477268626, 0.2634835172798558, -0.8184052669406316] +Grasp IK validation failed for candidate: joint_limits +[IK VALIDATION] Joint limits exceeded for solution: [-3.212679307978953, -0.8975253327497692, -2.7955912104680136, -1.7228527245500094, -1.923010513610798, 4.064257331777596, 1.4143351079695612] +Grasp IK validation failed for candidate: joint_limits +[IK VALIDATION] Joint limits exceeded for solution: [0.48679935734065954, 1.253734229608165, -1.2092402416522228, -0.08772842269617392, -0.8360823289504927, 4.329236702581151, -3.3490889597094258] +Grasp IK validation failed for candidate: joint_limits +[COLLISION DIAGNOSTIC] Robot link 6 colliding with obstacle 'Body ID 1' +[IK VALIDATION] Static/Target collision detected +Grasp IK validation failed for candidate: environment_static_collision +[COLLISION DIAGNOSTIC] Robot link 2 colliding with obstacle 'Body ID 1' +[IK VALIDATION] Static/Target collision detected +Grasp IK validation failed for candidate: environment_static_collision +[IK VALIDATION] Joint limits exceeded for solution: [1.9659762605830737, -1.2297839804089439, -1.9091855483363014, -2.017877358056217, -2.98203551453506, 3.96289519311043, 1.9945165142534935] +Grasp IK validation failed for candidate: joint_limits +[IK VALIDATION] Joint limits exceeded for solution: [-2.9693874134460327, -1.220992261748923, 1.8240504422055963, -1.2761579854906937, 1.8443632069504108, 0.5345342680642027, -1.6430538166629767] +Grasp IK validation failed for candidate: joint_limits +[IK VALIDATION] Joint limits exceeded for solution: [-0.5540881652960561, 1.5306155750633352, 1.5234914793774945, 0.0001246314165810735, -0.30231478517933397, 0.832739420923045, -0.9928391584418748] +Grasp IK validation failed for candidate: joint_limits +[COLLISION DIAGNOSTIC] Robot link 6 colliding with obstacle 'Body ID 1' +[IK VALIDATION] Static/Target collision detected +Grasp IK validation failed for candidate: environment_static_collision +[COLLISION DIAGNOSTIC] Robot link 6 colliding with obstacle 'Body ID 1' +[IK VALIDATION] Static/Target collision detected +Grasp IK validation failed for candidate: environment_static_collision +[IK VALIDATION] Joint limits exceeded for solution: [2.5670015636971386, -1.6328611636167176, 0.5284935380805713, 0.0036563954702510185, -2.1612771146724428, 0.795700001654653, -0.8743992458215266] +Grasp IK validation failed for candidate: joint_limits +[IK VALIDATION] Joint limits exceeded for solution: [1.9003243444921163, -1.6816311192280786, -1.5869540245112423, -2.0357837960209233, 2.9839629758459916, 3.969204593137905, 2.4151851843015684] +Grasp IK validation failed for candidate: joint_limits +[COLLISION DIAGNOSTIC] Robot link 6 colliding with obstacle 'Body ID 1' +[IK VALIDATION] Static/Target collision detected +Grasp IK validation failed for candidate: environment_static_collision +[IK VALIDATION] Position error too high: 0.0317 m (max 0.01 m) +Grasp IK validation failed for candidate: fk_position_error +[IK VALIDATION] Joint limits exceeded for solution: [-0.5700286329075956, 1.6346586964227434, 1.6202126949629798, 0.002950098520788357, -0.11151006214631744, 0.795951879271319, -0.8740976813151419] +Grasp IK validation failed for candidate: joint_limits +[IK VALIDATION] Joint limits exceeded for solution: [-2.9722858789935422, -1.509029527507082, 1.6765896171462655, -1.3323533180558964, 2.6781482914080845, 0.2372049246352299, -1.1723816657810318] +Grasp IK validation failed for candidate: joint_limits +[IK VALIDATION] Joint limits exceeded for solution: [2.9708289804721093, -1.8385701967792678, 1.1831169565771507, -0.8061904809595142, -2.5203204118362668, 0.46634626645403143, -0.6058660567063902] +Grasp IK validation failed for candidate: joint_limits +[IK VALIDATION] Joint limits exceeded for solution: [-3.1870940299214565, -1.6473570709474383, -1.6066282483598207, 0.1897792738918414, 0.01388975446389166, 1.1399366459811422, -0.8633101072651416] +Grasp IK validation failed for candidate: joint_limits +[IK VALIDATION] Joint limits exceeded for solution: [-3.241311151648956, -0.6642631682795287, -3.1809356666398925, -1.628685791606599, 1.3550217754020466, 1.3233414589699113, -1.5401416960080152] +Grasp IK validation failed for candidate: joint_limits +[IK VALIDATION] Joint limits exceeded for solution: [0.10029820520284473, 1.8346249573969562, -1.7374234465149176, -1.2390192866407228, -2.5927720204583977, 0.27556331242125415, -0.5315078473489677] +Grasp IK validation failed for candidate: joint_limits +[IK VALIDATION] Joint limits exceeded for solution: [-2.9724873803472036, -1.8351368968730974, 1.435452719348503, -1.336902455753413, -2.5781819347589128, 0.24523016723728294, -0.5028917300563057] +Grasp IK validation failed for candidate: joint_limits +[COLLISION DIAGNOSTIC] Robot link 6 colliding with obstacle 'Body ID 1' +[IK VALIDATION] Static/Target collision detected +Grasp IK validation failed for candidate: environment_static_collision +[COLLISION DIAGNOSTIC] Robot link 6 colliding with obstacle 'Body ID 1' +[IK VALIDATION] Static/Target collision detected +Grasp IK validation failed for candidate: environment_static_collision +[IK VALIDATION] Joint limits exceeded for solution: [-1.2183177775969836, 1.484563835631402, 1.3992609065352584, -2.031908945922617, -2.981374280989288, 3.9693167262339077, 2.1066636386392372] +Grasp IK validation failed for candidate: joint_limits +[COLLISION DIAGNOSTIC] Robot link 6 colliding with obstacle 'Body ID 1' +[IK VALIDATION] Static/Target collision detected +Grasp IK validation failed for candidate: environment_static_collision +[IK VALIDATION] Joint limits exceeded for solution: [-3.2754813201067177, -1.5247201003748705, -1.8978576417078166, -0.8943919834936378, -2.768569689081322, 4.042908392802891, 2.0989503192327703] +Grasp IK validation failed for candidate: joint_limits +[IK VALIDATION] Joint limits exceeded for solution: [0.2578540215757995, 1.227450395302566, -0.9458864971519447, 0.3696845397991608, -0.811318021393952, 4.042202357555598, -3.1367939042335564] +Grasp IK validation failed for candidate: joint_limits +[COLLISION DIAGNOSTIC] Robot link 6 colliding with obstacle 'Body ID 1' +[IK VALIDATION] Static/Target collision detected +Grasp IK validation failed for candidate: environment_static_collision +[COLLISION DIAGNOSTIC] Robot link 6 colliding with obstacle 'Body ID 1' +[IK VALIDATION] Static/Target collision detected +Grasp IK validation failed for candidate: environment_static_collision +[IK VALIDATION] Joint limits exceeded for solution: [-3.2869074323676375, -1.896479213326907, -0.7736941024411854, -1.3788098004039187, 2.014019418632842, 4.038699241855863, -3.0617852291752508] +Grasp IK validation failed for candidate: joint_limits +[IK VALIDATION] Joint limits exceeded for solution: [1.917712734280139, -1.484317265230674, -1.7369587947995333, -2.0366986331443635, -2.982629346026746, 3.96911770273456, 2.112145081752821] +Grasp IK validation failed for candidate: joint_limits +[IK VALIDATION] Joint limits exceeded for solution: [-2.9746843010701394, -1.3787706784495235, 1.7875978000674717, -1.3365900495907521, 2.3287251668631552, 0.29623161741840376, -1.3775390354435668] +Grasp IK validation failed for candidate: joint_limits +[IK VALIDATION] Position error too high: 0.0318 m (max 0.01 m) +Grasp IK validation failed for candidate: fk_position_error +[COLLISION DIAGNOSTIC] Robot link 6 colliding with obstacle 'Body ID 1' +[IK VALIDATION] Static/Target collision detected +Grasp IK validation failed for candidate: environment_static_collision +[COLLISION DIAGNOSTIC] Robot link 4 colliding with obstacle 'Body ID 1' +[IK VALIDATION] Static/Target collision detected +Grasp IK validation failed for candidate: environment_static_collision +[IK VALIDATION] Joint limits exceeded for solution: [3.2022977964996144, -1.629977964858368, 1.316096157204911, -1.3560804302059624, -2.8694990441043546, 4.00970236463595, 2.0732552945494827] +Grasp IK validation failed for candidate: joint_limits +[IK VALIDATION] Joint limits exceeded for solution: [2.426228033455641, -1.5015562887487612, -1.657851923152597, -1.4636439406360655, 0.6946850384826561, -0.13706115125825025, 2.972682286293831] +Grasp IK validation failed for candidate: joint_limits +[IK VALIDATION] Joint limits exceeded for solution: [-2.364314940314725, -1.4601453647379583, 1.5508250749101913, -2.0520565587997237, 2.985068705938143, 3.9763736194305457, 2.412405832898157] +Grasp IK validation failed for candidate: joint_limits +[IK VALIDATION] Joint limits exceeded for solution: [0.11623856896037262, 1.509289970493769, 0.7726644274808866, 0.0005205274227856312, -2.406489167443399, 0.7621003277458858, -0.8730434196457871] +Grasp IK validation failed for candidate: joint_limits +numActiveThreads = 0 +stopping threads +Thread with taskId 0 with handle 0000000000000554 exiting +Thread TERMINATED +finished +numActiveThreads = 0 +btShutDownExampleBrowser stopping threads +Thread with taskId 0 with handle 00000000000003C8 exiting +Thread TERMINATED +Traceback (most recent call last): + File "C:\Users\admin\C2-App-151\run_pipeline.py", line 54, in + main() + File "C:\Users\admin\C2-App-151\run_pipeline.py", line 40, in main + success = executor.execute_tasks(task_list) + File "C:\Users\admin\C2-App-151\llm_panda\pipeline_executor.py", line 518, in execute_tasks + success, q_current = self._pick_and_place_single_object(object_name, goal_location, q_current) + File "C:\Users\admin\C2-App-151\llm_panda\pipeline_executor.py", line 614, in _pick_and_place_single_object + path = rrt_pick.plan(q_start, q_sol) + File "C:\Users\admin\C2-App-151\llm_panda\pipeline_executor.py", line 302, in plan + smoothed_path = self._smooth_path(path) + File "C:\Users\admin\C2-App-151\llm_panda\pipeline_executor.py", line 433, in _smooth_path + if self._is_segment_valid(smoothed[i], smoothed[j]): + File "C:\Users\admin\C2-App-151\llm_panda\pipeline_executor.py", line 363, in _is_segment_valid + if self.collision_fn(q_interp): + File "C:\Users\admin\C2-App-151\llm_panda\pipeline_executor.py", line 607, in pick_collision_fn + return self._check_static_collision(q, object_id, diagnose=diagnose) + File "C:\Users\admin\C2-App-151\llm_panda\pipeline_executor.py", line 983, in _check_static_collision + if self._has_penetration_between(self.robot_id, body_id, exclude_linkA=-1): + File "C:\Users\admin\C2-App-151\llm_panda\pipeline_executor.py", line 922, in _has_penetration_between + contacts = pb.getClosestPoints(bodyA, bodyB, distance=0.0, **kwargs) +KeyboardInterrupt \ No newline at end of file diff --git a/main.py b/main.py new file mode 100644 index 0000000000000000000000000000000000000000..a657a50994382b3df567c8bab6562959e1823e65 --- /dev/null +++ b/main.py @@ -0,0 +1,1215 @@ +"""Entry point + Executor for the LLM-Panda pick-and-place demo. + +Pipeline +-------- + NL command --> LLMAgent (Module 1 text state in) --> function-call plan + --> Executor --> GraspPlanner (Module 2) + RobotController + (Module 3) + GripperController (Module 4) + +Run it:: + + python main.py --gui --command "Pick up the red cube and place it in the tray" + python main.py --gui # GUI + chat window + python main.py --command "gắp khối hộp màu đỏ đặt vào khay" # headless, VI +""" + +import argparse +import contextlib +import io +import json +import logging +import os +import queue as _queue +import random +import threading +import time +import tkinter as tk +from tkinter import scrolledtext +from typing import Optional + +import pybullet as pb +import pybullet_data +from pybullet_object_models import ycb_objects + +logger = logging.getLogger(__name__) + +from llm_panda import config +from llm_panda import logger as _logger_setup +from llm_panda.scene_manager import SceneManager +from llm_panda.grasp_planner import GraspPlanner +from llm_panda.gripper_controller import GripperController +from llm_panda.robot_controller import RobotController +from llm_panda.llm_agent import LLMAgent, RemoteLLMPlanner +from llm_panda.cost_map import plan_path + + +# --------------------------------------------------------------------------- # +# YCB object catalog (name, class, ycb_folder) +# --------------------------------------------------------------------------- # +_YCB_CATALOG = [ + ("banana", "banana", "YcbBanana"), + ("soup_can", "can", "YcbTomatoSoupCan"), + ("chips_can", "chips", "YcbMasterChefCan"), + # Low-profile objects (all < ~7.5 cm tall, well under the cans) so the arm + # flies OVER them in transit instead of risking a collision. See the + # height-aware cost map (llm_panda/cost_map.py). + ("tennis_ball", "ball", "YcbTennisBall"), # ~7.1 cm, ~7.1 cm wide (graspable) + ("pear", "pear", "YcbPear"), # ~7.4 cm + ("clamp", "clamp", "YcbMediumClamp"), # ~5.3 cm +] + +_YCB_DATA = ycb_objects.getDataPath() + + +def _load_ycb(folder, position): + """Load a YCB URDF at *position* (spawned slightly above the table).""" + urdf = os.path.join(_YCB_DATA, folder, "model.urdf") + flags = pb.URDF_USE_INERTIA_FROM_FILE | pb.URDF_USE_MATERIAL_COLORS_FROM_MTL + body = pb.loadURDF(urdf, position, flags=flags) + # Some YCB .mtl files set the diffuse colour Kd=0 (black) and rely solely on + # the texture map. With URDF_USE_MATERIAL_COLORS_FROM_MTL that black becomes + # the base colour and multiplies the texture down to black, so the object + # renders colourless (unlike banana/cans whose Kd≈0.64). Detect the black + # base and re-apply the texture over a white base so the real colour shows. + try: + base_rgba = pb.getVisualShapeData(body)[0][7] + if max(base_rgba[:3]) < 0.05: + tex_path = os.path.join(_YCB_DATA, folder, "texture_map.png") + if os.path.exists(tex_path): + tex = pb.loadTexture(tex_path) + pb.changeVisualShape(body, -1, textureUniqueId=tex, rgbaColor=[1, 1, 1, 1]) + except Exception: + pass + return body + + +class PandaSimulation: + """Owns the world, the robot stack, and the NL->action executor.""" + + def __init__(self, gui=False, seed=0, real_time=False, agent=None, viz=False): + self.gui = gui + self.viz = viz # 3D GUI overlay (obstacles / A* route / U-trajectory) + self._overlay = None + self.rng = random.Random(seed) + self.client = pb.connect(pb.GUI if gui else pb.DIRECT) + pb.setAdditionalSearchPath(pybullet_data.getDataPath()) + pb.setGravity(0, 0, config.GRAVITY) + pb.setTimeStep(config.SIM_TIMESTEP) + if gui: + pb.configureDebugVisualizer(pb.COV_ENABLE_GUI, 0) + pb.resetDebugVisualizerCamera(1.2, 50, -35, [0.5, 0.0, 0.2]) + if real_time: + pb.setRealTimeSimulation(1) + + self.scene = SceneManager() + self.grasp_planner = GraspPlanner() + self.agent = agent or LLMAgent() + self._carried = None # object_id currently held + self._pending_target_pos = None + + self._build_static_scene() + self._spawn_robot() + self._spawn_objects() + # Let everything settle onto the table. + for _ in range(120): + pb.stepSimulation() + + # ------------------------------------------------------------------ # + # Scene construction + # ------------------------------------------------------------------ # + def _build_static_scene(self): + pb.loadURDF("plane.urdf") + + # Table as a fixed box (full control over the table-top height). + tx, ty = config.TABLE_CENTER + hx, hy, hz = config.TABLE_HALF_EXTENTS + col = pb.createCollisionShape(pb.GEOM_BOX, halfExtents=[hx, hy, hz]) + vis = pb.createVisualShape(pb.GEOM_BOX, halfExtents=[hx, hy, hz], rgbaColor=config.TABLE_COLOR) + self.table_id = pb.createMultiBody(0, col, vis, [tx, ty, config.TABLE_BASE_Z]) + pb.changeDynamics(self.table_id, -1, lateralFriction=0.8) + + # Fixed tray just outside the table. + thx, thy, thz = config.TRAY_HALF_EXTENTS + tray_col = pb.createCollisionShape(pb.GEOM_BOX, halfExtents=[thx, thy, thz]) + tray_vis = pb.createVisualShape(pb.GEOM_BOX, halfExtents=[thx, thy, thz], rgbaColor=config.TRAY_COLOR) + self.tray_id = pb.createMultiBody( + 0, tray_col, tray_vis, + [config.TRAY_POSITION[0], config.TRAY_POSITION[1], config.TABLE_TOP_Z - thz], + ) + + def _spawn_robot(self): + # A pedestal raises the arm base to table/tray height for comfortable reach. + ped_half = config.ROBOT_PEDESTAL_HALF + ped_h = config.ROBOT_BASE_Z + if ped_h > 0: + ped_col = pb.createCollisionShape(pb.GEOM_BOX, halfExtents=[ped_half, ped_half, ped_h / 2]) + ped_vis = pb.createVisualShape(pb.GEOM_BOX, halfExtents=[ped_half, ped_half, ped_h / 2], + rgbaColor=[0.3, 0.3, 0.33, 1.0]) + self.pedestal_id = pb.createMultiBody(0, ped_col, ped_vis, [0, 0, ped_h / 2]) + self.robot_id = pb.loadURDF(config.PANDA_URDF, [0, 0, config.ROBOT_BASE_Z], useFixedBase=True) + self.gripper = GripperController(self.robot_id) + self.controller = RobotController(self.robot_id, gripper=self.gripper) + self.controller.table_id = self.table_id + self.controller.tray_id = self.tray_id + # High finger friction for reliable friction grasps. + for finger in config.FINGER_JOINT_INDICES: + pb.changeDynamics(self.robot_id, finger, lateralFriction=1.2) + self.controller.reset_to_home() + + def _spawn_objects(self): + """Drop YCB objects onto distinct random continuous table locations.""" + cx, cy = config.TABLE_CENTER + hx, hy = config.TABLE_HALF_EXTENTS[0], config.TABLE_HALF_EXTENTS[1] + m = config.TABLE_EDGE_MARGIN + x_min, x_max = cx - hx + m, cx + hx - m + y_min, y_max = cy - hy + m, cy + hy - m + + # Evenly spaced fallback grid (2 rows x 3 cols) if random sampling fails. + static_fallbacks = [ + [x, y, config.TABLE_TOP_Z + 0.05] + for y in (cy - 0.15, cy + 0.15) + for x in (cx - 0.10, cx, cx + 0.10) + ] + + spawned = [] + for i, (obj_name, obj_class, ycb_folder) in enumerate(_YCB_CATALOG): + spawn_pos = None + for _ in range(100): + x = self.rng.uniform(x_min, x_max) + y = self.rng.uniform(y_min, y_max) + if all(((x - sx) ** 2 + (y - sy) ** 2) ** 0.5 >= 0.11 for sx, sy, _ in spawned): + spawn_pos = [x, y, config.TABLE_TOP_Z + 0.05] + break + if spawn_pos is None: + spawn_pos = static_fallbacks[i % len(static_fallbacks)] + spawned.append(spawn_pos) + body = _load_ycb(ycb_folder, spawn_pos) + self.scene.register_object(body, obj_name, obj_class) + + # ------------------------------------------------------------------ # + # Executor: function call -> physical action + # ------------------------------------------------------------------ # + # Shortcut map: type "1"–"4" to run a preset command. + _SHORTCUTS = { + "1": "gắp chuối bỏ vào khay", + "2": "gắp lon chips bỏ vào khay", + "3": "gắp lon soup bỏ vào khay", + "4": "gắp lại", + } + + # Tolerances for the post-action "is the world where we expect?" checks. + _MOVE_XY_TOL = 0.12 # TCP must stop roughly above the requested XY + _PLACE_FALL_Z = config.TABLE_TOP_Z - 0.10 # below this => object fell off + # How many times the LLM may re-plan after a monitored failure. + MAX_REPLANS = 2 + + def _reachability_fn(self): + """Closure used by the State Parser: can the arm grasp object ``oid``?""" + def reachability_fn(oid): + pos, _ = pb.getBasePositionAndOrientation(oid) + loc = self.scene.classify_location(pos) + if loc == "elsewhere": + return False + cls = self.scene.get_class(oid) + try: + grasp_pos, grasp_ori = self.grasp_planner.compute_grasp_pose(oid, cls) + return self.controller.is_reachable(grasp_pos, grasp_ori) + except Exception: + return False + return reachability_fn + + def run_command(self, nl_command, verbose=True): + """Closed-loop control: parse state → LLM plan → monitored execution. + + Implements the three-part architecture: + + 1. **State Parser** — scan PyBullet into the text scene state. + 2. **Decomposition** — feed state + instruction to the LLM (CoT) for a + JSON function-call plan. + 3. **Monitoring** — run each call and verify the world reached the + expected state. On a verified failure (e.g. a stuck joint, or an + object that did not land where intended) the loop stops, recovers the + arm to a safe "best state", re-parses the *fresh* world and asks the + LLM for a new plan — up to :data:`MAX_REPLANS` times. + """ + nl_command = self._SHORTCUTS.get(nl_command.strip(), nl_command) + reachability_fn = self._reachability_fn() + last_failed_sig = None + plan = [] + + for attempt in range(self.MAX_REPLANS + 1): + # ── Component 1: State Parser (PyBullet world → text) ── + carried_name = self.scene.get_name(self._carried) if self._carried is not None else None + scene_state = self.scene.get_scene_state(reachability_fn=reachability_fn, carried_object=carried_name) + state_text = json.dumps(scene_state, indent=2) + + # ── Component 2: Decomposition (LLM + Chain-of-Thought → JSON) ── + plan = self.agent.plan(nl_command, state_text) + if verbose: + if attempt > 0: + logger.info(f"\n[MONITOR] Re-plan attempt {attempt}/{self.MAX_REPLANS} from fresh state") + logger.info(f"\n[SCENE] {self.scene.describe()}") + occ = scene_state.get("occupancy", {}) + if occ: + logger.info( + f"[SCENE] Table occupancy: {occ['occupied_area_m2']}/" + f"{occ['table_area_m2']} m^2 ({occ['occupancy_ratio'] * 100:.0f}% used, " + f"{occ['free_area_m2']} m^2 free)" + ) + logger.info(f"[USER ] {nl_command}") + logger.info(f"[PLAN ] {plan}") + + if not plan: + logger.warning("[WARN ] Planner produced no actionable steps.") + return plan + + sig = self._plan_signature(plan) + if attempt > 0 and sig == last_failed_sig: + # The re-planner produced the very plan that just failed: with + # no new information there is nothing to gain by retrying it. + logger.warning("[MONITOR] Re-plan reproduced the failing plan — no progress, aborting.") + return plan + + # ── Component 3: Monitored execution ── + result = self._execute_plan(plan, verbose=verbose, reachability_fn=reachability_fn) + if result["ok"]: + if verbose: + logger.info( + f"[DONE ] Hoàn thành kế hoạch ({len(plan)} bước) — {self.scene.describe()}" + ) + return plan + + last_failed_sig = sig + logger.warning( + f"[MONITOR] step {result['failed_index']} " + f"'{result['step'].get('function')}' failed: {result['reason']}" + ) + if attempt < self.MAX_REPLANS: + logger.warning("[MONITOR] Recovering arm to a safe state, then re-planning.") + self._recover_to_safe_state(verbose=verbose) + else: + logger.error("[MONITOR] Exhausted re-plan attempts; giving up on this command.") + + return plan + + def _execute_plan(self, plan, verbose=True, reachability_fn=None): + """Run each function call, verifying the expected post-state after each. + + Returns ``{"ok": True}`` on full success, or + ``{"ok": False, "failed_index": i, "step": step, "reason": str}`` on the + first step whose outcome does not match expectations. + """ + expected_location = None # destination named by the most recent move_to + n_steps = len(plan) + for i, step in enumerate(plan): + # Snapshot positions of all non-carried objects before executing + # (used only for the knock check below). + pre_positions = { + oid: pb.getBasePositionAndOrientation(oid)[0] + for oid in self.scene.object_ids + if oid != self._carried + } + held_before = self._carried + self.controller.reset_stuck() # arm-stall detector for this action + if verbose: + logger.info(f"[STEP {i + 1}/{n_steps}] {self._format_step(step)}") + self._execute(step, verbose=verbose) + if verbose: + # Knock detection: warn about objects that moved unexpectedly. + for oid, pre_pos in pre_positions.items(): + if oid == self._carried: + continue + post_pos, _ = pb.getBasePositionAndOrientation(oid) + dist = ((post_pos[0]-pre_pos[0])**2 + (post_pos[1]-pre_pos[1])**2 + (post_pos[2]-pre_pos[2])**2)**0.5 + if dist > 0.05: + name = self.scene.get_name(oid) + logger.warning( + f"[KNOCK] '{name}' moved {dist:.3f} m during last action " + f"({[round(c,3) for c in pre_pos]} → {[round(c,3) for c in post_pos]})" + ) + + # ── Monitoring: did the world reach the expected state? ── + ok, reason = self._verify_step(step, held_before, expected_location) + if step.get("function") == "move_to": + expected_location = step.get("args", {}).get("location_id") + if not ok: + return {"ok": False, "failed_index": i, "step": step, "reason": reason} + + return {"ok": True} + + def _verify_step(self, step, held_before, expected_location): + """Check the post-action world against the step's expected outcome. + + Returns ``(ok, reason)``. A stuck joint during the action is always a + failure; otherwise each verb has its own success criterion (object held + and lifted; arm parked above the target; object resting at the intended + surface with an empty gripper). + """ + func = step.get("function") + args = step.get("args", {}) + + if self.controller.is_stuck(): + return False, f"IK joint stuck during '{func}'" + + if func == "pick_up": + name = args.get("object_id") + oid = self.scene.name_to_id(name) + if oid is None: + return False, f"unknown object '{name}'" + if self._carried != oid: + return False, f"pick_up('{name}') did not secure the object" + pos, _ = pb.getBasePositionAndOrientation(oid) + if pos[2] < config.TABLE_TOP_Z + 0.05: + return False, f"'{name}' was not lifted (z={pos[2]:.3f})" + return True, "" + + if func == "move_to": + if self._carried is None: + return False, "move_to ended with nothing held" + target = self._pending_target_pos + if target is not None: + tcp = self.controller.tcp_position() + d = ((tcp[0] - target[0]) ** 2 + (tcp[1] - target[1]) ** 2) ** 0.5 + if d > self._MOVE_XY_TOL: + return False, f"arm stopped {d:.3f} m short of the target XY (likely stuck)" + return True, "" + + if func == "place_down": + if held_before is None: + return True, "" # nothing was held — a benign no-op + if self._carried is not None: + return False, "gripper still holding after place_down" + pos, _ = pb.getBasePositionAndOrientation(held_before) + if pos[2] < self._PLACE_FALL_Z: + return False, f"placed object fell off the surface (z={pos[2]:.3f})" + loc = self.scene.classify_location(pos) + # A "buffer" destination is just a free spot on the table. + expected_surface = "table" if expected_location == "buffer" else expected_location + if expected_surface and loc != expected_surface: + return False, f"object landed at '{loc}', expected '{expected_surface}'" + return True, "" + + return True, "" + + def _recover_to_safe_state(self, verbose=True): + """Return the arm to a known-good "best state" after a failed action. + + Lifts straight up to a safe height (keeping any carried object) and flies + home; if that controlled motion is itself stuck, teleports to the rest + pose as a last resort — without dropping a carried object. The next plan + is then generated from the resulting fresh state. + """ + safe_z = config.TABLE_TOP_Z + config.LIFT_HEIGHT + tcp = self.controller.tcp_position() + self.controller.reset_stuck() + self.controller.move_to_pose([tcp[0], tcp[1], safe_z]) # 1) up + self.controller.move_to_pose([config.TABLE_CENTER[0], 0.0, safe_z]) # 2) home + if self.controller.is_stuck(): + logger.warning("[RECOVER] controlled homing stuck — teleporting to rest pose") + self.controller.recover_to_rest(open_gripper=self._carried is None) + if verbose: + logger.info( + f"[RECOVER] arm at safe state {[round(c,3) for c in self.controller.tcp_position()]} " + f"(carrying={self.scene.get_name(self._carried) if self._carried is not None else None})" + ) + + @staticmethod + def _plan_signature(plan): + """Stable signature of a plan, for detecting a repeated failing plan.""" + return json.dumps(plan, sort_keys=True) + + @staticmethod + def _format_step(step): + """One-line human-readable form of a plan step, for execution logging.""" + func = step.get("function", "?") + args = step.get("args", {}) + if func == "pick_up": + return f"pick_up({args.get('object_id')})" + if func in ("move_to", "place_at"): + parts = [str(args.get("location_id"))] + if args.get("relation"): + parts.append(f"{args['relation']} {args.get('relative_to')}") + return f"{func}({', '.join(parts)})" + if func == "place_down": + return "place_down()" + return f"{func}({args})" + + def _execute(self, step, verbose=True): + func, args = step["function"], step["args"] + if func == "pick_up": + self._pick_up(args["object_id"], verbose) + elif func == "move_to": + self._move_to(args, verbose) + elif func == "place_down": + self._place_down(verbose) + elif func == "place_at": + self._place_at(args, verbose) + + def _pick_up(self, object_name, verbose=True): + object_id = self.scene.name_to_id(object_name) + if object_id is None: + logger.error(f"[ERR ] Unknown object '{object_name}'") + return + obj_class = self.scene.get_class(object_id) + + # Multi-angle approach: if a near neighbour would block a straight + # top-down descent, reach in diagonally from the object's open side + # (tilted "side" grasp) instead. This lets the arm extract an object + # whose top is blocked — e.g. a pear wedged beside a banana — without a + # collision, so even a mutual-blocking (cyclic) pair can be cleared. + clear_dir = self.scene.grasp_obstruction_dir(object_id) + if clear_dir is not None: + grasp_pos, grasp_ori = self.grasp_planner.compute_side_grasp_pose(object_id, clear_dir) + if verbose: + logger.info( + f"[ACT ] pick_up({object_name}) SIDE grasp (top-down blocked) " + f"clear_dir={[round(c,2) for c in clear_dir]} @{[round(c,3) for c in grasp_pos]}" + ) + force, held = self.controller.pick_side(object_id, grasp_pos, grasp_ori) + else: + grasp_pos, grasp_ori = self.grasp_planner.compute_grasp_pose(object_id, obj_class) + if verbose: + logger.info(f"[ACT ] pick_up({object_name}) grasp@{[round(c,3) for c in grasp_pos]}") + force, held = self.controller.pick(object_id, grasp_pos, grasp_ori) + if verbose: + logger.info(f"[GRIP ] force={force:.1f} N holding={held}") + if not held: + logger.warning(f"[WARN ] grasp failed for '{object_name}' — returning to home") + self._carried = None + self.controller.restore_object_collisions(object_id) + self.controller.move_to_pose( + [config.TABLE_CENTER[0], 0.0, config.TABLE_TOP_Z + config.LIFT_HEIGHT] + ) + return + + # Verify the object is actually elevated after the lift phase. + obj_pos, _ = pb.getBasePositionAndOrientation(object_id) + min_expected_z = config.TABLE_TOP_Z + config.LIFT_HEIGHT * 0.4 + if obj_pos[2] < min_expected_z: + logger.warning( + f"[WARN ] '{object_name}' slipped during lift " + f"(z={obj_pos[2]:.3f} < {min_expected_z:.3f}) — aborting carry" + ) + self.controller.gripper.open() + self._carried = None + self.controller.restore_object_collisions(object_id) + self.controller.move_to_pose( + [config.TABLE_CENTER[0], 0.0, config.TABLE_TOP_Z + config.LIFT_HEIGHT] + ) + return + + # Measure finger span and contact points for logging + span = self.controller.gripper.finger_span() + touching_fingers = [] + for finger in self.controller.gripper.finger_indices: + contacts = pb.getContactPoints( + bodyA=self.controller.robot_id, + bodyB=object_id, + linkIndexA=finger + ) + touching_fingers.append(len(contacts) > 0) + + logger.info( + f"[GRIP ] Grasp verification: finger span = {span * 1000:.1f} mm, " + f"contacts = {touching_fingers} (finger 1: {touching_fingers[0]}, finger 2: {touching_fingers[1]})" + ) + + self.controller.isolate_gripper_collisions(object_id) + self._carried = object_id + + def _reachable_placement_fn(self): + """Build a predicate: can the arm reach a candidate placement xy/z? + + Models the pose ``place()`` actually drives to — the TCP lowered so the + carried object's bottom sits at ``target_z + clearance``, i.e. TCP at + ``target_z + clearance + object_height``. Using the real (taller) place + height matters for tall objects (e.g. chips_can) so the optimiser doesn't + pick a far spot whose place pose is past the arm's reach. + """ + clearance = 0.02 # matches RobotController.place() default + + # Precompute grasp orientation and height once to avoid log spam and redundant work + try: + obj_class = self.scene.get_class(self._carried) + _, cached_grasp_ori = self.grasp_planner.compute_grasp_pose(self._carried, obj_class) + aabb_min, aabb_max = pb.getAABB(self._carried) + cached_obj_height = aabb_max[2] - aabb_min[2] + can_compute = True + except Exception: + can_compute = False + + def reachable_fn(pos): + if not can_compute: + return False + try: + place_tcp = [pos[0], pos[1], pos[2] + clearance + cached_obj_height] + return self.controller.is_reachable(place_tcp, cached_grasp_ori) + except Exception: + return False + return reachable_fn + + def _resolve_target(self, args): + """Turn a planner ``args`` dict into a concrete world ``[x, y, z]``. + + ``location_id`` is ``"tray"`` or ``"table"``. The continuous placement + optimiser picks a free, reachable, collision-free spot; on the table it + also honours an optional ``relation`` + ``relative_to`` (see + :meth:`SceneManager.find_free_placements`). Margins relax before any + fallback so crowded surfaces still pack objects side-by-side. + """ + location_id = args.get("location_id") + footprint = self.scene.get_footprint(self._carried) + footprint = (min(footprint[0], 0.115), min(footprint[1], 0.115)) + reachable_fn = self._reachable_placement_fn() + margins = (config.PLACEMENT_SAFETY_MARGIN, 0.01, 0.0) + + if location_id == "buffer": + # Strategy-layer buffer allocation: a free, reachable spot kept clear + # of the objects this obstacle was tangled with (``avoid``), so + # parking it there breaks the blocking relationship. Falls back to a + # plain free table spot. + avoid_names = args.get("avoid", []) + avoid_positions = [] + for nm in avoid_names: + aid = self.scene.name_to_id(nm) + if aid is not None: + p, _ = pb.getBasePositionAndOrientation(aid) + avoid_positions.append(p) + spot = self.scene.find_buffer_spot( + footprint, exclude_ids=[self._carried], + avoid_positions=avoid_positions, reachable_fn=reachable_fn, + ) + if spot is not None: + logger.info(f"[BUFFER] parking spot {[round(c,3) for c in spot]} " + f"(clear of {avoid_names})") + return spot + logger.warning("[WARN ] No buffer spot found, using table centre.") + return [config.TABLE_CENTER[0], config.TABLE_CENTER[1], config.TABLE_TOP_Z] + + if location_id == "tray": + for m in margins: + spots = self.scene.find_free_tray_placements( + footprint, exclude_ids=[self._carried], max_results=1, + reachable_fn=reachable_fn, margin=m, + ) + if spots: + if m < config.PLACEMENT_SAFETY_MARGIN: + logger.warning(f"[WARN ] Placed in tray at reduced safety margin={m:.2f} m.") + return spots[0] + # Tray has no fully-free window. Instead of stacking everything at a + # fixed class offset (which collides objects at one point and knocks + # them out of the tray), take the least-overlapping reachable, in-bounds + # spot so the objects stay spread apart. + spots = self.scene.find_free_tray_placements( + footprint, exclude_ids=[self._carried], max_results=1, + reachable_fn=reachable_fn, margin=0.0, best_effort=True, + ) + if spots: + logger.warning("[WARN ] Tray crowded — using least-overlap spot " + f"{[round(c, 3) for c in spots[0]]}.") + return spots[0] + logger.warning("[WARN ] No reachable tray spot, using class fallback offset.") + obj_class = self.scene.get_class(self._carried) + dx = config.TRAY_CLASS_OFFSET_X.get(obj_class, 0.0) + tx, ty, tz = config.TRAY_POSITION + return [tx + dx, ty, tz] + + if location_id == "table": + relation = args.get("relation") + relative_to = args.get("relative_to") + relative_to_pos = None + if relative_to: + ref_id = self.scene.name_to_id(relative_to) + if ref_id is not None: + relative_to_pos, _ = pb.getBasePositionAndOrientation(ref_id) + + # 1) Honour the requested relation first, relaxing the margin. + if relation and relative_to_pos is not None: + for m in margins: + spots = self.scene.find_free_placements( + footprint, exclude_ids=[self._carried], max_results=1, + reachable_fn=reachable_fn, margin=m, + relative_to_pos=relative_to_pos, relation=relation, + ) + if spots: + return spots[0] + # 2) Any free spot on the table. + for m in margins: + spots = self.scene.find_free_placements( + footprint, exclude_ids=[self._carried], max_results=1, + reachable_fn=reachable_fn, margin=m, + ) + if spots: + if m < config.PLACEMENT_SAFETY_MARGIN: + logger.warning(f"[WARN ] Placed on table at reduced safety margin={m:.2f} m.") + return spots[0] + # Table full: least-overlapping reachable spot beats stacking at centre. + spots = self.scene.find_free_placements( + footprint, exclude_ids=[self._carried], max_results=1, + reachable_fn=reachable_fn, margin=0.0, best_effort=True, + ) + if spots: + logger.warning("[WARN ] Table crowded — using least-overlap spot " + f"{[round(c, 3) for c in spots[0]]}.") + return spots[0] + logger.warning("[WARN ] No reachable table spot, using center.") + return [config.TABLE_CENTER[0], config.TABLE_CENTER[1], config.TABLE_TOP_Z] + + logger.error(f"[ERR ] Unknown location '{location_id}'") + return [config.TABLE_CENTER[0], config.TABLE_CENTER[1], config.TABLE_TOP_Z] + + def _place_at(self, args, verbose=True): + if self._carried is None: + logger.warning("[WARN ] place_at skipped — not holding anything") + return + target = self._resolve_target(args) + if verbose: + logger.info( + f"[ACT ] place_at({args.get('location_id')}, " + f"relation={args.get('relation')}, relative_to={args.get('relative_to')}) " + f"-> {[round(c, 3) for c in target]}" + ) + self.controller.place(target) + self._carried = None + self._pending_target_pos = None + self.controller.move_to_pose( # return home-ish + [config.TABLE_CENTER[0], 0.0, config.TABLE_TOP_Z + config.LIFT_HEIGHT] + ) + + def _visualize_move(self, tcp_pos, target, xy_path, waypoints, exclude): + """Draw the planning result onto the 3D scene if --viz is on (else no-op).""" + if not self.viz: + return + try: + from llm_panda import visualize + except Exception as exc: # pragma: no cover + logger.warning(f"[VIZ ] unavailable: {exc}") + return + if self._overlay is None: + self._overlay = visualize.GuiOverlay() + self._overlay.clear() + self._overlay.draw_obstacles(self.scene, exclude_ids=exclude) + if xy_path is not None: + self._overlay.draw_path(xy_path) + self._overlay.draw_trajectory(waypoints) + + def toggle_viz(self, kind="viz"): + """Flip the 3D overlay live (used by the :viz command).""" + self.viz = not self.viz + if not self.viz and self._overlay is not None: + self._overlay.clear() + return f"[OK ] 3D overlay {'ON' if self.viz else 'OFF'} (applies on next move_to)" + + def _move_to(self, args, verbose=True): + if self._carried is None: + logger.warning("[WARN ] move_to skipped — not holding anything") + return + target = self._resolve_target(args) + if verbose: + logger.info( + f"[ACT ] move_to({args.get('location_id')}, " + f"relation={args.get('relation')}, relative_to={args.get('relative_to')}) " + f"-> {[round(c, 3) for c in target]}" + ) + + self._pending_target_pos = target + + # Transport the carried object over to the target via a U-shaped path + # (lift to a corridor-clearing ceiling, then fly horizontally). We stop + # ABOVE the target — place_down performs the final descent. + held_id = self.controller.gripper._constrained_id + if held_id is not None: + aabb_min, aabb_max = pb.getAABB(held_id) + carried_height = aabb_max[2] - aabb_min[2] + exclude = [self.controller.robot_id, held_id] + else: + carried_height = 0.0 + exclude = [self.controller.robot_id] + + tcp_pos = self.controller.tcp_position() + + # Route the horizontal fly with A* on the destination surface's 2D cost + # map so the arm bends AROUND obstacles (other objects on that surface) + # instead of relying solely on flying over them. Works for both the + # table and the tray; anything else falls back to a straight U path. + surface = self.scene.classify_location(target) + xy_path = None + if surface in ("table", "tray"): + xy_path = plan_path( + self.scene, surface, (tcp_pos[0], tcp_pos[1]), (target[0], target[1]), + exclude_ids=exclude, carried_height=carried_height, + ) + if verbose and len(xy_path) > 1: + logger.info( + f"[A* ] route on {surface} around obstacles via " + f"{[[round(x, 3), round(y, 3)] for x, y in xy_path]}" + ) + waypoints = self.controller.plan_u_path( + tcp_pos, xy_path, target[2], + carried_height=carried_height, exclude_ids=exclude, + ) + else: + waypoints = self.controller.plan_u_trajectory( + tcp_pos, target, carried_height=carried_height, exclude_ids=exclude, + ) + + # Optional visual debugging of the planning result. + self._visualize_move(tcp_pos, target, xy_path, waypoints, exclude) + # Drop the final descend waypoint: hover above the target so place_down + # can perform the controlled descent. + self.controller.execute_trajectory(waypoints[:-1]) + + def _place_down(self, verbose=True): + if self._carried is None: + logger.warning("[WARN ] place_down() skipped — not holding anything") + return + + if self._pending_target_pos is None: + tcp_pos = self.controller.tcp_position() + target = [tcp_pos[0], tcp_pos[1], config.TABLE_TOP_Z] + logger.warning(f"[WARN ] place_down(): no pending target pos, using current TCP XY -> {target}") + else: + target = self._pending_target_pos + + if verbose: + logger.info(f"[ACT ] place_down() -> {target}") + + self.controller.place(target) + self._carried = None + self._pending_target_pos = None + self.controller.move_to_pose( # return home-ish + [config.TABLE_CENTER[0], 0.0, config.TABLE_TOP_Z + config.LIFT_HEIGHT] + ) + + def reset_objects(self, seed=None): + """Remove current objects and re-spawn them (optionally re-randomised).""" + for oid in self.scene.object_ids: + pb.removeBody(oid) + self.scene = SceneManager() # fresh registry + self._carried = None + self._pending_target_pos = None + if seed is not None: + self.rng = random.Random(seed) + self._spawn_objects() + for _ in range(480): # 2 s sim-time; tall/cylindrical objects need >0.5 s to settle + pb.stepSimulation() + self._validate_spawn() + + def _validate_spawn(self): + """Teleport any object that bounced off the table back to a free spot.""" + # Use physical table bounds (not the edge-margined usable area) so that + # objects near the table edge aren't falsely flagged as off-table. + cx, cy = config.TABLE_CENTER + hx, hy = config.TABLE_HALF_EXTENTS[0], config.TABLE_HALF_EXTENTS[1] + x0, x1 = cx - hx, cx + hx + y0, y1 = cy - hy, cy + hy + + needs_settle = False + for oid in self.scene.object_ids: + pos, ori = pb.getBasePositionAndOrientation(oid) + on_table = (x0 <= pos[0] <= x1 and y0 <= pos[1] <= y1 + and pos[2] >= config.TABLE_TOP_Z - 0.05) + if not on_table: + name = self.scene.get_name(oid) + footprint = self.scene.get_footprint(oid) + free_spots = self.scene.find_free_placements( + footprint, exclude_ids=[oid], max_results=1 + ) + if free_spots: + sx, sy, sz = free_spots[0] + pb.resetBasePositionAndOrientation(oid, [sx, sy, sz + 0.10], ori) + logger.warning( + f"[RESET] '{name}' off-table after spawn " + f"({[round(c,3) for c in pos]}) → teleported to " + f"{[round(c,3) for c in (sx, sy, sz)]}" + ) + needs_settle = True + else: + logger.error(f"[ERR ] Spawn validation: no free spot for '{name}'") + if needs_settle: + for _ in range(480): + pb.stepSimulation() + + def idle(self, seconds): + """Keep the GUI responsive for a while (no-op in DIRECT).""" + end = time.time() + seconds + while time.time() < end: + pb.stepSimulation() + time.sleep(config.SIM_TIMESTEP) + + # ------------------------------------------------------------------ # + # Interactive shell (REPL) + # ------------------------------------------------------------------ # + _HELP = ( + "Commands:\n" + " plan & execute, e.g. \"gắp khối đỏ đặt vào tray\"\n" + " :scene print the current scene state (JSON)\n" + " :reset [seed] re-spawn objects (optionally with a new seed)\n" + " :home move the arm back to the rest pose\n" + " :viz toggle the 3D overlay (obstacles / A* / U-path)\n" + " :help show this help\n" + " :quit / :q exit" + ) + + def interactive(self): + """Read-eval-print loop: keep one persistent world, run commands live.""" + logger.info("\n=== LLM-Panda interactive shell ===") + logger.info(self._HELP) + logger.info(f"\n[SCENE] {self.scene.describe()}") + while True: + try: + line = input("\npanda> ").strip() + except (EOFError, KeyboardInterrupt): + print() + break + if not line: + continue + if line in (":quit", ":q", ":exit"): + break + if line == ":help": + logger.info(self._HELP) + elif line == ":scene": + logger.info(self.scene.get_scene_state_text()) + elif line == ":home": + self.controller.reset_to_home() + logger.info("[OK ] arm homed") + elif line == ":viz": + logger.info(self.toggle_viz()) + elif line.split()[0] == ":reset": + parts = line.split() + seed = int(parts[1]) if len(parts) > 1 else None + self.reset_objects(seed=seed) + logger.info(f"[OK ] objects re-spawned -> {self.scene.describe()}") + elif line.startswith(":"): + logger.error(f"[ERR ] unknown command '{line}'. Type :help") + else: + try: + self.run_command(line) + except Exception as exc: # keep the shell alive on action errors + logger.error(f"[ERR ] {exc}") + + def disconnect(self): + pb.disconnect(self.client) + + +# --------------------------------------------------------------------------- # +# Chat GUI (tkinter) + background simulation runner +# --------------------------------------------------------------------------- # + +class _ListHandler(logging.Handler): + """Logging handler that appends formatted records to a list (for chat display).""" + + def __init__(self, target: list): + super().__init__(level=logging.INFO) + self._target = target + + def emit(self, record: logging.LogRecord): + self._target.append(self.format(record)) + + +class _SimRunner(threading.Thread): + """Background thread: continuously steps physics and processes commands.""" + + def __init__(self, sim: PandaSimulation, cmd_q: _queue.Queue, res_q: _queue.Queue): + super().__init__(daemon=True, name="sim-runner") + self.sim = sim + self.cmd_q = cmd_q + self.res_q = res_q + self._stop_event = threading.Event() + + def run(self): + # Real-time mode: PyBullet advances physics on its own clock between + # commands, so objects keep falling/settling even when we're idle. + pb.setRealTimeSimulation(1) + try: + while not self._stop_event.is_set(): + try: + cmd = self.cmd_q.get(timeout=0.05) + except _queue.Empty: + continue # physics still runs via real-time mode + + if cmd is None: # sentinel: GUI closed + break + # Hand-step during command execution for precise robot control. + pb.setRealTimeSimulation(0) + self._handle(cmd) + pb.setRealTimeSimulation(1) # resume continuous physics + finally: + pb.setRealTimeSimulation(0) + + def _handle(self, cmd: str): + output_lines: list = [] + try: + if cmd == ":scene": + self._put(self.sim.scene.get_scene_state_text()) + elif cmd == ":home": + self.sim.controller.reset_to_home() + self._put("[OK ] arm homed") + elif cmd == ":viz": + self._put(self.sim.toggle_viz()) + elif cmd.split()[0] == ":reset": + parts = cmd.split() + seed = int(parts[1]) if len(parts) > 1 else None + self.sim.reset_objects(seed=seed) + self._put(f"[OK ] objects re-spawned -> {self.sim.scene.describe()}") + elif cmd.startswith(":"): + self._put(f"[ERR ] unknown command '{cmd}'. Type :help", kind="error") + else: + # Capture logger output for the chat panel. + handler = _ListHandler(output_lines) + logging.getLogger().addHandler(handler) + try: + self.sim.run_command(cmd, verbose=True) + finally: + logging.getLogger().removeHandler(handler) + if output_lines: + self._put("\n".join(output_lines)) + except Exception as exc: + logger.error(f"[ERR ] {exc}", exc_info=True) + self._put(f"[ERR ] {exc}", kind="error") + finally: + self.res_q.put({"kind": "done"}) + + def _put(self, text: str, kind: str = "log"): + self.res_q.put({"kind": kind, "text": text}) + + def stop(self): + self._stop_event.set() + + +class ChatGUI: + """Tkinter chat window for issuing NL commands to the simulation.""" + + _HELP = ( + "=== LLM-Panda Chat ===\n" + "Nhập lệnh tự nhiên hoặc các lệnh hệ thống:\n" + " vd: \"gắp khối đỏ đặt vào tray\"\n" + " :scene xem trạng thái cảnh\n" + " :reset [seed] spawn lại vật thể\n" + " :home đưa tay máy về vị trí home\n" + " :viz bật/tắt overlay 3D (vật cản / A* / quỹ đạo chữ-U)\n" + " :help hiển thị trợ giúp\n" + " :quit / :q thoát\n" + ) + + def __init__(self, cmd_q: _queue.Queue, res_q: _queue.Queue): + self.cmd_q = cmd_q + self.res_q = res_q + + self.root = tk.Tk() + self.root.title("LLM-Panda – Control Panel") + self.root.geometry("540x660") + self.root.configure(bg="#1e1e2e") + self.root.resizable(True, True) + + # ── chat log ──────────────────────────────────────────────────── + self.log = scrolledtext.ScrolledText( + self.root, state="disabled", wrap=tk.WORD, + bg="#1e1e2e", fg="#cdd6f4", insertbackground="#cdd6f4", + font=("Courier", 10), relief=tk.FLAT, bd=0, + selectbackground="#45475a", + ) + self.log.pack(fill=tk.BOTH, expand=True, padx=8, pady=(8, 4)) + + self.log.tag_configure("heading", foreground="#cba6f7", + font=("Courier", 10, "bold")) + self.log.tag_configure("user", foreground="#89b4fa") # blue + self.log.tag_configure("system", foreground="#a6e3a1") # green + self.log.tag_configure("error", foreground="#f38ba8") # red + self.log.tag_configure("plan", foreground="#fab387") # peach + + # ── status bar ────────────────────────────────────────────────── + self._status = tk.StringVar(value="● Sẵn sàng") + tk.Label( + self.root, textvariable=self._status, + bg="#313244", fg="#cdd6f4", anchor="w", + font=("Courier", 9), padx=8, pady=3, + ).pack(fill=tk.X) + + # ── input row ─────────────────────────────────────────────────── + row = tk.Frame(self.root, bg="#1e1e2e") + row.pack(fill=tk.X, padx=8, pady=(4, 8)) + + self.entry = tk.Entry( + row, bg="#313244", fg="#cdd6f4", insertbackground="#cdd6f4", + font=("Courier", 10), relief=tk.FLAT, bd=4, + ) + self.entry.pack(side=tk.LEFT, fill=tk.X, expand=True, ipady=5) + self.entry.bind("", self._send) + self.entry.focus_set() + + tk.Button( + row, text=" Gửi ", command=self._send, + bg="#89b4fa", fg="#1e1e2e", activebackground="#74c7ec", + font=("Courier", 10, "bold"), relief=tk.FLAT, padx=8, pady=4, + cursor="hand2", + ).pack(side=tk.RIGHT, padx=(6, 0)) + + self._append(self._HELP, tag="heading") + self.root.after(80, self._poll) + + # ── public ────────────────────────────────────────────────────────── + def run(self): + self.root.protocol("WM_DELETE_WINDOW", self._on_close) + self.root.mainloop() + + # ── private ───────────────────────────────────────────────────────── + def _send(self, _event=None): + text = self.entry.get().strip() + if not text: + return + self.entry.delete(0, tk.END) + + if text in (":quit", ":q", ":exit"): + self._on_close() + return + if text == ":help": + self._append(self._HELP, tag="heading") + return + + self._append(f"\npanda> {text}\n", tag="user") + self.cmd_q.put(text) + self._status.set("● Đang xử lý…") + self.entry.config(state="disabled") + + def _poll(self): + try: + while True: + msg = self.res_q.get_nowait() + kind = msg.get("kind", "log") + text = msg.get("text", "") + if kind == "done": + self._status.set("● Sẵn sàng") + self.entry.config(state="normal") + self.entry.focus_set() + elif kind == "error": + self._append(text + "\n", tag="error") + else: + self._append(text + "\n") + except _queue.Empty: + pass + self.root.after(80, self._poll) + + def _append(self, text: str, tag: Optional[str] = None): + self.log.config(state="normal") + if tag: + self.log.insert(tk.END, text, tag) + else: + self.log.insert(tk.END, text) + self.log.see(tk.END) + self.log.config(state="disabled") + + def _on_close(self): + self.cmd_q.put(None) # signal sim thread to stop + self.root.destroy() + + +def _run_chat_gui(sim: PandaSimulation): + """Launch the chat panel + background sim-runner. Blocks until window closes.""" + cmd_q: _queue.Queue = _queue.Queue() + res_q: _queue.Queue = _queue.Queue() + + # Post initial scene info before the GUI starts polling. + res_q.put({"kind": "log", "text": f"[SCENE] {sim.scene.describe()}\n"}) + + runner = _SimRunner(sim, cmd_q, res_q) + runner.start() + + gui = ChatGUI(cmd_q, res_q) + gui.run() # blocks (tkinter mainloop in main thread) + + runner.stop() + runner.join(timeout=3.0) + + +# --------------------------------------------------------------------------- # +# CLI entry point +# --------------------------------------------------------------------------- # +def main(): + parser = argparse.ArgumentParser( + description="LLM-controlled Franka Panda pick-and-place", + epilog=( + "Modes:\n" + " --gui 3-D view + chat window (recommended)\n" + " --command \"...\" run one instruction, then exit (one-shot)\n" + " -i / --interactive drop into a live command shell\n" + " (no flags) interactive shell by default" + ), + formatter_class=argparse.RawDescriptionHelpFormatter, + ) + parser.add_argument("--gui", action="store_true", help="launch the PyBullet GUI + chat panel") + parser.add_argument("--seed", type=int, default=0, help="RNG seed for object placement") + parser.add_argument( + "--viz", action="store_true", + help="draw obstacles / A* route / U-trajectory onto the 3D scene (use with --gui)", + ) + parser.add_argument( + "-c", "--command", type=str, default=None, + help="natural-language instruction (one-shot unless --interactive)", + ) + parser.add_argument( + "-i", "--interactive", action="store_true", + help="enter the interactive shell (after --command, if given)", + ) + parser.add_argument( + "--llm", choices=["rule", "openai"], default="openai", + help="planner: 'rule' (offline) or 'openai' (real LLM via OPENAI_API_KEY, default)", + ) + parser.add_argument( + "--idle", type=float, default=5.0, + help="seconds to keep the GUI window open after a one-shot run", + ) + args = parser.parse_args() + + _logger_setup.setup() + + agent = None + if args.llm == "openai": + planner = RemoteLLMPlanner() + if not planner.api_key: + parser.error("--llm openai needs OPENAI_API_KEY (set it in .env or the environment)") + agent = LLMAgent(planner=planner) + logger.info(f"[LLM ] OpenAI planner enabled (model={planner.model})") + + sim = PandaSimulation(gui=args.gui, seed=args.seed, agent=agent, viz=args.viz) + try: + # One-shot command (non-interactive). + if args.command and not args.interactive: + try: + sim.run_command(args.command) + logger.info(f"\n[FINAL] {sim.scene.describe()}") + except Exception as exc: + logger.error(f"[ERR ] {type(exc).__name__}: {exc}") + if args.gui: + sim.idle(args.idle) + return + + # GUI mode → chat panel (blocks until window is closed). + if args.gui: + if args.command: + # Run the command first, then open the chat panel. + try: + sim.run_command(args.command) + logger.info(f"\n[FINAL] {sim.scene.describe()}") + except Exception as exc: + logger.error(f"[ERR ] {type(exc).__name__}: {exc}") + _run_chat_gui(sim) + return + + # Headless / terminal interactive shell. + if args.command: + try: + sim.run_command(args.command) + logger.info(f"\n[FINAL] {sim.scene.describe()}") + except Exception as exc: + logger.error(f"[ERR ] {type(exc).__name__}: {exc}") + + if args.interactive or not args.command: + sim.interactive() + + finally: + sim.disconnect() + + +if __name__ == "__main__": + main() diff --git a/pipeline_pick_place_robot_arm.md b/pipeline_pick_place_robot_arm.md new file mode 100644 index 0000000000000000000000000000000000000000..2007e953bc719afb959e43a19286009692085e80 --- /dev/null +++ b/pipeline_pick_place_robot_arm.md @@ -0,0 +1,813 @@ +# Pipeline hoàn chỉnh cho bài toán robot arm gắp và di chuyển vật theo hướng tiếp cận đã chỉnh sửa + +## 1. Mục tiêu và nguyên tắc chung của pipeline + +Tài liệu này mô tả **pipeline hoàn chỉnh** cho bài toán robot arm thực hiện tác vụ **pick-and-place** theo đúng các chỉnh sửa đã chốt. Mục tiêu là: robot nhận lệnh di chuyển một vật từ vị trí hiện tại đến vị trí đích, sau đó nếu còn vật khác thì tiếp tục thực hiện ngay từ trạng thái hiện tại; chỉ khi kết thúc toàn bộ nhiệm vụ thì robot mới quay về vị trí ban đầu. + +Pipeline này tuân theo các nguyên tắc sau: + +### 1.1. Không dùng pre-grasp như một giai đoạn bắt buộc +Robot **không bắt buộc** phải đi qua một pre-grasp pose rồi mới tiến vào grasp pose. Thay vào đó, hệ thống sẽ tìm trực tiếp **grasp pose cuối cùng** sao cho nếu robot đi tới được pose đó thì **chỉ cần đóng gripper là tiếp xúc với vật**. + +### 1.2. Không dùng approach direction như một khái niệm bắt buộc +Pipeline **không yêu cầu** phải định nghĩa trước một approach direction riêng. Điều cần có là **grasp pose cuối cùng** của end-effector, tức là pose mà robot có thể đi tới mà **không va chạm**, và tại đó chỉ cần đóng gripper là tiếp xúc với object. + +### 1.3. Collision rule thống nhất cho toàn bộ pipeline +Đây là chỉnh sửa quan trọng nhất của bài toán. **Trong mọi giai đoạn**, robot **không được va chạm với bất kỳ vật thể nào trong môi trường, kể cả object target**, ngoại trừ thời điểm đóng gripper tại grasp pose để tạo tiếp xúc gắp. Cụ thể: + +- Trong quá trình sinh và kiểm tra grasp pose: + - nếu robot ở grasp pose mà vẫn đang **xuyên vào object target** hoặc xuyên vào vật cản khác thì pose đó bị loại. +- Trong quá trình giải IK: + - nghiệm IK nào gây va chạm với **bất kỳ vật thể nào**, kể cả object target, đều bị loại. +- Trong quá trình motion planning bằng RRT-Connect: + - mọi cấu hình trung gian trên quỹ đạo đều phải collision-free với toàn bộ môi trường, bao gồm cả object target. +- Trong quá trình robot mang vật đi đến nơi đặt: + - robot vẫn không được va chạm với môi trường hay các vật thể khác. +- Bài toán **không dùng “collision mềm”**, không có khái niệm cho phép finger xuyên vào object trong lúc motion planning. +- Chỉ khi robot đã đến đúng grasp pose và thực hiện lệnh đóng gripper thì mới tạo tiếp xúc gắp. + +### 1.4. Không dùng attach constraint để đơn giản hóa mô phỏng +Trong toàn bộ quá trình gắp, di chuyển và đặt vật, **không được attach object vào gripper bằng constraint**. Điều này làm bài toán thực tế hơn vì object phải thực sự được giữ bằng tiếp xúc vật lý và ma sát của gripper, chứ không bị “dính cứng” vào tay robot bằng một ràng buộc nhân tạo. + +### 1.5. Tối ưu luồng công việc nhiều vật +Nếu sau khi đặt xong một vật mà vẫn còn vật khác cần gắp, robot sẽ **không quay về home pose**. Thay vào đó, robot **motion plan trực tiếp từ cấu hình hiện tại** sang tác vụ tiếp theo. Chỉ khi toàn bộ nhiệm vụ đã hoàn thành thì robot mới motion plan về vị trí ban đầu. + +--- + +# 2. Đầu vào và đầu ra của hệ thống + +## 2.1. Đầu vào + +Hệ thống cần các thành phần sau: + +### (A) Mô hình robot +- URDF hoặc mô hình động học của robot arm +- joint limits của toàn bộ khớp +- thông tin gripper: + - link nào là finger trái + - link nào là finger phải + - frame end-effector / TCP dùng cho IK +- pose ban đầu của robot hoặc cấu hình joint ban đầu \(q_{home}\) + +### (B) Mô hình object cần gắp +Object được biểu diễn bằng: +- **collision mesh** +- **visual mesh** + +Mesh này được dùng để: +- xác định bề mặt object +- tính normal trên bề mặt +- sinh contact pair candidate +- phục vụ collision checking trong môi trường mô phỏng + +### (C) Môi trường +- bàn, giá, kệ, tường, vật cản +- các object khác chưa cần gắp hoặc sẽ gắp sau +- pose của từng vật thể trong môi trường + +### (D) Danh sách nhiệm vụ pick-and-place +Ví dụ một task list có thể là: +- gắp object A từ pose hiện tại đến pose đích A +- sau đó gắp object B từ pose hiện tại đến pose đích B +- … +- sau khi xong toàn bộ thì quay về home pose + +### (E) Trạng thái hiện tại của robot +- cấu hình khớp hiện tại \(q_{current}\) + +--- + +## 2.2. Đầu ra + +Đầu ra của hệ thống là một chuỗi các quỹ đạo và hành động điều khiển, ví dụ: + +1. Quỹ đạo từ cấu hình hiện tại đến grasp pose của object thứ nhất +2. Lệnh đóng gripper +3. Quỹ đạo từ grasp pose đến place pose của object thứ nhất +4. Lệnh mở gripper +5. Quỹ đạo từ trạng thái hiện tại đến grasp pose của object thứ hai +6. Lệnh đóng gripper +7. Quỹ đạo đến place pose của object thứ hai +8. … +9. Quỹ đạo cuối cùng đưa robot về home pose khi hết nhiệm vụ + +--- + +# 3. Kiến trúc tổng thể của pipeline sau khi chỉnh sửa + +Pipeline tổng thể cho **một object** sẽ là: + +\[ +\text{Scene Setup} +\rightarrow +\text{Sinh contact pair} +\rightarrow +\text{Sinh grasp pose candidate} +\rightarrow +\text{Giải IK cho grasp pose} +\rightarrow +\text{Collision check nghiệm IK} +\rightarrow +\text{RRT-Connect đến grasp pose} +\rightarrow +\text{Đóng gripper để grasp} +\rightarrow +\text{RRT-Connect mang vật đến place pose} +\rightarrow +\text{Mở gripper để đặt vật} +\] + +Điểm quan trọng là pipeline **không sinh toàn bộ tập grasp candidate rồi chấm điểm hàng loạt** như phiên bản trước. Thay vào đó, theo chỉnh sửa của bài toán, pipeline sẽ hoạt động theo kiểu **tuần tự và quay lui**: + +1. Tìm **một contact pair hợp lệ** +2. Từ contact pair đó sinh ra **một grasp pose candidate** +3. Giải IK cho grasp pose đó +4. Nếu nghiệm IK không collision-free thì thử nghiệm IK khác hoặc grasp pose khác của cùng contact pair +5. Nếu tìm được IK collision-free thì chạy **RRT-Connect** +6. Nếu RRT-Connect thất bại, quay lui: + - thử grasp pose khác của cùng contact pair, hoặc + - nếu hết grasp pose thì tìm contact pair mới +7. Khi đã tới grasp pose thành công, đóng gripper và chuyển thẳng sang bài toán place + +--- + +# 4. Pipeline chi tiết cho một tác vụ pick-and-place + +## Giai đoạn 1. Khởi tạo scene và trạng thái hiện tại + +### 4.1.1. Nạp mô hình robot và môi trường +- Load URDF robot arm +- Load collision mesh / visual mesh của object target +- Load các obstacle và object khác trong scene +- Đặt robot ở cấu hình hiện tại \(q_{current}\) +- Đặt object target tại pose hiện tại của nó + +### 4.1.2. Xác định frame sử dụng +Cần phân biệt rõ các frame sau: +- **Object frame**: frame gắn với object +- **Grasp frame**: frame được xây dựng từ contact pair +- **End-effector frame / TCP**: frame mà IK sẽ điều khiển + +### 4.1.3. Collision rule của toàn bộ hệ thống +Rule thống nhất là: + +> Trong mọi giai đoạn tính toán, motion planning và kiểm tra pose, robot **không được va chạm với bất kỳ vật thể nào**, kể cả object target. Nếu phát hiện va chạm thì candidate đó bị loại hoặc quỹ đạo đó bị loại. + +Cụ thể: +- IK state collision → loại +- RRT node collision → loại +- grasp pose collision → loại +- place pose collision → loại +- quỹ đạo mang vật va chạm → loại + +--- + +## Giai đoạn 2. Biểu diễn object và sinh contact pair + +## 4.2.1. Biểu diễn hình học object +Object được biểu diễn bằng: +- collision mesh +- visual mesh + +Trong đó collision mesh là phần quan trọng nhất cho bài toán grasp planning vì: +- có thể sample điểm trên bề mặt +- có thể lấy normal tại các đỉnh hoặc tại điểm trên tam giác +- có thể dùng để kiểm tra điều kiện antipodal + +### 4.2.2. Tính normal trên mesh +Pipeline giả sử có thể sử dụng thư viện hoặc công cụ tính sẵn vector pháp tuyến trên mỗi đỉnh mesh. Khi đó với mỗi điểm hoặc mỗi đỉnh trên bề mặt, ta có: +- vị trí \(p\) +- vector pháp tuyến \(n\) + +Các normal này sẽ được dùng để sinh contact pair theo kiểu antipodal gần đúng. + +--- + +## Giai đoạn 3. Sinh contact pair theo hướng antipodal gần đúng + +Đây là bước trả lời câu hỏi: **robot sẽ đặt hai finger vào hai vị trí nào trên object**. + +### 4.3.1. Ý tưởng chung +Ta sẽ duyệt trên bề mặt mesh để tìm **một cặp điểm** \((c_1, c_2)\) có thể đóng vai trò là hai contact của hai finger. Việc tìm contact pair được thực hiện **theo từng cặp một**, không cần sinh toàn bộ rồi chấm điểm. Sau khi có một cặp hợp lệ, pipeline sẽ chuyển ngay sang bước tính grasp pose, IK và motion planning. + +Chỉ khi: +- grasp pose không hợp lệ, hoặc +- IK không tìm được nghiệm collision-free, hoặc +- motion planning không tìm được quỹ đạo, + +thì hệ thống mới quay lui để thử **contact pair khác**. + +### 4.3.2. Tiêu chí antipodal gần đúng +Một cặp điểm \((c_1, c_2)\) được xem là ứng viên nếu: +- khoảng cách giữa hai điểm nằm trong khả năng mở của gripper +- normal tại hai điểm gần đối nhau + +Gọi: +- \(n_1\): normal tại \(c_1\) +- \(n_2\): normal tại \(c_2\) + +Ta mong muốn: +\[ +n_1 \approx -n_2 +\] + +Đồng thời vector nối giữa hai contact: +\[ +d = \frac{c_2-c_1}{\|c_2-c_1\|} +\] + +nên gần song song với hướng pháp tuyến ngược: +\[ +d \approx -n_1 \approx n_2 +\] + +Điều này phản ánh việc hai finger kẹp vào hai mặt đối diện của object. + +### 4.3.3. Điều kiện kiểm tra contact pair hợp lệ +Một contact pair chỉ được giữ lại nếu thỏa điều kiện: + +#### Điều kiện 1. Khoảng cách giữa hai contact phù hợp với gripper +\[ +w_{min} \le \|c_2-c_1\| \le w_{max} +\] + +Trong đó: +- \(w_{min}\): khoảng mở nhỏ nhất mà gripper vẫn có thể giữ vật ổn định +- \(w_{max}\): khoảng mở tối đa của gripper + +### 4.3.4. Các điều kiện đã bỏ khỏi pipeline +Theo chỉnh sửa, **không sử dụng** các điều kiện sau trong bước lọc sơ bộ: +- không kiểm tra riêng “bề mặt xung quanh đủ đặt finger” +- không loại sớm contact pair chỉ vì quá sát bàn hoặc khó tiếp cận +- không chấm điểm contact pair + +Thay vào đó, pipeline để các bước sau như IK và motion planning quyết định contact pair đó có dùng được hay không. + +### 4.3.5. Cơ chế tìm contact pair +Pipeline vận hành như sau: +1. Duyệt qua các cặp điểm ứng viên trên mesh +2. Kiểm tra điều kiện antipodal gần đúng và điều kiện khoảng cách +3. Nếu cặp không hợp lệ → bỏ qua +4. Nếu cặp hợp lệ → **dừng bước tìm contact pair** và chuyển sang giai đoạn sinh grasp pose từ chính contact pair này +5. Chỉ khi toàn bộ quá trình phía sau thất bại thì mới quay lại để tìm cặp contact pair mới + +--- + +## Giai đoạn 4. Sinh grasp pose từ contact pair + +Sau khi tìm được một contact pair hợp lệ, pipeline sẽ xây dựng grasp pose ứng viên từ cặp đó. + +### 4.4.1. Tính grasp center +Với contact pair \((c_1,c_2)\), tâm grasp được tính: +\[ +p_c = \frac{c_1+c_2}{2} +\] + +Đây là điểm trung tâm giữa hai finger khi gripper ở grasp pose. + +### 4.4.2. Tính grasp axis +Trục đóng/mở của gripper khi grasp được lấy từ vector nối hai contact: +\[ +x_g = \frac{c_2-c_1}{\|c_2-c_1\|} +\] + +Ý nghĩa: +- trục này biểu diễn hướng nối giữa finger trái và finger phải +- đây là trục mà local closing axis của gripper phải trùng vào + +### 4.4.3. Dựng orientation cơ sở cho gripper +Giả sử trong local frame của gripper, ta biết trục đóng/mở là \(x_{local}\). Khi đó cần dựng một rotation cơ sở \(R_0\) sao cho: +\[ +R_0 x_{local} = x_g +\] + +Nói cách khác, \(R_0\) là orientation đưa gripper về tư thế mà hai finger thẳng hàng với contact pair. + +### 4.4.4. Lấy các orientation ứng viên quanh grasp axis +Sau khi đã có \(R_0\), gripper vẫn còn một bậc tự do quay quanh chính trục \(x_g\). Vì vậy, ta có thể tạo ra nhiều grasp pose candidate bằng cách quay quanh trục này với các góc roll khác nhau: +\[ +R_g(\phi) = R_0 \cdot \text{Rot}_{x_g}(\phi) +\] + +với \(\phi\) là các góc ứng viên. + +Tuy nhiên, theo đúng tinh thần pipeline đã chỉnh sửa, ta **không cần sinh toàn bộ và chấm điểm**. Thay vào đó: +- chọn một giá trị \(\phi\) +- dựng grasp pose +- thử IK +- nếu không thành công thì mới quay lại thử \(\phi\) khác + +### 4.4.5. Chuyển từ grasp frame sang end-effector target pose +Grasp center \(p_c\) không nhất thiết là vị trí của TCP. Do đó cần một transform offset cố định từ grasp frame sang end-effector frame: +\[ +T_{g\rightarrow ee} +\] + +Khi đó, với một grasp frame \(T_g(\phi)\), pose đích của end-effector là: +\[ +T_{ee}^{grasp}(\phi)=T_g(\phi)\cdot T_{g\rightarrow ee} +\] + +Đây chính là pose sẽ được đưa vào bộ giải IK. + +### 4.4.6. Cơ chế tuần tự của giai đoạn 4 +Giai đoạn này hoạt động theo kiểu: +1. Lấy contact pair hiện tại +2. Dựng một grasp pose candidate +3. Giải IK cho candidate đó +4. Nếu candidate thất bại thì thử grasp pose khác của **cùng contact pair** +5. Chỉ khi không grasp pose nào của contact pair này dẫn đến lời giải hợp lệ thì mới quay lui tìm contact pair khác + +--- + +## Giai đoạn 5. Giải IK cho grasp pose candidate + +### 4.5.1. Giải IK cho một candidate tại một thời điểm +Khác với phiên bản pipeline trước, giai đoạn này **không giải IK cho toàn bộ candidate cùng lúc**. Thay vào đó, hệ thống chỉ làm việc với **một grasp pose candidate đang xét**. + +Input của IK là: +- vị trí TCP đích +- orientation TCP đích + +Output là một nghiệm khớp: +\[ +q_{grasp} +\] + +### 4.5.2. Nếu bộ giải IK trả nhiều nghiệm +Nếu solver hoặc quy trình tìm kiếm cho phép lấy nhiều nghiệm IK cho cùng một pose, thì hệ thống sẽ kiểm tra lần lượt từng nghiệm. Cơ chế là: +1. Lấy nghiệm IK thứ nhất +2. Kiểm tra collision +3. Nếu collision → bỏ nghiệm đó, thử nghiệm khác +4. Nếu nghiệm collision-free → dùng nghiệm đó cho bước motion planning + +### 4.5.3. Collision check trên nghiệm IK +Sau khi có một nghiệm \(q_{grasp}\), hệ thống phải kiểm tra: +- self-collision của robot +- va chạm với bàn, tường, obstacle +- va chạm với **object target** +- va chạm với các object khác trong scene + +### 4.5.4. Tiêu chí xác định collision +Theo chỉnh sửa, việc kiểm tra collision với object target được làm theo nguyên tắc rất chặt: + +> Chỉ cần trong `getClosestPoints` tồn tại **bất kỳ cặp điểm nào có distance < 0** thì xem như **đang collision**. + +Tức là: +- nếu robot ở nghiệm IK mà có **bất kỳ penetration nào** với object target hoặc obstacle khác, nghiệm đó bị loại ngay +- không có collision policy mềm cho grasp pose +- không cho phép finger “đè vào” object trong giai đoạn IK checking + +### 4.5.5. Kết quả của giai đoạn 5 +Nếu tìm được một nghiệm IK collision-free cho grasp pose candidate hiện tại thì chuyển sang motion planning. Nếu: +- không có nghiệm IK nào collision-free cho grasp pose này → thử grasp pose khác của cùng contact pair +- hết grasp pose của contact pair mà vẫn không được → quay lại tìm contact pair mới + +--- + +## Giai đoạn 6. Motion planning đến grasp pose bằng RRT-Connect + +Sau khi có một nghiệm IK hợp lệ \(q_{grasp}\), hệ thống sẽ dùng **RRT-Connect** để tìm quỹ đạo từ cấu hình hiện tại đến cấu hình grasp. + +### 4.6.1. Trạng thái đầu và trạng thái đích +- trạng thái đầu: \(q_{current}\) +- trạng thái đích: \(q_{grasp}\) + +### 4.6.2. Không gian lập kế hoạch +RRT-Connect hoạt động trong **joint space**: +\[ +q = [q_1, q_2, ..., q_n] +\] + +Mỗi node của cây là một cấu hình khớp. + +### 4.6.3. Điều kiện một node được xem là hợp lệ +Một cấu hình \(q\) được coi là valid nếu: +1. thỏa joint limits +2. không self-collision +3. không va chạm với bàn, obstacle, môi trường +4. không va chạm với **object target** +5. không va chạm với bất kỳ vật thể nào khác trong scene + +### 4.6.4. Điều kiện một cạnh được xem là hợp lệ +Khi RRT-Connect nối từ \(q_a\) sang \(q_b\), hệ thống phải nội suy nhiều điểm trung gian giữa hai cấu hình và kiểm tra collision ở tất cả các điểm đó. Một cạnh chỉ được chấp nhận nếu **toàn bộ các cấu hình trung gian đều collision-free**. + +### 4.6.5. Không có collision relaxation cho object target +Đây là điểm phải nhấn mạnh: +- object target **cũng được xem là obstacle** trong toàn bộ quá trình motion planning đến grasp pose +- RRT-Connect không được phép tạo quỹ đạo mà finger hoặc bất kỳ link nào của robot xuyên vào object target trước khi tới grasp pose cuối + +### 4.6.6. Kết quả của giai đoạn 6 +Có hai trường hợp: + +#### Trường hợp 1: RRT-Connect tìm được quỹ đạo +Ta thu được một path: +\[ +\Pi_{pick} = [q_0, q_1, ..., q_{grasp}] +\] + +Khi đó chuyển sang giai đoạn thực thi grasp. + +#### Trường hợp 2: RRT-Connect không tìm được quỹ đạo +Nếu motion planning thất bại thì **không loại ngay contact pair**. Trước hết hệ thống nên quay lui theo thứ tự: +1. thử nghiệm IK khác cho grasp pose hiện tại nếu còn +2. nếu không còn nghiệm IK thì thử grasp pose khác của **cùng contact pair** +3. nếu mọi grasp pose của contact pair đều thất bại thì mới quay lại **tìm contact pair mới** + +--- + +## Giai đoạn 7. Thực thi grasp + +### 4.7.1. Robot đi theo quỹ đạo pick +Robot thực thi quỹ đạo \(\Pi_{pick}\) để đi từ cấu hình hiện tại đến grasp pose. + +### 4.7.2. Trạng thái grasp pose +Tại cuối quỹ đạo: +- end-effector ở đúng grasp pose đã chọn +- robot không va chạm với môi trường +- robot không xuyên vào object +- object nằm ở vị trí sao cho nếu gripper đóng lại thì hai finger sẽ tiếp xúc với object + +### 4.7.3. Đóng gripper +Robot thực hiện lệnh đóng gripper. Đây là thời điểm đầu tiên object được phép tiếp xúc với finger để hình thành grasp. + +### 4.7.4. Không attach object +Sau khi đóng gripper: +- **không được tạo fixed constraint** +- object vẫn là rigid body độc lập trong mô phỏng +- object được giữ nhờ lực kẹp, tiếp xúc và ma sát vật lý của gripper + +Điều này làm cho bài toán thực tế hơn nhưng đồng thời khó hơn, vì trong suốt quá trình mang vật, grasp có thể thất bại nếu lực kẹp không đủ hoặc quỹ đạo làm vật trượt khỏi gripper. + +--- + +## Giai đoạn 8. Tính place pose và motion plan mang vật đến vị trí đặt + +Theo chỉnh sửa của bài toán, sau khi grasp thành công sẽ **không chèn thêm lift pose trung gian** trước khi motion plan đặt vật. Thay vào đó, robot sẽ **motion plan trực tiếp từ trạng thái đang grasp** đến place pose. + +### 4.8.1. Xác định place pose của object +Ta biết pose đích của object: +\[ +T_O^{goal} +\] + +Đây là vị trí và orientation mà object phải đạt được sau khi đặt xuống. + +### 4.8.2. Xác định quan hệ giữa object và gripper tại thời điểm grasp +Tại grasp pose, object đang được giữ bởi gripper mà không attach. Tuy nhiên để tính toán place pose của end-effector, ta vẫn cần xác định **transform tương đối** giữa object và gripper tại thời điểm grasp thành công. + +Gọi: +\[ +T_{O\rightarrow ee}^{grasp} +\] +là transform từ object frame sang end-effector frame tại thời điểm object đang được grasp ổn định. + +Transform này có thể được xác định bằng cách lấy: +- pose hiện tại của object sau khi grasp +- pose hiện tại của end-effector +- tính biến đổi tương đối giữa hai frame + +### 4.8.3. Suy ra place pose của end-effector +Để object về đúng pose đích \(T_O^{goal}\), pose đích của end-effector phải thỏa: +\[ +T_{ee}^{place} = T_O^{goal}\cdot T_{O\rightarrow ee}^{grasp} +\] + +Đây là pose mà robot phải đưa gripper đến trong khi vẫn đang giữ object. + +### 4.8.4. Giải IK cho place pose +Từ \(T_{ee}^{place}\), giải IK để tìm cấu hình: +\[ +q_{place} +\] + +Nếu có nhiều nghiệm IK thì kiểm tra collision lần lượt giống như ở giai đoạn grasp: +- nghiệm nào collision-free thì giữ lại +- nghiệm collision thì loại + +### 4.8.5. Collision checking trong giai đoạn mang vật +Đây là phần khó hơn so với giai đoạn pick vì robot hiện đang cầm vật nhưng không attach vật vào gripper. Khi lập kế hoạch chuyển động từ grasp pose đến place pose, hệ thống phải đảm bảo: + +1. robot không va chạm với môi trường +2. object đang được giữ cũng không va chạm với môi trường +3. robot không va chạm với các vật thể khác +4. quỹ đạo đủ “êm” để object không bị trượt hoặc rơi nếu mô phỏng vật lý đang bật + +Vì object không attach, nên việc kiểm tra collision và tính khả thi của quỹ đạo phải phản ánh được trạng thái vật lý thật của hệ. + +### 4.8.6. Motion planning từ grasp pose đến place pose +Sau khi có nghiệm IK \(q_{place}\), dùng **RRT-Connect** để plan trực tiếp: +\[ +q_{grasp} \rightarrow q_{place} +\] + +Không chèn lift pose trung gian, không chèn pre-place pose trung gian, trừ khi về sau bài toán được mở rộng thêm. + +### 4.8.7. Nếu motion planning đến place thất bại +Nếu không tìm được quỹ đạo đến place pose, hệ thống cần quay lui theo logic hợp lý. Một chiến lược phù hợp là: +1. thử nghiệm IK khác cho place pose +2. nếu vẫn thất bại, thử grasp pose khác cho object hiện tại +3. nếu vẫn không được, quay lại tìm contact pair mới + +Nói cách khác, thành công của bài toán pick-and-place phụ thuộc không chỉ vào việc robot **gắp được** mà còn phải **đặt được** vật. + +--- + +## Giai đoạn 9. Đặt vật xuống + +### 4.9.1. Thực thi quỹ đạo place +Robot chạy theo quỹ đạo đã tìm được từ grasp pose đến place pose. + +### 4.9.2. Mở gripper +Khi robot đã đến đúng place pose: +- mở gripper +- object được giải phóng ra khỏi lực kẹp + +### 4.9.3. Không detach constraint vì không có attach constraint +Do từ đầu object không hề được attach, nên ở đây **không có bước detach**. Việc đặt vật hoàn toàn dựa trên cơ chế: +- robot đang giữ vật bằng tiếp xúc vật lý +- khi gripper mở ra, object được thả xuống tại vùng đặt + +### 4.9.4. Xác nhận object đã ở pose đích +Tùy yêu cầu của hệ thống, có thể kiểm tra object đã ở đủ gần pose đích hay chưa, ví dụ: +- sai số vị trí nhỏ hơn ngưỡng +- sai số orientation nhỏ hơn ngưỡng + +Nếu sai số quá lớn, có thể xem nhiệm vụ place thất bại và cần xử lý lại. + +--- + +# 5. Pipeline cho nhiều object liên tiếp + +Giả sử hệ thống có danh sách nhiều vật cần gắp: +\[ +\mathcal{T} = \{(O_1, T_{goal}^{(1)}), (O_2, T_{goal}^{(2)}), \ldots\} +\] + +Khi đó pipeline tổng quát là: + +## 5.1. Với từng object trong danh sách nhiệm vụ +Thực hiện toàn bộ pipeline từ: +1. tìm contact pair +2. sinh grasp pose +3. giải IK +4. RRT-Connect đến grasp +5. đóng gripper +6. giải IK cho place +7. RRT-Connect đến place +8. mở gripper + +## 5.2. Sau khi đặt xong một vật +Nếu **còn vật tiếp theo** thì: +- **không quay về home pose** +- lấy ngay cấu hình hiện tại của robot sau khi thả vật làm: +\[ +q_{current} +\] +- bắt đầu pipeline cho object tiếp theo từ chính cấu hình đó + +## 5.3. Khi hoàn thành toàn bộ danh sách nhiệm vụ +Chỉ khi không còn vật nào cần gắp nữa thì robot mới motion plan từ cấu hình hiện tại về cấu hình ban đầu: +\[ +q_{current} \rightarrow q_{home} +\] + +--- + +# 6. Thuật toán tổng thể dạng tuần tự và quay lui + +Dưới đây là logic hoàn chỉnh của hệ thống theo đúng các chỉnh sửa. + +## 6.1. Với một object + +### Bước 1. Khởi tạo +- lấy cấu hình hiện tại \(q_{current}\) +- load object target và môi trường + +### Bước 2. Duyệt contact pair trên mesh +Lặp qua các contact pair ứng viên theo thứ tự nào đó. + +#### Với mỗi contact pair: +1. Kiểm tra antipodal gần đúng +2. Kiểm tra khoảng cách giữa hai contact có nằm trong \([w_{min}, w_{max}]\) hay không +3. Nếu không hợp lệ thì bỏ qua và sang contact pair tiếp theo +4. Nếu hợp lệ thì chuyển sang bước sinh grasp pose + +### Bước 3. Duyệt grasp pose của contact pair hiện tại +Với contact pair đang xét: +1. tính grasp center +2. tính grasp axis +3. dựng orientation base +4. thử từng roll angle để tạo grasp pose candidate + +### Bước 4. Với từng grasp pose candidate +1. giải IK cho grasp pose +2. nếu có nhiều nghiệm IK thì xét lần lượt từng nghiệm + +#### Với mỗi nghiệm IK: +- kiểm tra self-collision +- kiểm tra collision với môi trường +- kiểm tra collision với object target +- chỉ cần có bất kỳ `distance < 0` trong `getClosestPoints` thì loại nghiệm + +Nếu có một nghiệm IK collision-free: +- chuyển sang bước motion planning pick + +Nếu mọi nghiệm IK của grasp pose này đều thất bại: +- quay lại thử grasp pose khác của cùng contact pair + +### Bước 5. Motion planning đến grasp pose +Dùng RRT-Connect từ \(q_{current}\) đến \(q_{grasp}\) + +Nếu thành công: +- thực thi quỹ đạo +- đóng gripper +- chuyển sang bước place + +Nếu thất bại: +- quay lui: + - thử grasp pose khác + - nếu hết grasp pose thì thử contact pair khác + +### Bước 6. Tính place pose +1. xác định transform tương đối object–gripper tại grasp +2. từ \(T_O^{goal}\) suy ra \(T_{ee}^{place}\) + +### Bước 7. Giải IK cho place pose +- giải IK +- kiểm tra collision các nghiệm +- giữ nghiệm collision-free + +Nếu không có nghiệm place hợp lệ: +- quay lui về grasp pose khác hoặc contact pair khác + +### Bước 8. Motion planning từ grasp đến place +Dùng RRT-Connect để plan trực tiếp từ cấu hình đang grasp đến cấu hình place. + +Nếu thành công: +- robot đi theo quỹ đạo +- mở gripper +- object được đặt xuống + +Nếu thất bại: +- quay lui về grasp pose khác hoặc contact pair khác + +### Bước 9. Kết thúc object hiện tại +- cập nhật cấu hình hiện tại của robot +- nếu còn object tiếp theo thì tiếp tục từ đây +- nếu không còn object thì motion plan về home pose + +--- + +# 7. Pseudocode hoàn chỉnh cho toàn hệ thống + +```python +def execute_task_list(task_list, robot, gripper, scene, q_home): + q_current = get_current_joint_state(robot) + + for task in task_list: + object_id = task.object_id + object_goal_pose = task.goal_pose + + success, q_current = pick_and_place_one_object( + robot=robot, + gripper=gripper, + scene=scene, + object_id=object_id, + object_goal_pose=object_goal_pose, + q_start=q_current + ) + + if not success: + return FAIL("Không thể hoàn thành task list") + + # chỉ khi hết nhiệm vụ mới quay về home + path_home = rrt_connect_plan(robot, q_current, q_home, scene) + if path_home is not None: + execute_joint_path(robot, path_home) + + return SUCCESS +``` + +```python +def pick_and_place_one_object(robot, gripper, scene, object_id, object_goal_pose, q_start): + set_robot_configuration(robot, q_start) + + contact_pairs = iterate_contact_pairs_from_mesh(object_id) + + for cp in contact_pairs: + if not is_antipodal_approx(cp): + continue + if not width_in_gripper_range(cp, gripper): + continue + + grasp_pose_candidates = generate_grasp_pose_candidates(cp, gripper) + + for grasp_pose in grasp_pose_candidates: + ik_solutions = solve_all_ik(robot, grasp_pose) + + for q_grasp in ik_solutions: + if in_collision(robot, q_grasp, scene, object_id): + continue + + pick_path = rrt_connect_plan(robot, q_start, q_grasp, scene) + if pick_path is None: + continue + + execute_joint_path(robot, pick_path) + close_gripper(gripper) + + T_obj_to_ee = compute_object_to_ee_transform(robot, object_id) + + place_pose = compute_place_pose(object_goal_pose, T_obj_to_ee) + place_ik_solutions = solve_all_ik(robot, place_pose) + + place_success = False + for q_place in place_ik_solutions: + if in_collision(robot, q_place, scene, object_id): + continue + + place_path = rrt_connect_plan(robot, q_grasp, q_place, scene) + if place_path is None: + continue + + execute_joint_path(robot, place_path) + open_gripper(gripper) + + q_after_place = get_current_joint_state(robot) + return True, q_after_place + + # nếu không place được thì cần quay lui + # ở mức triển khai thực tế có thể cần reset scene hoặc rollback trạng thái mô phỏng + reset_to_pre_grasp_state(robot, object_id, q_start) + break + + return False, q_start +``` + +--- + +# 8. Những điểm cần lưu ý khi hiện thực trong PyBullet hoặc simulator tương tự + +## 8.1. Collision checking bằng getClosestPoints +Theo quy ước của bài toán: +- nếu `getClosestPoints` trả về bất kỳ cặp nào có `distance < 0` thì xem như có va chạm +- áp dụng cho: + - robot với object target + - robot với obstacle + - robot với các object khác + - self-collision nếu cần xử lý riêng + +## 8.2. Bài toán không attach object sẽ khó hơn nhiều +Vì không attach constraint nên khi robot mang vật: +- object có thể bị trượt +- object có thể xoay trong gripper +- object có thể rơi nếu lực kẹp không đủ hoặc quỹ đạo quá gắt + +Do đó nếu mô phỏng vật lý thực sự được bật, motion planning chỉ dựa trên joint-space collision-free chưa chắc đã đủ; còn cần: +- điều khiển lực kẹp phù hợp +- quỹ đạo mượt +- có thể giới hạn gia tốc hoặc vận tốc + +## 8.3. Vấn đề rollback khi place thất bại +Trong pseudocode ở trên, nếu robot đã đóng gripper rồi nhưng không tìm được quỹ đạo place, hệ thống cần có cơ chế rollback hoặc reset scene để quay lại thử grasp khác. Đây là một điểm triển khai quan trọng vì lúc này trạng thái mô phỏng đã thay đổi: +- robot không còn ở \(q_{start}\) +- object có thể đã bị dịch chuyển +- gripper đang đóng + +Do đó trong triển khai thực tế, nên có cơ chế: +- lưu snapshot trạng thái mô phỏng trước khi thực thi pick +- nếu place thất bại thì khôi phục snapshot đó để thử grasp khác + +--- + +# 9. Kết luận của pipeline đã chỉnh sửa + +Pipeline cuối cùng của bài toán có thể tóm tắt như sau: + +## 9.1. Ý tưởng cốt lõi +- Object được biểu diễn bằng **collision mesh / visual mesh** +- Contact pair được sinh theo **antipodal gần đúng** dựa trên normal của mesh +- Hệ thống **không sinh toàn bộ candidate rồi chấm điểm**, mà làm theo kiểu: + 1. tìm một contact pair hợp lệ + 2. từ đó sinh grasp pose + 3. giải IK + 4. collision check + 5. motion plan bằng RRT-Connect + 6. nếu thất bại thì quay lui tìm grasp pose hoặc contact pair khác + +## 9.2. Collision rule +- Trong **mọi giai đoạn**, robot **không được va chạm với bất kỳ vật nào**, kể cả object target +- Chỉ cần có **distance < 0** trong `getClosestPoints` là xem như collision + +## 9.3. Grasp và place +- Robot đi đến grasp pose sao cho **chỉ cần đóng gripper là tiếp xúc với object** +- Sau khi grasp, robot **motion plan trực tiếp** đến place pose, **không có lift pose trung gian** +- Object **không được attach** vào gripper bằng constraint + +## 9.4. Xử lý nhiều vật +- Sau khi đặt xong một vật, nếu còn vật khác thì robot **không quay về home** +- Robot tiếp tục motion planning từ cấu hình hiện tại sang tác vụ tiếp theo +- Chỉ khi toàn bộ nhiệm vụ kết thúc thì robot mới motion plan về cấu hình ban đầu + +Đó là pipeline đã được sửa lại đúng theo toàn bộ các thay đổi của bài toán. diff --git a/pytest.ini b/pytest.ini new file mode 100644 index 0000000000000000000000000000000000000000..f07f045526eb3c87c5c548c0226defb30af9ce16 --- /dev/null +++ b/pytest.ini @@ -0,0 +1,3 @@ +[pytest] +norecursedirs = pybullet-object-models .git .github .pytest_cache +testpaths = tests diff --git a/recover.py b/recover.py new file mode 100644 index 0000000000000000000000000000000000000000..a5378780ae1e64c0ae3efc262274df5dfac11dda --- /dev/null +++ b/recover.py @@ -0,0 +1,43 @@ +import json + +log_path = r'C:\Users\admin\.gemini\antigravity-ide\brain\0197c1c1-77a8-49be-8344-f1d86156c524\.system_generated\logs\transcript_full.jsonl' +output_dir = r'C:\Users\admin\C2-App-151\llm_panda' + +written_files = {} + +with open(log_path, 'r', encoding='utf-8') as f: + for line in f: + try: + data = json.loads(line) + # Find tool calls in model response + if data.get('type') == 'PLANNER_RESPONSE' and 'tool_calls' in data: + for call in data['tool_calls']: + if call['tool_name'] == 'default_api:write_to_file': + args = call['tool_args'] + target = args.get('TargetFile', '') + content = args.get('CodeContent', '') + if 'geofik.py' in target: + written_files['geofik.py'] = content + if 'swivel_adapter.py' in target: + written_files['swivel_adapter.py'] = content + if 'evaluators.py' in target: + written_files['evaluators.py'] = content + if 'grasp_optimizer.py' in target: + written_files['grasp_optimizer.py'] = content + if 'task_nullspace.py' in target: + written_files['task_nullspace.py'] = content + if call['tool_name'] == 'default_api:replace_file_content': + args = call['tool_args'] + target = args.get('TargetFile', '') + if 'geofik.py' in target: + target_content = args.get('TargetContent', '') + replacement = args.get('ReplacementContent', '') + if 'geofik.py' in written_files: + written_files['geofik.py'] = written_files['geofik.py'].replace(target_content, replacement) + except Exception as e: + pass + +for fname, content in written_files.items(): + with open(output_dir + '\\' + fname, 'w', encoding='utf-8') as out_f: + out_f.write(content) + print(f'Recovered {fname}') diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..005c8caefa935712f8cb0379460662bcdd665201 --- /dev/null +++ b/requirements.txt @@ -0,0 +1,12 @@ +pybullet>=3.2.5 +numpy>=1.23 +pytest>=7.0 +fastapi>=0.100.0 +uvicorn>=0.23.0 +websockets>=11.0.0 +opencv-python-headless>=4.8.0 +pybullet-object-models>=0.0.1 + +# Optional - only for the real-LLM planner: python main.py --llm openai +openai>=1.0 +python-dotenv>=1.0 diff --git a/run_pipeline.py b/run_pipeline.py new file mode 100644 index 0000000000000000000000000000000000000000..6e121ed5f8d77e70646707eaa4507c57bf3b93d8 --- /dev/null +++ b/run_pipeline.py @@ -0,0 +1,54 @@ +import sys +import os +import argparse +import logging +import pybullet as pb + +# Ensure root of repo is in python path +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) + +from llm_panda import logger as _logger_setup +from main import PandaSimulation +from llm_panda.pipeline_executor import PipelineExecutor + +logger = logging.getLogger(__name__) + +def main(): + parser = argparse.ArgumentParser(description="Run complete Pick-and-Place Pipeline with strict collision rules and physical kẹp") + parser.add_argument("--gui", action="store_true", help="Launch the GUI visualization") + parser.add_argument("--seed", type=int, default=3, help="RNG seed for object placement") + parser.add_argument("--idle", type=float, default=5.0, help="Idle time after success") + args = parser.parse_args() + + # Setup logger + _logger_setup.setup() + + # Initialize standard simulation environment + sim = PandaSimulation(gui=args.gui, seed=args.seed) + + try: + # Define a multi-object task list + # Move soup_can to Slot_4, and banana to Slot_2 + task_list = [ + {"object_name": "banana", "goal_location": "tray"}, + {"object_name": "soup_can", "goal_location": "tray"} + ] + + executor = PipelineExecutor(sim) + + # Execute tasks! + success = executor.execute_tasks(task_list) + + if success: + logger.info("[SUCCESS] Pipeline completed all tasks successfully!") + else: + logger.error("[FAIL] Pipeline failed to complete tasks!") + + if args.gui: + sim.idle(args.idle) + + finally: + sim.disconnect() + +if __name__ == "__main__": + main() diff --git a/scratch_diagnose.py b/scratch_diagnose.py new file mode 100644 index 0000000000000000000000000000000000000000..ec7524b48370ca3620ba8a58dec6a7a28c963d85 --- /dev/null +++ b/scratch_diagnose.py @@ -0,0 +1,53 @@ +import pybullet as pb +import numpy as np +import math +import os +import sys + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +from main import PandaSimulation +from llm_panda import config +from llm_panda.pipeline_executor import MeshParser, ContactSampler, GraspCandidateGenerator, PipelineExecutor +from llm_panda.grasp_planner import GraspPlanner + +sim = PandaSimulation(gui=False, seed=3) +robot_id = sim.controller.robot_id +banana_id = sim.scene.name_to_id("banana") + +# Load mesh +from pybullet_object_models import ycb_objects +ycb_data = ycb_objects.getDataPath() +obj_path = os.path.join(ycb_data, "YcbBanana", "collision_vhacd.obj") +vertices, normals = MeshParser.load_obj(obj_path, scale=config.OBJECT_GLOBAL_SCALING) + +# Sample contact pairs +contact_pairs = ContactSampler.sample_antipodal_pairs(vertices, normals, num_samples=150) +obj_pos, obj_ori = pb.getBasePositionAndOrientation(banana_id) + +def compute_pose_error(target_pos, target_ori, actual_pos, actual_ori): + pos_err = np.linalg.norm(np.array(actual_pos) - np.array(target_pos)) + dot_product = abs(np.dot(np.array(actual_ori), np.array(target_ori))) + dot_product = min(1.0, max(-1.0, dot_product)) + ori_err = 2.0 * math.acos(dot_product) + return pos_err, ori_err + +executor = PipelineExecutor(sim) + +for cp_idx, cp in enumerate(contact_pairs[:10]): + c1, c2, n1, n2 = cp + grasp_candidates = GraspCandidateGenerator.get_grasp_pose_candidates(c1, c2, roll_steps=12) + for gc_idx, (local_pos, grasp_ori) in enumerate(grasp_candidates): + world_grasp_pos, world_grasp_ori = GraspPlanner.local_to_world( + obj_pos, obj_ori, local_pos, pb.getEulerFromQuaternion(grasp_ori) + ) + + # Solve IK candidates using PipelineExecutor's solver + candidates = executor._solve_ik_candidates(world_grasp_pos, world_grasp_ori, seed_q=config.ARM_REST_POSE, context="grasp") + + for cand_idx, q_sol in enumerate(candidates): + valid, reason = executor._validate_ik_solution( + q_sol, world_grasp_pos, world_grasp_ori, mode="grasp", target_object_id=banana_id, diagnose=True + ) + print(f"Pair {cp_idx} roll {gc_idx} cand {cand_idx}: valid={valid}, reason={reason}") + +sim.disconnect() diff --git a/scripts/__pycache__/benchmark_trajopt_pipeline.cpython-310.pyc b/scripts/__pycache__/benchmark_trajopt_pipeline.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0fb5be793593a0683ad38e23d5e38981e0a313b3 Binary files /dev/null and b/scripts/__pycache__/benchmark_trajopt_pipeline.cpython-310.pyc differ diff --git a/scripts/_pyrun.cmd b/scripts/_pyrun.cmd new file mode 100644 index 0000000000000000000000000000000000000000..fc12749469af82070100c01b67fcb80b96f8fff8 --- /dev/null +++ b/scripts/_pyrun.cmd @@ -0,0 +1,24 @@ +@echo off +REM Cross-platform Python launcher for AI log hooks (Windows cmd.exe). +REM Tries py -3 -> python -> python3 in order, runs the given script with all args. +REM Exits 0 silently if no Python is found - hooks must never block the AI tool. + +where py >nul 2>nul +if %ERRORLEVEL%==0 ( + py -3 %* + exit /b %ERRORLEVEL% +) + +where python >nul 2>nul +if %ERRORLEVEL%==0 ( + python %* + exit /b %ERRORLEVEL% +) + +where python3 >nul 2>nul +if %ERRORLEVEL%==0 ( + python3 %* + exit /b %ERRORLEVEL% +) + +exit /b 0 diff --git a/scripts/_pyrun.sh b/scripts/_pyrun.sh new file mode 100644 index 0000000000000000000000000000000000000000..d74576d76ed232ca4ac05798c71b81da666ccf02 --- /dev/null +++ b/scripts/_pyrun.sh @@ -0,0 +1,33 @@ +#!/usr/bin/env bash +# Cross-platform Python launcher for AI log hooks. +# Tries python3 → python → py -3 on PATH; on Windows, falls back to common +# Python install locations because Git Bash launched by some hooks gets a +# stripped PATH that omits the Windows Python directory. +# Designed to be sourced or called as: bash scripts/_pyrun.sh