def __init__(self, host='127.0.0.1', port=2000, city_name='Town03', render_pygame=True, warming_up_steps=50, window_size=5): self.client = carla.Client(host, port) self.client.set_timeout(2.0) self.hud = HUD(1700, 1000) self._carla_world = self.client.get_world() settings = self._carla_world.get_settings() settings.synchronous_mode = True settings.fixed_delta_seconds = 0.05 self._carla_world.apply_settings(settings) self.world = World(self._carla_world, self.hud) # time.sleep(2) self.render_pygame = render_pygame self.timestep = 0 self.warming_up_steps = warming_up_steps self.window_size = 5 self.current_state = defaultdict( list ) # {"CAV":[window_size, num_features=9], "LHDV":[window_size, num_features=6]}
def __init__(self, root_dir, source_limit, transform=None): self.world = World() self.speakers = [] for d_name in os.listdir(root_dir): if os.path.isdir(os.path.join(root_dir, d_name)): self.speakers.append(d_name) print(self.speakers) self.data = [] self.label = [] for i, d_name in enumerate(self.speakers): data_dir = os.path.join(root_dir, d_name) if os.path.isfile(os.path.join(data_dir, d_name + "_mcep.pickle")): with open(os.path.join(data_dir, d_name + "_mcep.pickle"), mode="rb") as data: mceps = pickle.load(data) mceps = mceps[:source_limit] self.data.extend(mceps) self.label.extend(np.ones((len(mceps))) * i) print("[{}] mcep loaded.".format(d_name)) else: mceps = [] f0s = [] for f in tqdm_notebook(os.listdir(data_dir)): if not ".wav" in f: continue file_path = os.path.join(data_dir, f) wav, _ = librosa.load(file_path, sr=hparams.fs) if len(wav) <= 10: continue wav, _ = librosa.effects.trim(wav) wav = wav.astype(np.double) f0, spec, ap = self.world.analyze(wav) mcep = self.world.mcep_from_spec(spec) mcep = mcep.reshape(mcep.shape[0], mcep.shape[1], 1) if mcep.shape[0] < 128: continue mceps.append(mcep) f0s.append(f0) # mceps = mceps[:source_limit] self.data.extend(mceps) self.label.extend(np.ones((len(mceps))) * i) with open(os.path.join(data_dir, d_name + "_mcep.pickle"), mode='wb') as f: pickle.dump(mceps, f) log_f0s_mean, log_f0s_std = logf0_statistics(f0s) mceps_mean, mceps_std = mcep_statistics(mceps) np.savez(os.path.join(data_dir, d_name + "_norm.npz"), log_f0s_mean=log_f0s_mean, log_f0s_std=log_f0s_std, mceps_mean=mceps_mean, mceps_std=mceps_std) print("[{}] voices converted.".format(d_name)) self.transform = transform self.converter = Converter(root_dir, self.speakers)
def node(turtle_name, indx, step, no_turtles, world): x = 0.0 y_start = indx * (world.window_height / no_turtles) y_end = (indx + 1) * (world.window_height / no_turtles) turtle = world.spawn(turtle_name, x, y_start) draw(turtle, y_start, y_end, world, step) world.kill(turtle_name) if __name__ == '__main__': rospy.init_node('draw') task = rospy.get_param('~task', default='none') world = World() step = rospy.get_param('~step_size', default=0.5) no_turtles = int(math.ceil(world.window_height / (step))) nodes = [] for i in range(no_turtles): nodes.append( Process(target=node, args=('t' + str(i), i, step, no_turtles, world))) for node in nodes: node.start() for node in nodes: node.join() turtle1 = Turtle('turtle1')
class CarlaEnv(object): ''' An OpenAI Gym Environment for CARLA. ''' def __init__(self, host='127.0.0.1', port=2000, city_name='Town03', render_pygame=True, warming_up_steps=50, window_size=5): self.client = carla.Client(host, port) self.client.set_timeout(2.0) self.hud = HUD(1700, 1000) self._carla_world = self.client.get_world() settings = self._carla_world.get_settings() settings.synchronous_mode = True settings.fixed_delta_seconds = 0.05 self._carla_world.apply_settings(settings) self.world = World(self._carla_world, self.hud) # time.sleep(2) self.render_pygame = render_pygame self.timestep = 0 self.warming_up_steps = warming_up_steps self.window_size = 5 self.current_state = defaultdict( list ) # {"CAV":[window_size, num_features=9], "LHDV":[window_size, num_features=6]} @staticmethod def action_space(self): throttle_brake = Discrete(3) # -1 brake, 0 keep, 1 throttle steering_increment = Discrete(3) return Tuple([throttle_brake, steering_increment]) @staticmethod def state_space(self): N = len(self.world.vehicles) F = 6 # FIXME not hard code return Box(low=-np.inf, high=np.inf, shape=(N, F), dtype=np.float32) def reset(self): # reset the render display panel if self.render_pygame: self.display = pygame.display.set_mode( (1280, 760), pygame.HWSURFACE | pygame.DOUBLEBUF) self.world.destroy() time.sleep(0.2) self.world.restart() self.current_state = defaultdict( list) #reinitialize the current states self.timestep = 0 self.frame_num = None self.carla_update() assert self.warming_up_steps > self.window_size, "warming_up_steps should be larger than the window size" [self.step(None) for _ in range(self.warming_up_steps)] return copy.deepcopy(self.current_state) def carla_update(self): self._carla_world.tick() # update in the simulator snap_shot = self._carla_world.wait_for_tick( ) # palse the simulator until future tick if self.frame_num is not None: # print(self.frame_num) if snap_shot.frame_count != self.frame_num + 1: print('frame skip!') self.frame_num = snap_shot.frame_count def step(self, rl_actions): self.world.cav_controller.step(rl_actions) self.world.ldhv_controller.step() self.world.bhdv_controller.step() self.carla_update() # self.carla_update() state_ = copy.deepcopy(self.get_state()) #next observation collision = self.check_collision() done_ = False if collision: print("collision here: ", collision) done_ = True reward_ = self.compute_reward(collision) self.timestep += 1 infos = {} if self.render_pygame: self.render_frame() return state_, reward_, done_, infos def render_frame(self): if self.display: self.world.render(self.display) pygame.display.flip() else: raise Exception("No display to render") def check_collision(self): if len(self.world.collision_sensor.history) > 0: return self.world.collision_sensor.history[-1] else: return None def get_state(self): for veh in self.world.vehicles: state = [] veh_name = veh.attributes['role_name'] location = veh.get_location() state += [location.x, location.y] speed = veh.get_velocity() state += [speed.x, speed.y] accel = veh.get_acceleration() state += [accel.x, accel.y] if self.current_state and len( self.current_state[veh_name]) == self.window_size: self.current_state[veh_name].pop(0) self.current_state[veh_name].append(state) current_control = self.world.cav_controller.current_control current_control = [ current_control['throttle'], current_control['steer'], current_control['brake'] ] #### one timestep behind # current_control = self.world.CAV.get_control() # current_control = [current_control.throttle, current_control.steer, current_control.brake] if self.current_state and len( self.current_state["current_control"]) == self.window_size: self.current_state["current_control"].pop(0) self.current_state["current_control"].append(current_control) return self.current_state def compute_reward(self, collision=None): weight_collision = 1 base_reward = 0 collision_penalty = 0 if collision: collision_penalty = collision[ 1] # the negative intensity of collision return base_reward - collision_penalty * weight_collision def compute_cost(self, state): pass def sych_distroy(self): actors = self._carla_world.get_actors() self.client.apply_batch( [carla.command.DestroyActor(x) for x in actors])
from agents import * from models import * from utils.World import * import sys import pickle """ This script is to visualize evaluation result. usage: python view_result.py path_to_record_file """ # instantiate the class f = open(sys.argv[1], 'rb') record = pickle.load(f) dT = record.dT exec('robot = ' + record.model + '(' + record.algorithm + '(), dT)') human = HumanBall3D(MobileAgent(), dT) w = World(dT, human, robot, record) base.run()
#!/usr/bin/env python import rospy from utils import Turtle from utils import World from math import cos, sin from turtlesim_examples.msg import Bumber rospy.init_node('bumber_node') world = World() pub = rospy.Publisher('bumber', Bumber, queue_size=10) msg = Bumber() name = rospy.get_param('~turtle_name', default='turtle1') radius = rospy.get_param('~radius', default=1.0) turtle1 = Turtle(name) theta = 0. x = turtle1.get_pose()[0][0] + radius * cos(theta) y = turtle1.get_pose()[0][0] + radius * sin(theta) try: turtle_scanner = world.spawn('turtle_scanner', x, y) except: turtle_scanner = Turtle('turtle_scanner') turtle_scanner.set_pen(1) diff = 0.5 while not rospy.is_shutdown(): theta += diff
import sys from utils import World, ElfLossException if __name__ == "__main__": for power in range(4, 20): w = World(sys.argv[1], elves_power=power) try: n = w.play(verbose=False, elves_loss=True) except ElfLossException: print(f"Elf lost with power {power}") else: tot_hit_pts = sum([obj.hit_points for obj in w.goblins_and_elves]) print( f"Battle with power {power} ended in round {n} with a total of " f"{tot_hit_pts}, solution is {tot_hit_pts*n}") break
pub = rospy.Publisher('scan', LaserScan, queue_size=10) name = rospy.get_param('~turtle_name', default='turtle1') map_tc = rospy.get_param('~map_topic', default='/map') range_max = rospy.get_param('~range_max', default=3.0) range_min = rospy.get_param('~range_min', default=0.0) angle_min = rospy.get_param('~angle_min', default=-1.5) angle_max = rospy.get_param('~angle_max', default=1.5) frame_id = rospy.get_param('~frame_id', default='base_link') linear_increment = rospy.get_param('~linear_increment', default=0.1) angle_increment = rospy.get_param('~angle_increment', default=0.01) freq = rospy.get_param('~rate', default=100) rate = rospy.Rate(freq) world = World(map_topic=map_tc) turtle1 = Turtle(name) msg = LaserScan() msg.angle_min = angle_min msg.angle_max = angle_max msg.angle_increment = angle_increment msg.range_max = range_max msg.range_min = range_min msg.time_increment = 0.001 msg.range_min = range_min msg.header.frame_id = frame_id start = time() while not rospy.is_shutdown(): scan_time = time() - start start = time()
_sphere2.material.specular = 0.8 # glassSphere.transform = scaling(0.5, 0.5, 0.5) # airSphere = Sphere() # airSphere.transform = scaling(0.5, 0.5, 0.5) # airSphere.material = Material() # airSphere.material.color = Color.white() # airSphere.material.diffuse = 0 # airSphere.material.shininess = 300.0 # airSphere.material.reflective = 0.9 # airSphere.material.transparency = 0.9 # airSphere.material.ambient = 0 # airSphere.material.specular = 0.9 # airSphere.material.refractive_index = 1.0000034 world = World() world.Objects = [Floor, _sphere, _sphere2] world.light = PointLight(Point(-10, 10, -10), Color(1, 1, 1)) cam = Camera(width, height, pi / 3) cam.transform = view_transform(Point(0, 1.5, -5), Point(0, 1, 0), Vector3(0, 1, 0)) # cam.transform = view_transform(Point(0,0, -5), Point(0, 0, 0), Vector3(0, 1, 0)) def PixelRender(x, y): global cam, world ray = ray_for_pixel(cam, x, y) color = color_at(world, ray) pixel(screen, x, y, color.ConvertColor()) pygame.display.flip()
import sys from utils import World if __name__ == "__main__": w = World(sys.argv[1]) w.print() n = w.play(verbose=False) tot_hit_pts = sum([obj.hit_points for obj in w.goblins_and_elves]) print( f"Battle ended in round {n} with a total of {tot_hit_pts}, solution is {tot_hit_pts*n}" ) w.print()
from agents import * from models import * from utils.World import * # end class world # instantiate the class dT = 0.05 # robot = RobotArm(SublevelSafeSet(), dT); # robot = Unicycle(SafeSet(), dT); robot = Ball(SafeSet(), dT) # human = InteractiveHumanBall2D(SafeSet(d_min=1, k_v=2), dT); human = HumanBall2D(MobileAgent, dT) w = World(dT, human, robot) base.run()