示例#1
0
  def reset(self):
    #    print("-----------reset simulation---------------")
    if self._physics_client_id < 0:
      if self._renders:
        self._p = bc.BulletClient(connection_mode=p2.GUI)
      else:
        self._p = bc.BulletClient()
      self._physics_client_id = self._p._client
 
      p = self._p
      p.resetSimulation()
      self.cartpole = p.loadURDF(os.path.join(pybullet_data_local.getDataPath(), "cartpole.urdf"),
                                 [0, 0, 0])
      p.changeDynamics(self.cartpole, -1, linearDamping=0, angularDamping=0)
      p.changeDynamics(self.cartpole, 0, linearDamping=0, angularDamping=0)
      p.changeDynamics(self.cartpole, 1, linearDamping=0, angularDamping=0)
      self.timeStep = 0.02
      p.setJointMotorControl2(self.cartpole, 1, p.VELOCITY_CONTROL, force=0)
      p.setJointMotorControl2(self.cartpole, 0, p.VELOCITY_CONTROL, force=0)
      p.setGravity(0, 0, -9.8)
      p.setTimeStep(self.timeStep)
      p.setRealTimeSimulation(0)
    p = self._p
    randstate = self.np_random.uniform(low=-0.05, high=0.05, size=(4,))
    p.resetJointState(self.cartpole, 1, randstate[0], randstate[1])
    p.resetJointState(self.cartpole, 0, randstate[2], randstate[3])
    #print("randstate=",randstate)
    self.state = p.getJointState(self.cartpole, 1)[0:2] + p.getJointState(self.cartpole, 0)[0:2]
    #print("self.state=", self.state)
    return np.array(self.state)
示例#2
0
  def __init__(self,
               urdfRoot=pybullet_data_local.getDataPath(),
               actionRepeat=10,
               isEnableSelfCollision=True,
               isDiscrete=False,
               renders=True):
    print("init")
    self._timeStep = 0.01
    self._urdfRoot = urdfRoot
    self._actionRepeat = actionRepeat
    self._isEnableSelfCollision = isEnableSelfCollision
    self._ballUniqueId = -1
    self._envStepCounter = 0
    self._renders = renders
    self._width = 100
    self._height = 10

    self._isDiscrete = isDiscrete
    if self._renders:
      self._p = bc.BulletClient(connection_mode=pybullet.GUI)
    else:
      self._p = bc.BulletClient()

    self.seed()
    self.reset()
    observationDim = len(self.getExtendedObservation())
    #print("observationDim")
    #print(observationDim)

    observation_high = np.array([np.finfo(np.float32).max] * observationDim)
    if (isDiscrete):
      self.action_space = spaces.Discrete(9)
    else:
      action_dim = 2
      self._action_bound = 1
      action_high = np.array([self._action_bound] * action_dim)
      self.action_space = spaces.Box(-action_high, action_high, dtype=np.float32)
    self.observation_space = spaces.Box(low=0,
                                        high=255,
                                        shape=(self._height, self._width, 4),
                                        dtype=np.uint8)

    self.viewer = None
示例#3
0
    def reset(self):
        if (self.physicsClientId < 0):
            self.ownsPhysicsClient = True

            if self.isRender:
                self._p = bullet_client.BulletClient(
                    connection_mode=pybullet.GUI)
            else:
                self._p = bullet_client.BulletClient()
            self._p.resetSimulation()
            self._p.setPhysicsEngineParameter(deterministicOverlappingPairs=1)
            #optionally enable EGL for faster headless rendering
            try:
                if os.environ["PYBULLET_EGL"]:
                    con_mode = self._p.getConnectionInfo()['connectionMethod']
                    if con_mode == self._p.DIRECT:
                        egl = pkgutil.get_loader('eglRenderer')
                        if (egl):
                            self._p.loadPlugin(egl.get_filename(),
                                               "_eglRendererPlugin")
                        else:
                            self._p.loadPlugin("eglRendererPlugin")
            except:
                pass
            self.physicsClientId = self._p._client
            self._p.configureDebugVisualizer(pybullet.COV_ENABLE_GUI, 0)

        if self.scene is None:
            self.scene = self.create_single_player_scene(self._p)
        if not self.scene.multiplayer and self.ownsPhysicsClient:
            self.scene.episode_restart(self._p)

        self.robot.scene = self.scene

        self.frame = 0
        self.done = 0
        self.reward = 0
        dump = 0
        s = self.robot.reset(self._p)
        self.potential = self.robot.calc_potential()
        return s
示例#4
0
  def __init__(
      self,
      urdf_root=pybullet_data_local.getDataPath(),
      action_repeat=1,
      distance_weight=1.0,
      energy_weight=0.005,
      shake_weight=0.0,
      drift_weight=0.0,
      distance_limit=float("inf"),
      observation_noise_stdev=0.0,
      self_collision_enabled=True,
      motor_velocity_limit=np.inf,
      pd_control_enabled=False,  #not needed to be true if accurate motor model is enabled (has its own better PD)
      leg_model_enabled=True,
      accurate_motor_model_enabled=True,
      motor_kp=1.0,
      motor_kd=0.02,
      torque_control_enabled=False,
      motor_overheat_protection=True,
      hard_reset=True,
      on_rack=False,
      render=False,
      kd_for_pd_controllers=0.3,
      env_randomizer=minitaur_env_randomizer.MinitaurEnvRandomizer()):
    """Initialize the minitaur gym environment.

    Args:
      urdf_root: The path to the urdf data folder.
      action_repeat: The number of simulation steps before actions are applied.
      distance_weight: The weight of the distance term in the reward.
      energy_weight: The weight of the energy term in the reward.
      shake_weight: The weight of the vertical shakiness term in the reward.
      drift_weight: The weight of the sideways drift term in the reward.
      distance_limit: The maximum distance to terminate the episode.
      observation_noise_stdev: The standard deviation of observation noise.
      self_collision_enabled: Whether to enable self collision in the sim.
      motor_velocity_limit: The velocity limit of each motor.
      pd_control_enabled: Whether to use PD controller for each motor.
      leg_model_enabled: Whether to use a leg motor to reparameterize the action
        space.
      accurate_motor_model_enabled: Whether to use the accurate DC motor model.
      motor_kp: proportional gain for the accurate motor model.
      motor_kd: derivative gain for the accurate motor model.
      torque_control_enabled: Whether to use the torque control, if set to
        False, pose control will be used.
      motor_overheat_protection: Whether to shutdown the motor that has exerted
        large torque (OVERHEAT_SHUTDOWN_TORQUE) for an extended amount of time
        (OVERHEAT_SHUTDOWN_TIME). See ApplyAction() in minitaur.py for more
        details.
      hard_reset: Whether to wipe the simulation and load everything when reset
        is called. If set to false, reset just place the minitaur back to start
        position and set its pose to initial configuration.
      on_rack: Whether to place the minitaur on rack. This is only used to debug
        the walking gait. In this mode, the minitaur's base is hanged midair so
        that its walking gait is clearer to visualize.
      render: Whether to render the simulation.
      kd_for_pd_controllers: kd value for the pd controllers of the motors
      env_randomizer: An EnvRandomizer to randomize the physical properties
        during reset().
    """
    self._time_step = 0.01
    self._action_repeat = action_repeat
    self._num_bullet_solver_iterations = 300
    self._urdf_root = urdf_root
    self._self_collision_enabled = self_collision_enabled
    self._motor_velocity_limit = motor_velocity_limit
    self._observation = []
    self._env_step_counter = 0
    self._is_render = render
    self._last_base_position = [0, 0, 0]
    self._distance_weight = distance_weight
    self._energy_weight = energy_weight
    self._drift_weight = drift_weight
    self._shake_weight = shake_weight
    self._distance_limit = distance_limit
    self._observation_noise_stdev = observation_noise_stdev
    self._action_bound = 1
    self._pd_control_enabled = pd_control_enabled
    self._leg_model_enabled = leg_model_enabled
    self._accurate_motor_model_enabled = accurate_motor_model_enabled
    self._motor_kp = motor_kp
    self._motor_kd = motor_kd
    self._torque_control_enabled = torque_control_enabled
    self._motor_overheat_protection = motor_overheat_protection
    self._on_rack = on_rack
    self._cam_dist = 1.0
    self._cam_yaw = 0
    self._cam_pitch = -30
    self._hard_reset = True
    self._kd_for_pd_controllers = kd_for_pd_controllers
    self._last_frame_time = 0.0
    print("urdf_root=" + self._urdf_root)
    self._env_randomizer = env_randomizer
    # PD control needs smaller time step for stability.
    if pd_control_enabled or accurate_motor_model_enabled:
      self._time_step /= NUM_SUBSTEPS
      self._num_bullet_solver_iterations /= NUM_SUBSTEPS
      self._action_repeat *= NUM_SUBSTEPS

    if self._is_render:
      self._pybullet_client = bc.BulletClient(connection_mode=pybullet.GUI)
    else:
      self._pybullet_client = bc.BulletClient()

    self.seed()
    self.reset()
    observation_high = (self.minitaur.GetObservationUpperBound() + OBSERVATION_EPS)
    observation_low = (self.minitaur.GetObservationLowerBound() - OBSERVATION_EPS)
    action_dim = 8
    action_high = np.array([self._action_bound] * action_dim)
    self.action_space = spaces.Box(-action_high, action_high, dtype=np.float32)
    self.observation_space = spaces.Box(observation_low, observation_high, dtype=np.float32)
    self.viewer = None
    self._hard_reset = hard_reset  # This assignment need to be after reset()
示例#5
0
def ExploreWorker(rank, num_processes, childPipe, args):
    print("hi:", rank, " out of ", num_processes)
    import pybullet as op1
    import pybullet_data_local as pd
    logName = ""
    p1 = 0
    n = 0
    space = 2
    simulations = []
    sims_per_worker = 10

    offsetY = rank * space
    while True:
        n += 1
        try:
            # Only block for short times to have keyboard exceptions be raised.
            if not childPipe.poll(0.0001):
                continue
            message, payload = childPipe.recv()
        except (EOFError, KeyboardInterrupt):
            break
        if message == _RESET:
            if (useGUI):
                p1 = bullet_client.BulletClient(op1.GUI)
            else:
                p1 = bullet_client.BulletClient(op1.DIRECT)
            p1.setTimeStep(timeStep)

            p1.setPhysicsEngineParameter(numSolverIterations=8)
            p1.setPhysicsEngineParameter(minimumSolverIslandSize=100)
            p1.configureDebugVisualizer(p1.COV_ENABLE_Y_AXIS_UP, 1)
            p1.configureDebugVisualizer(p1.COV_ENABLE_RENDERING, 0)
            p1.setAdditionalSearchPath(pd.getDataPath())
            p1.setGravity(0, -9.8, 0)
            logName = str("batchsim") + str(rank)
            for j in range(3):
                offsetX = 0  #-sims_per_worker/2.0*space
                for i in range(sims_per_worker):
                    offset = [offsetX, 0, offsetY]
                    sim = panda_sim.PandaSimAuto(p1, offset)
                    simulations.append(sim)
                    offsetX += space
                offsetY += space
            childPipe.send(["reset ok"])
            p1.configureDebugVisualizer(p1.COV_ENABLE_RENDERING, 1)
            for i in range(100):
                p1.stepSimulation()

            logId = p1.startStateLogging(op1.STATE_LOGGING_PROFILE_TIMINGS,
                                         logName)
            continue
        if message == _EXPLORE:
            sum_rewards = rank

            if useGUI:
                numSteps = int(20000)
            else:
                numSteps = int(5)
            for i in range(numSteps):
                for s in simulations:
                    s.step()
                p1.stepSimulation()
            #print("logId=",logId)
            #print("numSteps=",numSteps)

            childPipe.send([sum_rewards])
            continue
        if message == _CLOSE:
            p1.stopStateLogging(logId)
            childPipe.send(["close ok"])
            break
    childPipe.close()
示例#6
0
from pybullet_utils_local import bullet_client
import time
import math
import motion_capture_data
from pybullet_envs_local.deep_mimic.env import humanoid_stable_pd
import pybullet_data_local
import pybullet as p1
import humanoid_pose_interpolator
import numpy as np

pybullet_client = bullet_client.BulletClient(connection_mode=p1.GUI)

pybullet_client.setAdditionalSearchPath(pybullet_data_local.getDataPath())
z2y = pybullet_client.getQuaternionFromEuler([-math.pi * 0.5, 0, 0])
#planeId = pybullet_client.loadURDF("plane.urdf",[0,0,0],z2y)
planeId = pybullet_client.loadURDF("plane_implicit.urdf", [0, 0, 0],
                                   z2y,
                                   useMaximalCoordinates=True)
pybullet_client.changeDynamics(planeId, linkIndex=-1, lateralFriction=0.9)
#print("planeId=",planeId)

pybullet_client.configureDebugVisualizer(pybullet_client.COV_ENABLE_Y_AXIS_UP, 1)
pybullet_client.setGravity(0, -9.8, 0)

pybullet_client.setPhysicsEngineParameter(numSolverIterations=10)

mocapData = motion_capture_data.MotionCaptureData()
#motionPath = pybullet_data_local.getDataPath()+"/data/motions/humanoid3d_walk.txt"
motionPath = pybullet_data_local.getDataPath() + "/data/motions/humanoid3d_backflip.txt"
mocapData.Load(motionPath)
timeStep = 1. / 600
示例#7
0
    def __init__(self,
                 urdf_root=pybullet_data_local.getDataPath(),
                 urdf_version=None,
                 distance_weight=1.0,
                 energy_weight=0.005,
                 shake_weight=0.0,
                 drift_weight=0.0,
                 distance_limit=float("inf"),
                 observation_noise_stdev=SENSOR_NOISE_STDDEV,
                 self_collision_enabled=True,
                 motor_velocity_limit=np.inf,
                 pd_control_enabled=False,
                 leg_model_enabled=True,
                 accurate_motor_model_enabled=False,
                 remove_default_joint_damping=False,
                 motor_kp=1.0,
                 motor_kd=0.02,
                 control_latency=0.0,
                 pd_latency=0.0,
                 torque_control_enabled=False,
                 motor_overheat_protection=False,
                 hard_reset=True,
                 on_rack=False,
                 render=False,
                 num_steps_to_log=1000,
                 action_repeat=1,
                 control_time_step=None,
                 env_randomizer=None,
                 forward_reward_cap=float("inf"),
                 reflection=True,
                 log_path=None):
        """Initialize the minitaur gym environment.

    Args:
      urdf_root: The path to the urdf data folder.
      urdf_version: [DEFAULT_URDF_VERSION, DERPY_V0_URDF_VERSION,
        RAINBOW_DASH_V0_URDF_VERSION] are allowable
        versions. If None, DEFAULT_URDF_VERSION is used. DERPY_V0_URDF_VERSION
        is the result of first pass system identification for derpy.
        We will have a different URDF and related Minitaur class each time we
        perform system identification. While the majority of the code of the
        class remains the same, some code changes (e.g. the constraint location
        might change). __init__() will choose the right Minitaur class from
        different minitaur modules based on
        urdf_version.
      distance_weight: The weight of the distance term in the reward.
      energy_weight: The weight of the energy term in the reward.
      shake_weight: The weight of the vertical shakiness term in the reward.
      drift_weight: The weight of the sideways drift term in the reward.
      distance_limit: The maximum distance to terminate the episode.
      observation_noise_stdev: The standard deviation of observation noise.
      self_collision_enabled: Whether to enable self collision in the sim.
      motor_velocity_limit: The velocity limit of each motor.
      pd_control_enabled: Whether to use PD controller for each motor.
      leg_model_enabled: Whether to use a leg motor to reparameterize the action
        space.
      accurate_motor_model_enabled: Whether to use the accurate DC motor model.
      remove_default_joint_damping: Whether to remove the default joint damping.
      motor_kp: proportional gain for the accurate motor model.
      motor_kd: derivative gain for the accurate motor model.
      control_latency: It is the delay in the controller between when an
        observation is made at some point, and when that reading is reported
        back to the Neural Network.
      pd_latency: latency of the PD controller loop. PD calculates PWM based on
        the motor angle and velocity. The latency measures the time between when
        the motor angle and velocity are observed on the microcontroller and
        when the true state happens on the motor. It is typically (0.001-
        0.002s).
      torque_control_enabled: Whether to use the torque control, if set to
        False, pose control will be used.
      motor_overheat_protection: Whether to shutdown the motor that has exerted
        large torque (OVERHEAT_SHUTDOWN_TORQUE) for an extended amount of time
        (OVERHEAT_SHUTDOWN_TIME). See ApplyAction() in minitaur.py for more
        details.
      hard_reset: Whether to wipe the simulation and load everything when reset
        is called. If set to false, reset just place the minitaur back to start
        position and set its pose to initial configuration.
      on_rack: Whether to place the minitaur on rack. This is only used to debug
        the walking gait. In this mode, the minitaur's base is hanged midair so
        that its walking gait is clearer to visualize.
      render: Whether to render the simulation.
      num_steps_to_log: The max number of control steps in one episode that will
        be logged. If the number of steps is more than num_steps_to_log, the
        environment will still be running, but only first num_steps_to_log will
        be recorded in logging.
      action_repeat: The number of simulation steps before actions are applied.
      control_time_step: The time step between two successive control signals.
      env_randomizer: An instance (or a list) of EnvRandomizer(s). An
        EnvRandomizer may randomize the physical property of minitaur, change
          the terrrain during reset(), or add perturbation forces during step().
      forward_reward_cap: The maximum value that forward reward is capped at.
        Disabled (Inf) by default.
      log_path: The path to write out logs. For the details of logging, refer to
        minitaur_logging.proto.
    Raises:
      ValueError: If the urdf_version is not supported.
    """
        # Set up logging.
        self._log_path = log_path
        self.logging = minitaur_logging.MinitaurLogging(log_path)
        # PD control needs smaller time step for stability.
        if control_time_step is not None:
            self.control_time_step = control_time_step
            self._action_repeat = action_repeat
            self._time_step = control_time_step / action_repeat
        else:
            # Default values for time step and action repeat
            if accurate_motor_model_enabled or pd_control_enabled:
                self._time_step = 0.002
                self._action_repeat = 5
            else:
                self._time_step = 0.01
                self._action_repeat = 1
            self.control_time_step = self._time_step * self._action_repeat
        # TODO(b/73829334): Fix the value of self._num_bullet_solver_iterations.
        self._num_bullet_solver_iterations = int(
            NUM_SIMULATION_ITERATION_STEPS / self._action_repeat)
        self._urdf_root = urdf_root
        self._self_collision_enabled = self_collision_enabled
        self._motor_velocity_limit = motor_velocity_limit
        self._observation = []
        self._true_observation = []
        self._objectives = []
        self._objective_weights = [
            distance_weight, energy_weight, drift_weight, shake_weight
        ]
        self._env_step_counter = 0
        self._num_steps_to_log = num_steps_to_log
        self._is_render = render
        self._last_base_position = [0, 0, 0]
        self._distance_weight = distance_weight
        self._energy_weight = energy_weight
        self._drift_weight = drift_weight
        self._shake_weight = shake_weight
        self._distance_limit = distance_limit
        self._observation_noise_stdev = observation_noise_stdev
        self._action_bound = 1
        self._pd_control_enabled = pd_control_enabled
        self._leg_model_enabled = leg_model_enabled
        self._accurate_motor_model_enabled = accurate_motor_model_enabled
        self._remove_default_joint_damping = remove_default_joint_damping
        self._motor_kp = motor_kp
        self._motor_kd = motor_kd
        self._torque_control_enabled = torque_control_enabled
        self._motor_overheat_protection = motor_overheat_protection
        self._on_rack = on_rack
        self._cam_dist = 1.0
        self._cam_yaw = 0
        self._cam_pitch = -30
        self._forward_reward_cap = forward_reward_cap
        self._hard_reset = True
        self._last_frame_time = 0.0
        self._control_latency = control_latency
        self._pd_latency = pd_latency
        self._urdf_version = urdf_version
        self._ground_id = None
        self._reflection = reflection
        self._env_randomizers = convert_to_list(
            env_randomizer) if env_randomizer else []
        #self._episode_proto = minitaur_logging_pb2.MinitaurEpisode()
        if self._is_render:
            self._pybullet_client = bc.BulletClient(
                connection_mode=pybullet.GUI)
        else:
            self._pybullet_client = bc.BulletClient()
        if self._urdf_version is None:
            self._urdf_version = DEFAULT_URDF_VERSION
        self._pybullet_client.setPhysicsEngineParameter(enableConeFriction=0)
        self._pybullet_client.configureDebugVisualizer(pybullet.COV_ENABLE_GUI,
                                                       0)
        self.seed()
        self.reset()
        observation_high = (self._get_observation_upper_bound() +
                            OBSERVATION_EPS)
        observation_low = (self._get_observation_lower_bound() -
                           OBSERVATION_EPS)
        action_dim = NUM_MOTORS
        action_high = np.array([self._action_bound] * action_dim)
        self.action_space = spaces.Box(-action_high, action_high)
        self.observation_space = spaces.Box(observation_low, observation_high)
        self.viewer = None
        self._hard_reset = hard_reset  # This assignment need to be after reset()
示例#8
0
import pybullet_utils_local.bullet_client as bc
import pybullet
import pybullet_data_local

p0 = bc.BulletClient(connection_mode=pybullet.DIRECT)
p0.setAdditionalSearchPath(pybullet_data_local.getDataPath())

p1 = bc.BulletClient(connection_mode=pybullet.DIRECT)
p1.setAdditionalSearchPath(pybullet_data_local.getDataPath())

#can also connect using different modes, GUI, SHARED_MEMORY, TCP, UDP, SHARED_MEMORY_SERVER, GUI_SERVER
#pgui = bc.BulletClient(connection_mode=pybullet.GUI)

p0.loadURDF("r2d2.urdf")
p1.loadSDF("stadium.sdf")
print(p0._client)
print(p1._client)
print("p0.getNumBodies()=", p0.getNumBodies())
print("p1.getNumBodies()=", p1.getNumBodies())
示例#9
0
    def reset(self):

        if not self._isInitialized:
            if self.enable_draw:
                self._pybullet_client = bullet_client.BulletClient(
                    connection_mode=p1.GUI)
                #disable 'GUI' since it slows down a lot on Mac OSX and some other platforms
                self._pybullet_client.configureDebugVisualizer(
                    self._pybullet_client.COV_ENABLE_GUI, 0)
            else:
                self._pybullet_client = bullet_client.BulletClient()

            self._pybullet_client.setAdditionalSearchPath(
                pybullet_data_local.getDataPath())
            z2y = self._pybullet_client.getQuaternionFromEuler(
                [-math.pi * 0.5, 0, 0])
            self._planeId = self._pybullet_client.loadURDF(
                "plane_implicit.urdf", [0, 0, 0],
                z2y,
                useMaximalCoordinates=True)
            #print("planeId=",self._planeId)
            self._pybullet_client.configureDebugVisualizer(
                self._pybullet_client.COV_ENABLE_Y_AXIS_UP, 1)
            self._pybullet_client.setGravity(0, -9.8, 0)

            self._pybullet_client.setPhysicsEngineParameter(
                numSolverIterations=10)
            self._pybullet_client.changeDynamics(self._planeId,
                                                 linkIndex=-1,
                                                 lateralFriction=0.9)

            self._mocapData = motion_capture_data.MotionCaptureData()

            motion_file = self._arg_parser.parse_strings('motion_file')
            print("motion_file=", motion_file[0])

            motionPath = pybullet_data_local.getDataPath(
            ) + "/" + motion_file[0]
            #motionPath = pybullet_data_local.getDataPath()+"/motions/humanoid3d_backflip.txt"
            self._mocapData.Load(motionPath)
            timeStep = 1. / 240.
            useFixedBase = False
            self._humanoid = humanoid_stable_pd.HumanoidStablePD(
                self._pybullet_client, self._mocapData, timeStep, useFixedBase,
                self._arg_parser)
            self._isInitialized = True

            self._pybullet_client.setTimeStep(timeStep)
            self._pybullet_client.setPhysicsEngineParameter(numSubSteps=1)

            selfCheck = False
            if (selfCheck):
                curTime = 0
                while self._pybullet_client.isConnected():
                    self._humanoid.setSimTime(curTime)
                    state = self._humanoid.getState()
                    #print("state=",state)
                    pose = self._humanoid.computePose(
                        self._humanoid._frameFraction)
                    for i in range(10):
                        curTime += timeStep
                        #taus = self._humanoid.computePDForces(pose)
                        #self._humanoid.applyPDForces(taus)
                        #self._pybullet_client.stepSimulation()
                    time.sleep(timeStep)
        #print("numframes = ", self._humanoid._mocap_data.NumFrames())
        #startTime = random.randint(0,self._humanoid._mocap_data.NumFrames()-2)
        rnrange = 1000
        rn = random.randint(0, rnrange)
        startTime = float(rn) / rnrange * self._humanoid.getCycleTime()
        self.t = startTime

        self._humanoid.setSimTime(startTime)

        self._humanoid.resetPose()
        #this clears the contact points. Todo: add API to explicitly clear all contact points?
        #self._pybullet_client.stepSimulation()
        self._humanoid.resetPose()
        self.needs_update_time = self.t - 1  #force update
示例#10
0
    def __init__(self,
                 pybullet_sim_factory=boxstack_pybullet_sim,
                 render=True,
                 render_sleep=False,
                 debug_visualization=True,
                 hard_reset=False,
                 render_width=240,
                 render_height=240,
                 action_repeat=1,
                 time_step=1. / 240.,
                 num_bullet_solver_iterations=50,
                 urdf_root=pybullet_data_local.getDataPath()):
        """Initialize the gym environment.

    Args:
      urdf_root: The path to the urdf data folder.
    """
        self._pybullet_sim_factory = pybullet_sim_factory
        self._time_step = time_step
        self._urdf_root = urdf_root
        self._observation = []
        self._action_repeat = action_repeat
        self._num_bullet_solver_iterations = num_bullet_solver_iterations
        self._env_step_counter = 0
        self._is_render = render
        self._debug_visualization = debug_visualization
        self._render_sleep = render_sleep
        self._render_width = render_width
        self._render_height = render_height
        self._cam_dist = .3
        self._cam_yaw = 50
        self._cam_pitch = -35
        self._hard_reset = True
        self._last_frame_time = 0.0

        optionstring = '--width={} --height={}'.format(render_width,
                                                       render_height)

        print("urdf_root=" + self._urdf_root)

        if self._is_render:
            self._pybullet_client = bc.BulletClient(
                connection_mode=pybullet.GUI, options=optionstring)
        else:
            self._pybullet_client = bc.BulletClient()

        if (debug_visualization == False):
            self._pybullet_client.configureDebugVisualizer(
                flag=self._pybullet_client.COV_ENABLE_GUI, enable=0)
            self._pybullet_client.configureDebugVisualizer(
                flag=self._pybullet_client.COV_ENABLE_RGB_BUFFER_PREVIEW,
                enable=0)
            self._pybullet_client.configureDebugVisualizer(
                flag=self._pybullet_client.COV_ENABLE_DEPTH_BUFFER_PREVIEW,
                enable=0)
            self._pybullet_client.configureDebugVisualizer(
                flag=self._pybullet_client.
                COV_ENABLE_SEGMENTATION_MARK_PREVIEW,
                enable=0)

        self._pybullet_client.setAdditionalSearchPath(urdf_root)
        self.seed()
        self.reset()

        observation_high = (self._example_sim.GetObservationUpperBound())
        observation_low = (self._example_sim.GetObservationLowerBound())

        action_dim = self._example_sim.GetActionDimension()
        self._action_bound = 1
        action_high = np.array([self._action_bound] * action_dim)
        self.action_space = spaces.Box(-action_high, action_high)
        self.observation_space = spaces.Box(observation_low, observation_high)

        self.viewer = None
        self._hard_reset = hard_reset  # This assignment need to be after reset()
示例#11
0
#rudimentary MuJoCo mjcf to ROS URDF converter using the UrdfEditor

import pybullet_utils_local.bullet_client as bc
import pybullet_data_local as pd

import pybullet_utils_local.urdfEditor as ed
import argparse
parser = argparse.ArgumentParser(
    formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument('--mjcf',
                    help='MuJoCo xml file to be converted to URDF',
                    default='mjcf/humanoid.xml')
args = parser.parse_args()

p = bc.BulletClient()
p.setAdditionalSearchPath(pd.getDataPath())
objs = p.loadMJCF(args.mjcf, flags=p.URDF_USE_IMPLICIT_CYLINDER)

for o in objs:
    #print("o=",o, p.getBodyInfo(o), p.getNumJoints(o))
    humanoid = objs[o]
    ed0 = ed.UrdfEditor()
    ed0.initializeFromBulletBody(humanoid, p._client)
    robotName = str(p.getBodyInfo(o)[1], 'utf-8')
    partName = str(p.getBodyInfo(o)[0], 'utf-8')

    print("robotName=", robotName)
    print("partName=", partName)

    saveVisuals = False
    ed0.saveUrdf(robotName + "_" + partName + ".urdf", saveVisuals)
示例#12
0
import pybullet_data_local as pd
import pybullet_utils_local as pu
import pybullet
import pybullet_utils_local.bullet_client as bc
import time

p = bc.BulletClient(connection_mode=pybullet.GUI)
p.setAdditionalSearchPath(pd.getDataPath())
p.loadURDF("plane_transparent.urdf", useMaximalCoordinates=True)
p  #.setPhysicsEngineParameter(numSolverIterations=10, fixedTimeStep=0.01)

p.configureDebugVisualizer(p.COV_ENABLE_PLANAR_REFLECTION, 1)
p.configureDebugVisualizer(p.COV_ENABLE_RENDERING, 0)

y2z = p.getQuaternionFromEuler([0, 0, 1.57])
meshScale = [1, 1, 1]
visualShapeId = p.createVisualShape(shapeType=p.GEOM_MESH,
                                    fileName="domino/domino.obj",
                                    rgbaColor=[1, 1, 1, 1],
                                    specularColor=[0.4, .4, 0],
                                    visualFrameOrientation=y2z,
                                    meshScale=meshScale)

boxDimensions = [0.5 * 0.00635, 0.5 * 0.0254, 0.5 * 0.0508]
collisionShapeId = p.createCollisionShape(p.GEOM_BOX,
                                          halfExtents=boxDimensions)

for j in range(12):
    print("j=", j)
    for i in range(35):
        #p.loadURDF("domino/domino.urdf",[i*0.04,0, 0.06])