def start_clicked(self): self.ui.start.setEnabled(False) self.ui.fixed.setEnabled(False) if self.simulator: self.update_simulator() else: self.simulator = Simulator( fixed_time_step=self.ui.fixed.isChecked()) threading.Thread(target=self.start_simulator, name="Start simulator Thread").start() self.ui.status.setText( "<html><head/><body><p><span style=\"color:#222;\">Simulator is Starting</span></p></body></html>" ) self.ui.start.setText("Restart Simulation")
def play_file(filename, existing): if not os.path.exists(filename): logger.error("File does not exists") return with Simulator(start=not existing, autoquit=False, fixed_time_step=False) as simulator: simulator.set_paused(True) simulator.remove_all_vehicles() simulator.start_playback(filename)
def start_clicked(self): self.ui.start.setEnabled(False) self.ui.fixed.setEnabled(False) if self.simulator: self.update_simulator() else: self.simulator = Simulator(fixed_time_step=self.ui.fixed.isChecked()) threading.Thread(target=self.start_simulator, name="Start simulator Thread").start() self.ui.status.setText( "<html><head/><body><p><span style=\"color:#222;\">Simulator is Starting</span></p></body></html>") self.ui.start.setText("Restart Simulation")
def play_replay(resultid, existing, startpos): seconds = None if startpos: try: seconds = int(startpos) except ValueError: minutes, seconds = [int(a) for a in startpos.split(':')] seconds += minutes * 60 if not os.path.exists('local_replays'): os.makedirs('local_replays') filename = os.path.join('local_replays', 'replay_%d.bin' % resultid) if not os.path.exists(filename): network.download_replay(resultid, filename) with Simulator(start=not existing, autoquit=False, fixed_time_step=False) as simulator: simulator.set_paused(True) simulator.remove_all_vehicles() simulator.start_playback(filename) if seconds: simulator.seek_and_pause_replay(seconds) simulator.set_replay_paused(False)
from lib.preprocessing import Stats from lib.simulation import Simulator if __name__ == "__main__": league = Stats("bl3", "2020") league.create() simulator = Simulator(league) simulator.run(5) simulator.to_json()
class ControllerMainWindow(QtGui.QMainWindow): def __init__(self, parent=None): super(ControllerMainWindow, self).__init__(parent) self.ui = Ui_MainWindow() self.ui.setupUi(self) self.setup_configurations() self.assign_widgets() self.simulator = None self.ui.stop.setEnabled(False) self.timer = QTimer(self) self.timer.timeout.connect(self.update) self.timer.start(1000) self.show() desktop = QtGui.QDesktopWidget().availableGeometry() y = self.y() x = (desktop.width() - 1280) / 2 - self.width() - 50 self.move(x, y) def setup_configurations(self): for i, config in enumerate(configurations): self.ui.configuration.insertItem(i, config[0]) def assign_widgets(self): self.ui.start.clicked.connect(self.start_clicked) self.ui.stop.clicked.connect(self.stop_clicked) def on_about_to_quit(self): if self.simulator: self.simulator.close() def stop_clicked(self): self.ui.stop.setEnabled(False) if self.simulator: self.simulator.close() self.ui.fixed.setEnabled(True) self.simulator = None self.ui.start.setText("Start Simulation") def start_clicked(self): self.ui.start.setEnabled(False) self.ui.fixed.setEnabled(False) if self.simulator: self.update_simulator() else: self.simulator = Simulator( fixed_time_step=self.ui.fixed.isChecked()) threading.Thread(target=self.start_simulator, name="Start simulator Thread").start() self.ui.status.setText( "<html><head/><body><p><span style=\"color:#222;\">Simulator is Starting</span></p></body></html>" ) self.ui.start.setText("Restart Simulation") def start_simulator(self): self.simulator.start_and_connect() self.update_simulator() def update_simulator(self): base_config = configurations[self.ui.configuration.currentIndex()][1] throughput = self.ui.throughput.value() config = configs.througput(base_config, throughput=throughput) logger.info("Max Waits: %s", [sp['max_wait'] for sp in config['spawners']]) logger.info("Min Waits: %s", [sp['min_wait'] for sp in config['spawners']]) logger.info('Pausing the simulation') self.simulator.set_paused(True) logger.info('Removing all vehicles') self.simulator.remove_all_vehicles() logger.info('Resetting the spawners') self.simulator.reset_all_spawners() logger.info('Configuring the spawners') for spawner_conf in config['spawners']: self.simulator.configure_spawner(spawner_conf) logger.info('Starting the simulation') self.simulator.set_paused(False) logger.info('Resetting the stats') self.simulator.reset_stats() self.simulator.clear_queue() self.ui.start.setEnabled(True) self.ui.stop.setEnabled(True) def update(self): if self.simulator: try: stats = self.simulator.get_newest_stats() if stats: minutes, seconds = divmod(int(stats['time']), 60) stats['time'] = time(minute=minutes, second=seconds) self.ui.current_values.setText("""Time: {time:%M:%S} Current Throughput: From City: {throughputs[0]}, To City: {throughputs[1]} Incidents: {incidents} Vehicles Spawned: {spawned} Vehicles on Road: {onroad}""".format(**stats)) self.ui.status.setText( "<html><head/><body><p><span style=\"color:#00b548;\">Simulator is Running</span></p></body></html>" ) except SimulatorIsClosedException: self.ui.status.setText( "<html><head/><body><p><span style=\"color:#b50003;\">Simulator is not Running</span></p></body></html>" ) self.simulator.close() self.simulator = None self.ui.start.setText("Start Simulation") self.ui.stop.setEnabled(False) self.ui.fixed.setEnabled(True) return
class ControllerMainWindow(QtGui.QMainWindow): def __init__(self, parent=None): super(ControllerMainWindow, self).__init__(parent) self.ui = Ui_MainWindow() self.ui.setupUi(self) self.setup_configurations() self.assign_widgets() self.simulator = None self.ui.stop.setEnabled(False) self.timer = QTimer(self) self.timer.timeout.connect(self.update) self.timer.start(1000) self.show() desktop = QtGui.QDesktopWidget().availableGeometry() y = self.y() x = (desktop.width() - 1280) / 2 - self.width() - 50 self.move(x, y) def setup_configurations(self): for i, config in enumerate(configurations): self.ui.configuration.insertItem(i, config[0]) def assign_widgets(self): self.ui.start.clicked.connect(self.start_clicked) self.ui.stop.clicked.connect(self.stop_clicked) def on_about_to_quit(self): if self.simulator: self.simulator.close() def stop_clicked(self): self.ui.stop.setEnabled(False) if self.simulator: self.simulator.close() self.ui.fixed.setEnabled(True) self.simulator = None self.ui.start.setText("Start Simulation") def start_clicked(self): self.ui.start.setEnabled(False) self.ui.fixed.setEnabled(False) if self.simulator: self.update_simulator() else: self.simulator = Simulator(fixed_time_step=self.ui.fixed.isChecked()) threading.Thread(target=self.start_simulator, name="Start simulator Thread").start() self.ui.status.setText( "<html><head/><body><p><span style=\"color:#222;\">Simulator is Starting</span></p></body></html>") self.ui.start.setText("Restart Simulation") def start_simulator(self): self.simulator.start_and_connect() self.update_simulator() def update_simulator(self): base_config = configurations[self.ui.configuration.currentIndex()][1] throughput = self.ui.throughput.value() config = configs.througput(base_config, throughput=throughput) logger.info("Max Waits: %s", [sp['max_wait'] for sp in config['spawners']]) logger.info("Min Waits: %s", [sp['min_wait'] for sp in config['spawners']]) logger.info('Pausing the simulation') self.simulator.set_paused(True) logger.info('Removing all vehicles') self.simulator.remove_all_vehicles() logger.info('Resetting the spawners') self.simulator.reset_all_spawners() logger.info('Configuring the spawners') for spawner_conf in config['spawners']: self.simulator.configure_spawner(spawner_conf) logger.info('Starting the simulation') self.simulator.set_paused(False) logger.info('Resetting the stats') self.simulator.reset_stats() self.simulator.clear_queue() self.ui.start.setEnabled(True) self.ui.stop.setEnabled(True) def update(self): if self.simulator: try: stats = self.simulator.get_newest_stats() if stats: minutes, seconds = divmod(int(stats['time']), 60) stats['time'] = time(minute=minutes, second=seconds) self.ui.current_values.setText( """Time: {time:%M:%S} Current Throughput: From City: {throughputs[0]}, To City: {throughputs[1]} Incidents: {incidents} Vehicles Spawned: {spawned} Vehicles on Road: {onroad}""".format(**stats)) self.ui.status.setText( "<html><head/><body><p><span style=\"color:#00b548;\">Simulator is Running</span></p></body></html>") except SimulatorIsClosedException: self.ui.status.setText( "<html><head/><body><p><span style=\"color:#b50003;\">Simulator is not Running</span></p></body></html>") self.simulator.close() self.simulator = None self.ui.start.setText("Start Simulation") self.ui.stop.setEnabled(False) self.ui.fixed.setEnabled(True) return
def run_locally(existing, config_name, throughput, short): config_name = config_name.upper() base_config = getattr(configs, config_name) config = configs.througput(base_config, throughput=throughput) if short: config['warmup_time'] = 30 config['run_time'] = 30 with Simulator(start=not existing) as simulator: logger.info("Max Waits: %s", [sp['max_wait'] for sp in config['spawners']]) logger.info("Min Waits: %s", [sp['min_wait'] for sp in config['spawners']]) logger.info('Pausing the simulation') simulator.set_paused(True) logger.info('Removing all vehicles') simulator.remove_all_vehicles() logger.info('Resetting the spawners') simulator.reset_all_spawners() logger.info('Configuring the spawners') for spawner_conf in config['spawners']: simulator.configure_spawner(spawner_conf) logger.info("Starting the recording") try: os.mkdir('recordings') except WindowsError: pass replayname = time.strftime( 'recordings/recording_%Y.%m.%d_%H.%M.%S.bin') simulator.start_recording(replayname) logger.info('Starting the simulation') simulator.set_paused(False) logger.info('Resetting the stats') simulator.reset_stats() logger.info('Warming up the simulation') time_start = time.time() simulator.clear_queue() print '' while True: stats = simulator.receive_stats() logger.debug("(Warmup) Got stats: %s", stats) if time.time() - time_start < 2.0: # Ensure we wait at least 2 seconds, in case of old data continue if stats['time'] >= config['warmup_time']: break print(CURSOR_UP_ONE + ERASE_LINE + CURSOR_UP_ONE) print ' '.join( ['%s: %s' % (key, value) for key, value in stats.items()]) logger.info("Warmup complete!") timeline = [] log = [] print '' max_time = config['run_time'] + config['warmup_time'] last_status = -100.0 while True: stats = simulator.receive_stats() timeline.append(stats) logger.debug("Got stats: %s", stats) for entry in simulator.get_log_entries(): log.append(entry) logger.info("Got log entry") logger.debug("Got log entry: %s", entry) current_time = stats['time'] if current_time >= max_time: break percent_complete = (current_time / max_time) * 100.0 print(CURSOR_UP_ONE + ERASE_LINE + CURSOR_UP_ONE) print( ' '.join( ['%s: %s' % (key, value) for key, value in stats.items()]) + " %.1f %%" % percent_complete) logger.info("Stopping Recording") simulator.stop_recording() logger.info("Completed run") incidents = timeline[-1]['incidents'] - timeline[0]['incidents'] throughputs = [d['throughputs'][1] for d in timeline] avg_throughput = sum(throughputs) / len(throughputs) logger.info("Avg Throughput: %.2f" % avg_throughput) logger.info("Incidents: %d" % incidents)
def engine_record(replayname): with Simulator(autoquit=False, fixed_time_step=True, use_engine=True) as simulator: simulator.start_recording(replayname)
def record_movie(existing, matinee, camera, vehicle, camera_name, follow, resultid, startpos, record, followcam, speed, offset_y, offset_z, look_distance, look_offset_z, look_offset_y, rev, endpos, fov, show_arrows, behaviors, start_dist, fsmooth): # Since - looks like a parameter, we replace m by -, this way m can be used instead of # - at the command line. offset_y = offset_y.replace('m', '-') if offset_y else None offset_z = offset_z.replace('m', '-') if offset_z else None look_distance = look_distance.replace('m', '-') if look_distance else None look_offset_z = look_offset_z.replace('m', '-') if look_offset_z else None look_offset_y = look_offset_y.replace('m', '-') if look_offset_y else None behaviors = behaviors.split(',') if behaviors else [] behaviors = [a.strip() for a in behaviors] if not os.path.exists('local_replays'): os.makedirs('local_replays') minutes = 0 try: seconds = float(startpos) except ValueError: minutes, seconds = [float(a) for a in startpos.split(':')] total_seconds = seconds + minutes * 60 end_minutes = 0 try: end_seconds = int(endpos) except ValueError: end_minutes, end_seconds = [int(a) for a in endpos.split(':')] end_total_seconds = end_seconds + end_minutes * 60 try: resultid = int(resultid) filename = os.path.join('local_replays', 'replay_%d.bin' % resultid) if not os.path.exists(filename): network.download_replay(resultid, filename) except ValueError: filename = resultid resultid = os.path.split(filename)[-1] print filename moviename = "%s_%02d%02d" % (resultid, minutes, seconds) if matinee: moviename += "_mat_%s" % matinee if camera: moviename += "_cam_%s" % camera if vehicle: moviename += "_veh_%s_%s" % (vehicle, camera_name) if followcam: moviename += "_followcam_%s_%s_%s_%s" % (speed, offset_z, offset_y, fov) if look_distance: moviename += "_%s_%s_%s" % (look_distance, look_offset_z, look_offset_y) if rev: moviename += "_rev" if follow: moviename += "_follow_%s" % follow with Simulator(start=not existing, autoquit=True, fixed_time_step=True, dumpmovie=record, moviename=moviename) as simulator: if not record: simulator.execute_command('r.setres 1920x1080') # First we remove all existing vehicles simulator.set_paused(True) simulator.remove_all_vehicles() simulator.set_arrows_visible(show_arrows, behaviors) simulator.start_playback(filename) if total_seconds > 0: simulator.seek_and_pause_replay(total_seconds) simulator.set_replay_paused(False) if matinee: simulator.start_matinee('Matinee' + matinee) if camera: simulator.select_camera('Camera' + camera) if vehicle: simulator.select_vehicle_camera(int(vehicle), camera_name) if follow: simulator.camera_look_at_vehicle(int(follow)) if followcam: simulator.followcam( speed=float(speed), offset_z=float(offset_z), offset_y=float(offset_y), look_distance=float(look_distance) if look_distance else 0.0, rev=rev, look_offset_y=float(look_offset_y) if look_offset_y else 0.0, look_offset_z=float(look_offset_z) if look_offset_z else 0.0, fov=float(fov), start_distance=float(start_dist), fsmooth=float(fsmooth)) print('') while True: stats = simulator.receive_stats() total_seconds = stats['time'] minutes, seconds = divmod(total_seconds, 60) print(CURSOR_UP_ONE + ERASE_LINE + CURSOR_UP_ONE) print('%02d:%02d / %02d:%02d' % (minutes, seconds, end_minutes, end_seconds)) if total_seconds >= end_total_seconds: break