Ejemplo n.º 1
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))))
Ejemplo n.º 2
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
Ejemplo n.º 3
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()
Ejemplo n.º 4
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")
Ejemplo n.º 5
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()
Ejemplo n.º 6
0
    def __init__(self,
                 _client,
                 _drones,
                 _initial_positions,
                 _malicious,
                 _anomaly_type,
                 _time_factor=1):
        Scenario.__init__(self, _client, _drones, _initial_positions,
                          _malicious, _anomaly_type, _time_factor)

        num_of_sim_drones = 5

        # Create a rectangle of size 200 x 200 and split randomly to all drones
        initial_rectangle = Rectangle((-25, -25), (25, 25))
        rectangles = initial_rectangle.divide(num_of_sim_drones)
        self.paths = [to_airsim_path(r.get_path()) for r in rectangles]

        # Set the time of the scenario to be the time it will take to survey the average rectangle
        # (2 is the velocity of the drones)
        distance_list = [r.get_distance() for r in rectangles]
        avg_distance = sum(distance_list) / len(distance_list)
        self.time = avg_distance / (2 * _time_factor)

        # The initial position each drone is the initial point in its path
        self.goto_initial_locations([path[0] for path in self.paths])

        self.started = False
        self.started_anomaly = False
        # Get the beginning time of the scenario
        self.start = time.perf_counter()
Ejemplo n.º 7
0
def api():
    try:
        rjs = request.get_json(force=True)

        method = rjs['functionName']
        if method == 'register':
            response = json.dumps({"uuid": Manager.register_user()},
                                  ensure_ascii=False)
            from scenario import Scenario
            Scenario.test_curcit()
            return response
        guid = rjs['uuid']
        data = rjs['data']

        client = users[guid]
        response = api_mapping[method](client, data)

    except Exception as e:
        if hasattr(e, 'name'):
            return json.dumps({
                "status": False,
                "message": e.name,
                "response": None
            })
        raise e

    return json.dumps(
        {
            "status": True,
            "message": "Всё ОК",
            "response": response
        },
        ensure_ascii=False)
Ejemplo n.º 8
0
def commandui(args=sys.argv[1:]):
    parser = optparse.OptionParser(usage="%prog [options]", version="%prog 1.0")

    parser.add_option("-s", "--scenario",
                      dest="scenario",
                      action="store_true",
                      default=False,
                      help='run scenario request - login first, then run multi-requests')
    parser.add_option("-a", "--app",
                      dest="app",
                      action="store_true",
                      default=False,
                      help='run application if. parameter checking request - login first, then run multi-requests')
    parser.add_option("-w", "--web",
                      dest="web",
                      action="store_true",
                      default=False,
                      help='run web if. parameter checking request - login first, then run multi-requests')
    
    (options, args) = parser.parse_args(args)
    
    if options.scenario: # update tools
        s = Scenario()
        s.run()
    elif options.app:
        p = Param()
        p.run()
        p.print_result()
    elif options.web:
        p = WebParam()
        p.run()
        p.print_result()
Ejemplo n.º 9
0
    def __init__(self, sniff_thread, tcp_handshake, dpid):
        Scenario.__init__(self, sniff_thread, tcp_handshake)
        self.echo = False
        self.xid = 0
        self.dpid = dpid
        self.answer_features = False
        self.answer_config = False
        self.answer_barrier = False
        self.answer_role = False
        self.answer_stats = False
        self.answer_stats_ports = False
        self.answer_request_port_desc = False
        self.answer_stats_manufacturer = False
        self.answer_flow = False
        self.counter_dict = {
            'echo': 0,
            'config': 0,
            'features': 0,
            'barrier': 0,
            'role': 0,
            'stats': 0,
            'port_desc': 0,
            'flows': 0
        }

        self.rules = {}
Ejemplo n.º 10
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()
Ejemplo n.º 11
0
    def get_slope_weights():
        slope_weight_array_size = 256
        slope_weights = []

        exp = Coeff.get_current_slope_resistance() / (
            UGMDefines.MAX_SLOPE_RESISTANCE_VALUE / 2)
        critical_slope = int(float(Scenario.get_scen_value('critical_slope')))
        for i in range(critical_slope):
            val = (critical_slope - 1 / critical_slope)
            slope_weights.append(1.0 - math.pow(val, exp))

        for i in range(critical_slope, slope_weight_array_size):
            slope_weights.append(1.0)

        if Scenario.get_scen_value('logging') and Scenario.get_scen_value(
                'log_slope_weights'):
            Logger.log("***** LOG OF SLOPE WEIGHTS *****")
            Logger.log(f"Critical Slope =  {critical_slope}")
            Logger.log(
                f"Current Slope Resist = {Coeff.get_current_slope_resistance()}"
            )
            Logger.log(
                f"Max Slope Resistance value = {UGMDefines.MAX_SLOPE_RESISTANCE_VALUE}"
            )
            for i, weight in enumerate(slope_weights):
                if i < critical_slope:
                    Logger.log(f"weight[{i}] = {weight}")

            Logger.log(f"All other values to slope weights = 1.0")

        return slope_weights
Ejemplo n.º 12
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
Ejemplo n.º 13
0
    def write_z_prob_grid(z, name):
        # copy background int z_prob_ptr and remap background pixels
        # which collide with the seed, prob colors, and date
        nrows = IGrid.nrows
        ncols = IGrid.ncols
        total_pix = nrows * ncols

        background = IGrid.igrid.get_background_grid()
        prob_color_cnt = len(Scenario.get_scen_value('probability_color'))

        lower_bounds = [UGMDefines.SEED_COLOR_INDEX, UGMDefines.DATE_COLOR_INDEX]
        upper_bounds = [UGMDefines.SEED_COLOR_INDEX + prob_color_cnt, UGMDefines.DATE_COLOR_INDEX]
        indices = [UGMDefines.SEED_COLOR_INDEX + prob_color_cnt + 1, UGMDefines.DATE_COLOR_INDEX - 1]

        z_prob = Utilities.map_grid_to_index(background, lower_bounds, upper_bounds, indices, total_pix)

        if Processing.get_processing_type() == Globals.mode_enum['predict']:
            # Map z_ptr pixels into desired prob indices and save in overlay
            prob_list = Scenario.get_scen_value('probability_color')
            lower_bounds = []
            upper_bounds = []
            indices = []
            for i, prob in enumerate(prob_list):
                lower_bounds.append(prob.lower_bound)
                upper_bounds.append(prob.upper_bound)
                indices.append(i + 2)

            indices[0] = 0
            overlay = Utilities.map_grid_to_index(z, lower_bounds, upper_bounds, indices, total_pix)

            # Overlay overlay grid onto the z_prob grid
            z_prob = Utilities.overlay(z_prob, overlay)

            # Overlay urban_seed into the z_prob grid
            z_prob = Utilities.overlay_seed(z_prob, total_pix)
        else:
            # TESTING
            # Map z grid pixels into desired seed_color_index and save in overlay pt
            lower_bounds = [1]
            upper_bounds = [100]
            indices = [UGMDefines.SEED_COLOR_INDEX]

            overlay = Utilities.map_grid_to_index(z.gridData, lower_bounds, upper_bounds, indices, total_pix)

            # Overlay overlay grid onto the z_prob grid
            z_prob = Utilities.overlay(z_prob, overlay)

        # The file writer needs to take in a Grid, so we're going to wrap our z_prob list in a grid
        z_prob_grid = IGrid.wrap_list(z_prob)
        if IGrid.using_gif:
            filename = f"{Scenario.get_scen_value('output_dir')}{IGrid.igrid.get_location()}" \
                       f"{name}{Processing.get_current_year()}.gif"
        else:
            filename = f"{Scenario.get_scen_value('output_dir')}{IGrid.igrid.get_location()}" \
                       f"{name}{Processing.get_current_year()}.tif"
            IGrid.echo_meta(f"{Scenario.get_scen_value('output_dir')}"
                            f"{IGrid.igrid.get_location()}{name}{Processing.get_current_year()}.tfw", "urban")

        date = f"{Processing.get_current_year()}"
        ImageIO.write_gif(z_prob_grid, Color.get_probability_table(), filename, date, IGrid.nrows, IGrid.ncols)
Ejemplo n.º 14
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
Ejemplo n.º 15
0
    def __iter__(self):
        EVENT('scenario_outline', self)
        
        for ex in self.examples:
            EVENT('examples', ex)
            
            pattern = re.compile(r'<(%s)>' % '|'.join(ex.table.columns))
            self.current_columns = ex.table.columns
            self.current_widths = ex.table.widths
           
            for values in ex.table.rows:
                self.current_row = values
                # Substitute outline parameters.
                for step in self.steps:
                    step.name, used = subst_params(step.name_template, pattern, values)
                    if step.multi is not None:
                        if type(step.multi) == types.StringType:
                            # PyString
                            step.multi, used_in_multi = subst_params(step.multi_template, pattern, values)
                        else:
                            # Table
                            used_in_multi = step.multi.subst(pattern, values)
                        used |= used_in_multi
                    step.full_reset()
                    step.used_parameters = used
                Scenario.reset(self)
                yield self

        self.status = 'done'
        self.exception = None
        self.tb = None
        
        EVENT('scenario_outline', self)
Ejemplo n.º 16
0
    def write_restart_data(filename, diffusion_coeff, breed_coeff, spread_coeff,
                           slope_resist_coeff, road_grav_coeff, count, counter):
        if Scenario.get_scen_value('logging') and Scenario.get_scen_value('log_writes'):
            Logger.log(f"Writing restart data to file: {filename}")

        restart_file = open(filename, "w")
        restart_file.write(f"{diffusion_coeff} {breed_coeff} {spread_coeff} {slope_resist_coeff} {road_grav_coeff} {count} {counter}")
        restart_file.close()
Ejemplo n.º 17
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()
Ejemplo n.º 18
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()
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()
Ejemplo n.º 20
0
    def analyze(fmatch):
        output_dir = Scenario.get_scen_value('output_dir')
        run = Processing.get_current_run()
        write_avg_file = Scenario.get_scen_value('write_avg_file')
        avg_filename = f'{output_dir}avg.log'
        write_std_dev_file = Scenario.get_scen_value('write_std_dev_file')
        std_filename = f'{output_dir}std_dev.log'
        control_filename = f'{output_dir}control_stats.log'

        if write_avg_file:
            if not os.path.isfile(avg_filename):
                Stats.create_stats_val_file(avg_filename)

        if write_std_dev_file:
            if not os.path.isfile(std_filename):
                Stats.create_stats_val_file(std_filename)

        if Processing.get_processing_type() != Globals.mode_enum['predict']:
            if not os.path.isfile(control_filename):
                Stats.create_control_file(control_filename)

            # start at i = 1; i = 0 is the initial seed
            # I think I need to put a dummy stats_val to represent the initial seed
            Stats.average.append(StatsVal())
            for i in range(1, IGrid.igrid.get_num_urban()):
                year = IGrid.igrid.get_urban_year(i)
                Stats.calculate_averages(i)
                Stats.process_grow_log(run, year)

                if write_avg_file:
                    Stats.write_stats_val_line(avg_filename, run, year,
                                               Stats.average[i], i)
                if write_std_dev_file:
                    Stats.write_stats_val_line(std_filename, run, year,
                                               Stats.std_dev[i], i)

            Stats.do_regressions()
            Stats.do_aggregate(fmatch)
            Stats.write_control_stats(control_filename)

        if Processing.get_processing_type() == Globals.mode_enum['predict']:
            start = int(Scenario.get_scen_value('prediction_start_date'))
            stop = Processing.get_stop_year()

            for year in range(start + 1, stop + 1):
                Stats.clear_stats()
                Stats.process_grow_log(run, year)
                if write_avg_file:
                    Stats.write_stats_val_line(avg_filename, run, year,
                                               Stats.average[0], 0)
                if write_std_dev_file:
                    Stats.write_stats_val_line(std_filename, run, year,
                                               Stats.std_dev[0], 0)

        Stats.clear_stats()
Ejemplo n.º 21
0
class TestScenarioZeroOrigin(TestCase):
    def setUp(self):
        self.scenario = Scenario('testScenarioZeroOrigin.csv')

    def test_zero(self):  # 0
        self.assertAlmostEqual(self.scenario.sample(0), 2)

    def test_one_half(self):  # 0
        self.assertAlmostEqual(self.scenario.sample(72), 2.5)

    def test_one(self):  # 144
        self.assertAlmostEqual(self.scenario.sample(144), 3)

    def test_two(self):  # 288
        self.assertAlmostEqual(self.scenario.sample(288), 4)

    def test_three(self):  # 432
        self.assertAlmostEqual(self.scenario.sample(432), 5)

    def test_five(self):  # 720
        self.assertAlmostEqual(self.scenario.sample(720), 7)

    def test_eight(self):  # 1152
        self.assertAlmostEqual(self.scenario.sample(1152), 9)

    def test_nine(self):  # 1296
        self.assertAlmostEqual(self.scenario.sample(1296), 9.5)

    def test_ten(self):  # 1440
        self.assertAlmostEqual(self.scenario.sample(1440), 10)
Ejemplo n.º 22
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
Ejemplo n.º 23
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)
Ejemplo n.º 24
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
Ejemplo n.º 25
0
    def monte_carlo(cumulate, land1):
        log_it = Scenario.get_scen_value("logging")

        z = PGrid.get_z()
        total_pixels = IGrid.get_total_pixels()
        num_monte_carlo = int(
            Scenario.get_scen_value("monte_carlo_iterations"))

        for imc in range(num_monte_carlo):
            Processing.set_current_monte(imc)
            '''print("--------Saved-------")
            print(Coeff.get_saved_diffusion())
            print(Coeff.get_saved_spread())
            print(Coeff.get_saved_breed())
            print(Coeff.get_saved_slope_resistance())
            print(Coeff.get_saved_road_gravity())
            print("--------------------")'''

            # Reset the Parameters
            Coeff.set_current_diffusion(Coeff.get_saved_diffusion())
            Coeff.set_current_spread(Coeff.get_saved_spread())
            Coeff.set_current_breed(Coeff.get_saved_breed())
            Coeff.set_current_slope_resistance(
                Coeff.get_saved_slope_resistance())
            Coeff.set_current_road_gravity(Coeff.get_saved_road_gravity())

            if log_it and Scenario.get_scen_value("log_initial_coefficients"):
                Coeff.log_current()

            # Run Simulation
            Stats.init_urbanization_attempts()
            TimerUtility.start_timer('grw_growth')
            Grow.grow(z, land1)
            TimerUtility.stop_timer('grw_growth')

            if log_it and Scenario.get_scen_value("log_urbanization_attempts"):
                Stats.log_urbanization_attempts()

            # Update Cumulate Grid
            for i in range(total_pixels):
                if z.gridData[i] > 0:
                    cumulate.gridData[i] += 1

            # Update Annual Land Class Probabilities
            if Processing.get_processing_type(
            ) == Globals.mode_enum["predict"]:
                LandClass.update_annual_prob(land1.gridData, total_pixels)

        # Normalize Cumulative Urban Image
        for i in range(total_pixels):
            cumulate.gridData[i] = (100 *
                                    cumulate.gridData[i]) / num_monte_carlo
Ejemplo n.º 26
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)))
Ejemplo n.º 27
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)
Ejemplo n.º 28
0
    def update_annual_prob(land1, total_pixels):
        if len(Scenario.get_scen_value("landuse_data_file")) < 1:
            return

        if Scenario.get_scen_value("logging") and Scenario.get_scen_value(
                "log_writes"):
            Logger.log(f"Updating file {LandClass.annual_prob_filename}")

        for i in range(LandClass.get_num_landclasses()):
            cur_annual_prob = LandClass.annual_prob[i]

            for j in range(total_pixels):
                if i == LandClass.new_indices[land1[j]]:
                    cur_annual_prob[j] += 1
Ejemplo n.º 29
0
class TestSampleRoundingErrors(TestCase):
    def setUp(self):
        self.scenario = Scenario('testScenarioRoundingErrors.csv')

    def test_zero(self):
        self.assertAlmostEqual(self.scenario.sample(0), 0.501526, places=3)

    def test_one_half(self):
        self.assertAlmostEqual(self.scenario.sample(0.5), 0.6885285, places=3)

    def test_one(self):
        self.assertAlmostEqual(self.scenario.sample(1), 0.875531, places=3)

    def test_end(self):
        self.assertAlmostEqual(self.scenario.sample(1440), 0.766185, places=3)
Ejemplo n.º 30
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())
Ejemplo n.º 31
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())
Ejemplo n.º 32
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")
Ejemplo n.º 33
0
def main():
    import pygame
    from colors import BLACK, WHITE
    from pygame.locals import QUIT
    from scenario import Scenario
    test = Scenario(3)
    screen = test.display.screen
    while True:
        agents = [Agent((choice(range(test.display.width)),
                         choice(range(test.display.height))),
                        0,
                        10,
                        None, test.display) for _ in range(500)]
        test.display.clear(BLACK)
        ball = choice(range(150, 774)), choice(range(150, 518))
        opponent = choice(range(150, 774)), choice(range(150, 518))
        test.draw_field("g", 0)
        #pygame.draw.circle(screen, BLUE, ball, 10)
##        pygame.draw.circle(screen, WHITE, goal, 10)
##        pygame.draw.circle(screen, RED, opponent, 10)
##        for x in range(0, test.display.width, 2 * SCALE):
##            for y in range(0, test.display.height, 2 * SCALE):
##                #print(x, y)
##                angle = f(x, y)
##                x_component, y_component = cos(angle), sin(angle)
##                test.(screen, RED, (x, y),
##                                   (x + int(x_component * SCALE * 1.5),
##                                    y + int(y_component * SCALE * 1.5)))
##                pygame.draw.aaline(screen, GREEN, (x, y),
##                                   (x + int(x_component * SCALE),
##                                    y + int(y_component * SCALE)))

        for n in range(4000):
            for event in pygame.event.get():
                if event.type == QUIT:
                    return
##                else:
##                    print(event.type)
            pygame.draw.circle(screen, WHITE, goal, 10)
            #pygame.draw.circle(screen, RED, opponent, 10)
            for agent in agents:
                agent.rotate_to(g(*agent.loc))
                agent.advance()
                agent.draw(0)
            pygame.display.flip()
Ejemplo n.º 34
0
 def __init__(self, name, path):
     self.name = name
     self.path = path
     self.data_file = os.path.join(os.path.dirname(self.path), "data", self.name+".dat")
     self.raw_data_file = self.data_file+".raw"
     self.save_flag = False
     self.scenario = Scenario(self)
     self.req = None
     self.response = None
     self.recv_data = None
Ejemplo n.º 35
0
def readScenario(file,users,supply):
    
    fin=open(file)
    title=fin.readline()
    scenario=Scenario(title)
    
    print "*** reading scenario file:",file ," :", title
     
    seek(fin,"USER ID")
  
    while True:
            line=fin.readline()
            toks=line.split("\t")
            if len(toks) != 2:
                break
            user=users[toks[0]]
            number=int(toks[1])
            print "%25s" % user.id,"\t",number
            scenario.appendCase(Case(user,number,supply))
            
    return scenario
Ejemplo n.º 36
0
    'username': '******',
    'password': '******',
    'project_id': 'someprojectid',
    'user_domain_name': 'demodomain',
    'project_domain_name': 'demodeomain'
}
demo_clients = km.find_user_credentials('Default', 'demo', 'member')


# Create then delete
logger.debug("\n\nClassic create then delete")
flavor = '1'
image = '94f3805c-f59c-4dca-9cfe-40edf001c256'
name = 'scenario_test'
scenario = Scenario() \
    .chain(server_create, admin_clients, name, flavor, image) \
    .chain(server_delete, admin_clients)

state = {}
scenario.run(state)


logger.debug("\n\nDelete not found with expected")
scenario = Scenario() \
    .chain(server_delete, admin_clients, expected_exceptions=[NovaNotFound])
scenario.run(context={'server_id': '94f3805c-f59c-4dca-9cfe-40edf001c252'})


logger.debug("\n\nCreate with admin, delete with demo.")
scenario = Scenario() \
    .chain(server_create, admin_clients, name, flavor, image) \
 residual_energy_array_temp = []
 residual_energy_JFI_array_temp = []
 for sim_flag in range(sim_num):
     print "with %d sources and %d nodes at the %d-th simulation..."%(source_num_per_lane*lane_num,\
     relay_num_per_lane*lane_num, sim_flag)
     reward_array_temp2 = []
     residual_energy_array_temp2 = []
     # do run
     net_info = Net_info(lane_num, 
                    source_num_per_lane, 
                    relay_num_per_lane)
     net_info.initialize_channel_parameters(assumption_flag = "iid")
     net_info.initialize_power_level(p_max, initial_energy)        
     scenario = Scenario(mobility, distribution, net_info, const, 
                      lane_width, 
                      communication_delay,
                      movement_delay,                 
                      total_sim_time)
     scenario.initialization()
     for epoch in range(epoch_num):
         #print "adaptation at %d-th epoch..."%(epoch,)
         balg.coop(scenario, algorithm_flag = "stochastic_selection")
         scenario.update_position()
         scenario.update()
     #record results
     for lane_pool in scenario.node_pool:
         for node in lane_pool:
             residual_energy_array_temp2.append(node.residual_energy)
     for player in scenario.relayNodes:
         reward_array_temp2.append(player.reward)
 
Ejemplo n.º 38
0
pygame.init()

core.width = 640
core.height = 480
core.appName = "Depths of Mars"
core.init()

data.init()

framerate = 40
clock = pygame.time.Clock()
pygame.time.set_timer(pygame.USEREVENT+1, 1000/framerate)

#snd = pygame.mixer.Sound("snd/31855__HardPCM__Chip015.wav")

scenario = Scenario()

while not scenario.quit:

    for event in pygame.event.get():
        if event.type == pygame.QUIT: scenario.quit = True
        if event.type == pygame.KEYDOWN: core.controls.onKeyDn(event.key)
        if event.type == pygame.KEYUP: core.controls.onKeyUp(event.key)
        if event.type == pygame.USEREVENT+1: scenario.behave()
    #endfor

    core.screen.fill((0,0,0))
    scenario.draw()
    core.screen.blit(core.font.render("%.3f"%(clock.get_fps()), False, (0,255,0)), (0,0))
    pygame.display.flip()
Ejemplo n.º 39
0
 def full_reset(self):
     Scenario.full_reset(self)
Ejemplo n.º 40
0
 def reset(self):
     Scenario.reset(self)
     self.current_columns = None
     self.current_widths = None
     self.current_row = None
Ejemplo n.º 41
0
 def __init__(self, **attrs):
     Scenario.__init__(self, **attrs)
     
     self.full_reset()
Ejemplo n.º 42
0
from twx.botapi import TelegramBot, ReplyKeyboardMarkup, ReplyKeyboardHide
from user import User
from scenario import Scenario
import time
import sys
import sqlite3

scenario_file = 'script.rpy'
if len(sys.argv) > 1:
	scenario_file = sys.argv[1]

scenario = Scenario(scenario_file)

User.db = sqlite3.connect('space-quest.db')

def get_message_reply(message):	
	user = User(message.sender.id)
	if message.text == "/start" or message.text == "🔄 Начать заново":
		user.progressLabel, user.progressKey, user.active, user.variables = "start", -1, 1, {}
		user.save() 	
		return ("Вы начали игру заново", ReplyKeyboardMarkup.create([['⏸ Приостановить игру']],resize_keyboard=True))
	elif message.text == "/pause" or message.text == "⏸ Приостановить игру":
		user.active = 0
		user.save()
		return ("Игра приостановлена", ReplyKeyboardMarkup.create([['🔄 Начать заново'],['▶️ Продолжить игру']],resize_keyboard=True))
	elif message.text == "/continue" or message.text == "▶️ Продолжить игру":
		user.active = 1
		user.save()
		return ("Игра возобновлена", ReplyKeyboardMarkup.create([['⏸ Приостановить игру']],resize_keyboard=True))
	else:
		scenario.load(user)
Ejemplo n.º 43
0
class TestCase(object):
    def __init__(self, name, path):
        self.name = name
        self.path = path
        self.data_file = os.path.join(os.path.dirname(self.path), "data", self.name+".dat")
        self.raw_data_file = self.data_file+".raw"
        self.save_flag = False
        self.scenario = Scenario(self)
        self.req = None
        self.response = None
        self.recv_data = None

    def set_save_flag(self, flag):
        self.save_flag = flag

    def _save_data(self, path, data):
        data_path = os.path.dirname(path)
        if not os.path.exists(data_path):
            os.system("mkdir -p %s"%data_path)

        with open(path, "w") as fd:
            fd.write(data)
            
    def save_raw_data(self):
        self._save_data(self.raw_data_file, self.recv_data)

    def save_data(self):
        self._save_data(self.data_file, self.recv_data)
            
    def send(self, seq=0, url=""):
        def decorator(func):
            def wrapper():
                mode, post_dict = func()
                if mode == "get":
                    self.req = urllib2.Request(url)
                elif mode == "post" and post_dict is not None and \
                         isinstance(post_dict, dict):
                    self.req = urllib2.Request(url, post_dict)
                else:
                    print "fail to get the request mode"
                    return False
                self.response = urllib2.urlopen(self.req)
                return True
            self.scenario.add(seq, "send", wrapper, url)
            return wrapper
        
        return decorator
        
    def recv(self, seq=0, title=""):
        def decorator(func):
            def wrapper():
                self.recv_swap = self.response.read()
                rtn, self.recv_data = func(self.recv_swap)
                self.save_raw_data()
                if self.save_flag is True:
                    self.save_data()
                return rtn
            self.scenario.add(seq, "recv", wrapper, title)
            return wrapper

        return decorator

    def verify(self, seq=0, title=""):
        old = None
        if os.path.exists(self.data_file):
            with open(self.data_file, "r") as fd:
                old = fd.read()
        def decorator(func):
            def wrapper():
                rtn = func(self.recv_data, old)
                if rtn is False:
                    print "fail to verify, check the raw data %s"%self.raw_data_file
                return rtn
            self.scenario.add(seq, "verify", wrapper, title)
            return wrapper
        return decorator
    def __repr__(self):
        s = "TestCase: %s %s\n"%(self.name, self.path)
        s += repr(self.scenario)
        return s

    def process(self):
        print "\nTestCase # %s #"%self.name
        self.scenario.process()