Python pybullet.connect() Examples
The following are 30
code examples of pybullet.connect().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
pybullet
, or try the search function
.
Example #1
Source File: client.py From costar_plan with Apache License 2.0 | 6 votes |
def open(self): ''' Decide how we will create our interface to the underlying simulation. We can create a GUI connection or something else. ''' options = "" if self.opengl2: connect_type = pb.GUI options = "--opengl2" elif self.gui: connect_type = pb.GUI else: connect_type = pb.DIRECT self.client = pb.connect(connect_type, options=options) GRAVITY = (0,0,-9.8) pb.setGravity(*GRAVITY) # place the robot in the world and set up the task self.task.setup()
Example #2
Source File: bullet_client.py From rex-gym with Apache License 2.0 | 6 votes |
def __init__(self, connection_mode=None): """Creates a Bullet client and connects to a simulation. Args: connection_mode: `None` connects to an existing simulation or, if fails, creates a new headless simulation, `pybullet.GUI` creates a new simulation with a GUI, `pybullet.DIRECT` creates a headless simulation, `pybullet.SHARED_MEMORY` connects to an existing simulation. """ self._shapes = {} if connection_mode is None: self._client = pybullet.connect(pybullet.SHARED_MEMORY) if self._client >= 0: return else: connection_mode = pybullet.DIRECT self._client = pybullet.connect(connection_mode)
Example #3
Source File: balancebot_env.py From balance-bot with MIT License | 6 votes |
def __init__(self, render=False): self._observation = [] self.action_space = spaces.Discrete(9) self.observation_space = spaces.Box(np.array([-math.pi, -math.pi, -5]), np.array([math.pi, math.pi, 5])) # pitch, gyro, com.sp. if (render): self.physicsClient = p.connect(p.GUI) else: self.physicsClient = p.connect(p.DIRECT) # non-graphical version p.setAdditionalSearchPath(pybullet_data.getDataPath()) # used by loadURDF self._seed() # paramId = p.addUserDebugParameter("My Param", 0, 100, 50)
Example #4
Source File: widowx_controller.py From visual_foresight with MIT License | 6 votes |
def __init__(self, robot_name, print_debug, email_cred_file='', log_file='', control_rate=100, gripper_attached='default'): super(WidowXController, self).__init__(robot_name, print_debug, email_cred_file, log_file, control_rate, gripper_attached) self._redist_rate = rospy.Rate(50) self._arbotix = ArbotiX('/dev/ttyUSB0') assert self._arbotix.syncWrite(MAX_TORQUE_L, [[servo_id, 255, 0] for servo_id in SERVO_IDS]) != -1, "failure during servo configuring" assert self._arbotix.syncWrite(TORQUE_LIMIT, [[servo_id, 255, 0] for servo_id in SERVO_IDS]) != -1, "failure during servo configuring" self._joint_lock = Lock() self._angles, self._velocities = {}, {} rospy.Subscriber("/joint_states", JointState, self._joint_callback) time.sleep(1) self._joint_pubs = [rospy.Publisher('/{}/command'.format(name), Float64, queue_size=1) for name in JOINT_NAMES[:-1]] self._gripper_pub = rospy.Publisher('/gripper_prismatic_joint/command', Float64, queue_size=1) p.connect(p.DIRECT) widow_x_urdf = '/'.join(__file__.split('/')[:-1]) + '/widowx/widowx.urdf' self._armID = p.loadURDF(widow_x_urdf, useFixedBase=True) p.resetBasePositionAndOrientation(self._armID, [0, 0, 0], p.getQuaternionFromEuler([np.pi, np.pi, np.pi])) self._n_errors = 0
Example #5
Source File: panda_ik_controller.py From robosuite with MIT License | 6 votes |
def setup_inverse_kinematics(self): """ This function is responsible for doing any setup for inverse kinematics. Inverse Kinematics maps end effector (EEF) poses to joint angles that are necessary to achieve those poses. """ # Set up a connection to the PyBullet simulator. p.connect(p.DIRECT) p.resetSimulation() # get paths to urdfs self.robot_urdf = pjoin( self.bullet_data_path, "panda_description/urdf/panda_arm.urdf" ) # load the urdfs self.ik_robot = p.loadURDF(self.robot_urdf, (0, 0, 0.9), useFixedBase=1) # Simulation will update as fast as it can in real time, instead of waiting for # step commands like in the non-realtime case. p.setRealTimeSimulation(1)
Example #6
Source File: sawyer_ik_controller.py From robosuite with MIT License | 6 votes |
def setup_inverse_kinematics(self): """ This function is responsible for doing any setup for inverse kinematics. Inverse Kinematics maps end effector (EEF) poses to joint angles that are necessary to achieve those poses. """ # Set up a connection to the PyBullet simulator. p.connect(p.DIRECT) p.resetSimulation() # get paths to urdfs self.robot_urdf = pjoin( self.bullet_data_path, "sawyer_description/urdf/sawyer_arm.urdf" ) # load the urdfs self.ik_robot = p.loadURDF(self.robot_urdf, (0, 0, 0.9), useFixedBase=1) # Simulation will update as fast as it can in real time, instead of waiting for # step commands like in the non-realtime case. p.setRealTimeSimulation(1)
Example #7
Source File: pose_env.py From tensor2robot with Apache License 2.0 | 6 votes |
def __init__(self, render_mode='DIRECT', hidden_drift=False, urdf_root=''): """Construct a Duck pose prediction task. Args: render_mode: Whether to render headless or with a GUI. hidden_drift: If True, each task will assign a hidden random drift where the rendered pose differs from the true pose. Requires meta-learning adaptation to solve. urdf_root: Path to URDF files. """ if render_mode == 'GUI': self.cid = pybullet.connect(pybullet.GUI) elif render_mode == 'DIRECT': self.cid = pybullet.connect(pybullet.DIRECT) self._width, self._height = 64, 64 self._urdf_root = urdf_root self._hidden_drift = hidden_drift self._hidden_drift_xyz = None self._setup() self.reset_task()
Example #8
Source File: bullet_client.py From soccer-matlab with BSD 2-Clause "Simplified" License | 6 votes |
def __init__(self, connection_mode=None): """Creates a Bullet client and connects to a simulation. Args: connection_mode: `None` connects to an existing simulation or, if fails, creates a new headless simulation, `pybullet.GUI` creates a new simulation with a GUI, `pybullet.DIRECT` creates a headless simulation, `pybullet.SHARED_MEMORY` connects to an existing simulation. """ self._shapes = {} if connection_mode is None: self._client = pybullet.connect(pybullet.SHARED_MEMORY) if self._client >= 0: return else: connection_mode = pybullet.DIRECT self._client = pybullet.connect(connection_mode)
Example #9
Source File: client.py From costar_plan with Apache License 2.0 | 6 votes |
def _start_ros(self, name): ''' Simple function to boot up a ROS core and make sure that we connect to it. The goal is to manage internal ROS stuff via this script to provide an easy and repeatable interface when running experiments. ''' self._start_process(['roscore'], 1.) started = False tries = 0 while not started: try: rospy.init_node(name) started = True except Exception, e: pass finally:
Example #10
Source File: bullet_client.py From soccer-matlab with BSD 2-Clause "Simplified" License | 6 votes |
def __init__(self, connection_mode=None): """Creates a Bullet client and connects to a simulation. Args: connection_mode: `None` connects to an existing simulation or, if fails, creates a new headless simulation, `pybullet.GUI` creates a new simulation with a GUI, `pybullet.DIRECT` creates a headless simulation, `pybullet.SHARED_MEMORY` connects to an existing simulation. """ self._shapes = {} if connection_mode is None: self._client = pybullet.connect(pybullet.SHARED_MEMORY) if self._client >= 0: return else: connection_mode = pybullet.DIRECT self._client = pybullet.connect(connection_mode)
Example #11
Source File: env_bases.py From GtS with MIT License | 5 votes |
def __init__(self, config, scene_type, tracking_camera): ## Properties already instantiated from SensorEnv/CameraEnv # @self.robot self.gui = config["mode"] == "gui" self.model_id = config["model_id"] self.timestep = 0.1 #internal gibson self.frame_skip = 1 #internal gibson self.resolution = config["resolution"] self.tracking_camera = tracking_camera self.robot = None # initial_orn, initial_pos = config["initial_orn"], self.config["initial_pos"] if config["display_ui"]: #self.physicsClientId = p.connect(p.DIRECT) self.physicsClientId = p.connect(p.GUI, "--opengl2") p.configureDebugVisualizer(p.COV_ENABLE_GUI, 0) elif (self.gui): self.physicsClientId = p.connect(p.GUI, "--opengl2") else: self.physicsClientId = p.connect(p.DIRECT) self.camera = Camera() self._seed() self._cam_dist = 3 self._cam_yaw = 0 self._cam_pitch = -30 self.scene_type = scene_type self.scene = None
Example #12
Source File: kuka_grasp_block_playback.py From soccer-matlab with BSD 2-Clause "Simplified" License | 5 votes |
def readLogFile(filename, verbose = True): f = open(filename, 'rb') print('Opened'), print(filename) keys = f.readline().decode('utf8').rstrip('\n').split(',') fmt = f.readline().decode('utf8').rstrip('\n') # The byte number of one record sz = struct.calcsize(fmt) # The type number of one record ncols = len(fmt) if verbose: print('Keys:'), print(keys) print('Format:'), print(fmt) print('Size:'), print(sz) print('Columns:'), print(ncols) # Read data wholeFile = f.read() # split by alignment word chunks = wholeFile.split(b'\xaa\xbb') log = list() for chunk in chunks: if len(chunk) == sz: values = struct.unpack(fmt, chunk) record = list() for i in range(ncols): record.append(values[i]) log.append(record) return log #clid = p.connect(p.SHARED_MEMORY)
Example #13
Source File: env_bases.py From midlevel-reps with MIT License | 5 votes |
def __init__(self, config, scene_type, tracking_camera): ## Properties already instantiated from SensorEnv/CameraEnv # @self.robot self.gui = config["mode"] == "gui" if "model_id" in config: self.model_id = config["model_id"] self.timestep = config["speed"]["timestep"] self.frame_skip = config["speed"]["frameskip"] self.resolution = config["resolution"] self.tracking_camera = tracking_camera self.robot = None target_orn, target_pos = config["target_orn"], self.config["target_pos"] initial_orn, initial_pos = config["initial_orn"], self.config["initial_pos"] if config["display_ui"]: #self.physicsClientId = p.connect(p.DIRECT) self.physicsClientId = p.connect(p.GUI, "--opengl2") p.configureDebugVisualizer(p.COV_ENABLE_GUI, 0) elif (self.gui): self.physicsClientId = p.connect(p.GUI, "--opengl2") else: self.physicsClientId = p.connect(p.DIRECT) self.camera = Camera() self._seed() self._cam_dist = 3 self._cam_yaw = 0 self._cam_pitch = -30 self.scene_type = scene_type self.scene = None
Example #14
Source File: enjoy_TF_PybulletInvertedDoublePendulum_v0_2017may.py From bullet-gym with MIT License | 5 votes |
def demo_run(): env = gym.make("PybulletInvertedDoublePendulum-v0") cid = p.connect(p.SHARED_MEMORY) # only show graphics if the browser is already running.... if cid < 0: cid = p.connect(p.DIRECT) pi = SmallReactivePolicy(env.observation_space, env.action_space) while 1: frame = 0 score = 0 restart_delay = 0 obs = env.reset() while 1: time.sleep(0.05) a = pi.act(obs) obs, r, done, _ = env.step(a) score += r frame += 1 still_open = env.render("human") if still_open==False: return if not done: continue if restart_delay==0: print("score=%0.2f in %i frames" % (score, frame)) restart_delay = 60*2 # 2 sec at 60 fps else: restart_delay -= 1 if restart_delay > 0: continue break
Example #15
Source File: enjoy_TF_PybulletInvertedPendulum_v0_2017may.py From bullet-gym with MIT License | 5 votes |
def demo_run(): env = gym.make("PybulletInvertedPendulum-v0") cid = p.connect(p.SHARED_MEMORY) # only show graphics if the browser is already running.... if cid < 0: cid = p.connect(p.DIRECT) pi = SmallReactivePolicy(env.observation_space, env.action_space) while 1: frame = 0 score = 0 restart_delay = 0 obs = env.reset() while 1: time.sleep(0.05) a = pi.act(obs) obs, r, done, _ = env.step(a) score += r frame += 1 still_open = env.render("human") if still_open==False: return if not done: continue if restart_delay==0: print("score=%0.2f in %i frames" % (score, frame)) restart_delay = 60*2 # 2 sec at 60 fps else: restart_delay -= 1 if restart_delay==0: break
Example #16
Source File: Trainer.py From bullet-gym with MIT License | 5 votes |
def __init__(self): # initialize random seed np.random.seed(int(time.time())) cid = p.connect(p.SHARED_MEMORY) # only show graphics if the browser is already running.... self.visualize = (cid >= 0) if cid < 0: cid = p.connect(p.DIRECT) # If no shared memory browser is active, we switch to headless mode (DIRECT is much faster)
Example #17
Source File: enjoy_TF_PybulletInvertedPendulumSwingup_v0_2017may.py From bullet-gym with MIT License | 5 votes |
def demo_run(): env = gym.make("PybulletInvertedPendulumSwingup-v0") cid = p.connect(p.SHARED_MEMORY) # only show graphics if the browser is already running.... if cid < 0: cid = p.connect(p.DIRECT) pi = SmallReactivePolicy(env.observation_space, env.action_space) while 1: frame = 0 score = 0 restart_delay = 0 obs = env.reset() while 1: time.sleep(0.05) a = pi.act(obs) obs, r, done, _ = env.step(a) score += r frame += 1 still_open = env.render("human") if still_open==False: return if not done: continue if restart_delay==0: print("score=%0.2f in %i frames" % (score, frame)) restart_delay = 60*2 # 2 sec at 60 fps else: restart_delay -= 1 if restart_delay > 0: continue break
Example #18
Source File: env.py From assistive-gym with MIT License | 5 votes |
def render(self, mode='human'): if not self.gui: self.gui = True p.disconnect(self.id) self.id = p.connect(p.GUI, options='--background_color_red=0.8 --background_color_green=0.9 --background_color_blue=1.0 --width=%d --height=%d' % (self.width, self.height)) self.world_creation = WorldCreation(self.id, robot_type=self.robot_type, task=self.task, time_step=self.time_step, np_random=self.np_random, config=self.config) self.util = Util(self.id, self.np_random) # print('Physics server ID:', self.id)
Example #19
Source File: MJCFHopperv0Env.py From bullet-gym with MIT License | 5 votes |
def __init__(self, opts): self.gui = opts.gui self.max_episode_len = opts.max_episode_len self.delay = opts.delay if self.gui else 0.0 # do some parameter setting from your parser arguments and add other configurations # how many time to repeat each action per step(). # and how many sim steps to do per state capture # (total number of sim steps = action_repeats * steps_per_repeat self.repeats = opts.action_repeats self.steps_per_repeat = opts.steps_per_repeat # setup bullet p.connect(p.GUI if self.gui else p.DIRECT) p.setGravity(0,0,-9.81) PybulletMujocoEnv.__init__(self, "envs/models/mjcf/hopper.xml", "walker", 0.02, frame_skip=2, action_dim=3, obs_dim=8, repeats=self.repeats) self.torso = self.parts["torso"] self.foot = self.parts["foot"] self.thigh_joint = self.joints["thigh_joint"] self.leg_joint = self.joints["leg_joint"] self.foot_joint = self.joints["foot_joint"] self.metadata = { 'discrete_actions' : False, 'continuous_actions': True, 'render.modes': ['human', 'rgb_array'], 'video.frames_per_second': int(np.round(1.0 / self.timestep / self.frame_skip)) }
Example #20
Source File: gym_env.py From mushroom-rl with MIT License | 5 votes |
def __init__(self, name, horizon, gamma): """ Constructor. Args: name (str): gym id of the environment; horizon (int): the horizon; gamma (float): the discount factor. """ # MDP creation self._close_at_stop = True if '- ' + name in pybullet_envs.getList(): import pybullet pybullet.connect(pybullet.DIRECT) self._close_at_stop = False self.env = gym.make(name) self.env._max_episode_steps = np.inf # Hack to ignore gym time limit. # MDP properties assert not isinstance(self.env.observation_space, gym_spaces.MultiDiscrete) assert not isinstance(self.env.action_space, gym_spaces.MultiDiscrete) action_space = self._convert_gym_space(self.env.action_space) observation_space = self._convert_gym_space(self.env.observation_space) mdp_info = MDPInfo(observation_space, action_space, gamma, horizon) if isinstance(action_space, Discrete): self._convert_action = lambda a: a[0] else: self._convert_action = lambda a: a super().__init__(mdp_info)
Example #21
Source File: bullet_client.py From pyrobot with MIT License | 5 votes |
def __init__(self, connection_mode=pybullet.DIRECT, options=""): """Create a simulation and connect to it.""" self._client = pybullet.connect(pybullet.SHARED_MEMORY) if self._client < 0: print("options=", options) self._client = pybullet.connect(connection_mode, options=options) self._shapes = {}
Example #22
Source File: renderer.py From mvp_grasp with BSD 3-Clause "New" or "Revised" License | 5 votes |
def __init__(self, im_width, im_height, fov, near_plane, far_plane, DEBUG=False): self.im_width = im_width self.im_height = im_height self.fov = fov self.near_plane = near_plane self.far_plane = far_plane aspect = self.im_width/self.im_height self.pm = pb.computeProjectionMatrixFOV(fov, aspect, near_plane, far_plane) self.camera_pos = np.array([0, 0, 0.5]) self.camera_rot = self._rotation_matrix([0, np.pi, 0]) self.objects = [] if DEBUG: self.cid = pb.connect(pb.GUI) else: self.cid = pb.connect(pb.DIRECT) pb.setAdditionalSearchPath(pybullet_data.getDataPath()) pb.setGravity(0, 0, -10) self.draw_camera_pos() self._rendered = None self._rendered_pos = None self._rendered_rot = None
Example #23
Source File: bullet_robot_env.py From Rainbow_ddpg with MIT License | 5 votes |
def __init__(self, n_actions, # Dimension of action vector. n_substeps, # Number of simulation steps to do in every env step. observation_type="low_dim", done_after=float("inf"), use_gui=False, frame_memory_len=0): self.n_substeps = n_substeps self.metadata = { 'render.modes': ['rgbd_array'], 'video.frames_per_second': int(np.round(1.0 / self.dt)) } self.numSteps = 0 if use_gui: physics_client = p.connect(p.GUI) else: physics_client = p.connect(p.DIRECT) self.p = PhysClientWrapper(p, physics_client) self.p.setAdditionalSearchPath(pybullet_data.getDataPath()) self.doneAfter = done_after self.observation_type = observation_type self.seed() self.frameMemoryLen = frame_memory_len if frame_memory_len: self.frameMemory = deque(maxlen=frame_memory_len) self.viewMatrix = p.computeViewMatrix([-1.05, 0, 0.68], [0.1, 0, 0], [-0.5, 0, 1]) self.projMatrix = p.computeProjectionMatrixFOV( fov=45, aspect=4. / 3., nearVal=0.01, farVal=2.5) self.light = { "diffuse": 0.4, "ambient": 0.5, "spec": 0.2, "dir": [10, 10, 100], "col": [1, 1, 1] } self._env_setup(initial_qpos=None) self.action_space = spaces.Box( -1, 1, shape=(n_actions, ), dtype='float32') self.pixels_space = spaces.Box( -np.inf, np.inf, shape=(84, 84, 3), dtype='float32') if observation_type == "low_dim": self.observation_space = self.low_dim_space elif observation_type == "pixels": self.observation_space = self.pixels_space elif observation_type == "pixels_stacked": self.observation_space = spaces.Box( -np.inf, np.inf, shape=(84, 84, 12), dtype='float32') elif observation_type == "pixels_depth": self.observation_space = spaces.Box( -np.inf, np.inf, shape=(84, 84), dtype='float32') else: raise Exception("Unimplemented observation_type")
Example #24
Source File: baxter_ik_controller.py From robosuite with MIT License | 5 votes |
def setup_inverse_kinematics(self, urdf_path): """ This function is responsible for doing any setup for inverse kinematics. Inverse Kinematics maps end effector (EEF) poses to joint angles that are necessary to achieve those poses. """ # These indices come from the urdf file we're using self.effector_right = 27 self.effector_left = 45 # Use PyBullet to handle inverse kinematics. # Set up a connection to the PyBullet simulator. p.connect(p.DIRECT) p.resetSimulation() self.ik_robot = p.loadURDF(urdf_path, (0, 0, 0), useFixedBase=1) # Relevant joints we care about. Many of the joints are fixed and don't count, so # we need this second map to use the right ones. self.actual = [13, 14, 15, 16, 17, 19, 20, 31, 32, 33, 34, 35, 37, 38] self.num_joints = p.getNumJoints(self.ik_robot) n = p.getNumJoints(self.ik_robot) self.rest = [] self.lower = [] self.upper = [] self.ranges = [] for i in range(n): info = p.getJointInfo(self.ik_robot, i) # Retrieve lower and upper ranges for each relevant joint if info[3] > -1: self.rest.append(p.getJointState(self.ik_robot, i)[0]) self.lower.append(info[8]) self.upper.append(info[9]) self.ranges.append(info[9] - info[8]) # Simulation will update as fast as it can in real time, instead of waiting for # step commands like in the non-realtime case. p.setRealTimeSimulation(1)
Example #25
Source File: bullet_client.py From soccer-matlab with BSD 2-Clause "Simplified" License | 5 votes |
def __init__(self, connection_mode=pybullet.DIRECT, options=""): """Create a simulation and connect to it.""" self._client = pybullet.connect(pybullet.SHARED_MEMORY) if(self._client<0): print("options=",options) self._client = pybullet.connect(connection_mode,options=options) self._shapes = {}
Example #26
Source File: testMJCF.py From soccer-matlab with BSD 2-Clause "Simplified" License | 5 votes |
def test(args): p.connect(p.GUI) p.setAdditionalSearchPath(pybullet_data.getDataPath()) fileName = os.path.join("mjcf", args.mjcf) print("fileName") print(fileName) p.loadMJCF(fileName) while (1): p.stepSimulation() p.getCameraImage(320,240) time.sleep(0.01)
Example #27
Source File: enjoy_TF_AntBulletEnv_v0_2017may.py From soccer-matlab with BSD 2-Clause "Simplified" License | 5 votes |
def main(): pybullet.connect(pybullet.DIRECT) env = gym.make("AntBulletEnv-v0") env.render(mode="human") pi = SmallReactivePolicy(env.observation_space, env.action_space) env.reset() while 1: frame = 0 score = 0 restart_delay = 0 obs = env.reset() while 1: time.sleep(1./60.) a = pi.act(obs) obs, r, done, _ = env.step(a) #print("reward") #print(r) score += r frame += 1 distance=5 yaw = 0 still_open = env.render("human") if still_open==False: return if not done: continue if restart_delay==0: print("score=%0.2f in %i frames" % (score, frame)) restart_delay = 60*2 # 2 sec at 60 fps else: restart_delay -= 1 if restart_delay==0: break
Example #28
Source File: minitaur_test.py From soccer-matlab with BSD 2-Clause "Simplified" License | 5 votes |
def main(unused_args): timeStep = 0.01 c = p.connect(p.SHARED_MEMORY) if (c<0): c = p.connect(p.GUI) params = [0.1903581461951056, 0.0006732219568880068, 0.05018085615283363, 3.219916795483583, 6.2406418167980595, 4.189869754607539] evaluate_func = 'evaluate_desired_motorAngle_2Amplitude4Phase' energy_weight = 0.01 finalReturn = evaluate_params(evaluateFunc = evaluate_func, params=params, objectiveParams=[energy_weight], timeStep=timeStep, sleepTime=timeStep) print(finalReturn)
Example #29
Source File: unittests.py From soccer-matlab with BSD 2-Clause "Simplified" License | 5 votes |
def test_loadurdf(self): import pybullet as p p.connect(p.DIRECT) ob = p.loadURDF("r2d2.urdf") self.assertEqual(ob,0) p.disconnect()
Example #30
Source File: unittests.py From soccer-matlab with BSD 2-Clause "Simplified" License | 5 votes |
def test_connect_direct(self): import pybullet as p cid = p.connect(p.DIRECT) self.assertEqual(cid,0) p.disconnect()