Exemplo n.º 1
0
    def __init__(self, visualisation, small=None, map_name=None, sensors=None):
        if sensors is None:
            sensors = [Sensor(0.12, 0.08, 2, math.radians(30), math.radians(45)),
                       Sensor(0.14, 0.04, 2, math.radians(30), math.radians(15)),
                       Sensor(0.14, -0.04, 2, math.radians(30), math.radians(-15)),
                       Sensor(0.12, -0.08, 2, math.radians(30), math.radians(-45))]  # ,
        # Sensor(-0.15, 0, 2, math.radians(30), math.radians(-180))]

        # FIXME Delete these if program still runs correctly.
        #initial_action = [0.2, 0]
        #self.actions = [(0.2, -2), (0.2, 0), (0.2, 2)]
        #self.action_dimension = 2

        self.state_size = len(sensors)

        self.visualisation = visualisation

        x = 1
        y = 1
        heading = 0
        if map_name is None and small is None:
            self.environment = simulator.Simulator()
        elif map_name is None:
            self.environment = simulator.Simulator(small=small)
        elif small is None:
            self.environment = simulator.Simulator(map_name=map_name)
        else:
            self.environment = simulator.Simulator(small=small, map_name=map_name)

        self.robot = Robot(x, y, heading, sensors, leds=[False, False])
        self.wheel_distance = WHEELBASE
        self.size = 0.15
Exemplo n.º 2
0
def S1_run(
        jules_nc='jules/output/sensitivity_runs/crp_g_77_6.8535_0.17727_0.000573.3_hourly.nc',
        fname='s1_sim_dict.p',
        year=2012,
        month=1,
        days=364,
        lai_coeff=0.1,
        s=0.015):
    simulator = sim.Simulator(jules_nc=jules_nc,
                              year=year,
                              month=month,
                              days=days)
    S1_simulator = sim.S1_simulator(lai_coef=lai_coeff,
                                    s=s,
                                    omega=0.1,
                                    jules_nc=jules_nc,
                                    year=year,
                                    month=month,
                                    days=days)
    sim_dict = {}
    sim_dict['nc_file'] = jules_nc
    sim_dict['S1_dates'] = S1_simulator.date_lst
    sim_dict['dates'] = simulator.date_lst
    sim_dict['lai'] = simulator.lai_lst
    sim_dict['can_height'] = simulator.canht_lst
    sim_dict['soil_m'] = simulator.soilm_lst
    for x in xrange(3):
        sim_dict[S1_simulator.backscatter_keys[x]] = \
            [10*np.log10(S1_simulator.SAR_list[s1c].__dict__['stot'][S1_simulator.backscatter_keys[x]])
             for s1c in xrange(len(S1_simulator.SAR_list))]

    f = open(fname, 'wb')
    pickle.dump(sim_dict, f)
    f.close()
    return 'simulator pickled'
Exemplo n.º 3
0
def plot_value_function(agent_class, run, i):
    ''' Plot the value functions for run i. '''
    plt.clf()
    agent = load(agent_class, run)
    state0 = simulator.Simulator().get_state()
    values, qval1, qval2 = [], [], []
    min_range = -SHIFT_VECTOR[i]
    max_range = SCALE_VECTOR[i]
    variables = []
    for j in range(VALUE_STEPS):
        var = max_range * (1. * j / VALUE_STEPS) + min_range
        state0[i] = var
        values.append(agent.value_function(state0))
        feat = agent.action_features[0](state0)
        qval1.append(agent.action_weights[0].dot(feat))
        qval2.append(agent.action_weights[1].dot(feat))
        variables.append(var)
    max_val = max(max(qval1), max(qval2), min(values))
    min_val = min(min(qval1), min(qval2), min(values))
    plt.plot(variables, values, '-b', label='$V(s)$')
    plt.plot(variables, qval1, '-r', label='$Q(s, a_1)$')
    plt.plot(variables, qval2, '-g', label='$Q(s, a_2)$')
    plt.axis([min_range, max_range, min_val, max_val])
    plt.legend(loc='lower right')
    plt.xlabel(str(i))
    plt.ylabel('$V$')
    plt.savefig('./runs/' + agent.name + '/value_functions/s' + str(i),
                bbox_inches='tight')
Exemplo n.º 4
0
def plot_x_dx(agent_class, run):
    ''' Plot the value function over x, dx. '''
    plt.clf()
    agent = load(agent_class, run)
    fig = plt.figure()
    state = simulator.Simulator().get_state()
    plot = fig.add_subplot(111, projection='3d')
    plot.set_xlabel('x')
    plot.set_ylabel('dx')
    plot.set_zlabel('Action-Value')
    xxrange = np.arange(0, 1000, 10.0)
    yyrange = np.arange(0, 200, 10.0)
    xgrid, ygrid = np.meshgrid(xxrange, yyrange)
    get_state = lambda x, dx: np.append(np.array([x, dx]), state[2:])
    function2 = lambda x, dx: agent.action_weights[0].dot(
        fourier_basis(get_state(x, dx)))
    function3 = lambda x, dx: agent.action_weights[1].dot(
        fourier_basis(get_state(x, dx)))
    functions = [function2, function3]
    colours = [[1, 0, 0]]
    for col, func in zip(colours, functions):
        zarray = np.array(
            [func(x, dx) for x, dx in zip(np.ravel(xgrid), np.ravel(ygrid))])
        zgrid = zarray.reshape(xgrid.shape)
        print col
        plot.plot_surface(xgrid, ygrid, zgrid, color=col)
    plt.savefig('./runs/' + agent.name + '/value_functions/xdx',
                bbox_inches='tight')
Exemplo n.º 5
0
def main():
    """The runnable program"""

    print("DustSucker2000 Simulator by Olle Frisberg")
    print("")

    print("This software aims to simulate how our new vacuum cleaner moves.")
    print("Input format:")
    print("Line 0: <Lx> <Ly> (The dimensions of the room")
    print(
        "Line 1: <wsymb> <x> <y> (The initial direction and coordinates of the DustSucker2000"
    )
    print("Line 2: <commands> (The commands to execute in serial)")
    print("Supported commands:")
    print("A: Move forward 1 meter")
    print("L: Turn left 90 degrees")
    print("R: Turn right 90 degrees")
    print("")

    # Parse the input
    ip = inputparser.InputParser()
    Lx, Ly, wsymb, x, y, commands = ip.getParsed()

    # Create the cleaner object
    vc = vacuumcleaner.VacuumCleaner(wsymb, x, y)

    # Uncomment this to show parsed input
    #print(Lx,Ly,vc.getAngle(),x,y,commands)

    sim = simulator.Simulator(Lx, Ly, vc)  # Create a simulator object
    sim.start(commands)  # Start simulation
    res = sim.getResult()  # Get simulation result

    print("Result: " + res)
Exemplo n.º 6
0
def create_db(size=DB_SIZE, townhall_level=4):
    # using the same main base for all simulations - no problem with 1 simulator
    game_board = board.GameBoard(
        generate_base.generate_base_by_level(townhall_level))
    sim = simulator.Simulator(game_board)

    # Create filepaths
    seed = random.randint(1, 10000)
    x_path = DATABASES + str(townhall_level) + "/X_" + str(
        size) + "_TH_LVL_" + str(townhall_level) + "_" + str(seed) + ".csv"
    y_path = DATABASES + str(townhall_level) + "/Y_" + str(
        size) + "_TH_LVL_" + str(townhall_level) + "_" + str(seed) + ".csv"

    # Write Headers
    with open(x_path, "a+") as f_army:
        with open(y_path, "a+") as f_res:
            # write headers
            f_res.write(game_board.get_titles() + ",total" + "\n")
            f_army.write(
                generate_army.generate_army_by_level(townhall_level)[1] + "\n")

    # Run "size" simulations
    for i in range(size):
        print("Current Row:\t", i)
        army, titles = generate_army.generate_army_by_level(townhall_level)
        stats = sim.run(army, save_end_state=True, debug=False)

        # Open and write in files for every iteration. Append.
        with open(x_path, "a") as f_army:
            with open(y_path, "a") as f_res:
                f_army.write(get_writable_army(army) + "\n")
                f_res.write(stats["end_state"] + "\n")

    print("Finished DB of size:\t", size)
Exemplo n.º 7
0
    def test_multiple_moves(self):
        sim = api.Simulator()
        distance = 180
        angle = 70
        self.__turtle.left(angle)
        self.__turtle.forward(distance)
        self.__turtle.backward(distance / 2)
        self.__turtle.right(angle * 2)

        sim.left(angle)
        sim.forward(distance)
        sim.backward(int(distance / 2))
        sim.right(angle * 2)

        self.compare_pos(sim.position(), self.__turtle.position())

        self.__turtle.backward(distance * 3)
        sim.backward(distance * 3)

        self.compare_pos(sim.position(), self.__turtle.position())

        self.__turtle.right(340)
        self.__turtle.forward(distance)

        sim.right(340)
        sim.forward(distance)

        self.compare_pos(sim.position(), self.__turtle.position())
Exemplo n.º 8
0
def main():
    import timeit
    for event_date in event_dates:
        print event_date
        event_datetime_obj = datetime.strptime(event_date + " " + event_start_time, '%Y-%m-%d %H:%M:%S')
        symbol = mkdt_utils.getSymbol(instrument_root, event_datetime_obj)
        df = mkdt_utils.getMarketDataFrameForTradingDate(event_date, instrument_root, symbol, "100ms")
        if isinstance(df.head(1).time[0], basestring):
            df.time = df.time.apply(mkdt_utils.str_to_dt)
        df.set_index(df['time'], inplace=True)

	start_dt = datetime.strptime(event_date + " " + trading_start_time, '%Y-%m-%d %H:%M:%S')
        max_entry_dt = datetime.strptime(event_date + " " + max_entry_time, '%Y-%m-%d %H:%M:%S')
        stop_dt = datetime.strptime(event_date + " " + trading_stop_time, '%Y-%m-%d %H:%M:%S')

	dollar_value_per_price_level = 12.5  # specific to Euro
	Sim = simulator.Simulator(df)
	Strat = Strategy(df, start_dt, max_entry_dt, stop_dt, Sim, dollar_value_per_price_level, spike_5s_pred[event_date])
	Sim.initStrategy(Strat)
	log_df = Strat.start()

	dir_path = '/local/disk1/temp_eg/log_run/'
        filename = 'log_run_' + event_name + '_' + instrument_root + '_' + event_date.replace('-', '')
        store_filename = dir_path + filename + '.h5'
        store = pd.HDFStore(store_filename)
        store['log_df'] = log_df
        store.close()


	print "FINISHED"
Exemplo n.º 9
0
    def test_next_command(self):
        d = api.TimeDecorator(api.Simulator())
        start_pos = (0.0, 0.0, 15)

        self.assertEqual(d.position(), start_pos)
        d.forward(978)

        self.assertEqual(d.next, {'command': 'forward', 'value': 958})
        d.tick()
        self.assertEqual(d.next, {'command': 'forward', 'value': 938})

        d.forward(350)
        self.assertEqual(d.next, {'command': 'forward', 'value': 330})

        d.reset()
        self.assertEqual(d.next, {'command': None, 'value': 0})

        d.forward(600)
        self.assertEqual(d.next, {'command': 'forward', 'value': 580})

        d.backward(300)
        self.assertEqual(d.next, {'command': 'backward', 'value': 280})

        d.tick()
        self.assertEqual(d.next, {'command': 'backward', 'value': 260})
Exemplo n.º 10
0
 def test_method_not_implemented(self):
     d = api.TimeDecorator(api.Simulator())
     try:
         d.foo()
         self.fail("Exception not thrown")
     except AttributeError:
         pass
Exemplo n.º 11
0
 def trySimulator(self, numHonest, numByzantine, printer, eventTrace, logger):
     sim = None
     try:
         sim = simulator.Simulator(numHonest=numHonest, numByzantine=numByzantine, printer=printer, event_trace=eventTrace, logger=logger)
     except:
         print("Error creating simulator")
     return sim
Exemplo n.º 12
0
 def simulationSettings(self, enable=False, values=None):
     if enable:
         self.simulationEnabled = True
         self.simulator = simulator.Simulator(values, settings.getInterval())
     if not enable:
         self.simulator = None
         self.simulationEnabled = False
Exemplo n.º 13
0
def first():
  R = 1000
  ROUND = 50
  COUNT = 5
  NUMBER_OF_NODES = 20
  NUMBER_OF_SERVICES = 15
  START_NODE_COUNT = 16
  sweep = np.linspace(START_NODE_COUNT, NUMBER_OF_NODES, COUNT)
  auctionCost = np.zeros((2, COUNT))
  randomCost = np.zeros((2, COUNT))
  nearestCost = np.zeros((2, COUNT))
  for r in range(ROUND):
    print("@round: {}".format(r))
    state = generateState(r=R, numberOfNodes=NUMBER_OF_NODES, numberOfServices=NUMBER_OF_SERVICES)
    lastNodeCount = None
    for c, n in enumerate(sweep):
      print("\t@count: {}".format(c))
      for type in range(2):
        if type is 0:
          print("\t\twithout cloud")
        else:
          print("\t\twith cloud")
        sim = simulator.Simulator("", R, switches=state["switches"])
        if type is 1:
          sim.addCloud(numberOfResources=20, C=1000)
        for serviceIndex in range(NUMBER_OF_SERVICES):
          sim.addService(F=state['serviceF'][serviceIndex], R=state['serviceR'][serviceIndex], alpha=state['serviceAlpha'][serviceIndex], w=state['serviceW'][serviceIndex], center=state['servicePosition'][serviceIndex], sources=state['serviceSources'][serviceIndex], destinations=state['serviceDestinations'][serviceIndex])
        nodeCount = int(n)
        if lastNodeCount is None:
          print("\t\tNode Range: 0-{}".format(nodeCount))
        else:
          print("\t\tNode Range: {}-{}".format(lastNodeCount, nodeCount))
        for nodeIndex in range(nodeCount):
          sim.addNode(C=2000, U=state['nodeU'][nodeIndex], position=state['nodePosition'][nodeIndex])
        print("\t\tsimulation started")
        sim.run()
        auctionCost[type, c] += sim.totalCost() / NUMBER_OF_SERVICES / ROUND
        sim.run(random=True)
        randomCost[type, c] += sim.totalCost()/ NUMBER_OF_SERVICES / ROUND
        sim.run(nearest=True)
        nearestCost[type, c] += sim.totalCost() / NUMBER_OF_SERVICES / ROUND
        lastNodeCount = nodeCount
  output = {}
  output["nodes"] = sweep.tolist()
  output["average_costs"] = {}
  output["average_costs"]["auction"] = auctionCost[0,:].tolist()
  output["average_costs"]["auction_cloud"] = auctionCost[1,:].tolist()
  output["average_costs"]["nearest"] = nearestCost[0,:].tolist()
  with open('figure6_2.json', 'w') as outfile:
    json.dump(output, outfile)
  plt.clf()
  plt.plot(sweep, auctionCost[0,:], 'r+-', label="Auction Based")
  plt.plot(sweep, auctionCost[1,:], 'r*-', label="Auction Based (with Cloud)")
  plt.plot(sweep, nearestCost[0,:], 'g+-', label="Nearest Resource")
#  plt.plot(sweep, nearestCost[1,:], 'g*-', label="Nearest Resource (with Cloud)")
  plt.legend()
  plt.xlabel('# of Computation Nodes')
  plt.ylabel('Average Cost')
  plt.grid(True)
  plt.show()
Exemplo n.º 14
0
def main():
    """
    Create results files and run simulation with given params.

    Get simulation parameters from the command line;
    create summary files (one for storing all results
    from this group of tests, the other only results
    from this parameter set); run the simulation with
    the given parameters.

    Args
    ----
    None

    Returns
    -------
    None
    """
    # get parameters
    opt = parse_cmd_line_args()

    # TODO move this initialisation to simulator?
    initialise_results(opt)

    # create and run simulation
    sim = simulator.Simulator(opt)
    sim.print_info()
    sim.run(sim.start_cycle)
Exemplo n.º 15
0
def S2_run(
        jules_nc='jules/output/sensitivity_runs/crp_g_77_6.8535_0.17727_0.000573.3_hourly.nc',
        fname='s2_sim_dict.p',
        year=2012,
        month=1,
        days=364):
    simulator = sim.Simulator(jules_nc=jules_nc,
                              year=year,
                              month=month,
                              days=days)
    S2_simulator = sim.S2_simulator(jules_nc=jules_nc,
                                    year=year,
                                    month=month,
                                    days=days)
    sim_dict = {}
    sim_dict['nc_file'] = jules_nc
    sim_dict['S2_dates'] = S2_simulator.date_lst
    sim_dict['dates'] = simulator.date_lst
    sim_dict['lai'] = simulator.lai_lst
    sim_dict['can_height'] = simulator.canht_lst
    sim_dict['soil_m'] = simulator.soilm_lst
    for x in range(13):
        sim_dict[S2_simulator.band_labels[x]] = S2_simulator.all_BRF_arr[:, x]
    f = open(fname, 'wb')
    pickle.dump(sim_dict, f)
    f.close()
    return 'simulator pickled'
Exemplo n.º 16
0
def main():
    x = 0.0
    y = 0.0
    z = 0.0

    i = 0
    avgs = {'x': [], 'y': [], 'z': []}

    comm = usb.Communications(38400)
    sim = simulator.Simulator()
    vertices = getObjectVertices()
    sim.setup(vertices)

    while (True):
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                deconstruct()

        try:
            line = comm.readLine().strip()
        except:
            continue

        # angles = getAnglesFromADXL345(line)
        angles = getAnglesFromGY512(line)
        # print angles
        # time.sleep(1)
        if not angles:
            continue

        x += angles[0]
        y += angles[1]
        z += angles[2]
        sim.updateDisplay(x, y, z)
Exemplo n.º 17
0
def run(cust_start, cust_end, exp_start, exp_end, range, out):
    print("Simulation starting for " + str(range) + " customer.")
    sim = simulator.Simulator()
    sim.initialize_parameters(cust_start, cust_end, exp_start, exp_end)
    sim.simulation(range, out)
    print("Simulation ended.")
    return sim
Exemplo n.º 18
0
def three():
    R = 1000
    COUNT = 20
    ROUND = 200
    NUMBER_OF_NODES = 1000
    NUMBER_OF_SERVICES = 300
    alphas = np.linspace(1e0, 1e1, COUNT)
    averageCosts = np.zeros((2, COUNT))
    successfulRounds = np.zeros((2, COUNT))
    for r in range(ROUND):
        state = generateState(r=R,
                              numberOfNodes=NUMBER_OF_NODES,
                              numberOfServices=NUMBER_OF_SERVICES)
        for type in range(2):
            print("@type: {}".format(type))
            for i, alpha in enumerate(alphas):
                sim = simulator.Simulator("", R, switches=state["switches"])
                print("\t@i: {} -> alpha: {:.4f}".format(i, alpha))
                for serviceIndex in range(NUMBER_OF_SERVICES):
                    serviceAlpha = alpha if serviceIndex == 0 else state[
                        'serviceAlpha'][serviceIndex]
                    sim.addService(
                        F=state['serviceF'][serviceIndex],
                        R=state['serviceR'][serviceIndex],
                        center=state['servicePosition'][serviceIndex],
                        sources=state['serviceSources'][serviceIndex],
                        destinations=state['serviceDestinations']
                        [serviceIndex],
                        alpha=serviceAlpha,
                        w=state['serviceW'][serviceIndex])
                for nodeIndex in range(NUMBER_OF_NODES):
                    sim.addNode(C=2000,
                                U=state['nodeU'][nodeIndex],
                                position=state['nodePosition'][nodeIndex])
                if type is 1:
                    sim.addCloud(numberOfResources=40, C=10000)
                sim.run()
                s = sim.services[0]
                if s.node:
                    print(s.w)
                    averageCosts[type, i] += s.costs[s.node]
                    successfulRounds[type, i] += 1
    for i, _ in enumerate(alphas):
        for type in range(2):
            try:
                averageCosts[type, i] /= successfulRounds[type, i]
            except Exception as e:
                print(e)
    output = {}
    output["alphas"] = alphas.tolist()
    output["without_cloud"] = {}
    output["without_cloud"]["average_costs"] = averageCosts[0, :].tolist()
    output["without_cloud"]["normalized_utility"] = (averageCosts[0, :] /
                                                     alphas).tolist()
    output["with_cloud"] = {}
    output["with_cloud"]["average_costs"] = averageCosts[1, :].tolist()
    output["with_cloud"]["normalized_utility"] = (averageCosts[1, :] /
                                                  alphas).tolist()
    with open('figure3.json', 'w') as outfile:
        json.dump(output, outfile)
Exemplo n.º 19
0
    def setUp(self):
        try:
            self.sim = simulator.Simulator(False)
        except RuntimeError:
            self.sim = simulator.Simulator.get_instance()

        self.comp = Compartment("comp")
def initialiseSimulator(cars,speed_limit,init_speeds=None,vehicle_spacing=3,lane_width=None,dt=.1,graphic_position=None,graphic_dimensions=None,debug=False):
    """Takes in a list of cars and a boolean indicating whether to produce graphics.
       Outputs the standard straight road simulator environment with the input cars initialised
       on the map with the first car (presumed ego) ahead of the second"""
    #Construct the simulation environment
    if init_speeds is None:
        car_speeds = [speed_limit for _ in range(len(cars))] #both cars start going at the speed limit
    else:
        car_speeds = init_speeds

    num_junctions = 3
    num_roads = 2
    road_angles = [0,0]
    road_lengths = [5,100] #Shorter track for generating results
    junc_pairs = [(0,1),(1,2)]

    starts = [[(0,1),1],[(0,1),0]] #Follower car is initialised on the first road, leading car on the 3rd (assuring space between them)
    dests = [[(1,2),1],[(1,2),1]] #Simulation ends when either car passes the end of the 

    run_graphics = True
    draw_traj = False #trajectories are uninteresting by deafault

    runtime = 120.0 #max runtime; simulation will terminate if run exceeds this length of time

    #Initialise the simulator object, load vehicles into the simulation, then initialise the action simulation
    sim = simulator.Simulator(run_graphics,draw_traj,runtime,debug,dt=dt,graphic_position=graphic_position,graphic_dimensions=graphic_dimensions)
    sim.loadCars(cars)

    sim.initialiseSimulator(num_junctions,num_roads,road_angles,road_lengths,junc_pairs,\
                                                    car_speeds,starts,dests,lane_width=lane_width)
    return sim
Exemplo n.º 21
0
    def __init__(self,
                 json,
                 translation_threshold=1.5,
                 rotation_threshold=math.pi / 4.,
                 time_penalty=6):
        """
        :param json: path to json file
        :param translation_threshold: translation threshold on OX axis
        :param rotation_threshold: rotation threshold relative to OY axis
        :param time_penalty: time penalty for human intervention
        """
        self.json = json
        self.translation_threshold = translation_threshold
        self.rotation_threshold = rotation_threshold
        self.time_penalty = time_penalty

        self._read_json()
        self._reset()

        # initialize simulator
        self.simulator = simulator.Simulator(
            self.K,
            self.M,
            time_penalty=self.time_penalty,
            distance_limit=self.translation_threshold,
            angle_limit=self.rotation_threshold)
Exemplo n.º 22
0
def four():
    R = 100
    COUNT = 20
    ROUND = 200
    NUMBER_OF_NODES = 400
    NUMBER_OF_SERVICES = 300
    SERVICE_START_RATIO = 0.3
    sweep = np.linspace(NUMBER_OF_SERVICES * SERVICE_START_RATIO,
                        NUMBER_OF_SERVICES, COUNT)
    averageCosts = np.zeros((2, COUNT))
    successfulRounds = np.zeros((2, COUNT))
    for r in range(ROUND):
        state = generateState(r=R,
                              numberOfNodes=NUMBER_OF_NODES,
                              numberOfServices=NUMBER_OF_SERVICES)
        for type in range(2):
            print("@type: {}".format(type))
            for i, numberOfServices in enumerate(sweep):
                numberOfServices = int(numberOfServices)
                sim = simulator.Simulator("", R, switches=state["switches"])
                print("\t@i: {} -> service count: {:.4f}".format(
                    i, numberOfServices))
                for serviceIndex in range(numberOfServices):
                    sim.addService(
                        F=state['serviceF'][serviceIndex],
                        R=state['serviceR'][serviceIndex],
                        center=state['servicePosition'][serviceIndex],
                        sources=state['serviceSources'][serviceIndex],
                        destinations=state['serviceDestinations']
                        [serviceIndex],
                        alpha=state['serviceAlpha'][serviceIndex],
                        w=state['serviceW'][serviceIndex])
                for nodeIndex in range(NUMBER_OF_NODES):
                    sim.addNode(C=2000,
                                U=state['nodeU'][nodeIndex],
                                position=state['nodePosition'][nodeIndex])
                if type is 1:
                    sim.addCloud(numberOfResources=40, C=10000)
                sim.run()
                for serviceIndex in range(int(sweep[0])):
                    s = sim.services[serviceIndex]
                    if s.node is None:
                        averageCosts[type, i] += s.alpha * s.w * s.R
                    else:
                        averageCosts[type, i] += s.costs[s.node]
                    successfulRounds[type, i] += 1
    for i, _ in enumerate(sweep):
        for type in range(2):
            try:
                averageCosts[type, i] /= successfulRounds[type, i]
            except Exception as e:
                print(e)
    output = {}
    output["services"] = sweep.tolist()
    output["without_cloud"] = {}
    output["without_cloud"]["average_costs"] = averageCosts[0, :].tolist()
    output["with_cloud"] = {}
    output["with_cloud"]["average_costs"] = averageCosts[1, :].tolist()
    with open('figure4.json', 'w') as outfile:
        json.dump(output, outfile)
Exemplo n.º 23
0
def initialiseSimulator(cars,speed_limit,graphics,init_speeds,lane_width=None):
    """Takes in a list of cars and a boolean indicating whether to produce graphics.
       Outputs the standard straight road simulator environment with the input cars initialised
       on the map with the first car (presumed ego) ahead of the second"""
    num_junctions = 5
    num_roads = 4
    road_angles = [90 for _ in range(num_junctions)]
    road_lengths = [5,20,5,270]
    junc_pairs = [(i,i+1) for i in range(num_roads)]

    starts = [[(0,1),1],[(0,1),0]] #Follower car is initialised on the first road, leading car on the 3rd (assuring space between them)
    dests = [[(1,2),0],[(1,2),0]] #Simulation ends when either car passes the end of the 

    run_graphics = graphics
    draw_traj = False #trajectories are uninteresting by deafault
    debug = False #don't want debug mode

    runtime = 120.0 #max runtime; simulation will terminate if run exceeds this length of time

    #Initialise the simulator object, load vehicles into the simulation, then initialise the action simulation
    sim = simulator.Simulator(run_graphics,draw_traj,runtime,debug,dt=cars[0].timestep)
    sim.loadCars(cars)

    sim.initialiseSimulator(num_junctions,num_roads,road_angles,road_lengths,junc_pairs,\
                                                    init_speeds,starts,dests,lane_width=lane_width)

    return sim
Exemplo n.º 24
0
    def __init__(self,
                 json,
                 translation_threshold=1.5,
                 rotation_threshold=0.2,
                 time_penalty=6,
                 frame_rate=3):
        """
        :param json: path to json file
        :param translation_threshold: translation threshold on OX axis
        :param rotation_threshold: rotation threshold relative to OY axis
        :param time_penalty: time penalty for human intervention
        """
        self.json = json
        self.translation_threshold = translation_threshold
        self.rotation_threshold = rotation_threshold
        self.time_penalty = time_penalty
        self.frame_rate = frame_rate
        self.crop = Crop()

        self._read_json()
        self.reset()

        # initialize simulator
        self.simulator = simulator.Simulator(
            time_penalty=self.time_penalty,
            distance_limit=self.translation_threshold,
            angle_limit=self.rotation_threshold)

        # set transformation matrix
        self.T = np.eye(3)
Exemplo n.º 25
0
    def __init__(self, arm_name, sim=None, view=True):
        """
        :param arm_name: "left" or "right"
        :param sim: OpenRave simulator (or create if None)
        """
        assert arm_name == 'left' or arm_name == 'right'

        self.arm_name = arm_name
        self.tool_frame = '{0}_gripper_tool_frame'.format(arm_name[0])
        self.joint_names = [
            '{0}{1}'.format(arm_name[0], joint_name)
            for joint_name in self.joint_name_suffixes
        ]

        self.sim = sim
        if self.sim is None:
            self.sim = simulator.Simulator()

            if view:
                self.sim.env.SetViewer('qtcoin')

        self.robot = self.sim.robot
        self.manip = self.sim.larm if arm_name == 'left' else self.sim.rarm
        self.tool_frame_link = self.robot.GetLink(self.tool_frame)

        self.gripper_joint = self.robot.GetJoint(
            '{0}_gripper_l_finger_joint'.format(arm_name[0]))

        self.joint_indices = self.manip.GetArmIndices()
Exemplo n.º 26
0
def plot_single_barb_mat_3d(armies):
    # Make data.
    X = []
    Y = []
    Z = []

    gb = board.GameBoard(
        base_from_html.html_to_game_board("bases/base_th4_2.html"))
    sim = simulator.Simulator(gb)

    for army in armies:
        stats = sim.run(army)
        x, y = army[0].get_pos()

        X.append(x)
        Y.append(y)
        Z.append(stats["percent"])

    # plot 3d
    fig = plt.figure()
    ax = fig.gca(projection='3d')

    # Plot the surface.
    surf = ax.scatter(X,
                      Y,
                      Z,
                      cmap=cm.coolwarm,
                      linewidth=0,
                      antialiased=False)
    plt.show()
Exemplo n.º 27
0
def plot_episode(agent, run):
    ''' Plot an example run. '''
    with file('./runs/'+agent.name+'/'+str(run)+'.obj', 'r') as file_handle:
        agent = pickle.load(file_handle)
        sim = simulator.Simulator()
        import interface
        agent.run_episode(sim)
        interface.Interface().draw_episode(sim, 'after')
Exemplo n.º 28
0
    def run(self):
        print "Starting " + self.name

        gVars.interfaceData = BoatData.BoatData()
        hardware = simulator.Simulator(gVars.verbose, gVars.reset, gVars.gust,
                                       gVars.dataToUI)
        while 1:
            hardware.update()
Exemplo n.º 29
0
def solve2():
    R = 1000
    COUNT = 10
    ROUND = 2
    NUMBER_OF_NODES = 300
    NUMBER_OF_SERVICES = 100
    #  betas = np.logspace(5, 5.5, COUNT)
    betas = np.linspace(160000, 200000, COUNT)
    #ws = (np.logspace(-3, -0.1, 10))
    averageRate = np.zeros((2, COUNT))
    averageDelay = np.zeros((2, COUNT))
    for i in range(ROUND):
        print('@{}'.format(i))
        state = generateState(r=R,
                              numberOfNodes=NUMBER_OF_NODES,
                              numberOfServices=NUMBER_OF_SERVICES)
        for index, beta in enumerate(betas):
            w = 1 / (1 + beta)
            print('\t@{}-> beta:{:.3f} w: {:.3f}'.format(index, beta, w))
            sim = simulator.Simulator("", R, switches=state["switches"])
            for serviceIndex in range(NUMBER_OF_SERVICES):
                sim.addService(
                    F=state['serviceF'][serviceIndex],
                    R=state['serviceR'][serviceIndex],
                    center=state['servicePosition'][serviceIndex],
                    sources=state['serviceSources'][serviceIndex],
                    destinations=state['serviceDestinations'][serviceIndex],
                    alpha=state['serviceAlpha'][serviceIndex],
                    w=w)
            for nodeIndex in range(NUMBER_OF_NODES):
                sim.addNode(C=2000,
                            U=state['nodeU'][nodeIndex],
                            position=state['nodePosition'][nodeIndex])
            sim.run()
            for s in sim.services:
                if s.node:
                    averageRate[0, index] += abs(
                        s.R - s.rates[s.node]) / NUMBER_OF_SERVICES / ROUND
                    averageDelay[
                        0,
                        index] += s.taus[s.node] / NUMBER_OF_SERVICES / ROUND
    fig, ax1 = plt.subplots()
    plt1 = ax1.plot(betas,
                    averageRate[0, :],
                    'g*-',
                    label="Average Difference in Rate")
    ax1.set_xlabel('$\\beta$')
    ax1.set_ylabel('average difference in rate')
    ax2 = ax1.twinx()
    plt2 = ax2.plot(betas, averageDelay[0, :], 'b+-', label="Average Delay")
    ax2.set_ylabel('average delay (s)')
    lns = plt1 + plt2
    labs = [l.get_label() for l in lns]
    ax1.legend(lns, labs, loc=0)
    ax1.grid(True)
    fig.tight_layout()
    plt.show()
    sim.plot()
Exemplo n.º 30
0
 def create(self, num, model, init_val):
     sim_id = len(self.simulators)
     sim = simulator.Simulator(model, num, init_val)
     self.simulators.append(sim)
     return [{
         'eid': '%s.%s' % (sim_id, eid),
         'type': model,
         'rel': []
     } for eid, inst in enumerate(sim.instances)]