Spaces:
Sleeping
Sleeping
File size: 3,000 Bytes
7c1d4f6 16d8047 7c1d4f6 16d8047 7c1d4f6 16d8047 7c1d4f6 16d8047 7c1d4f6 16d8047 7c1d4f6 16d8047 7c1d4f6 16d8047 7c1d4f6 16d8047 7c1d4f6 16d8047 7c1d4f6 16d8047 7c1d4f6 16d8047 7c1d4f6 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 | """
Physics simulation module for robot designs.
"""
import pybullet as p
import numpy as np
from typing import Dict, Any, List, Tuple
from src.core.robot_design import RobotDesign
class PhysicsSimulator:
"""Base class for physics simulation."""
def __init__(self):
"""Initialize the physics simulator."""
self.client = p.connect(p.DIRECT)
p.setGravity(0, 0, -9.81)
def simulate(self, design: RobotDesign) -> Dict[str, Any]:
"""Simulate the robot design and return performance metrics."""
raise NotImplementedError("Subclasses must implement simulate()")
def cleanup(self):
"""Clean up simulation resources."""
p.disconnect(self.client)
class PyBulletSimulator(PhysicsSimulator):
"""PyBullet-based physics simulator implementation."""
def simulate(self, design: RobotDesign) -> Dict[str, Any]:
"""Simulate the robot design using PyBullet."""
try:
# Create ground plane
p.createMultiBody(
baseMass=0,
baseCollisionShapeIndex=p.createCollisionShape(p.GEOM_PLANE),
basePosition=[0, 0, 0]
)
# Create robot body
robot_id = p.createMultiBody(
baseMass=design.mass,
baseCollisionShapeIndex=p.createCollisionShape(
p.GEOM_BOX,
halfExtents=[design.dimensions[0]/2, design.dimensions[1]/2, design.dimensions[2]/2]
),
basePosition=[0, 0, design.dimensions[2]/2]
)
# Run simulation
results = {
"stability": self._check_stability(robot_id),
"performance": self._measure_performance(robot_id, design)
}
return results
except Exception as e:
return {"error": str(e)}
finally:
self.cleanup()
def _check_stability(self, robot_id: int) -> float:
"""Check robot stability during simulation."""
# Simple stability check based on final position
final_pos, _ = p.getBasePositionAndOrientation(robot_id)
return 1.0 if abs(final_pos[2]) < 0.1 else 0.0
def _measure_performance(self, robot_id: int, design: RobotDesign) -> Dict[str, float]:
"""Measure robot performance metrics."""
return {
"speed": design.max_speed,
"efficiency": design.efficiency,
"stability": self._check_stability(robot_id)
}
class SimulationFactory:
"""Factory for creating physics simulators."""
@staticmethod
def create_simulator(simulator_type: str = "pybullet") -> PhysicsSimulator:
"""Create a physics simulator instance."""
if simulator_type == "pybullet":
return PyBulletSimulator()
else:
raise ValueError(f"Unsupported simulator type: {simulator_type}") |