class TestSimuation(TestCase): def setUp(self): self.simulation = Simulation("test.json", connection_timeout=0, scan_timeout=0) self.connection = self.simulation.connection() @timeout(0.1) def test_connection_keeps_building_packets(self): """Random packets are built for the network topology approximation.""" packets = 10000 while packets > 0: packet = self.connection.next() self.assertIsNotNone(packet) packets -= 1 def test_discovery_ip_returns_nothing_for_missing_node(self): """A simulated scan returns nothing.""" self.assertEqual(self.simulation.discovery_ip('10.1.3.8'), {}) def test_discovery_ip_for_missing_configuration(self): """A simulated scan for a host having no services returns nothing.""" self.assertEqual(self.simulation.discovery_ip('10.1.3.3'), {"scanned" : "false"}) def test_discovery_ip_returns_correct_configuration(self): """A simulated scan returns correct running services.""" self.assertEqual(self.simulation.discovery_ip('10.1.3.1'), {"test1" : "test1"}) self.assertEqual(self.simulation.discovery_ip('10.1.3.2'), {"test2" : "test2"})
def init_simulation(): if request.method == 'POST': global sim if sim == None: sim = Simulation(configDB, configDB, configDB) sim.init_sim(datetime.now()) return "success", 201 else: return "conflict", 409 return "HTTP-Method not supported", 404
class Bootstrap(object): def __init__(self, env): self.env = env # create simulation enviromment img = np.zeros((900, 800, 3), dtype=np.uint8) self.sim = Simulation(self.env, img) def processSimulation(self): # initialize Sioux Falls network siouxfalls = SiouxFalls(0.0025) # create Sioux Fall network by enumerating across all links for linkid, t0 in enumerate(siouxfalls.t0): # calculate length of link with sqrt((x1 - x2)^2 + (y1 - y2)^2) length = np.sqrt( np.power(siouxfalls.x1[linkid] - siouxfalls.x2[linkid], 2) + np.power(siouxfalls.y1[linkid] - siouxfalls.y2[linkid], 2)) / 600. mu = siouxfalls.mu[linkid] # assign nodeID to each link if check pass in node list for i, node in enumerate(siouxfalls.nodes): if linkid+1 in node: nodeID = i # assign turn ratio to each link turns = {} for j, turn in enumerate(siouxfalls.turns[linkid]): turns[j + 1] = turn # assign exit probability from last item in turn list ([-1]) turns['exit'] = turns.pop(list(turns.keys())[-1]) # generate coordinates of each link (for visualization) pt1 = (np.float32(siouxfalls.x1[linkid] / 600.), np.float32(siouxfalls.y1[linkid] / 600.)) pt2 = (np.float32(siouxfalls.x2[linkid] / 600.), np.float32(siouxfalls.y2[linkid] / 600.)) c = (pt1, pt2) # draw link on map self.sim.networkLines.append(c) # add link to sim.network self.sim.network.addLink(linkID=linkid+1, turns=turns, type='link', length=length, t0=t0, MU=mu, nodeID=nodeID, coordinates=c) # initialize car generation self.env.process(self.sim.source( 10, LAMBDA=siouxfalls.flambda[linkid], linkid=linkid+1)) yield self.env.timeout(1)
def entry_point(path): """ Entry point for application """ configuration = read_configuration(path) print("Configuration readed succesfully.") simulation = Simulation(configuration) print("Running simulation.") GUI(simulation).run() exit()
def entry_point(path): """ Entry point for application """ configuration = read_configuration(path) print("Configuration readed succesfully.") car_generator = CarProperGenerator lights_manager = LightsManager optimizer = Optimiser(configuration, car_generator, lights_manager) print("Starting optimization.") report_string, times = optimizer.optimise() print("") print(report_string) print("New times ", times) pygame.init() screen = pygame.display.set_mode(WINDOW_SIZE) prev_update_time = clock() simulation = Simulation(car_generator, lights_manager, configuration) # type: Simulation simulation.set_phases_durations(times) game_map = simulation.map lights_painter = simulation.map.get_lights_painter() game_map.prepare(screen) done = False while not done: if pygame.key.get_pressed()[pygame.K_ESCAPE]: done = True for event in pygame.event.get(): if event.type == pygame.QUIT: done = True curr_time = clock() if curr_time - prev_update_time > 0.2: prev_update_time = curr_time simulation.update() game_map.draw(screen, simulation.points) lights_painter.draw(screen, simulation.get_lights()) pygame.time.Clock().tick(60) pygame.display.flip() sys.exit()
def setupSimulation(model_data): needTypes = script_loader.readObjectsFromScript(model_data["need_types"], "need_types") needTypesDict = {} for needType in needTypes: needTypesDict[needType.getName()] = needType diseaseTypes = script_loader.readObjectsFromScript(model_data["disease_types"], "disease_types") theGrid = grid_generator.generate(model_data) persons = person_generator.generate(model_data, needTypesDict, diseaseTypes) for needType in needTypes: needType.initialize(needTypesDict, persons, theGrid) logging.write("output", needType.getName()) for diseaseType in diseaseTypes: diseaseType.initialize(needTypesDict) logging.registerCategory("disease." + diseaseType.getName()) return Simulation(persons, theGrid, diseaseTypes, mt_generator.generate(theGrid, 10, 5))
def create_and_run_simulation(name, city_name, scale, city_list, interventions): change_task_status(name, TaskStatus.STARTED, {'started_at': int(time.time())}) Params.load_from( os.path.join(os.path.dirname(os.path.dirname(__file__)), 'simulation', 'params.json')) population_loader = PopulationLoader() world = population_loader.get_world(city_name=city_name, scale=scale) sim = Simulation(world, 0, interventions, False, outdir=os.path.join(TASKS_DIR, name)) sim.infect_random_set(INITIAL_INFECTED_NUM, "N/A", None) sim.run_simulation(DAYS, name, datas_to_plot=[]) change_task_status(name, TaskStatus.FINISHED, {'finished_at': int(time.time())})
def setUp(self): self.simulation = Simulation("test.json", connection_timeout=0, scan_timeout=0) self.connection = self.simulation.connection()
def init(): global boatData, autopilot, simulation print("Retrieving data from rudder service on " + os.getenv("BACKEND")) connected = False while not connected: # try to get boat data from backend try: url = os.getenv("BACKEND") + "/boat/v1/" headers = {'Authorization': 'Bearer ' + os.getenv("TOKEN")} r = requests.get(url, headers=headers) r.raise_for_status() # save data locally boatData = r.json() connected = True except requests.HTTPError: raise Exception("Access error!") except requests.ConnectionError: print("Couldn't connect, retrying!") connected = False time.sleep(1) if not boatData: raise Exception("No boat data!") # initialization message print("\n" + "╔═╗┌─┐┌─┐┌┬┐┬┌─┐╔═╗┌─┐┬┬ \n" + "║ │ │└─┐│││││ ╚═╗├─┤││ \n" + "╚═╝└─┘└─┘┴ ┴┴└─┘╚═╝┴ ┴┴┴─┘") print(f" | {boatData['BoatEmblem']}") print(f" | {boatData['Series']}, {boatData['Make']}") print(f" | {len(boatData['Motors'])} Motor(s)") print(f" | {len(boatData['Sensors'])} Sensor(s)") print() # load hardware for motor in boatData['Motors']: motorTypes.__setitem__(motor['Type'], motor['Name']) motors.__setitem__( motor['Name'], ServoMotor( motor['Name'], pca.channels[int(motor['Channel']) - 1] if SIMULATION is False else None, float(motor['Min']), float(motor['Max']), float(motor['Default']), motor['Type'])) # load sensors for sensor in boatData['Sensors']: sensorTypes.__setitem__(sensor['Type'], sensor['Name']) if sensor['Type'] == "gps": sensors.__setitem__( sensor['Name'], GpsSensor(sensor['Name'], os.getenv("UBLOX_TOKEN"), sensor['Channel'], SIMULATION)) if sensor['Type'] == "bandwidth": sensors.__setitem__(sensor['Name'], Bandwidth(sensor['Name'])) if sensor['Type'] == "ip": sensors.__setitem__(sensor['Name'], IP(sensor['Name'])) # if sensor['Type'] == "imu": # sensors.__setitem__(sensor['Name'], IMU(sensor['Name'])) if sensor['Type'] == "bno": sensors.__setitem__(sensor['Name'], BNO(sensor['Name'], SIMULATION)) if sensor['Type'] == "wind": sensors.__setitem__( sensor['Name'], DigitalWindSensor(sensor['Name'], os.getenv("OPENWEATHERMAP_TOKEN"))) if sensor['Type'] == "shore": sensors.__setitem__( sensor['Name'], DigitalShoreSensor(sensor['Name'], os.getenv("ONWATER_TOKEN"))) # load autopilot autopilot = AutoPilot( 0, motors.__getitem__(motorTypes.__getitem__('rudder')), motors.__getitem__(motorTypes.__getitem__('sail')), motors.__getitem__(motorTypes.__getitem__('engine')), sensors.__getitem__(sensorTypes.__getitem__('gps')), sensors.__getitem__(sensorTypes.__getitem__('bno')), sensors.__getitem__(sensorTypes.__getitem__('wind')), sensors.__getitem__(sensorTypes.__getitem__('shore'))) if SIMULATION: # start simulation simulation = Simulation(motors, motorTypes, sensors, sensorTypes) connect_socket() try: # start periodic tasks that the boat has to execute for fetching sensor data, # executing the autopilot and simulation and transmitting telemetry # asyncio.run(main_loops()) loop = asyncio.get_event_loop() loop.create_task(internet_loop()) loop.create_task(meta_loop()) loop.create_task(autopilot_loop()) loop.create_task(digital_shore_loop()) loop.create_task(shore_api_loop()) loop.create_task(digital_wind_loop()) loop.create_task(simulation_loop()) loop.run_forever() except asyncio.CancelledError: pass except KeyboardInterrupt: if SIMULATION is False: pca.deinit() quit()
i2c_bus = busio.I2C(SCL, SDA) pca = pca_driver.PCA9685(i2c_bus) pca.frequency = 24 # boat data boatData = {} sensors = {} sensorTypes = {} motors = {} motorTypes = {} # autopilot autopilot: AutoPilot # simulation simulation = Simulation({}, {}, {}, {}) async def internet_check(): """function to check internet connection and register outages early""" try: t = requests.get('https://rudder.cosmicsail.online', timeout=3).text except requests.exceptions.Timeout: # print("timeout!") reset_all_motors() return False except requests.exceptions.ConnectionError: print("connection error!") reset_all_motors() return False finally:
def entrypoint(): configuration = read_configuration() simulation = Simulation(configuration) GUI(simulation).run() exit()
from simulation.simulation import Simulation from display.screen import Screen from brain.space import Volume import numpy as np screen_size = np.array([600, 600]) BACKGROUND_COLOR = (154, 154, 158) RECORD_SETTINGS = ("gallery/imgs", "gallery/videos", "result", 24) space = Volume(shape='rect', location=np.array([0, 0, 0]), size=screen_size) sim = Simulation( space, Screen(screen_size, BACKGROUND_COLOR, "GENERIC SIMULATION NAME", space, RECORD_SETTINGS)) for i in range(1): sim.create_random_agent(14) for i in range(300): sim.environment.generate_new_food() sim.run(-1, 1, 0.5)
import pygame # from experiments.aggregation.config import config # from experiments.covid.config import config from experiments.flocking.config import config from simulation.simulation import Simulation """ Code for multi-agent simulation in PyGame with/without physical objects in the environment """ if __name__ == "__main__": pygame.init() sim = Simulation(num_agents=config["base"]["n_agents"], screen_size=(config["screen"]["width"], config["screen"]["height"]), swarm_type=config["base"]["swarm_type"], iterations=config["screen"]["frames"]) sim.run()
import tkinter as tk from client.gui import GUI from simulation.simulation import Simulation import cProfile if __name__ == '__main__': sim = Simulation() ui = GUI(sim) ui.title("Interactive Multi-Agents Flocking Simulation") pr = cProfile.Profile() pr.enable() ui.mainloop() pr.disable() pr.dump_stats('stats.cprofile')
import argparse import json from os import listdir from simulation.simulation import Simulation parser = argparse.ArgumentParser() parser.add_argument('--config') parser.add_argument('--folder') args = parser.parse_args() if (args.config): with open(args.config) as f: configuration = json.load(f) with open(args.config + '.out', 'w+') as fout: sim = Simulation(configuration, fout) sim.run() elif (args.folder): for conf_file in listdir(args.folder): if (conf_file.endswith('json')): with open(args.folder + '/' + conf_file) as f: configuration = json.load(f) with open(args.folder + '/' + conf_file + '.out', 'w+') as fout: sim = Simulation(configuration, fout) sim.run()
def run4(n): simulation = Simulation(n) simulation.start4()
def run(n): simulation = Simulation(n) solutions = simulation.start2() print("------------------") print("Solutions") print(len(solutions.get_solutions()))
from simulation.simulation import Simulation import pygame #from experiments.flocking import parameters as p # from experiments.aggregation import parameters as p from experiments.covid import parameters as p """ Code for multi-agent simulation in PyGame with/without physical objects in the environment """ if __name__ == "__main__": pygame.init() sim = Simulation(num_agents=p.N_AGENTS, screen_size=p.SCREEN, swarm_type=p.SWARM, iterations=p.FRAMES) sim.run()
tree_line2 = anytree.Node(name='tree_line2', parent=inv4, \ device=RC_tree(RC_line(r*L5, c*L5, sections), RC_line(r*L51, c*L51, sections), \ RC_line(r*L52, c*L52, sections))) inv5 = anytree.Node(name='inv5', parent=tree_line2, device=Inverter()) inv6 = anytree.Node(name='inv6', parent=tree_line2, device=Inverter()) line6 = anytree.Node(name='line6', parent=inv5, device=RC_line(r*L6, c*L6, sections)) line7 = anytree.Node(name='line7', parent=inv6, device=RC_line(r*L7, c*L7, sections)) ffd3 = anytree.Node(name='ffd4', parent=line6, device=FFD()) ffd4 = anytree.Node(name='ffd5', parent=line7, device=FFD()) ################################################################ ### Estimacion, simulacion y comparacion de los resultados ################################################################ # Creamos una simulacion y mostramos los resultados sim = Simulation(ffd1, "simulation/circuit.cir", "simulation/simulation.txt", vdd, True) sim.build_simulation(rising_edge) [t50_vector, slew_vector] = sim.simulate_delays() #print("************* Delays **************") #print(t50_vector) #print("************* Slew **************") #print(slew_vector) # Creamos la instancia del circuito y calculamos el delay circuit = circuit(circuit_tree) delay, simulated_delay = circuit.find_delay(ffd3, rising_edge, True) print(f"El delay total del circuito es: \n" \ f"Estimado: {delay} \n" \ f"Simulado: {simulated_delay} \n")
def __init__(self, env): self.env = env # create simulation enviromment img = np.zeros((900, 800, 3), dtype=np.uint8) self.sim = Simulation(self.env, img)
if __name__ == "__main__": parser = setup_argparser() args = parser.parse_args() setup_loggers(args.verbose) if os.getuid() != 0: logger.error("Must be run as root.") exit(1) if args.simulation is not None: from simulation.simulation import Simulation args.interface = "virtual_interface" bind_simulation(Simulation(args.simulation)) global processes processes = [] set_ports(args.type) services(args.benchmark, args.interface, args.filter, args.batch_threads) setup_dissemination(args) signal.signal(signal.SIGINT, signal_handler) for process in processes: process.start() for process in processes: process.join()
def main(): ################################# # initialize discrete event env # ################################# env = simpy.Environment() # use instant simulation # env = simpy.rt.RealtimeEnvironment(factor=1.) # use real time simulation # initialize Sioux Falls network siouxfalls = SiouxFalls(0.0025) # create simulation enviromment img = np.zeros((900, 800, 3), dtype=np.uint8) sim = Simulation(env, img) # create Sioux Fall network by enumerating across all links for linkid, t0 in enumerate(siouxfalls.t0): # calculate length of link with sqrt((x1 - x2)^2 + (y1 - y2)^2) length = np.sqrt( np.power(siouxfalls.x1[linkid] - siouxfalls.x2[linkid], 2) + np.power(siouxfalls.y1[linkid] - siouxfalls.y2[linkid], 2)) / 600. mu = siouxfalls.mu[linkid] # assign nodeID to each link if check pass in node list for i, node in enumerate(siouxfalls.nodes): if linkid + 1 in node: nodeID = i # assign turn ratio to each link turns = {} for j, turn in enumerate(siouxfalls.turns[linkid]): turns[j + 1] = turn # assign exit probability from last item in turn list ([-1]) turns['exit'] = turns.pop(list(turns.keys())[-1]) # generate coordinates of each link (for visualization) pt1 = (np.float32(siouxfalls.x1[linkid] / 600.), np.float32(siouxfalls.y1[linkid] / 600.)) pt2 = (np.float32(siouxfalls.x2[linkid] / 600.), np.float32(siouxfalls.y2[linkid] / 600.)) c = (pt1, pt2) # draw link on map sim.networkLines.append(c) # add link to sim.network sim.network.addLink(linkID=linkid + 1, turns=turns, type='link', length=length, t0=t0, MU=mu, nodeID=nodeID, coordinates=c) # initialize car generation env.process( sim.source(10, LAMBDA=siouxfalls.flambda[linkid], linkid=linkid + 1)) # draw initial network for i in sim.networkLines: cv2.line(sim.img, i[0], i[1], (255, 255, 255), 3) for linkid in sim.network.links: loc = (0.25 * np.asarray(sim.network.links[linkid]['coordinates'][1]) + 0.75 * np.asarray(sim.network.links[linkid]['coordinates'][0])) cv2.putText(sim.img, str(linkid), tuple(loc), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 255, 255)) name = 'Sioux Falls Network' cv2.imshow(name, sim.img) # start visualization update process env.process(sim.visualization(frequency=0.2, name=name)) # wait for keypress to start simulation print('press space to start') k = cv2.waitKey(0) if k == 27: sys.exit() # run simulation env.run() ###################################### # simulation statistics and graphing # ###################################### df = pd.DataFrame( sorted(sim.data, key=lambda x: x[3]), columns=['carID', 'link', 'event', 'time', 'queue', 't_queue']) print(df) # cars statistics totalTravelTime = (df[['carID', 'time']].groupby(['carID']).max() - df[['carID', 'time']].groupby(['carID']).min()) totalTravelTime.columns = ['totalTravelTime'] totalSegments = df.loc[df['event'] == 'arrival'][['carID', 'link']] totalSegments = totalSegments.groupby(['carID']).count() totalSegments.columns = ['totalSegments'] meanWaitTime = df.loc[df['event'] == 'departure'][['carID', 't_queue']] meanWaitTime = meanWaitTime.groupby(['carID']).mean() meanWaitTime.columns = ['meanWaitTime'] carStatistics = pd.concat([totalTravelTime, totalSegments, meanWaitTime], axis=1) # links statistics stats.meanQueueLength(plt, df) plt.figure(2) for link in sim.network.links.keys(): df2 = df.loc[(df['link'] == link) & (df['event'] != 'entry')] if df2.empty is False and df2['t_queue'].sum() > 0.: plt.plot(df2[['time']], df2[['queue']], label='link %s' % link) plt.title('Queueing Simulation') plt.ylabel('queue length') plt.xlabel('time (s)') plt.legend() plt.show() print('Press any key to exit') cv2.waitKey(0)
from config.parameter_setting import MPCConfig from steer_vehicle_model.kinematics_model import Kinematics_Model from controller.model_predictive_controller import MPCController from simulation.simulation import Simulation from path_design.create_path import ReferencePath if __name__ == '__main__': Simulation(Kinematics_Model, MPCController, ReferencePath, MPCConfig)
root = Tk() root.geometry(str(Object.CANVAS_WIDTH) + "x" + str(Object.CANVAS_HEIGHT)) center_x, center_y = Object.CANVAS_WIDTH / 2, Object.CANVAS_HEIGHT / 2 center_part = ObjectDimension(center_x, center_y, 50, 50) motor_radius = 15 margin_delta = 30 motor_left = ObjectDimension(center_x - margin_delta - motor_radius / 2, center_y - motor_radius, motor_radius * 2, motor_radius * 2) motor_right = ObjectDimension(center_x + margin_delta - motor_radius, center_y - motor_radius, motor_radius * 2, motor_radius * 2) corner_radius = 15 corner_left = ObjectDimension(margin_delta, margin_delta, corner_radius * 2, corner_radius * 2) corner_right = ObjectDimension( Object.CANVAS_WIDTH - margin_delta - corner_radius * 2, margin_delta, corner_radius * 2, corner_radius * 2) simulation = Simulation(motor_left, motor_right, corner_left, corner_right) app = Window(root, simulation) root.after(16, app.frame) root.mainloop()
def run3(n): simulation = Simulation(n) simulation.start3()