コード例 #1
0
    def build_graph(self):
        """
        Arrange all the nodes (or all but one) as a ring.
        Then link them depending on the kind of network desired.
        """
        nbr_nodes = SimEngine.gui_get(NBR_NODES)
        graph_type = SimEngine.gui_get(GRAPH_TYPE)

        # If we are generating a star or a wheel network, arrange nbr_nodes-1 as
        # a ring and use the other node as the center node.

        # If we are generating another type of graph, arrange all the nodes as a ring.

        nbr_ring_nodes = (nbr_nodes -
                          1) if graph_type in ['star', 'wheel'] else nbr_nodes

        # create_ordered_agents() creates the indicated number of nodes and arranges
        # them in a ring. It returns a list of the nodes in ring-order.
        ring_node_list = self.create_ordered_agents(nbr_ring_nodes)

        if graph_type in ['star', 'wheel'] and nbr_nodes > 0:
            self.create_agents(1)

        # Now link the nodes according to the desired graph.
        if nbr_nodes:
            self.link_nodes_for_graph(graph_type, nbr_nodes, ring_node_list)
コード例 #2
0
def draw_links(links, sleep_time=0.6):
    cached_world_links_set = World.links
    World.links = set()
    gui_set(gui.GOSTOP,
            text='pause',
            button_color=('white', 'red'),
            enabled=True)
    gui_set(gui.GO_ONCE, enabled=False)
    gui_set(SimEngine.simple_gui.SETUP, enabled=False)
    gui_set(SimEngine.simple_gui.EXIT, enabled=False)
    paused = False
    while links:
        (SimEngine.event, SimEngine.values) = gui.WINDOW.read(timeout=10)
        if SimEngine.event == gui.GOSTOP:
            gui_set(gui.GOSTOP,
                    text='pause' if paused else 'continue',
                    button_color=('white', 'red' if paused else 'green'))
            paused = not paused
            SimEngine.draw_world()
        if not paused:
            lnk = links.pop(0)
            if lnk in World.links:
                World.links.remove(lnk)
            World.links.add(lnk)
            SimEngine.draw_world()
        if sleep_time:
            sleep(sleep_time)
    gui_set(SimEngine.simple_gui.EXIT, enabled=True)
    gui_set(gui.GOSTOP,
            text='stop',
            button_color=('white', 'red'),
            enabled=True)
    World.links = cached_world_links_set
コード例 #3
0
 def force_as_dxdy(pixel_a: Pixel_xy, pixel_b: Pixel_xy,
                   screen_distance_unit, repulsive):
     """
     Compute the force between pixel_a pixel and pixel_b and return it as a velocity: direction * force.
     """
     direction: Velocity = normalize_dxdy((
         pixel_a - pixel_b) if repulsive else (pixel_b - pixel_a))
     d = pixel_a.distance_to(pixel_b, wrap=False)
     if repulsive:
         dist = max(
             1,
             pixel_a.distance_to(pixel_b, wrap=False) /
             screen_distance_unit)
         rep_coefficient = SimEngine.gui_get('rep_coef')
         rep_exponent = SimEngine.gui_get('rep_exponent')
         force = direction * (10**rep_coefficient) / 10 * dist**rep_exponent
         return force
     else:  # attraction
         dist = max(1, max(d, screen_distance_unit) / screen_distance_unit)
         att_exponent = SimEngine.gui_get('att_exponent')
         force = direction * dist**att_exponent
         # If the link is too short, push away instead of attracting.
         if d < screen_distance_unit:
             force = force * (-1)
         att_coefficient = SimEngine.gui_get('att_coef')
         return 10**(att_coefficient - 1) * force
コード例 #4
0
 def best_random_route(self):
     if SimEngine.gui_get(MIDDLE_ROUTE):
         if BraessParadoxWorld.middle == 0 or BraessParadoxWorld.top == 0 or BraessParadoxWorld.bottom == 0:
             return randint(0, 2)
         else:
             if randint(0, 99) < 100 - SimEngine.gui_get(RANDOMNESS):
                 if BraessParadoxWorld.middle < BraessParadoxWorld.top and BraessParadoxWorld.middle < BraessParadoxWorld.bottom:
                     return 2
                 else:
                     if BraessParadoxWorld.top < BraessParadoxWorld.middle and BraessParadoxWorld.top < BraessParadoxWorld.bottom:
                         return 0
                     else:
                         return 1
             else:
                 return randint(0, 2)
     else:
         if BraessParadoxWorld.top == 0 or BraessParadoxWorld.bottom == 0:
             return randint(0, 1)
         else:
             if randint(0, 99) < 100 - SimEngine.gui_get(RANDOMNESS):
                 if BraessParadoxWorld.top < BraessParadoxWorld.bottom:
                     return 0
                 else:
                     return 1
             else:
                 return randint(0, 1)
コード例 #5
0
    def end_commute(self):
        BraessParadoxWorld.travel_time = (World.ticks - self.birth_tick) / 450
        if BraessParadoxWorld.avg == 0:
            BraessParadoxWorld.avg = BraessParadoxWorld.travel_time
        else:
            BraessParadoxWorld.avg = ((19 * BraessParadoxWorld.avg + BraessParadoxWorld.travel_time) / 20)

        if self.route == 0:
            if BraessParadoxWorld.top == 0:
                BraessParadoxWorld.top = BraessParadoxWorld.travel_time
            else:
                BraessParadoxWorld.top = (BraessParadoxWorld.travel_time + (
                        SimEngine.gui_get(SMOOTHING) - 1) * BraessParadoxWorld.top) / SimEngine.gui_get(SMOOTHING)
        else:
            if self.route == 1:
                if BraessParadoxWorld.bottom == 0:
                    BraessParadoxWorld.bottom = BraessParadoxWorld.travel_time
                else:
                    BraessParadoxWorld.bottom = (BraessParadoxWorld.travel_time + (
                            SimEngine.gui_get(SMOOTHING) - 1) * BraessParadoxWorld.bottom) / SimEngine.gui_get(
                        SMOOTHING)
            else:
                if BraessParadoxWorld.middle == 0:
                    BraessParadoxWorld.middle = BraessParadoxWorld.travel_time
                else:
                    BraessParadoxWorld.middle = (BraessParadoxWorld.travel_time + (
                            SimEngine.gui_get(SMOOTHING) - 1) * BraessParadoxWorld.middle) / SimEngine.gui_get(
                        SMOOTHING)

        # World.agents.remove gave errors, so move the agent to off-road instead
        self.move_to_patch(World.patches[BOTTOM_RIGHT + 3])
        self.set_heading(0)
        print(BraessParadoxWorld.travel_time)
コード例 #6
0
    def best_random_route(self):
        middle_on = SimEngine.gui_get("middle_on")
        randomness = SimEngine.gui_get("randomness")
        middle = Commuter_World.middle
        bottom = Commuter_World.bot
        top = Commuter_World.top

        if middle_on:
            if middle == 0 or bottom == 0 or top == 0:
                return randint(0, 2)
            elif randint(0, 100) < (100 - randomness):
                if middle < top and middle < bottom:
                    return 2
                elif top < middle and top < bottom:
                    return 0
                else:
                    return 1
            else:
                return randint(0, 2)
        elif top == 0 or bottom == 0:
            return randint(0, 1)
        elif randint(0, 100) < (100 - randomness):
            if top < bottom:
                return 0
            else:
                return 1
        else:
            return randint(0, 1)
コード例 #7
0
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        # self.pos_to_switch is a dictionary that maps position values in a binary number to range(8) represented
        # as 3-digit binary strings:
        #     {1: '000', 2: '001', 4: '010', 8: '011', 16: '100', 32: '101', 64: '110', 128: '111'}
        # The three digits are the rule components and the keys to the switches.
        # To see it, try: print(self.pos_to_switch) after executing the next line.
        # The function bin_str() is defined in utils.py

        # The following two lines do the same thing. Explain how both work.
        pos_to_switch_a = {2**i: bin_str(i, 3) for i in range(8)}
        pos_to_switch_b = dict(zip([2**i for i in range(8)], CA_World.bin_0_to_7))
        assert pos_to_switch_a == pos_to_switch_b
        self.pos_to_switch = ...  # pos_to_switch_a or pos_to_switch_b

        # The rule number used for this run, initially set to 110 as the default rule.
        # (You might also try rule 165.)
        # The following sets the local variable self.rule_nbr. It doesn't change the 'Rule_nbr' slider widget.
        self.rule_nbr = 110
        # Set the switches and the binary representation of self.rule_nbr.
        self.set_switches_from_rule_nbr()
        self.set_binary_nbr_from_rule_nbr()
        self.init = None

        # self.ca_lines is a list of lines, each of which is a list of 0/1. Each line represents
        # a state of the CA, i.e., all the cells in the line. self.ca_list contains the entire
        # history of the CA.
        self.ca_lines: List[List[int]] = []
        # gui.WINDOW['rows'].update(value=len(self.ca_lines))
        SimEngine.gui_set('rows', value=len(self.ca_lines))
コード例 #8
0
    def setup(self):
        Agent.id = 0
        Minority_Game_World.steps_to_win = SimEngine.get_gui_value(
            STEPS_TO_WIN)
        # Adjust how far one step is based on number of steps needed to win
        Minority_Game_World.one_step = (
            gui.PATCH_COLS -
            2) * gui.BLOCK_SPACING() / Minority_Game_World.steps_to_win
        # For longer/shorter races, speed up/slow down frames/second
        gui.set_fps(round(6 * Minority_Game_World.steps_to_win / 50))

        # self.done will be True if this a repeat game with the same agents.
        if self.done:
            self.reset_agents()
            return

        # This is the normal setup.
        Minority_Game_World.nbr_agents = SimEngine.get_gui_value(NBR_AGENTS)
        if Minority_Game_World.nbr_agents % 2 == 0:
            Minority_Game_World.nbr_agents += (
                1 if Minority_Game_World.nbr_agents <
                gui.WINDOW[NBR_AGENTS].Range[1] else (-1))
            gui.WINDOW[NBR_AGENTS].update(value=Minority_Game_World.nbr_agents)
        Minority_Game_World.random_agent_ids = {
            0, Minority_Game_World.nbr_agents - 1
        }

        # Generate a random initial history
        self.history_length = SimEngine.get_gui_value(HISTORY_LENGTH)
        self.history = [choice([0, 1]) for _ in range(self.history_length)]

        self.generate_the_agents()
コード例 #9
0
 def select_route(self):
     if SimEngine.gui_get(SELECTION_ALGORITHM) == EMPIRICAL_ANALYTICAl:
         return self.analytical_route()
     if SimEngine.gui_get(SELECTION_ALGORITHM) == PROBABILISTIC_GREEDY:
         return self.probabilistic_greedy_route()
     if SimEngine.gui_get(SELECTION_ALGORITHM) == BEST_RANDOM:
         return self.best_random_route()
コード例 #10
0
    def step(self):
        """
        Take one step in the simulation.
        (a) Generate an additional line for the ca. (Use a copy of self.ca_lines[-1].)
        (b) Extend all lines in ca_lines if the new line is longer (with additional 1's) than its predecessor.
        (c) Trim the new line and add it to the end of self.ca_lines.
        (d) Refresh display from values in self.ca_lines.
        """
        # (a)
        new_line: str = self.generate_new_line_from_current_line(
            self.ca_lines[-1])

        # (b)
        # Extend lines in self.ca_lines at each end as needed. (Don't extend for extra 0's at the ends.)
        # If either end is '1', add '0' to that end of all strings.
        # Can't drop the 0's first because we would lose track of which end was extended.
        ...

        # (c)
        # ==> String-specific <==
        # (Must compare to '1'. Can't just use character as boolean. '0' is treated as True.)
        start = 0 if new_line[0] == '1' else 1
        end = len(new_line) if new_line[-1] == '1' else len(new_line) - 1
        trimmed_new_line: str = new_line[start:end]
        # Add trimmed_new_line to the end of self.ca_lines
        self.ca_lines.append(trimmed_new_line)

        # (d)

        # Refresh the display from self.ca_lines
        self.set_display_from_lines()

        # Update the 'rows' widget.
        SimEngine.gui_set('rows', value=...)
コード例 #11
0
    def flock(self, showing_flockmates):
        # NetLogo allows one to specify the units within the Gui widget.
        # Here we do it explicitly by multiplying by BLOCK_SPACING().
        vision_limit_in_pixels = SimEngine.gui_get('vision') * BLOCK_SPACING()

        flockmates = self.agents_in_radius(vision_limit_in_pixels)

        if len(flockmates) > 0:

            # If showing_flockmates, create links to flockmates if they don't already exist.
            if showing_flockmates:
                for flockmate in flockmates:
                    # Don't make a link if it already exists.
                    if not link_exists(self, flockmate):
                        Link(self, flockmate, color=Color('skyblue3'))

            nearest_neighbor = min(
                flockmates, key=lambda flockmate: self.distance_to(flockmate))

            min_separation = SimEngine.gui_get(
                'minimum separation') * BLOCK_SPACING()
            if self.distance_to(nearest_neighbor) < min_separation:
                self.separate(nearest_neighbor)
            else:
                self.align(flockmates)
                self.cohere(flockmates)
コード例 #12
0
ファイル: ca_outline3.py プロジェクト: rmedina0531/PyLogo
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        # self.pos_to_switch is a dictionary that maps position values in a binary number to range(8) represented
        # as 3-digit binary strings:
        #     {1: '000', 2: '001', 4: '010', 8: '011', 16: '100', 32: '101', 64: '110', 128: '111'}
        # The three digits are the rule components and the keys to the switches.
        # To see it, try: print(self.pos_to_switch) after executing the next line.
        # The function bin_str() is defined in utils.py

        self.pos_to_switch = dict(
            zip([2**i for i in range(8)], CA_World.bin_0_to_7))
        # print(self.pos_to_switch)

        # The rule number used for this run, initially set to 110 as the default rule.
        # (You might also try rule 165.)
        # The following sets the local variable self.rule_nbr. It doesn't change the 'Rule_nbr' slider widget.
        self.rule_nbr = 110
        # Set the switches and the binary representation of self.rule_nbr.
        self.set_switches_from_rule_nbr()
        self.set_binary_nbr_from_rule_nbr()
        self.init = None

        # self.ca_lines is a list of lines, each of which is a list of 0/1. Each line represents
        # a state of the CA, i.e., all the cells in the line. self.ca_list contains the entire
        # history of the CA.
        '''self.ca_lines is that cointains the rows of the 1d automaton, the : in pythion denotes the type that will be assigned to the variable
        in this case A list containing a list of integers. It is initializing this list as empty'''
        self.ca_lines: List[List[int]] = []
        # gui.WINDOW['rows'].update(value=len(self.ca_lines))
        '''this line is setting the number of ca_lines, (the number of rows) to the graphical representation of the CA,
        which in this case will be 0 since it is currently empty'''
        SimEngine.gui_set('rows', value=len(self.ca_lines))
コード例 #13
0
    def setup(self):
        Agent.id = 1
        GA_World.individual_class = TSP_Individual
        GA_World.chromosome_class = TSP_Chromosome.factory

        # The following GUI elements are defined in ga.py.
        # We can't set their default values in this file's GUI.
        # The only way to do it is explicitly.
        gui_set('Max generations', value=float('inf'))
        gui_set('prob_random_parent', value=20)

        # Don't display the following standard GA features.
        for label in ['Discrep:', 'discrepancy', 'Gens:', 'generations']:
            gui_set(label, visible=False)

        TSP_Agent.show_labels = gui_get('show_labels')

        (SimEngine.event, SimEngine.values) = gui.WINDOW.read(timeout=10)
        SimEngine.draw_world()

        # auto_setup is initially True (by default). The next line aborts setup in that case.
        # The purpose is to allow the system to create a display but not run gen_population,
        # which is run when the user clicks setup. That works because auto_setup is set to
        # False by SimEngine after setup run, which happens automatically. So, if auto_setup
        # is False, we will complete setup and generate the initial population.
        if not SimEngine.auto_setup:
            self.msp_links = None
            if gui_get('Animate construction'):
                print(
                    f'\nGenerating the initial population of {gui_get("pop_size")} paths.'
                )
            super().setup()
コード例 #14
0
    def step(self):
        """
        Update the world by moving the agents.
        """
        spawn_rate = SimEngine.gui_get('spawn rate')
        middle_on = SimEngine.gui_get("middle_on")
        delay_on = SimEngine.gui_get("delay")

        # check if the checkboxes have changed (Middle On? and Move by Delay?)
        World.highway.check_delay(middle_on, delay_on)
        World.highway.check_middle(middle_on, delay_on)

        # set the route count of each route to 0
        World.num_top = 0
        World.num_bot = 0
        World.num_mid = 0

        # move the computers
        self.move_commuters()

        # set the patch color and patch delay
        for patch in World.patches:
            if patch.road_type == 1:
                patch.determine_congestion(spawn_rate, World.highway, delay_on)

        # spawn agents
        self.spawn_commuter()
コード例 #15
0
 def build_initial_line(self):
     """
     Construct the initial CA line.
     It is a random line if SimEngine.gui_get('Random?').
     It is a line (of length ca_display_size) of 0's if SimEngine.gui_get('init_line') == ''.
     Otherwise it is the string in SimEngine.gui_get('init_line') converted into 0's and 1's.
     (' ' and '0' are converted to 0; everything else is converted to 1.)
     However, if the rule includes 000 -> 1,pad the line with 0's on both ends to fill the display.
     How much to put on each end depends on the user-specific initial line and the requested justification.
     """
     if SimEngine.gui_get('Random?'):
         line = [choice([0, 1]) for _ in range(self.ca_display_size)] if self.lists else \
                ''.join([choice(['0', '1']) for _ in range(self.ca_display_size)])
     else:
         padding = self.padding_element * (self.ca_display_size)
         if SimEngine.gui_get('init_line') == '':
             line = padding
         else:
             line_0 = SimEngine.gui_get('init_line')
             # Convert line_0 to 0's and 1's
             # Treat '0' and ' ' as "not on".
             line = [0 if c in ' 0' else 1 for c in line_0] if self.lists else \
                    ''.join(['0' if c in ' 0' else '1' for c in line_0])
             if SimEngine.gui_get('000'):
                 justification = SimEngine.gui_get('justification')
                 line_len = len(line)
                 actual_padding = padding[line_len:]
                 line = actual_padding + line if justification == 'Right' else \
                        line + actual_padding if justification == 'Left' else \
                        actual_padding[len(actual_padding)//2:] + line + actual_padding[len(actual_padding)//2:]
     return line
コード例 #16
0
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        # self.pos_to_switch is a dictionary that maps position values in a binary number to range(8) represented
        # as 3-digit binary strings:
        #     {1: '000', 2: '001', 4: '010', 8: '011', 16: '100', 32: '101', 64: '110', 128: '111'}
        # The three digits are the rule components and the keys to the switches.
        # To see it, try: print(self.pos_to_switch) after executing the next line.
        # The function bin_str() is defined in utils.py

        # self.pos_to_switch0 = {2**i: bin_str(i, 3) for i in range(8)}
        self.pos_to_switch = dict(
            zip([2**i for i in range(8)], CA_World.bin_0_to_7))
        # print(self.pos_to_switch0 == self.pos_to_switch)

        # The rule number used for this run, initially set to 110 as the default rule.
        # (You might also try rule 165.)
        # The following sets the local variable self.rule_nbr. It doesn't change the 'Rule_nbr' slider widget.
        self.rule_nbr = 110
        # Set the switches and the binary representation of self.rule_nbr.
        self.set_switches_from_rule_nbr()
        self.set_binary_nbr_from_rule_nbr()

        # self.ca_lines is a list of lines, each of which is a list or string of 0/1. Each line
        # representsa state of the CA, i.e., all the symbols in the line. self.ca_list contains
        # the entire history of the CA.
        self.lists = None
        self.padding_element = None
        self.ca_lines = []
        SimEngine.gui_set('rows', value=len(self.ca_lines))
コード例 #17
0
    def spawn_commuters(self):

        if self.spawn_time >= 250//SimEngine.gui_get('spawn_rate'):
            time = 0
            if SimEngine.gui_get('mode') == selfish:
                route, time = self.route_dict[SimEngine.gui_get('mode')]()
            else:
                route = self.route_dict[SimEngine.gui_get('mode')]()
            # self.agent_class() creates a class at a certain pixel.
            # This line creates an agent at the center pixel of the top left patch.
            new_commuter: Commuter = self.agent_class(spawn_pixel=self.top_left_center_pixel, speed=0.0, birth_tick=self.ticks)
            new_commuter.route = route

            new_commuter.base_speed = new_commuter.base_speed - time
            new_commuter.speed = new_commuter.base_speed

            if new_commuter.route in (middle_road, dynamic_road):
                new_commuter.face_xy(self.top_right_center_pixel)
            # Static Route
            else:
                new_commuter.face_xy(self.bottom_left_center_pixel)

            self.spawn_time = 1

        else:
            self.spawn_time += 1

        # Note we probably won't use 250.
        # track spawn-time, if spawn-time is greater than 250 / spawn-rate,
        # at the patch in the upper left corner, spawn a commuter
        # with several values associated with time spawned, the time it is still commuting,
        # the route it will take, and it's behavior when choosing a route
        pass
コード例 #18
0
    def determine_congestion(self):
        '''Determines the congestion in the top and bottom road segments'''

        #calculate congestion for the top road
        #patches in the top road
        top_road = self.patches_line(self.top_left_patch,
                                     self.top_right_patch)[1:-1]
        top_road_commuters = [
            x for x in World.agents if x.current_patch() in top_road
        ]

        delay = len(top_road_commuters) * SimEngine.gui_get(
            VARIABLE_CONGESTION_DELAY)
        # print(len(top_road_commuters))
        for patch in top_road:
            patch.delay = delay

        #calcultate the congestion for the bottom road
        delay = 1
        bottom_road = self.patches_line(self.bottom_left_patch,
                                        self.bottom_right_patch)[1:-1]
        bottom_road_commuters = [
            x for x in World.agents if x.current_patch() in bottom_road
        ]

        delay = len(bottom_road_commuters) * SimEngine.gui_get(
            VARIABLE_CONGESTION_DELAY)
        for patch in bottom_road:
            patch.delay = delay
コード例 #19
0
 def select_route(self):
     if SimEngine.gui_get(SELECTION_ALGORITHM) == EMPIRICAL_ANALYTICAl:
         return self.probabilistic_analytic()
     if SimEngine.gui_get(SELECTION_ALGORITHM) == PROBABILISTIC_GREEDY:
         return self.greedy()
     if SimEngine.gui_get(SELECTION_ALGORITHM) == BEST_KNOWN:
         return self.best_route()
コード例 #20
0
    def setup(self):
        """
        Set up for state 1. Build the contraption piece by piece.
        """
        self.top_spring = Braess_Link.vertical_linked_nodes(Braess_Link, self.x, Braess_World.top)

        self.top_cord = self.top_spring.extend_linked_nodes(Braess_Cord)

        self.bottom_spring = self.top_cord.extend_linked_nodes(Braess_Link)

        self.weight_cord = self.bottom_spring.extend_linked_nodes(Braess_Cord)

        # Make node_2 of the weight_cord the weight.
        Braess_World.weight_node = self.weight_cord.node_2
        Braess_World.weight_node.shape_name = CIRCLE
        Braess_World.weight_node.color = Color('plum4')

        #                            ## Done with building state 1. ##                            #

        self.adjustable_links = [self.top_spring, self.top_cord, self.bottom_spring, self.weight_cord]

        SimEngine.gui_set(Braess_World.CUT_CORD, enabled=False)
        Braess_World.state = 1
        Agent.some_agent_changed = True

        # In case we did the animation in slow motion and this is a second run.
        # Can't do this when animation ends because we want to stay
        # in slow motion as the springs contract and lift the weight.
        SimEngine.fps = 60
コード例 #21
0
    def step(self):

        # If we are doing animation:
        if Braess_World.state == 'a':
            if not Agent.key_step_done:
                Agent.run_an_animation_step()
            else:
                self.setup_2()
            return

        # We are not doing animation. We are in either state_1 or state_2. Process them normally.
        # If there was a change during the previous step, see if additional changes are needed.
        if Agent.some_agent_changed:
            # When a link changes length, Agent.some_agent_changed is set to True.
            Agent.some_agent_changed = False
            for lnk in self.adjustable_links:
                lnk.adjust_nodes()
        else:
            # Since no agent changed on the previous step, we're done with this state.

            # "Click" the STOP button.
            gui.WINDOW[GOSTOP].click()

            # Enable/disable the Cut-cord button depending on whether we are leaving state 1.
            SimEngine.gui_set(Braess_World.CUT_CORD, enabled=(Braess_World.state == 1))
コード例 #22
0
    def determine_congestion(self):
        trafic_variable_top_road = self.draw_line(self.top_left,
                                                  self.top_right)[1:-1]
        trafic_variable_top_road_commuters = [
            x for x in World.agents
            if x.current_patch() in trafic_variable_top_road
        ]

        delay = len(trafic_variable_top_road_commuters) * SimEngine.gui_get(
            VARIABLE_CONGESTION_DELAY)

        for patch in trafic_variable_top_road:
            patch.delay = delay

        #calcultate the congestion for the bottom road
        delay = 1
        bottom_road = self.draw_line(self.bottom_left, self.bottom_right)[1:-1]
        bottom_road_commuters = [
            x for x in World.agents if x.current_patch() in bottom_road
        ]

        delay = len(bottom_road_commuters) * SimEngine.gui_get(
            VARIABLE_CONGESTION_DELAY)
        for patch in bottom_road:
            patch.delay = delay
コード例 #23
0
 def build_initial_line(self):
     """
     Construct the initial CA line.
     It is a random line if SimEngine.gui_get('Random?').
     It is a line (of length ca_display_size) if SimEngine.gui_get('init_line') == ''.
     Otherwise it is the string in SimEngine.gui_get('init_line') converted into 0's and 1's.
     (' ' and '0' are converted to 0; everything else is converted to 1.) 
     However, if the rule includes 000 -> 1,pad the line with 0's on both ends to fill the display.
     How much to put on each end depends on the user-specific initial line and the requested justification.
     """
     if SimEngine.gui_get('Random?'):
         line = ...
     else:
         # A line of 0's.
         padding = [0] * (self.ca_display_size)
         if SimEngine.gui_get('init_line') == '':
             line = padding
         else:
             line_0 = SimEngine.gui_get('init_line')
             # Convert line_0 to 0's and 1's
             line = [... for c in line_0]
             # If the rule include 000 -> 1, fill out the new line with 0's.
             if SimEngine.gui_get('000'):
                 justification = SimEngine.gui_get('justification')
                 line_len = len(line)
                 actual_padding = padding[line_len:]
                 line = ... if justification == 'Right' else \
                        ... if justification == 'Left' else \
                        ... #  justification == 'Center'
     return line
コード例 #24
0
    def selfish_route(self):
        agents_on_dynamic_road = 0
        agents_on_static_road = 0
        agents_on_middle_road = 0

        for commuter in self.agents:
            if commuter.route == dynamic_road:
                agents_on_dynamic_road += 1
            elif commuter.route == static_road:
                agents_on_static_road += 1
            else:
                agents_on_middle_road += 1

        static_road_rate = SimEngine.gui_get('static')
        dynamic_road_rate = SimEngine.gui_get('dynamic')

        static_road_time = static_road_rate + (
            agents_on_middle_road + agents_on_static_road) / dynamic_road_rate
        middle_road_time = ((agents_on_dynamic_road + agents_on_middle_road) / dynamic_road_rate) \
                           + ((agents_on_static_road + agents_on_middle_road) / dynamic_road_rate)
        dynamic_road_time = (agents_on_dynamic_road /
                             dynamic_road_rate) + static_road_rate

        if SimEngine.gui_get('middle_on'):
            three_roads = [(static_road, static_road_time / 20),
                           (middle_road, middle_road_time / 20),
                           (dynamic_road, dynamic_road_time / 20)]
            selection = min(three_roads, key=lambda x: x[1])
        else:
            two_roads = [(static_road, static_road_time / 20),
                         (dynamic_road, dynamic_road_time / 20)]
            selection = min(two_roads, key=lambda x: x[1])

        return selection
コード例 #25
0
def PyLogo(world_class=World,
           caption=None,
           gui_left_upper=None,
           gui_right_upper=None,
           agent_class=Agent,
           patch_class=Patch,
           auto_setup=True,
           patch_size=11,
           board_rows_cols=(51, 51),
           clear=None,
           bounce=None,
           fps=None):
    if gui_left_upper is None:
        gui_left_upper = []
    if caption is None:
        caption = utils.extract_class_name(world_class)
    sim_engine = SimEngine(gui_left_upper,
                           caption=caption,
                           gui_right_upper=gui_right_upper,
                           patch_size=patch_size,
                           board_rows_cols=board_rows_cols,
                           clear=clear,
                           bounce=bounce,
                           fps=fps)
    gui.WINDOW.read(timeout=10)

    the_world = world_class(patch_class, agent_class)

    gui.WINDOW.read(timeout=10)
    sim_engine.top_loop(the_world, auto_setup=auto_setup)
コード例 #26
0
 def make_switches_and_rule_nbr_consistent(self):
     """
     Make the Slider, the switches, and the bin number consistent: all should contain self.rule_nbr.
     """
     # gui.WINDOW['Rule_nbr'].update(value=self.rule_nbr)
     SimEngine.gui_set('Rule_nbr', value=self.rule_nbr)
     self.set_switches_from_rule_nbr()
     self.set_binary_nbr_from_rule_nbr()
コード例 #27
0
    def mutate(self) -> Individual:
        if randint(0, 100) <= SimEngine.gui_get('replace_gene'):
            (self.chromosome, self.fitness, _) = self.replace_gene_in_chromosome(self.fitness, self.chromosome)

        if randint(0, 100) <= SimEngine.gui_get('reverse_subseq'):
            self.chromosome = self.reverse_subseq(self.chromosome)
            self.fitness = self.compute_fitness()

        return self
コード例 #28
0
 def __init__(self, **kwargs):
     color = SimEngine.gui_get(COLOR)
     color = Color(color) if color != RANDOM else None
     if 'shape_name' not in kwargs:
         shape_name = SimEngine.gui_get(SHAPE)
         kwargs['shape_name'] = shape_name
     super().__init__(color=color, **kwargs)
     # Is the  node selected?
     self.selected = False
コード例 #29
0
 def init_globals(self):
     gb.randomness = SimEngine.gui_get('Randomness')
     gb.mode = SimEngine.gui_get('Algorithm')
     gb.middle_on = SimEngine.gui_get('Middle')
     gb.spawn_rate = SimEngine.gui_get('Spawn Rate')
     gb.smoothing = SimEngine.gui_get('Smoothing')
     gb.top_left = World.patches_array[4, 4]
     gb.top_right = World.patches_array[4, 46]
     gb.bottom_right = World.patches_array[46, 46]
     gb.bottom_left = World.patches_array[46, 4]
コード例 #30
0
 def setup(self):
     # Create a list of Individuals as the initial population.
     # self.pop_size must be even since we generate children two at a time.
     self.pop_size = (SimEngine.gui_get('pop_size')//2)*2
     self.tournament_size = SimEngine.gui_get('tourn_size')
     GA_World.fitness_target = SimEngine.gui_get('fitness_target')
     self.population = self.initial_population()
     self.best_ind = None
     self.generations = 0
     self.set_results()