def main():
    Scenario(oracles=[CuckooFilter(fpp_threshold)]).run()
    Scenario(oracles=[CuckooFilter(fpp_threshold),
                      CuckooFilter(0.00002)]).run()
    Scenario(oracles=[
        CuckooFilter(fpp_threshold),
        CuckooFilter(0.000001),
        CuckooFilter(0.00001)
    ]).run()
    logger.print()
Exemplo n.º 2
0
def main():
    cfgs = Global_Cfgs()
    scenario = Scenario(scenario_name=cfgs.get('scenario'))

    start_scene = cfgs.get('start_scene')
    try:
        for scene in iter(scenario):
            if start_scene is None or scene.scene_name.strip().lower(
            ) == start_scene.strip().lower():
                start_scene = None
                scene.run_scene()
            else:
                Console_UI().inform_user(
                    f'Skip \'{scene.scene_name}\' - waiting for \'{start_scene}\''
                )

    except RuntimeError as error:
        Console_UI().warn_user(error)
        Console_UI().inform_user("\n\n Traceback: \n")

        traceback.print_exc()
    except KeyboardInterrupt:
        Console_UI().inform_user(
            f'\nInterrupted by ctrl+c - stopped ad "{scene.scene_name}"')
    else:
        Console_UI().inform_user("Done with all scenarios!")

    Console_UI().inform_user('To view results, checkout the tensorboard:')
    Console_UI().inform_user(
        f'tensorboard --logdir /media/max/HD_1_3TB/log/{cfgs.sub_log_path}/tensorboard'
    )
def create_scenarios():
    alt_opt_cfg = join(faster_rcnn_root, "experiments/cfgs/faster_rcnn_alt_opt.yml")
    base_scenario = Scenario(
        scenarios_dir=scenarios_dir,
        scenario="scales_2_4_8",
        train_imdb="technicaldrawings_single-numbers_train",
        test_imdb="technicaldrawings_single-numbers_val",
        weights_path=join(faster_rcnn_root, "data/imagenet_models/ZF.v2.caffemodel"),  # you have to download this first
        gpu_id=0,
        max_iters=[1, 1, 1, 1],  # max iters
        rpn_config=RpnConfig(num_classes=2, anchor_scales=[8, 16, 32], anchor_feat_stride=16),
        fast_rcnn_config=FastRcnnConfig(num_classes=2),
        solver_config=SolverConfig(),
        config=yaml.load(open(alt_opt_cfg))
    )

    small_scales = deepcopy(base_scenario)
    small_scales.name("scales_4_8_16")
    small_scales.rpn_config.anchor_scales = [4, 8, 16]
    small_scales.fast_rcnn_config.anchor_scales = small_scales.rpn_config.anchor_scales

    default_scales = deepcopy(base_scenario)
    default_scales.name("scales_8_16_32")
    default_scales.rpn_config.anchor_scales = [8, 16, 32]
    default_scales.fast_rcnn_config.anchor_scales = default_scales.rpn_config.anchor_scales

    large_scales = deepcopy(base_scenario)
    large_scales.name("scales_16_32_64")
    large_scales.rpn_config.anchor_scales = [16, 32, 64]
    large_scales.fast_rcnn_config.anchor_scales = large_scales.rpn_config.anchor_scales

    return small_scales, default_scales, large_scales
Exemplo n.º 4
0
def main():
    random.seed(42)
    scenario_file = "input/market_patterns.csv"
    df_scenarios = pd.read_csv(scenario_file)
    for col in ["start", "end"]:
        df_scenarios[col] = pd.to_datetime(df_scenarios[col])
    scenarios = []
    for i, row in df_scenarios.iterrows():
        if row["skip"] == "yes":
            continue
        del row["skip"]
        s = Scenario(**row)
        s.populate_data()
        scenarios.append(s)

    stg_class = ExpRatioStrategy
    # stg_class = LinearRatioStrategy

    for i, scenario in enumerate(scenarios):
        st = StrategyTrainer(stg_class=stg_class)
        st.prepare(pop_size=100, ngen=100, sigma_divider=1000)
        # if i == 1:
        #     continue
        print(f"Training under {scenario}...")
        st.update_scenario(scenario)
        stg = st.train(verbose=True)
        print(f"Best strategy under {scenario}: {stg}")
        print("Scenario: {}".format("\t".join(map(str, stg.params))))
Exemplo n.º 5
0
    def add_new_scenario(self,
                         settings,
                         yeah_id=None,
                         next_block_id=0,
                         next_link_id=0):
        """ Adds a new scenario to the kernel, using the settings given as argument. Other optional arguments may be given - they are only used when this function is used in the process of persistence: at restoration, we must ensure that scenarios have the same id than they had before saving.

		:param settings: The settings dictionary that will be used to initialize the scenario.
		:type element: :class:`python dict` 
		:param yeah_id: (optional) the id to give to the new scenario, only used in the process of persistence.
		:type element: :class:`string`
		:param next_block_id: (optional) used to set the next_block_id attribute of the new scenario, only used in the process of persistence
		:type element: :class:`int`
		:param next_link_id: (optional) sed to set the next_link_id attribute of the new scenario, only used in the process of persistence
		:type element: :class:`int`
		
		"""

        new_scenario = Scenario(self,
                                settings=settings,
                                next_block_id=next_block_id,
                                next_link_id=next_link_id)

        if yeah_id == None:
            self.id = self.next_scenario_id
            new_scenario.id = 'scenario' + str(self.next_scenario_id)
            self.next_scenario_id += 1
        else:
            new_scenario.id = yeah_id

        self.add(new_scenario)
        return new_scenario
Exemplo n.º 6
0
def main(scenario_name, ic_name='std_ic', save=False):
    """Run the offline path planner.

    This function import the scenario named 'scenario_name' from the folder /cfg/ and takes the initial conditions
    named 'ic_name' from the yaml file /cfg/initial_conditions.yaml.

    After importing, it solves it and saves it (if save flag is true) in a .pickle file in the /example/ folder.

    Args:
        scenario_name (str): The name of the scenario which should be solved.
        ic_name (str): The initial condition name which should be used.
        save (bool): Boolean flag to save and store the result.

    Return:
        tot_dV (float): Total amount of deltaV consumed in km/s.
        chaser (Chaser): Chaser state after the mission (used for testing).

    """

    # Import scenario and initial conditions
    scenario = Scenario()
    scenario.import_yaml_scenario(scenario_name, ic_name)

    # Solve scenario
    solver = Solver()
    solver.initialize_solver(scenario)
    solver.solve_scenario()

    # Save manoeuvre plan
    if save:
        scenario.export_solved_scenario(solver.manoeuvre_plan)

    return solver.tot_dV, solver.chaser
Exemplo n.º 7
0
    def test_scenario_one_multiple_searcher(self):
        m = BasicMap(15, 15)

        middle = (7,7)

        # Add some lost persons to the map
        lp00 = RandomWalkLostPerson(m)
        lp00.init(middle)

        searchers = []


        for i in range(10):
            # Add some searchers to the map
            searcher = RandomWalkSearcher(m)
            searcher.init(middle)
            searchers.append(searcher)


        s = Scenario(m, [lp00], searchers)
        s.simulate(100)  # Simulate for N time steps
        print("lost person history: \n")
        print(lp00.get_history())
        print("\n")
        for i in range(10):
            print("searcher history: " , i)
            print(searchers[i].get_history())
            print("\n")
Exemplo n.º 8
0
def create_latency_vs_percent_found(max_latency, number_samples, max_timestep):
    iterations = []

    for i in trange(max_latency):
        num_yes = 0
        for j in range(number_samples):

            m = BasicMap(15, 15)

            middle = (7, 7)

            # Add some lost persons to the map
            lp00 = RandomWalkLostPerson(m)
            lp00.init(middle)

            # Add some searchers to the map
            searcher00 = RandomWalkSearcher(m)
            searcher00.init(middle)

            s = Scenario(m, [lp00], [searcher00], i)
            count = s.simulate(max_timestep)  # Simulate for N time steps
            if s.num_rescued > 0:
                num_yes += 1
        perc_found = num_yes / number_samples
        iterations.append(perc_found * 100)

    plt.plot(iterations)
    plt.xlabel('Latency')
    plt.ylabel('% lost persons found')
    plt.savefig('latency_vs_percent_found.pdf', bbox_inches='tight')
    plt.close()
Exemplo n.º 9
0
def create_searchers_vs_time(max_searchers, latency, number_samples,
                             num_time_steps):
    iterations = []

    for num_searchers in trange(1, max_searchers + 1):
        total = 0
        for i in range(number_samples):
            m = BasicMap(15, 15)
            middle = (7, 7)

            # Add some lost persons to the map
            lp00 = RandomWalkLostPerson(m)
            lp00.init(middle)

            searchers = []

            for j in range(num_searchers):
                # Add some searchers to the map
                searcher = RandomWalkSearcher(m)
                searcher.init(middle)
                searchers.append(searcher)

            s = Scenario(m, [lp00], searchers)
            count = s.simulate(num_time_steps)  # Simulate for N time steps
            total += count
        avg = total / number_samples

        iterations.append(avg)

    plt.plot(list(range(1, max_searchers + 1)), iterations)
    plt.xlabel('Number of searchers')
    plt.ylabel('Average number of search time steps')
    plt.savefig('searchers_vs_time.pdf', bbox_inches='tight')
    plt.close()
Exemplo n.º 10
0
def get_latest_scenario(scenario_id, my_jwt=None):
    my_saved_scenario = SavedScenario.query.get(scenario_id)
    if my_saved_scenario:
        package_id = my_saved_scenario.package_id
    else:
        package_id = DEMO_PACKAGE_ID

    if scenario_id.startswith("demo"):
        tablename = "jump_scenario_details_demo"
    else:
        tablename = "jump_scenario_details_paid"
    rows = None
    with get_db_cursor() as cursor:
        command = u"""select scenario_json from {} where scenario_id='{}' order by updated desc limit 1;""".format(
            tablename, scenario_id)
        # print command
        cursor.execute(command)
        rows = cursor.fetchall()

    scenario_data = None

    if rows:
        scenario_data = json.loads(rows[0]["scenario_json"])

    my_scenario = Scenario(package_id, scenario_data, my_jwt=my_jwt)
    return my_scenario
Exemplo n.º 11
0
def create_latency_vs_timestep(max_latency, number_samples, max_timestep):
    iterations = []

    for i in trange(max_latency):
        total = 0
        for j in range(number_samples):

            m = BasicMap(15, 15)

            middle = (7, 7)

            # Add some lost persons to the map
            lp00 = RandomWalkLostPerson(m)
            lp00.init(middle)

            # Add some searchers to the map
            searcher00 = RandomWalkSearcher(m)
            searcher00.init(middle)

            s = Scenario(m, [lp00], [searcher00], i)
            count = s.simulate(max_timestep)  # Simulate for N time steps
            total += count
        avg = total / number_samples
        iterations.append(avg)

    plt.plot(iterations)
    plt.xlabel('Latency')
    plt.ylabel('Average number of search time steps')
    plt.savefig('latency_vs_time_steps.pdf', bbox_inches='tight')
    plt.close()
Exemplo n.º 12
0
def get_quadrantPartitionPerformance(num_searchers=15,
                                     max_timestep=100,
                                     latency=15,
                                     number_samples=1000):
    iterations = []

    for i in range(0, num_searchers + 1):
        total = 0
        for j in range(number_samples):

            m = BasicMap(15, 15)

            partitioner = QuadrantPartitioner()
            [rows_midpoint, cols_midpoint] = partitioner.partition(m)
            quad01_rows = (0, rows_midpoint)
            quad01_cols = (0, cols_midpoint)
            quad02_rows = (0, rows_midpoint)
            quad02_cols = (cols_midpoint, m.numColumns() - 1)
            quad03_rows = (rows_midpoint, m.numRows() - 1)
            quad03_cols = (0, cols_midpoint - 1)
            quad04_rows = (rows_midpoint, m.numRows() - 1)
            quad04_cols = (cols_midpoint, m.numColumns() - 1)

            middle = (7, 7)

            # Add some lost persons to the map
            lp00 = RandomWalkLostPerson(m)
            lp00.init(middle)

            # Add some searchers to the map
            searchers = []
            for j in range(0, i):
                if j % 4 == 0:
                    # Assign to quadrant 1
                    searcher = RandomWalkSearcher(m, quad01_rows, quad01_cols)
                elif j % 4 == 1:
                    # Assign to quadrant 2
                    searcher = RandomWalkSearcher(m, quad02_rows, quad02_cols)
                elif j % 4 == 2:
                    # Assign to quadrant 3
                    searcher = RandomWalkSearcher(m, quad03_rows, quad03_cols)
                else:
                    # Assign to quadrant 4
                    searcher = RandomWalkSearcher(m, quad04_rows, quad04_cols)
                searcher.init(middle)
                searchers.append(searcher)

            s = Scenario(m, [lp00], searchers, latency)
            count = s.simulate(max_timestep)  # Simulate for N time steps
            total += count
        avg = total / number_samples
        iterations.append(avg)

    plt.title("searchers vs time step")
    plt.plot(list(range(len(iterations))), iterations)
    plt.xlabel('searchers')
    plt.ylabel('time step')
    plt.show()
    print(iterations)
    return iterations
Exemplo n.º 13
0
def runSimulation(seed):
    ''' Temporarily putting a main function here to cycle through scenarios'''

    print("===========================================")
    print("THE ETHICAL ENGINE")
    print("===========================================")
    print()

    set_seed(seed)
    keepRunning = True
    while keepRunning:
        scene = Scenario()
        print(scene)
        print()
        result = ruleset1(scene)
        # result = ruleset2(scene)
        # result = ruleset3(scene)
        # result = my_decision(scene)
        print()
        input('Hit any key to see decision: ')
        print('I choose to save the', result)
        print()

        # For breaking the loop
        response = input("Hit 'q' to quit or 'enter' to continue: ")
        if response == 'q':
            keepRunning = False

    print('Done')
Exemplo n.º 14
0
def run_exp(scenario, remove_small, or_level, current_sites, remove_timeout,
            exclude_sites, _rnd):
    config.OR_LEVEL = config.OR_LEVEL if or_level is None else or_level
    config.REMOVE_SMALL = (config.REMOVE_SMALL
                           if remove_small is None else remove_small)
    config.REMOVE_TIMEOUT = (config.REMOVE_TIMEOUT
                             if remove_timeout is None else remove_timeout)
    scenario_obj = Scenario(scenario, exclude_sites=exclude_sites)
    traces = scenario_obj.get_traces(current_sites=current_sites)
    result = analyse.simulated_original(traces)
    X, y, d = scenario_obj.get_features_cumul(current_sites)
    X = preprocessing.MinMaxScaler().fit_transform(X)  # scaling is idempotent
    clf = result.clf.estimator
    y_pred = model_selection.cross_val_predict(clf,
                                               X,
                                               y,
                                               cv=10,
                                               n_jobs=config.JOBS_NUM)
    _add_as_artifact(y.tolist(), "y_true")
    _add_as_artifact(y_pred.tolist(), "y_prediction")
    _add_as_artifact(d, "y_domains")
    return {
        'C': result.clf.estimator.C,
        'gamma': result.clf.estimator.gamma,
        'sites': traces.keys(),
        'score': result.best_score_,
        'type': "cumul",
        'C_gamma_result': _format_results(result.results),
        # todo: remove duplicates (or_level...), after checking that they match
        'outlier_removal': scenario_obj.trace_args,
        'size_increase': scenario_obj.size_increase(),
        'time_increase': scenario_obj.time_increase()
    }
Exemplo n.º 15
0
    def start(self):
        pygame.init()

        scenario = Scenario(self.width, self.height)

        clock = pygame.time.Clock()

        scenario.create_scenario()

        while True:
            clock.tick(30)

            scenario.create_character()

            # scenario.create_scenario()

            # print(clock.get_fps())

            keys = pygame.key.get_pressed()

            # Este -for- "vigia" cada evento do jogo, caso a letra q seja pressionada
            # ou clique no botão de fechar a janela o jogo encerra.
            for event in pygame.event.get():
                if event.type == QUIT or keys[pygame.K_ESCAPE]:
                    print("Bye...")
                    pygame.quit()
                    exit()

            pygame.display.update()
Exemplo n.º 16
0
def make_env():

    w = Scenario()
    world = w.make_world()
    env = MultiAgentEnv(world, w.reset_world, w.reward, w.observation,
                        w.get_direct_angle, w.has_winner)
    return env
Exemplo n.º 17
0
 def get_game_scenario(self, location):
     x, y = location
     try:
         game_scenario = self.game_scenarios[str(x) + "x" + str(y)]
     except KeyError:
         game_scenario = self.game_scenarios["default"]
     return Scenario(**game_scenario)
Exemplo n.º 18
0
    def start(self, input_event=None):
        with self.__lock:

            if self.status() == 0:
                if input_event:
                    self.__scenario = input_event
                try:
                    if not isinstance(self.__scenario, Scenario):
                        if self.__scenario is None:
                            raise Exception(
                                "No input given (either dict or scenario)")

                        self.__scenario = Scenario(self.__scenario)

                    self.__status = 1
                    self.msg("Input event = " + str(self.__scenario))
                    #self.msg("Database event = "+ self.__scenario.dbstr())

                except Exception as e:
                    if _DEBUG_:
                        import traceback
                        traceback.print_exc()
                    self.stop(e)
                    #raise e
            return self
Exemplo n.º 19
0
    def __init__(self, w, h):
        super().__init__(w, h)
        self.scenario = Scenario()
        self.width_bound = [1, w - 1]
        self.height_bound = [1, h - 1]
        self.evaluation_unit = 10

        #Enables/Disables EA
        self.strategy_aware = True

        self.goal_aware = True  # each goal can be seperately turned on/off
        self.resource_aware = True  #awareness of broken bulbs

        #awarenss of window and its control system
        self.context_aware = True  #window controls system
        self.domain_aware = True  #window gives light

        # time awareness: Pattern detected --> the mid section is always empty
        # Mid section should be ignore in initial population and mutations, it will lead to more efficient strategy generation. it worked! mutate() and generate_individuals() have been updated to reflect this.
        self.time_aware = True
        self.time_aware_width_bound = [0, self.width]
        self.time_aware_height_bound = [
            int(self.height * 0.35),
            int(self.width * 0.65)
        ]

        # hypothesis:?

        self.goals = {
            'luminosity': {
                'enabled': True,
                'maximize': True,
                'evaluate': self.evaluate_luminosity
            },
            'cost': {
                'enabled': True,
                'maximize': False,
                'evaluate': self.evaluate_cost
            }
        }

        self.weight = {
            'present': 6.0,  #luminosity
            'cost': 4.0,
            'penalty_broken_bulb': 12.0,
            'context': 3.5
            #time:
        }
        #self.presence, self.bulbs = self.scenario.diagonal(self.width, self.height)
        #self.presence, self.bulbs = self.scenario.stripes(self.width, self.height)
        #self.presence, self.bulbs = self.scenario.corners(self.width, self.height)
        self.presence, self.bulbs = self.scenario.corners2(
            self.width, self.height)
        #self.presence, self.bulbs = self.scenario.extreme(self.width, self.height)

        if self.strategy_aware:
            self.init_deap()
Exemplo n.º 20
0
    def __init__(self, w, h):
        super().__init__(w,h)
        self.scenario = Scenario()
        self.width_bound = [1, w-2]
        self.height_bound = [1, h-2]
        #self.presence, self.bulbs = self.scenario.diagonal(self.width, self.height)
        #self.presence, self.bulbs = self.scenario.corners(self.width, self.height)
        self.presence, self.bulbs = self.scenario.corners2(self.width, self.height)

        self.init_figures()
Exemplo n.º 21
0
def run(working_map:Map):
    """
    La fonction 'run' lance l'animation sur la Map passé en paramètre
    
    :parameters working_map: Classe `Map` correspondant à la carte sur laquelle faire l'animation
    """
    # Création du contexte graphique
    fig, ax = plt.subplots()
    plt.ion()
    ax.margins(0,0)
    ax.axis("equal")

    # Création de la carte
    simulation_map = working_map(ax)    # Création de la carte

    # Option d'affage de la route (voie des véhicules)
    if SHOW_ROADS:
        for roadmap in simulation_map.roadmap:
            ax.plot(
                [pos.x for pos in roadmap],
                [pos.y for pos in roadmap],
                color='lightgray', linestyle='--'   # Affiche en pointillé gris clair
            )

    # Création de la liste de véhicules
    traffic = [Vehicule(axe=ax, path=simulation_map.roadmap[rd.randint(0, len(simulation_map.roadmap) - 1)])
               for x in range(NB_VEHICULE)]

    # Génération de l'animation
    departure_time = [x for x in range(0, MAX_DEPARTURE, MIN_TIME)] # On définit les heures de départ possibles
    for i, vehicule in enumerate(traffic): # Pour chaque véhicule ...
        # ... on choisit une heure de départ au hasard et jamais la même heure
        vehicule.start(departure_time.pop(rd.randint(0,len(departure_time)-1)))
        # ... On choisie au hasard une vitesse initiale de véhicule
        vehicule.speed = [1,2,3,4][rd.randint(0,3)]

    # Création du film (instantiation du scénario)
    movie = Scenario(ax)

    # Affichage du paysage
    simulation_map.landscape()

    # Lancement de l'animation
    ani = animation.FuncAnimation(fig=fig,
                                  func=movie,
                                  frames=movie.get_sequence(),
                                  interval=FRAMES_INTERVAL,
                                  blit=True,
                                  save_count=2000,      # Nombre de frame tampon (calculé par avance
                                  )

    #ani.save('./video_TIPE.mp4', fps=30)
    plt.show(True)
    return ani
Exemplo n.º 22
0
 def __init__(self, w, h):
     super().__init__(w, h)
     self.width_bound = [1, w - 2]
     self.height_bound = [1, h - 2]
     self.scenario = Scenario()
     #self.presence, self.bulbs = self.scenario.diagonal(self.width, self.height)
     #self.presence, self.bulbs = self.scenario.corners(self.width, self.height)
     self.presence, self.bulbs = self.scenario.corners2(
         self.height, self.width)
     #self.presence, self.bulbs = self.scenario.stripes(self.width, self.height)
     self.plans = []
     self.generate_plans(20)
Exemplo n.º 23
0
def get_lanePartitionPerformance(num_searchers=15,
                                 max_timestep=100,
                                 max_latency=15,
                                 number_samples=100):
    # TODO - Finish this.
    iterations = []

    num_rows = 15
    num_cols = 15

    for i in range(1, num_searchers + 1):
        # Get our lanes!!!
        lanes = []
        lane_size = (num_cols - 1) / i
        for j in range(0, i):
            lower = j * lane_size
            upper = (j + 1) * lane_size
            lanes.append((math.floor(lower) + 1, math.floor(upper)))
        lanes[0] = (0, lanes[0][1])
        print(lanes)

        total = 0
        for j in range(number_samples):

            m = BasicMap(15, 15)

            middle = (7, 7)

            # Add some lost persons to the map
            lp00 = RandomWalkLostPerson(m)
            lp00.init(middle)

            # Add some searchers to the map
            searchers = []
            for k in range(0, len(lanes)):
                searcher = VerticalSweepSearcher(m, lanes[k])
                searcher.init((0, math.floor((lanes[k][0] + lanes[k][1]) / 2)))
                searchers.append(searcher)

            s = Scenario(m, [lp00], searchers, max_latency)
            count = s.simulate(max_timestep)  # Simulate for N time steps
            total += count
        avg = total / number_samples
        iterations.append(avg)

    plt.title("latency vs time step")
    plt.plot(list(range(len(iterations))), iterations)
    plt.xlabel('latency')
    plt.ylabel('time step')
    plt.show()
    print(iterations)
    return iterations
Exemplo n.º 24
0
def getNoPartitionStats(num_searchers, number_samples, max_timestep, latency):
    num_yes = 0
    avg_found = []
    perc_found = 0
    num_timesteps_successful = []
    num_timesteps_overall = []
    for i in range(number_samples):

        m = BasicMap(101, 101)

        middle = (50, 50)

        # Add some lost persons to the map
        lp00 = RandomWalkLostPerson(m)
        lp00.init(middle)

        # Add some searchers to the map
        searchers = []
        for j in range(0, num_searchers):
            searcher = RandomWalkSearcher(m)
            searcher.init(middle)
            searchers.append(searcher)

        s = Scenario(m, [lp00], searchers, latency=latency)
        count = s.simulate(max_timestep)  # Simulate for N time steps
        if count < max_timestep:
            num_yes += 1
            num_timesteps_successful.append(count)
        num_timesteps_overall.append(count)
        perc_found = num_yes / (i + 1)
        perc_found = perc_found * 100
        avg_found.append(perc_found)

    # Graph convergence
    plt.title(
        "Convergence to expected probability of success, no partitioning")
    plt.plot(list(range(number_samples)), avg_found)
    plt.xlabel('Number of Samples')
    plt.ylabel('Probability of Success')
    plt.savefig('convergence_psucess.png')

    print("Result: Percent Lost Person Discovered = " + str(perc_found))
    print("Average Number of Time Steps (when successful): " +
          str(sum(num_timesteps_successful) / len(num_timesteps_successful)))
    print("Standard deviation: " +
          str(statistics.stdev(num_timesteps_successful)))
    print("Average Number of Time Steps (overall): " +
          str(sum(num_timesteps_overall) / len(num_timesteps_overall)))
    print("Standard deviation: " +
          str(statistics.stdev(num_timesteps_overall)))
Exemplo n.º 25
0
    def __init__(self, w, h):
        super().__init__(w,h)
        self.scenario = Scenario()
        #self.presence, self.bulbs = self.scenario.diagonal(self.width, self.height)
        #self.presence, self.bulbs = self.scenario.stripes(self.width, self.height)
        self.presence, self.bulbs = self.scenario.corners(self.width, self.height)

        self.init_deap()
        self.init_figures()
        
        

        
        self.pop = self.toolbox.population(n=1000)
Exemplo n.º 26
0
    def test_scenario_randomWalker(self):
        m = BasicMap(10, 10)

        # Add some lost persons to the map
        lp00 = RandomWalkLostPerson(m)
        lp00.init((2, 5))

        # Add some searchers to the map
        searcher00 = StationarySearcher(m)
        searcher00.init((4, 8))

        s = Scenario(m, [lp00], [searcher00])
        s.simulate(10)  # Simulate for N time steps
        print(lp00.get_history())
        print(searcher00.get_history())
Exemplo n.º 27
0
    def test_scenario_shortestPath(self):
        m = BasicMap(10, 10)

        # Add some lost persons to the map
        lp00 = ShortestPathLostPerson(m, (0, 9))
        lp00.init((2, 5))

        # Add some searchers to the map
        searcher00 = StationarySearcher(m)
        searcher00.init((1, 9))

        s = Scenario(m, [lp00], [searcher00], True)
        s.simulate(100)  # Simulate for N time steps
        print(lp00.get_history())
        print(searcher00.get_history())
Exemplo n.º 28
0
    def test_quadrant_partitioner(self):
        m = BasicMap(25, 25)

        middle = (12, 12)

        # Add some lost persons to the map
        lp00 = RandomWalkLostPerson(m)
        lp00.init(middle)

        # Partition map into quadrants
        searchers = []

        partitioner = QuadrantPartitioner()
        [rows_midpoint, cols_midpoint] = partitioner.partition(m)
        quad01_rows = (0, rows_midpoint)
        quad01_cols = (0, cols_midpoint)
        s00 = RandomWalkSearcher(m, quad01_rows, quad01_cols)
        s00.init(middle)
        searchers.append(s00)

        quad02_rows = (0, rows_midpoint)
        quad02_cols = (cols_midpoint, m.numColumns()-1)
        s01 = RandomWalkSearcher(m, quad02_rows, quad02_cols)
        s01.init(middle)
        searchers.append(s01)

        quad03_rows = (rows_midpoint, m.numRows()-1)
        quad03_cols = (0, cols_midpoint-1)
        s02 = RandomWalkSearcher(m, quad03_rows, quad03_cols)
        s02.init(middle)
        searchers.append(s02)

        quad04_rows = (rows_midpoint, m.numRows()-1)
        quad04_cols = (cols_midpoint, m.numColumns()-1)
        s03 = RandomWalkSearcher(m, quad04_rows, quad04_cols)
        s03.init(middle)
        searchers.append(s03)

        scenario = Scenario(m, [lp00], searchers, latency=50)
        scenario.simulate(100)

        print("lost person history: \n")
        print(lp00.get_history())
        print("\n")
        for i in range(4):
            print("searcher history: " , i)
            print(searchers[i].get_history())
            print("\n")
Exemplo n.º 29
0
    def __init__(self, settings):

        # ----- init simulator -----
        self.simulation_id = settings['simulation_id'] if settings[
            'simulation_id'] else random.randint(1000, 9999)
        self.time = 0.0
        self.time_step = 1.0
        random.seed(self.simulation_id)

        # ----- create scenario -----
        scenario = Scenario(settings['scenario_type'], settings['scenario_id'])
        self.scenario_type = scenario.scenario_type
        self.scenario_id = scenario.scenario_id
        self.time_max = scenario.time_max

        # ----- init logger -----
        self.logger = Logger(settings['logger_verbose_level'])

        # ----- init reporter -----
        reporter_settings = {
            'print_enabled': settings['reporter_print'],
            'export_enabled': settings['reporter_export']
        }
        reporter_init_data = {
            'experiment_id':
            settings['experiment_id'],
            'scenario_type':
            self.scenario_type,
            'scenario_id':
            self.scenario_id,
            'time_max':
            self.time_max,
            'simulation_id':
            self.simulation_id,
            'planner':
            settings['planner'],
            'agents_ids': [
                agent_specs['id']
                for agent_specs in scenario.team_specs['agents_specs']
            ],
        }
        self.reporter = Reporter(reporter_settings, reporter_init_data)

        # ----- init behavior & team -----
        self.behavior = Behavior(scenario.behavior_specs,
                                 scenario.actions_names, self.logger)
        self.team = Team(scenario.team_specs, settings['planner'], self.logger,
                         self.reporter)
Exemplo n.º 30
0
def audit(decision_fn, num_scenarios=100000, seed=None):
    log_file = get_log_file(decision_fn.__name__)
    if seed is not None:
        set_seed(seed)
    for _ in range(num_scenarios):
        scenario = Scenario(youInCar=False,
                            legalCrossing=False,
                            pedsInLane=True)
        decision = decision_fn(scenario)
        if decision not in ['passengers', 'pedestrians']:
            print(scenario)
            message = 'Expected "passengers" or "pedestrian", '
            message += 'but got "{}" instead'.format(decision)
            raise ValueError(message)
        log_scenario(log_file, scenario, decision)
    calculate_stats(log_file)