예제 #1
0
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)

CAR_RECT = Rect(0, 0, 5, 5)

if __name__ == '__main__':
    SIMULATOR = Simulator([
        vec(50, 40), vec(100, 44), vec(300, 36), vec(450, 40),
        vec(50, 160), vec(100, 180), vec(200, 160), vec(450, 160),
        vec(200, 10), vec(200, 40), vec(150, 172), vec(200, 400)
    ], [
        [1], [9], [3], [7],
        [5], [10], [7], [11],
        [9], [10, 2], [11, 6], [7, 10, 6]
    ], {
        0: TrafficLight(2, 1, 2),
        1: TrafficLight(2, 1, 2),
        2: TrafficLight(2, 1, 2),
        3: TrafficLight(2, 1, 2),
        4: TrafficLight(2, 1, 2),
        5: TrafficLight(2, 1, 2),
        6: TrafficLight(2, 1, 2)
    }, [
        (vec(70, 200), 1, 4)
    ])

    SIMULATOR.createCar(Thinker(), 0)
    SIMULATOR.createCar(Thinker(), 1)

    # initialize pygame and create window
    pygame.init()
예제 #2
0
import json

from simulator.hero import all_heroes
from simulator.simulator import Simulator

#hero1 = all_heroes["Nino"]
#hero2 = all_heroes["Lucina"]
hero1 = all_heroes["Robin (M)"]
hero2 = all_heroes["Takumi"]
#hero1.stats.attack = 20
#hero2.stats.attack = 20

print(hero1)
print(hero1.stats)
print(hero1.skills)
print()
print(hero2)
print(hero2.stats)
print(hero2.skills)
print()
print()

sim = Simulator(hero1, hero2)
sim.run()

print()
print()

sim = Simulator(hero2, hero1)
sim.run()
예제 #3
0
import numpy as np
from simulator.drone import Drone
from simulator.controller import Controller
from simulator.simulator import Simulator

if __name__ == '__main__':

    drone = Drone()
    controller = Controller(drone)
    # Simulate some disturbance in the angular velocity.
    angular_disturbance = np.array([[0.0], [0.0], [0.0]])
    drone.thetadot = angular_disturbance
    simulator = Simulator(drone, controller)
    simulator.simulate(30)  # simulate n secs
예제 #4
0
    def __init__(self, num_nodes):
        #: Cluster configuration
        self.NUM_NODES = num_nodes  # node_id: 0,1,2,...
        #: fixed 9 apps
        self.NUM_APPS = 7
        #: initialized state to zero matrix
        self._state_reset()
        # clustering
        self.baisc_oath_name = 'subScheduler_'
        path_surffix = "./checkpoint/"
        self.subScheduler_api_0 = subScheduler(path_name=self.baisc_oath_name +
                                               '0',
                                               surffix='0',
                                               path_surffix=path_surffix)
        self.subScheduler_api_1 = subScheduler(path_name=self.baisc_oath_name +
                                               '10',
                                               surffix='10',
                                               path_surffix=path_surffix)
        self.subScheduler_api_2 = subScheduler(path_name=self.baisc_oath_name +
                                               '20',
                                               surffix='20',
                                               path_surffix=path_surffix)
        self.subScheduler_api_3 = subScheduler(path_name=self.baisc_oath_name +
                                               '30',
                                               surffix='30',
                                               path_surffix=path_surffix)
        self.subScheduler_api_4 = subScheduler(path_name=self.baisc_oath_name +
                                               '40',
                                               surffix='40',
                                               path_surffix=path_surffix)
        self.subScheduler_api_5 = subScheduler(path_name=self.baisc_oath_name +
                                               '50',
                                               surffix='50',
                                               path_surffix=path_surffix)
        self.subScheduler_api_6 = subScheduler(path_name=self.baisc_oath_name +
                                               '60',
                                               surffix='60',
                                               path_surffix=path_surffix)
        self.subScheduler_api_7 = subScheduler(path_name=self.baisc_oath_name +
                                               '70',
                                               surffix='70',
                                               path_surffix=path_surffix)
        self.subScheduler_api_8 = subScheduler(path_name=self.baisc_oath_name +
                                               '80',
                                               surffix='80',
                                               path_surffix=path_surffix)
        self.subScheduler_api_9 = subScheduler(path_name=self.baisc_oath_name +
                                               '90',
                                               surffix='90',
                                               path_surffix=path_surffix)
        self.subScheduler_api_10 = subScheduler(
            path_name=self.baisc_oath_name + '100',
            surffix='100',
            path_surffix=path_surffix)
        self.subScheduler_api_11 = subScheduler(
            path_name=self.baisc_oath_name + '110',
            surffix='110',
            path_surffix=path_surffix)
        self.subScheduler_api_12 = subScheduler(
            path_name=self.baisc_oath_name + '120',
            surffix='120',
            path_surffix=path_surffix)
        self.subScheduler_api_13 = subScheduler(
            path_name=self.baisc_oath_name + '130',
            surffix='130',
            path_surffix=path_surffix)
        self.subScheduler_api_14 = subScheduler(
            path_name=self.baisc_oath_name + '140',
            surffix='140',
            path_surffix=path_surffix)
        self.subScheduler_api_15 = subScheduler(
            path_name=self.baisc_oath_name + '150',
            surffix='150',
            path_surffix=path_surffix)
        self.subScheduler_api_16 = subScheduler(
            path_name=self.baisc_oath_name + '160',
            surffix='160',
            path_surffix=path_surffix)
        self.subScheduler_api_17 = subScheduler(
            path_name=self.baisc_oath_name + '170',
            surffix='170',
            path_surffix=path_surffix)
        self.subScheduler_api_18 = subScheduler(
            path_name=self.baisc_oath_name + '180',
            surffix='180',
            path_surffix=path_surffix)
        self.subScheduler_api_19 = subScheduler(
            path_name=self.baisc_oath_name + '190',
            surffix='190',
            path_surffix=path_surffix)

        self.sim = Simulator()
        sys.exit(1)

    total_num_leader_msg = 0
    total_orig_num_leader_msg = 0
    total_num_pos_msg = 0
    total_valid_time = 0
    total_avg_cvg_time = 0
    total_max_cvg_time = 0
    total_num_leader_changes = 0

    for _ in range(cmd_args.trials):
        sim = Simulator(
            rm,  #route manager
            algo,  #algorithm module
            connec,
            "simulator/maps",  #map folder
            visual=
            False,  # set to True if need to visually observe the simulation
            new_route=
            True  # set to True if not need to re-generate vehicle routes
        )
        rm.bind_simulator(sim)
        sim.start_simulation()

        num_leader_msg = sim.get_count("leader_msg")
        num_orig_leader_msg = sim.get_count("original_leader_msg")
        num_pos_msg = sim.get_count("pos_msg")
        valid_time = sim.get_valid_time()
        avg_cvg_time = sim.get_avg_cvg_time()
        max_cvg_time = sim.get_max_cvg_time()
        num_leader_changes = sim.get_nbr_leader_changes()
예제 #6
0
class LraClusterEnv():
    def __init__(self, num_nodes, ifSimulator=True):
        #: Cluster configuration
        self.NUM_NODES = num_nodes
        # TODO: heterogeneous cluster
        self.NUM_APPS = 7
        self._state_reset()
        if ifSimulator:
            self.sim = Simulator()

    def _state_reset(self):
        self.state = np.zeros([self.NUM_NODES, self.NUM_APPS])

    def reset(self):
        self._state_reset()
        return self._get_state()

    def step(self, action, appid):
        """
        :param action: node chosen
        :param appid: current app_id of the container to be allocated
        :return: new state after allocation
        """
        curr_app = appid
        self.state[action][curr_app] += 1  # locate
        state = self._get_state()
        return state

    def _get_state(self):
        return self.state

    @property
    def _get_throughput_predictor(self):
        # testbed: using predictor
        return self.state

    def get_all_node_throughput(self):
        node_tput_list = []
        for nid in range(self.NUM_NODES):
            state_this_node = self.state[nid]
            tput_this_node = (
                self.sim.predict(state_this_node.reshape(1, -1)) *
                state_this_node).sum()
            node_tput_list.append(tput_this_node)
        return sum(node_tput_list)

    def get_tput_total_env(self):
        return self._get_throughput_predictor

    def _create_preference(self):
        from scipy.sparse import diags

        # cardinality of application itself
        # a b c d e f g h i
        # - 2 i i - 2 2 i -
        # -: cardinality == negative, i.e., anti-affinity
        # 2: cardinality == 2, if 1 < num <= cardinality, +50%, if num > cardinality, -50%
        # i: cardinatliy == infinity, i.e., affinity
        preference = diags([-1, 2, np.inf, np.inf, -1, 2, 2, np.inf,
                            -1]).todense()

        # cardinality of application
        # -: abc, def, ghi
        # i: adg, beh, cfi
        # 2: af, di
        # 5: cd, fg
        # 0: others
        neg_group = [[0, 1, 2], [3, 4, 5], [6, 7, 8]]
        inf_group = [[0, 3, 6], [1, 4, 7], [2, 5, 8]]
        two_group = [[0, 5], [3, 8]]
        fiv_group = [[2, 3], [5, 6]]

        def assign_preference(pre, group, value):
            for g in group:
                length = len(g)
                for temp_i in range(length):
                    a = g[temp_i]
                    for temp_j in range(length):
                        if temp_i != temp_j:
                            b = g[temp_j]
                            pre[a, b] = value
                            pre[b, a] = value
            return pre

        preference = assign_preference(preference, neg_group, -1)
        preference = assign_preference(preference, inf_group, np.inf)
        preference = assign_preference(preference, two_group, 2)
        preference = assign_preference(preference, fiv_group, 5)
        preference = np.array(preference)  # necessary.
        """
        Simulation: 9 nodes, 9 Apps, 81 containers
        Preference:
         [[-1. -1. -1. inf  0.  2. inf  0.  0.]
         [-1.  2. -1.  0. inf  0.  0. inf  0.]
         [-1. -1. inf  5.  0. inf  0.  0. inf]
         [inf  0.  5. inf -1. -1. inf  0.  2.]
         [ 0. inf  0. -1. -1. -1.  0. inf  0.]
         [ 2.  0. inf -1. -1.  2.  5.  0. inf]
         [inf  0.  0. inf  0.  5.  2. -1. -1.]
         [ 0. inf  0.  0. inf  0. -1. inf -1.]
         [ 0.  0. inf  2.  0. inf -1. -1. -1.]]

        # -: abc, def, ghi
        # i: adg, beh, cfi
        # 2: af, di
        # 5: cd, fg
        # 0: others
        """
        return preference

    def get_throughput_single_node(self, nid):

        state_this_node = self.state[nid]
        # TODO: we could change sum() to mean(), if using latency
        tput_this_node = (self.sim.predict(state_this_node.reshape(1, -1)) *
                          state_this_node).sum()

        return tput_this_node, self.sim.predict(state_this_node.reshape(1, -1))

    def get_throughput_given_state(self, container_list):
        state_this_node = np.array(container_list)
        tput_this_node = (self.sim.predict(state_this_node.reshape(1, -1)) *
                          state_this_node).sum()
        return tput_this_node, self.sim.predict(state_this_node.reshape(1, -1))
예제 #7
0
    def __label_single_maps(self, atlas_name, feature_list: List[str],
                            label_list: List[str],
                            single_feature_list: List[str],
                            single_label_list: List[str],
                            overwrite: bool) -> List[Dict[str, any]]:
        """
        Passed atlas name, feature list, label list, and returns res object with the map features labelled for training
        """
        if not atlas_name:
            return []

        if not overwrite and self.__services.resources.training_data_dir.exists(
                "training_" + atlas_name, ".pickle"):
            self.__services.debug.write(
                "Found in training data. Loading from training data",
                DebugLevel.BASIC)
            return self.__services.resources.training_data_dir.load(
                "training_" + atlas_name)

        self.__services.debug.write("Loading maps", DebugLevel.BASIC)
        maps: List[Map] = self.__services.resources.maps_dir.get_atlas(
            atlas_name).load_all()

        res: List[Dict[str, any]] = []

        progress_bar: Progress = self.__services.debug.progress_debug(
            len(maps), DebugLevel.BASIC)
        progress_bar.start()

        # process atlas
        for m in maps:
            config = Configuration()
            config.simulator_algorithm_type = AStar
            config.simulator_testing_type = AStarTesting
            config.simulator_initial_map = m
            services: Services = Services(config)
            simulator: Simulator = Simulator(services)
            testing: AStarTesting = simulator.start()

            features: Dict[str, any] = {}
            arg: str
            for arg in [
                    "map_obstacles_percentage", "goal_found",
                    "distance_to_goal", "original_distance_to_goal", "trace",
                    "total_steps", "total_distance",
                    "smoothness_of_trajectory", "total_time", "algorithm_type",
                    "fringe", "search_space"
            ]:
                features[arg] = testing.get_results()[arg]

            features["features"] = MapProcessing.get_sequential_features(
                testing.map, feature_list)
            features["labels"] = MapProcessing.get_sequential_labels(
                testing.map, label_list)
            features["single_features"] = MapProcessing.get_single_features(
                m, single_feature_list)
            features["single_labels"] = MapProcessing.get_single_labels(
                m, single_label_list)
            res.append(features)
            progress_bar.step()

        return res
예제 #8
0
def test_simulator_initialized_correct_state():
    simulator = Simulator(5, 5)
    assert simulator.get_board_size() == [5, 5]
예제 #9
0
 def __init__(self, start_time, timestep, dispatch_policy, matching_policy):
     self.simulator = Simulator(start_time, timestep)
     self.agent = Agent(dispatch_policy, matching_policy)
     self.last_vehicle_id = 1
     self.vehicle_queue = []
예제 #10
0
from functions.TEMA import TEMAdecision
from functions.TRIMA import TRIMAdecision
from functions.WMA import WMAdecision
from simulator.simulator import Simulator
import pandas_datareader as web
import pandas as pd
import datetime as dt

start = dt.datetime(2015, 1, 1)
end = dt.datetime(2017, 12, 31)

asset = 'AAPL'
data = web.DataReader(asset, 'morningstar', start=start, end=end)
data.index = data.index.droplevel()

sim = Simulator(data, std_purchase=10)
sim.add_indicator('EMA-20', EMAdecision(data, 20))
sim.add_indicator('KAMA-20', KAMAdecision(data, 20))
sim.add_indicator('SMA-20', SMAdecision(data, 20))
sim.add_indicator('SMA-100', SMAdecision(data, 10))
sim.add_indicator('TEMA-20', TEMAdecision(data, 20))
sim.add_indicator('TRIMA-20', TRIMAdecision(data, 20))
sim.add_indicator('WMA-20', WMAdecision(data, 20))

#print(sim.security.head())
#print(sim.security.tail())

sim.calc_earning()
print('\n Resumen')
print('Capital final {}'.format(sim.final_capital))
print('Acciones finales {}'.format(sim.shares_own))
예제 #11
0
class Experiment(object):

    def __init__(self, start_time, timestep, dispatch_policy, matching_policy):
        self.simulator = Simulator(start_time, timestep)
        self.agent = Agent(dispatch_policy, matching_policy)
        self.last_vehicle_id = 1
        self.vehicle_queue = []

    def reset(self, start_time=None, timestep=None):
        # self.simulator.log_score()
        self.simulator.reset(start_time, timestep)

    def populate_vehicles(self, vehicle_locations):
        n_vehicles = len(vehicle_locations)
        vehicle_ids = range(self.last_vehicle_id, self.last_vehicle_id + n_vehicles)
        self.last_vehicle_id += n_vehicles

        # locations = [mesh.convert_xy_to_lonlat(x, y)[::-1] for x in range(MAP_WIDTH) for y in range(MAP_HEIGHT)]
        # p = sum(self.dummy_agent.dispatch_policy.demand_predictor.predict(self.simulator.get_current_time())[0])
        # p = p.flatten() / p.sum()
        # vehicle_locations = [locations[i] for i in np.random.choice(len(locations), size=n_vehicles, p=p)]
        t = self.simulator.get_current_time()
        entering_time = np.random.uniform(t, t + ENTERING_TIME_BUFFER, n_vehicles).tolist()
        q = sorted(zip(entering_time, vehicle_ids, vehicle_locations))
        self.vehicle_queue = q

    def enter_market(self):
        t = self.simulator.get_current_time()
        while self.vehicle_queue:
            t_enter, vehicle_id, location = self.vehicle_queue[0]
            if t >= t_enter:
                self.vehicle_queue.pop(0)
                self.simulator.populate_vehicle(vehicle_id, location)
            else:
                break

    def step(self, verbose=False):
        self.enter_market()
        self.simulator.step()
        vehicles = self.simulator.get_vehicles_state()
        requests = self.simulator.get_new_requests()
        # print("R: ", len(requests))
        current_time = self.simulator.get_current_time()
        m_commands, d_commands = self.agent.get_commands(current_time, vehicles, requests)
        self.simulator.match_vehicles(m_commands)
        self.simulator.dispatch_vehicles(d_commands)

        net_v = vehicles[vehicles.status != status_codes.V_OFF_DUTY]
        if len(m_commands) > 0:
            average_wt = np.mean([command['duration'] for command in m_commands]).astype(int)
        else:
            average_wt = 0
        summary = "{:d}, {:d}, {:d}, {:d}, {:d}, {:d}, {:d}".format(
            current_time, len(net_v), len(net_v[net_v.status == status_codes.V_OCCUPIED]),
            len(requests), len(m_commands), len(d_commands), average_wt
        )
        sim_logger.log_summary(summary)

        if verbose:
            print("summary: ({})".format(summary), flush=True)

    def dry_run(self, n_steps):
        for _ in range(n_steps):
            self.simulator.step()
예제 #12
0
 def run_graphical_for(self, ticks):
     s = Simulator(self.nodes)
     s.run_graphical(ticks)
예제 #13
0
 def run_for(self, ticks):
     s = Simulator(self.nodes)
     s.run(ticks)
    #  '0_1d4480abe9aa45ce51a99c0e19a8a54', '1_1d4480abe9aa45ce51a99c0e19a8a54', '2_1d4480abe9aa45ce51a99c0e19a8a54',
    #  '3_1d4480abe9aa45ce51a99c0e19a8a54', '4_1d4480abe9aa45ce51a99c0e19a8a54', '1_1d9b04c979dfbddca84874d9f682ce6c',
    #  '2_1d9b04c979dfbddca84874d9f682ce6c', '4_1d9b04c979dfbddca84874d9f682ce6c', '0_1b370d5326cb7da75318625c74026d6',
    #  '1_1b370d5326cb7da75318625c74026d6', '3_1b370d5326cb7da75318625c74026d6', '4_1b370d5326cb7da75318625c74026d6',
    #  '0_3b947648cfb77c92dc6e31f308657eca', '3_3b947648cfb77c92dc6e31f308657eca', '1_1e23d88e517b711567ff608a5fbe6aa8'])
    scenes = scenes[name_filter]

    # Hack to fix pybullet-pylab incompatibility on mac os
    if args.gui:
        import pylab as plt
        plt.figure()

    if args.debug:
        plt.ion()

    sim = Simulator(use_egl=False, gui=args.gui)  # Change to no gui
    sim.cam.pos = [
        0.,
        np.cos(np.deg2rad(args.angle)) * args.distance,
        np.sin(np.deg2rad(args.angle)) * args.distance
    ]
    sim.add_gripper(os.environ['GRIPPER_PATH'])

    net = Network(model_fn=args.network)

    _global_start = time.time()
    for scene_idx in range(len(scenes)):
        try:
            scene_name = scenes_ds['name'][scene_idx]
            logging.debug('Testing scene %s' % scene_name)
            sim.restore(scenes[scene_idx], os.environ['MODELS_PATH'])
예제 #15
0
    def augment_label_maps(self, atlases: List[str], feature_list: List[str],
                           label_list: List[str],
                           single_feature_list: List[str],
                           single_label_list: List[str]) -> None:
        if not atlases:
            return

        self.__services.debug.write(
            """Starting Augmentation: [
            atlases: {},
            feature_list: {},
            label_list: {},
            single_feature_list: {},
            single_label_list: {}
        ] 
        """.format(atlases, feature_list, label_list, single_feature_list,
                   single_label_list), DebugLevel.BASIC)

        label_atlas_name = "training_" + "_".join(atlases)

        self.__services.debug.write("Loading maps", DebugLevel.BASIC)
        maps: List[Map] = []
        for name in atlases:
            maps = maps + self.__services.resources.maps_dir.get_atlas(
                name).load_all()

        self.__services.debug.write("Loading atlas", DebugLevel.BASIC)
        t: List[Dict[str,
                     any]] = self.__services.resources.training_data_dir.load(
                         label_atlas_name)

        progress_bar: Progress = self.__services.debug.progress_debug(
            len(t), DebugLevel.BASIC)
        progress_bar.start()

        for i in range(len(t)):
            config = Configuration()
            config.simulator_algorithm_type = AStar
            config.simulator_testing_type = AStarTesting
            config.simulator_initial_map = maps[i]
            services: Services = Services(config)
            simulator: Simulator = Simulator(services)
            testing: AStarTesting = simulator.start()

            if feature_list:
                seq_features = MapProcessing.get_sequential_features(
                    testing.map, feature_list)
                for q in range(len(t[i]["features"])):
                    t[i]["features"][q].update(seq_features[q])

            if label_list:
                seq_labels = MapProcessing.get_sequential_labels(
                    testing.map, label_list)
                for q in range(len(t[i]["labels"])):
                    t[i]["labels"][q].update(seq_labels[q])

            if single_feature_list:
                t[i]["single_features"].update(
                    MapProcessing.get_single_features(maps[i],
                                                      single_feature_list))

            if single_label_list:
                t[i]["single_labels"].update(
                    MapProcessing.get_single_labels(maps[i],
                                                    single_label_list))
            progress_bar.step()

        self.__services.debug.write(
            "Saving atlas augmentation: " + str(label_atlas_name),
            DebugLevel.BASIC)
        self.__services.resources.training_data_dir.save(label_atlas_name, t)
        self.__services.debug.write(
            "Finished atlas augmentation: " + str(label_atlas_name) + "\n",
            DebugLevel.BASIC)
예제 #16
0
 def __init__(self):
     self.simulator = Simulator()
예제 #17
0
class BinanceEnv(gym.Env):
    metadata = {'render.modes': ['human']}

    def __init__(self):
        super(BinanceEnv, self).__init__()
        self.action_space = spaces.Discrete(7)
        self.observation_space = spaces.Box(low=0, high=1,
                                            shape=(65,), dtype=np.float16)
        self.binance = BinanceReader()
        self.simulator = Simulator()
        self.current_step = 0
        self.initial_step = 0
        self.last_price = 0.0
        self.is_testing = True

    def next_observation(self):
        # Get the stock data points for the last 5 days and scale to between 0-1
        # asks, bids = self.simulator.get_order_book()
        # data = list()
        # for item in asks:
        #     data.append(item[1])
        # asks = np.asarray(data)
        # data = list()
        # for item in bids:
        #     data.append(item[1])
        # bids = np.asarray(data)
        recent_trades = self.simulator.get_recent_trades()
        # data = list()
        # for item in recent_trades:
        #     data.append([item[1], item[2]])
        # recent_trades = np.asarray(data)
        self.last_price = self.simulator.get_last_price()
        max_short, max_long = self.simulator.get_max_short_and_long()
        obs = np.append(recent_trades, self.simulator.profit)
        # obs = np.append(obs, recent_trades)
        # obs = np.append(obs, self.simulator.profit)
        obs = np.append(obs, self.simulator.balance)
        obs = np.append(obs, self.last_price)
        obs = np.append(obs, np.asarray(max_long))
        obs = np.append(obs, np.asarray(max_short))
        return np.asarray(obs, dtype=np.float)

    def reset(self):
        self.simulator = Simulator()
        if self.is_testing:
            self.current_step = 70000
        else:
            self.current_step = random.randint(0, int(self.simulator.max_steps / 1.3))
        self.simulator.current_step = self.current_step
        self.initial_step = self.current_step
        return self.next_observation()

    def _take_action(self, action_type):
        # Set the current price to a random price within the time step
        # print('\n action = ', action_type)
        if action_type == 0:
            volume = Decimal(abs(self.simulator.get_volume()))
            self.simulator.long(volume)
        elif action_type == 1:
            self.simulator.close_long(True)
        elif action_type == 2:
            self.simulator.close_long(False)
        elif action_type == 3:
            volume = Decimal(abs(self.simulator.get_volume()))
            self.simulator.short(volume)
        elif action_type == 4:
            self.simulator.close_short(True)
        elif action_type == 5:
            self.simulator.close_short(False)
        # self.render()

    def render(self, mode='human', close=False):
        # Render the environment to the screen
        self.simulator.update_account()
        print(f'Step: {self.current_step}')
        print(f'Current price: {self.last_price}')
        print(f'Balance: {self.simulator.balance}')
        print(f'Available balance: {self.simulator.available_balance}')
        print(
            f'Total trades:: {self.simulator.count_trades}')
        print(
            f'Current profit: {self.simulator.profit} (Max profit: {self.simulator.max_profit})')

    def step(self, action):
        # Execute one time step within the environment
        self._take_action(action)

        self.current_step += 1
        self.simulator.current_step += 1
        reward = float(self.simulator.reward)
        done = False
        if self.simulator.profit < - 100 \
                or self.current_step + 1 == self.simulator.max_steps \
                or self.current_step - self.initial_step > 10000:
            done = True

        obs = self.next_observation()

        return obs, reward, done, {}
예제 #18
0
def test_simulator_initialized_correct_size():
    simulator = Simulator(31, 57)
    assert simulator.get_board_size() == [31, 57]
예제 #19
0
    parser.add_argument('--nolog', action='store_true')
    parser.add_argument('--subsample', default=None, type=float, help='Subsample depth image by provided factor before feeding to network')
    parser.add_argument('--gui', action='store_true')
    parser.add_argument('-e', nargs='+', default=None, type=int, help='epochs to evaluate, if next arg is model, separate with -- ')

    args = parser.parse_args()

    model_fns = glob.glob(args.model + '/*.hdf5')
    assert len(model_fns) > 0
    model_name = model_fns[0].split('/')[-2]

    # Get input size and initialize simulator camera with it
    from keras.models import load_model
    _, height, width, _ = load_model(model_fns[0]).input_shape

    sim = Simulator(gui=args.gui, timeout=4, debug=True, use_egl=False, stop_th=1e-3)
    sim.cam.height = height
    sim.cam.width = width

    scenes = h5py.File(args.scenes, 'r')

    dt = datetime.datetime.now().strftime('%y%m%d_%H%M')
    model_results_path = os.path.join(args.results, '{}_{}'.format(dt, model_name))
    if not os.path.exists(model_results_path):
        os.makedirs(model_results_path)
    results_fn = model_results_path + '/results.txt'
    results_f = open(results_fn, 'w')
    results_f.write('ARGUMENTS:\n'+''.join(['{}: {}\n'.format(item[0], item[1]) for item in vars(args).items()]))
    results_f.write('---\n')
    print_attrs(scenes, results_f)
예제 #20
0
    for name in PluginController().get_loaded_plugins():
        result[name] = None

    return result

parser = OptionParser()
parser.add_option("-p", "--plugins", dest="plugins", help="List of plugins to load separated by commas")
parser.add_option("-d", "--debug",   default=False, action="store_true", dest="debug", help="Enable debug log")

(options, args) = parser.parse_args()

if options.debug:
    Logger.set_loglevel("DEBUGL2")

sim = Simulator()

sim.load_plugin("corecommands", "core")
sim.load_plugin("aclcommands", "core")

if options.plugins:
    plugins = options.plugins.split(",")

    for plugin in plugins:
        Logger.info("Loading %s" % plugin)
        try:
            sim.load_plugin(plugin)
        except Exception as e:
            Logger.log_traceback(sim)
            sys.exit(1)
예제 #21
0
def run_simulation(series=False):
    sim = Simulator("config/simulator_config.yaml", series=series)
    sim.train()
    return sim.config.General.rootdir
예제 #22
0
from simulator.workload_generator import WorkloadGenerator


import copy


if __name__ == '__main__':    
    wGen = WorkloadGenerator(num_jobs=400, rate_jobs=5, rate_io=0.3,
                             mean_job_time=800, mean_io_time=3,
                             sd_job_time=5, sd_io_time=1, time_unit=1)

    ##############################
    #   Simulate with Euler
    ##############################
    scheduler = RoundRobin(enableEuler=True)    
    simulator = Simulator(scheduler)
    workload1 = wGen.generateWorkload()
    
    workload2 = copy.deepcopy(workload1)
    simulator.setWorkload(workload1)
    simulator.run()

    ##############################
    #   Simulate without Euler
    ##############################    
    scheduler = RoundRobin(enableEuler=False)
    
    simulator = Simulator(scheduler)

    simulator.setWorkload(workload2)
    simulator.run()
예제 #23
0
from simulator.simulator import Simulator
from simulator.route_manager import RouteManager
from algorithm import AlgorithmManager as algo
# from algorithm import DummyAlgorithmManager as algo
from connection import ConnectionManager as conn
rm = RouteManager("simulator/maps/simple")
#algo = AlgorithmManager
sim = Simulator(
    rm,  #route manager
    algo,  #algorithm module
    conn,  #connection module
    "simulator/maps/simple"  #map folder
)

rm.bind_simulator(sim)
sim.start_simulation()
예제 #24
0
class LraClusterEnv():
    def __init__(self, num_nodes):
        #: Cluster configuration
        self.NUM_NODES = num_nodes  # node_id: 0,1,2,...
        #: fixed 9 apps
        self.NUM_APPS = 7
        #: initialized state to zero matrix
        self._state_reset()
        # clustering
        self.baisc_oath_name = 'subScheduler_'
        path_surffix = "./checkpoint/"
        self.subScheduler_api_0 = subScheduler(path_name=self.baisc_oath_name +
                                               '0',
                                               surffix='0',
                                               path_surffix=path_surffix)
        self.subScheduler_api_1 = subScheduler(path_name=self.baisc_oath_name +
                                               '10',
                                               surffix='10',
                                               path_surffix=path_surffix)
        self.subScheduler_api_2 = subScheduler(path_name=self.baisc_oath_name +
                                               '20',
                                               surffix='20',
                                               path_surffix=path_surffix)
        self.subScheduler_api_3 = subScheduler(path_name=self.baisc_oath_name +
                                               '30',
                                               surffix='30',
                                               path_surffix=path_surffix)
        self.subScheduler_api_4 = subScheduler(path_name=self.baisc_oath_name +
                                               '40',
                                               surffix='40',
                                               path_surffix=path_surffix)
        self.subScheduler_api_5 = subScheduler(path_name=self.baisc_oath_name +
                                               '50',
                                               surffix='50',
                                               path_surffix=path_surffix)
        self.subScheduler_api_6 = subScheduler(path_name=self.baisc_oath_name +
                                               '60',
                                               surffix='60',
                                               path_surffix=path_surffix)
        self.subScheduler_api_7 = subScheduler(path_name=self.baisc_oath_name +
                                               '70',
                                               surffix='70',
                                               path_surffix=path_surffix)
        self.subScheduler_api_8 = subScheduler(path_name=self.baisc_oath_name +
                                               '80',
                                               surffix='80',
                                               path_surffix=path_surffix)
        self.subScheduler_api_9 = subScheduler(path_name=self.baisc_oath_name +
                                               '90',
                                               surffix='90',
                                               path_surffix=path_surffix)
        self.subScheduler_api_10 = subScheduler(
            path_name=self.baisc_oath_name + '100',
            surffix='100',
            path_surffix=path_surffix)
        self.subScheduler_api_11 = subScheduler(
            path_name=self.baisc_oath_name + '110',
            surffix='110',
            path_surffix=path_surffix)
        self.subScheduler_api_12 = subScheduler(
            path_name=self.baisc_oath_name + '120',
            surffix='120',
            path_surffix=path_surffix)
        self.subScheduler_api_13 = subScheduler(
            path_name=self.baisc_oath_name + '130',
            surffix='130',
            path_surffix=path_surffix)
        self.subScheduler_api_14 = subScheduler(
            path_name=self.baisc_oath_name + '140',
            surffix='140',
            path_surffix=path_surffix)
        self.subScheduler_api_15 = subScheduler(
            path_name=self.baisc_oath_name + '150',
            surffix='150',
            path_surffix=path_surffix)
        self.subScheduler_api_16 = subScheduler(
            path_name=self.baisc_oath_name + '160',
            surffix='160',
            path_surffix=path_surffix)
        self.subScheduler_api_17 = subScheduler(
            path_name=self.baisc_oath_name + '170',
            surffix='170',
            path_surffix=path_surffix)
        self.subScheduler_api_18 = subScheduler(
            path_name=self.baisc_oath_name + '180',
            surffix='180',
            path_surffix=path_surffix)
        self.subScheduler_api_19 = subScheduler(
            path_name=self.baisc_oath_name + '190',
            surffix='190',
            path_surffix=path_surffix)

        self.sim = Simulator()

    def _state_reset(self):
        self.state = np.zeros([self.NUM_NODES, self.NUM_APPS])

    def reset(self):
        self._state_reset()
        return self._get_state()

    def step(self, action, appid):
        """
        :param action: node chosen
        :param appid: current app_id of the container to be allocated
        :return: new state after allocation
        """
        curr_app = appid
        self.state[action][curr_app] += 1  # locate
        state = self._get_state()
        return state

    def _get_state(self):
        return self.state

    @property
    def _get_throughput(self):

        state_all = np.empty([0, self.NUM_APPS])

        for nid in range(self.NUM_NODES):
            container_list = self.state[nid]
            num_container = sum(container_list)
            predictor_class = int((num_container - 1) / 10)
            if predictor_class > 19:
                predictor_class = 19
            assert (predictor_class >= 0) & (predictor_class <= 19)
            if predictor_class == 0:
                state_this = self.subScheduler_api_0.get_total_tput(
                    container_list)
            elif predictor_class == 1:
                state_this = self.subScheduler_api_1.get_total_tput(
                    container_list)
            elif predictor_class == 2:
                state_this = self.subScheduler_api_2.get_total_tput(
                    container_list)
            elif predictor_class == 3:
                state_this = self.subScheduler_api_3.get_total_tput(
                    container_list)
            elif predictor_class == 4:
                state_this = self.subScheduler_api_4.get_total_tput(
                    container_list)
            elif predictor_class == 5:
                state_this = self.subScheduler_api_5.get_total_tput(
                    container_list)
            elif predictor_class == 6:
                state_this = self.subScheduler_api_6.get_total_tput(
                    container_list)
            elif predictor_class == 7:
                state_this = self.subScheduler_api_7.get_total_tput(
                    container_list)
            elif predictor_class == 8:
                state_this = self.subScheduler_api_8.get_total_tput(
                    container_list)
            elif predictor_class == 9:
                state_this = self.subScheduler_api_9.get_total_tput(
                    container_list)
            elif predictor_class == 10:
                state_this = self.subScheduler_api_10.get_total_tput(
                    container_list)
            elif predictor_class == 11:
                state_this = self.subScheduler_api_11.get_total_tput(
                    container_list)
            elif predictor_class == 12:
                state_this = self.subScheduler_api_12.get_total_tput(
                    container_list)
            elif predictor_class == 13:
                state_this = self.subScheduler_api_13.get_total_tput(
                    container_list)
            elif predictor_class == 14:
                state_this = self.subScheduler_api_14.get_total_tput(
                    container_list)
            elif predictor_class == 15:
                state_this = self.subScheduler_api_15.get_total_tput(
                    container_list)
            elif predictor_class == 16:
                state_this = self.subScheduler_api_16.get_total_tput(
                    container_list)
            elif predictor_class == 17:
                state_this = self.subScheduler_api_17.get_total_tput(
                    container_list)
            elif predictor_class == 18:
                state_this = self.subScheduler_api_18.get_total_tput(
                    container_list)
            elif predictor_class == 19:
                state_this = self.subScheduler_api_19.get_total_tput(
                    container_list)
            state_all = np.append(state_all, state_this, 0)

        total_tput = (self.sim.predict(state_all.reshape(-1, self.NUM_APPS)) *
                      state_all).sum()

        return total_tput

    def get_tput_total_env(self):
        return self._get_throughput
예제 #25
0
    # if real1 or real2:
    #     world = common.world.World(colour)
    # else:
    world = simulator.world.World(colour)

    assert not (real1 and real2), \
        "How are we to run 2 physical robots??"

    pitch = selectPitch(inputs, once)

    sim = Simulator( pitch=pitch,
                     vision=vision,
                     headless=headless,
                     world=world,
                     robot1=(ai1, real1),
                     robot2=(ai2, real2),
                     colour=colour,
                     real_world=None, #(real1 or real2),
                     )
    sim.run()

def selectPitch(inputs, once):
    selectedInputs = [ k for k,v in inputs.items() if v ]
    if len(selectedInputs) > 1:
        print "Only one pitch input can be used at a time"
        sys.exit(2)
    elif len(selectedInputs) == 0:
        # The default is to use a static background
        name = 'image'
        inputs['image'] = "vision/media/calibrated-background-cropped.png"
                                            noise_type=noise_type,
                                            batch_size=batch_size,
                                            proba_coeff=proba_coeff,
                                            train_data_size=train_data_size,
                                            version='v5')
    names.append(name)
    scheduled_lr = {1: 0.1, 62000: 0.01}  # annealing of learning rate

    sim = Simulator(model=model,
                    learning_rate=learning_rate,
                    noise_list=noise_list,
                    batch_size=batch_size,
                    n_epochs=n_epochs,
                    name=name,
                    burn_in_period=burn_in_period,
                    noise_type=noise_type,
                    scheduled_lr=scheduled_lr,
                    swap_step=swap_step,
                    separation_ratio=0,
                    n_simulations=1,
                    test_step=test_step,
                    loss_func_name=loss_func_name,
                    proba_coeff=proba_coeff,
                    mode=None)

    sim.train(train_data_size=train_data_size,
              train_data=x_train,
              train_labels=y_train,
              validation_data=x_valid,
              validation_labels=y_valid,
              test_data=x_test,
              test_labels=y_test)
예제 #27
0
 def actor(self):
     simulator = Simulator(scenario=self.scenarios[0])
     return simulator.combatant_by_name(self.actor_name)
예제 #28
0
for trial in range(0, repeat_count):
    # Set one manually...
    #seed = "\x61\xcb\x82\x90"

    seed = os.urandom(4)
    print "random.seed() = 0x{}".format(binascii.hexlify(seed))
    random.seed(seed)

    # Set message printing level
    Simulator.EXTRA_VERBOSE = False
    Simulator.VERBOSE = False
    Channel.VERBOSE = False
    Node.EXTRA_VERBOSE = False
    Node.EXTRA_VERBOSE = False

    sim = Simulator()
    loss_rate = 0.60  # loss rate (0.0 to 1.0)
    min_delay = 0.000001  # 1 micro-second minimum delay
    mean_dealy = 0.000020  # 20 micro-second delay

    delay_generator = ExponentialDelay(min_delay, mean_dealy)

    alice_output = Channel(sim, delay_generator, loss_rate)
    alice = Node(sim, "ALICE", True, alice_output)

    bob_output = Channel(sim, delay_generator, loss_rate)
    bob = Node(sim, "BOB  ", False, bob_output)

    alice.set_peer(bob)
    bob.set_peer(alice)
예제 #29
0
 def test_step(self):
     road = Mock()
     dispatcher = Mock()
     simulator = Simulator(road=road, dispatcher=dispatcher)
     # No hooks.
     simulator.step()
     self.assertEqual(simulator.steps, 1)
     dispatcher.dispatch.assert_called_once()
     road.step.assert_called_once()
     # Test hooks are run.
     hook = Mock()
     simulator.addHook(hook)
     simulator.step()
     self.assertEqual(simulator.steps, 2)
     hook.run.assert_called_once()
     # Tests hooks are removed correctly.
     hook.run.reset_mock()
     simulator.removeHook(hook)
     simulator.step()
     self.assertEqual(simulator.steps, 3)
     hook.run.assert_not_called()
예제 #30
0
import signal
import sys

from simulator.car import Car
from simulator.recorder import Recorder
from simulator.simulator import Simulator


def signal_handler(signal, frame):
    recorder.stop()
    print 'Recording Saved to ' + recorder.file_name
    sys.exit(0)


simulator = Simulator()
car = Car(simulator)
recorder = Recorder(car)

simulator.connect()
simulator.start()

recorder.start()

print 'Now Recording Driving...'
print 'Press Ctrl-C to Stop Recording'

signal.signal(signal.SIGINT, signal_handler)
signal.pause()
예제 #31
0
import sys
import os
sys.path.insert(1, os.path.join(sys.path[0], '..'))

from simulator.action_history import ActionHistory
from simulator.plotter import Plotter
from simulator.simulator import Simulator
from graph_known_correspondence import GraphSLAM

import numpy as np

if __name__ == '__main__':
    dt = 1.0

    # load testcase
    s = Simulator('../testcase/map2.txt', '../testcase/robot1.txt')
    ah = ActionHistory(dt)
    ah.LoadFromFile('../testcase/action_history_loop.txt')

    # set up the SLAM algorithm
    Q = np.diag([0.1, 0.1, 0.1]) # process noise; (x, y, theta). should be over-estimates
    R = np.diag([0.2, 0.2, 0.01]) # measurement noise; (dist, bearing, signature),
    algo = GraphSLAM()
    algo.Initialize(Q, R, ah.GetLength(), s.world.GetFeatureCount())
    
    # test the SLAM algorithm with the simulator
    ah.Rewind()
    while (not ah.EOF()):
        t, ra = ah.GetNext()
        m = s.Update(t, ra)
        algo.Update(t, ra, m)
예제 #32
0
import random
from time import time

import matplotlib.pyplot as plt
import numpy as np

from simulator.simulator import Simulator
from mcl_algorithms.trinary_mcl.main import TrinaryMCL

if __name__ == "__main__":
    start = time()
    simulator = Simulator()

    num_time_instances = 100
    percentage_are_anchors = 0.2

    num_nodes = 50
    communication_radius = 50
    max_width = 500
    max_height = 500
    max_v = 10

    # random.seed(0)

    simulator_results, algorithm_results = simulator.run(
        num_time_instances=num_time_instances,
        num_nodes=num_nodes,
        num_anchors=num_nodes * percentage_are_anchors,
        stage_size=(max_width, max_height),
        max_v=max_v,
        communication_radius=communication_radius)
예제 #33
0
from simulator.simulator import Simulator

simulator =  Simulator(1)
simulator.initSimulation(10)