Example #1
0
 def __init__(self):
     self.console = Console()
     self.landscape = Landscape()
     self.display = Display(self.landscape, self.console)
     self.control = Controller(self.console)
     self.cursorX = 2
     self.cursorY = 2
Example #2
0
def test_is_valid_position():
    x = 10
    y = 10
    nb_patches = 0
    landscape = Landscape(x, y, nb_patches)
    assert not landscape.is_valid_position(x, y-1)
    assert not landscape.is_valid_position(0, -1)
    assert landscape.is_valid_position(5, 5)
Example #3
0
def test_resources_which_can_be_eaten():
    x = 10
    y = 10
    nb_patches = 0
    x_pos = 4
    y_pos = 6
    resource_dim = 75
    landscape = Landscape(x, y, nb_patches)
    landscape.land[x_pos, y_pos] = resource_dim
    assert landscape.resources_which_can_be_eaten(x_pos, y_pos) == resource_dim
Example #4
0
def test_landscape_creation():
    x = 10
    y = 10
    nb_patches = 3
    landscape = Landscape(x, y, nb_patches)
    assert landscape.land.shape == (x, y)
    assert (landscape.land > 0).sum() >= nb_patches

    too_many_patch = x * y + 1
    with pytest.raises(Exception):
        Landscape(x, y, too_many_patch)
Example #5
0
 def __init__(self, dim_arg=DEFAULT_DIM, move_vec_arg=DEFAULT_MOVE_VECTORS):
     self.dim = dim_arg
     self.move_vectors = move_vec_arg
     self.landscape = Landscape(self.dim)
     self.cur_location = ([int(self.dim / 2), int(self.dim / 2)])
     self.cur_location = tuple(self.cur_location)
     self.path_target = None
     self.default_chance = 1 / (self.dim * self.dim)
     self.likelihood = np.ones(shape=(self.dim, self.dim))
     self.likelihood *= self.default_chance
     self.query_counter = np.zeros((self.dim, self.dim))
     self.cur_path_target = None
Example #6
0
def getLandscape():
    # itesm representing end of the world at both edges
    image = globals.IMAGESDICT['corner']
    negativeRect = pygame.Rect([-150, globals.WINHEIGHT - globals.TILEHEIGHT, globals.TILEWIDTH, globals.TILEHEIGHT])
    landscape = Landscape(image, negativeRect)
    allLandscapeList.add(landscape)
    allSpriteList.add(landscape)

    image = globals.IMAGESDICT['corner']
    positiveRect = pygame.Rect([globals.LEVEL[0] - globals.TILEWIDTH, globals.WINHEIGHT - globals.TILEHEIGHT, globals.TILEWIDTH, globals.TILEHEIGHT])
    landscape = Landscape(image, positiveRect)
    allLandscapeList.add(landscape)
    allSpriteList.add(landscape)
    return
Example #7
0
def getInitialObstacles():
    """ gets the position of the initial blocks """
    # hardcode number of blocks
    # will account for movemnet
    from random import choice
    from globals import TILEWIDTH, TILEHEIGHT, WINHEIGHT, TILEFLOORHEIGHT, LEVEL, HALFWINWIDTH

    no_of_blocks = 50
    for b in range(no_of_blocks // 2):
        # get image
        # image = globals.IMAGESDICT['rock']
        for y in range(1,5):
            image = globals.IMAGESDICT[choice(['ugly tree', 'rock', 'tall tree'])]
            # make rect
            spaceRect = pygame.Rect((b * TILEWIDTH, y * TILEFLOORHEIGHT, TILEWIDTH, TILEFLOORHEIGHT))
            landscape = Landscape(image, spaceRect)
            allLandscapeList.add(landscape)
            allSpriteList.add(landscape)

    image = globals.IMAGESDICT['corner']
    negativeRect = pygame.Rect([-150, WINHEIGHT - TILEHEIGHT, TILEWIDTH, TILEHEIGHT])
    landscape = Landscape(image, negativeRect)
    allLandscapeList.add(landscape)
    allSpriteList.add(landscape)

    image = globals.IMAGESDICT['corner']
    positiveRect = pygame.Rect([LEVEL[0] - TILEWIDTH, WINHEIGHT - TILEHEIGHT, TILEWIDTH, TILEFLOORHEIGHT])
    landscape = Landscape(image, positiveRect)
    allLandscapeList.add(landscape)
    allSpriteList.add(landscape)

    bottomRect = pygame.Rect([HALFWINWIDTH, LEVEL[1] - TILEHEIGHT, TILEWIDTH, TILEFLOORHEIGHT])
    landscape = Landscape(image, bottomRect)
    allLandscapeList.add(landscape)
    allSpriteList.add(landscape)

    for x in range(0, LEVEL[0], 50):
        for y in range(10):
            image = globals.IMAGESDICT[choice(['ugly tree', 'rock', 'tall tree'])]
            spaceRect = pygame.Rect((x, LEVEL[1] - (y * TILEHEIGHT), TILEWIDTH, TILEFLOORHEIGHT))
            landscape = Landscape(image, spaceRect)
            if choice([0,1,0]):
                allLandscapeList.add(landscape)
                allSpriteList.add(landscape)


    return
Example #8
0
    def bayes_update_on_move(self):
        # Fetch the observation on boundry crossing from the landscape
        clue = self.landscape.get_last_transition()
        if clue is None:
            return
        target_move_vectors = Landscape.get_target_move_vectors()

        other_t_ids = np.zeros((self.dim, self.dim)) - 1
        num_moves_arr = np.zeros((self.dim, self.dim))
        for x in range(self.dim):
            for y in range(self.dim):
                coords = (x, y)
                t_id = self.landscape.t_id_map[coords]
                if t_id not in clue:
                    other_t_id = -1
                    continue
                if t_id == clue[0]:
                    other_t_id = clue[1]
                else:
                    other_t_id = clue[0]
                other_t_ids[coords] = other_t_id

                # Calculate the number of moves from (x,y) that match the
                # transition description
                neighbors = coords + target_move_vectors
                for neighbor in neighbors:
                    neighbor = tuple(neighbor)
                    if not self.in_bounds(neighbor):
                        continue
                    if self.landscape.t_id_map[neighbor] == other_t_id:
                        num_moves_arr[coords] += 1

        new_belief = np.zeros((self.dim, self.dim))
        for x in range(self.dim):
            for y in range(self.dim):
                coords = (x, y)
                # Get the t_id of the terrain we're on and the prev terrain
                t_id = self.landscape.t_id_map[coords]
                other_t_id = other_t_ids[coords]
                if other_t_id == -1:
                    continue

                poss_prev_locations = coords - target_move_vectors

                for neighbor in poss_prev_locations:
                    neighbor = tuple(neighbor)
                    if not self.in_bounds(neighbor):
                        continue
                    # neighbor is
                    if self.landscape.t_id_map[neighbor] != other_t_id:
                        # Filter out wrong t_id
                        continue
                    num_trans = num_moves_arr[neighbor]
                    new_belief[coords] += ((1 / num_trans) *
                                           self.likelihood[neighbor])

        self.likelihood = new_belief
        self.likelihood /= np.sum(self.likelihood)
Example #9
0
class Simulation:
	def __init__(self, size=200, r1=3, r2=5, r3=10, r4=10, load_filename=None):
		self.landscape = Landscape(size, size, self, r1, r2, r3, r4, load_filename)
		if not load_filename:
			self.agents = set()
			for i in range(100): #200
				self.add_agent(Agent(self.landscape, self))

	def step(self, phase, maNum=10, miNum=400, byNum=2000, brNum=5000, buNum=400, pDecay=0.75, tDecay=0.25, corNum=5):
		self.landscape.step(phase, maNum, miNum, byNum, brNum, buNum, pDecay, tDecay, corNum)
		killlist = []
		for agent in list(self.agents):
			agent.step(self.landscape)
			if agent.water < 0 or agent.resource < 0:
				killlist.append(agent)
		for agent in killlist:
			self.kill(agent)
		gc.collect()

	def add_agent(self, agent):
		self.agents.add(agent)

	def kill(self, agent):
		self.agents.discard(agent)
		self.landscape.remove_agent(agent)

	def view(self, step):
		return self.landscape.view(step)

	def output(self, filedir):
		self.landscape.output(filedir)
Example #10
0
class Main:
    def __init__(self):
        self.console = Console()
        self.landscape = Landscape()
        self.display = Display(self.landscape, self.console)
        self.control = Controller(self.console)
        self.cursorX = 2
        self.cursorY = 2

    def run(self):
        exit = False
        while not exit:
            self.display.setCursorPosition(self.cursorX, self.cursorY)
            self.display.draw()
            userinput = self.control.getKey()
            if userinput == self.control.QUIT:
                exit = True
            else:
                self.processinput(self.control.buffer)

        self.console.gotoLine(self.landscape.height + 3)
        self.console.printText(self.landscape.generateCode())

    def processinput(self, command):
        if command.endswith(self.control.UP) and self.cursorY > 0:
            self.cursorY = self.cursorY - 1

        if command.endswith(self.control.DOWN
                            ) and self.cursorY < self.landscape.height - 1:
            self.cursorY = self.cursorY + 1

        if command.endswith(self.control.LEFT) and self.cursorX > 0:
            self.cursorX = self.cursorX - 1

        if command.endswith(self.control.RIGHT
                            ) and self.cursorX < self.landscape.width - 1:
            self.cursorX = self.cursorX + 1

        if command.endswith(self.control.SET):
            self.landscape.set(self.cursorX, self.cursorY)

        if command.endswith(self.control.CLEAR):
            self.landscape.clear(self.cursorX, self.cursorY)

        if command.endswith(self.control.CLEARLINE):
            self.landscape.clearLine(self.cursorY)

        if command.endswith(self.control.COPYLINEABOVE) and self.cursorY > 0:
            self.landscape.copyLine(self.cursorY - 1, self.cursorY)
Example #11
0
def testing(input_a,plan,itern=10):
    sum = 0.0
    for _ in range(itern):
        im_list = input_a
        inf = construct_influence_matrix_from_list(im_list)
        fit1 = FitnessContributionTable(inf)
        land1 = Landscape(fitness_contribution_matrix = fit1)
        land1.compute_all_locations_id(plan)
        land1.standardize()
        sum+= count_local_peak(land1,False) 
    return sum / float(itern)
Example #12
0
def test_add_resources_as_patch():
    x = 10
    y = 10
    nb_patches = 0
    x_pos = 4
    y_pos = 6
    resource_dim = 75
    landscape = Landscape(x, y, nb_patches)
    landscape.add_resources_as_patch(x_pos, y_pos, resource_dim)
    assert landscape.land[x_pos, y_pos] == resource_dim
    assert (landscape.land[landscape.land != resource_dim] < resource_dim).all()
    assert (landscape.land[landscape.land != resource_dim] > 0).any()

    landscape.add_resources_as_patch(x_pos, y_pos, resource_dim)
    assert landscape.land[x_pos, y_pos] == Landscape.MAX_VALUE
Example #13
0
def data_likelihood(trials,
                    sbert_model_name,
                    initial_max_activation=1.0,
                    initial_decay_rate=0.1,
                    initial_memory_capacity=5.0,
                    initial_learning_rate=0.9,
                    initial_semantic_strength_coeff=1.0):
    """
    Generalized cost function for fitting the Landscape model optimized using the numba library.
    
    Output scales inversely with the likelihood that the model and specified parameters would generate the specified
    trials. For model fitting, is usually wrapped in another function that fixes and frees parameters for optimization.

    **Arguments**:
    - trials: int64-array where rows identify a unique trial of responses and columns corresponds to a unique recall
      index.
    - A configuration for each parameter of model

    **Returns** the negative sum of log-likelihoods across specified trials conditional on the specified parameters and
    the mechanisms of InstanceCMR.
    """

    model = Landscape(sbert_model_name, initial_max_activation,
                      initial_decay_rate, initial_memory_capacity,
                      initial_learning_rate, initial_semantic_strength_coeff)

    model.experience(np.eye(item_count, item_count + 1, 1))

    likelihood = np.ones(np.shape(trials))

    for trial_index in range(len(trials)):
        trial = trials[trial_index]

        for recall_index in range(len(trial)):
            recall = trial[recall_index]
            likelihood[trial_index, recall_index] = \
                model.outcome_probabilities()[recall]
            model.force_recall(recall)
            if recall == 0:
                break

    return -np.sum(np.log(likelihood))
Example #14
0
    def task(self, node, number_of_nodes, pipes):

        width = 10  # Landscape width
        height = 10  # Landscape height
        densitylimit = 50  # Density above which agents move.
        number_of_agents = 1000
        node_number_of_agents = 0
        iterations = 100  # Model iterations before stopping
        agents = []

        # Setup landcsape.

        landscape = Landscape()
        landscape.width = width
        landscape.height = height

        pipe_to_zero = None

        # Setup agents

        if (node != 0):

            node_number_of_agents = int(number_of_agents /
                                        (number_of_nodes - 1))

            if (node == (number_of_nodes - 1)):
                node_number_of_agents = int(node_number_of_agents +
                                            (number_of_agents %
                                             (number_of_nodes - 1)))

            pipe_to_zero = pipes[node - 1]

            for i in range(node_number_of_agents):

                agents.append(Agent())
                agents[i].densitylimit = densitylimit
                agents[
                    i].landscape = landscape  # Agents get a reference to the
                # landscape to interrogate for densities.
                # They could also get a reference to the
                # agent list if agents need to talk,
                # but here they don't.

                # Allocate agents a start location.

                x = int(width / 2)  # Set to middle for start
                y = int(height / 2)  # Set to middle for start

                agents[i].x = x
                agents[i].y = y

            # Give the landscape a reference to the agent list so it
            # can find out where they all are and calculate densities.

            landscape.agents = agents

        # Print start map

        # Run

        for time in range(iterations):

            # Send out the local densities to node zero

            if (node != 0):

                landscape.calc_densities()

                densities = landscape.getdensities()

                pipe_to_zero.send(densities)

            else:  # if node is node zero

                # Get the local densities in to node zero

                densities = []
                for x in range(width):
                    for y in range(height):
                        densities.append(0)

                for i in range(len(pipes)):

                    # Get the local density from each node i.

                    local_densities = pipes[i].recv()

                    # Add node i's density surface to the global surface.

                    for x in range(width):
                        for y in range(height):
                            densities[(y * width) + x] = densities[
                                (y * width) +
                                x] + local_densities[(y * width) + x]

            # Send out the global densities to the nodes

            if (node == 0):

                for i in range(len(pipes)):

                    pipes[i].send(densities)

            else:

                # Receive the global densities from node zero.

                global_densities = pipe_to_zero.recv()

                landscape.setdensities(global_densities)

                # Move the agents if the density is too high.

                for i in range(node_number_of_agents):

                    agents[i].step()

            # Report

            if (node == 0):
                print("time = ", time, " -------------------")
                landscape.setdensities(densities)
                for x in range(width):
                    for y in range(height):
                        print(landscape.getdensityat(x, y), end=" ")
                    print("")
Example #15
0
class LsFinder:
    """Performs the probabilistic search on a randomly generated landscape
    """

    # pylint: disable=too-many-instance-attributes

    def __init__(self, dim_arg=DEFAULT_DIM, move_vec_arg=DEFAULT_MOVE_VECTORS):
        self.dim = dim_arg
        self.move_vectors = move_vec_arg
        self.landscape = Landscape(self.dim)
        self.cur_location = ([int(self.dim / 2), int(self.dim / 2)])
        self.cur_location = tuple(self.cur_location)
        self.path_target = None
        self.default_chance = 1 / (self.dim * self.dim)
        self.likelihood = np.ones(shape=(self.dim, self.dim))
        self.likelihood *= self.default_chance
        self.query_counter = np.zeros((self.dim, self.dim))
        self.cur_path_target = None

    def reset_all(self):
        """Resets the finder with a new map and recenters the cur_location
        """
        self.landscape = Landscape(self.dim)
        self.reset_finder()

    def reset_finder(self):
        """Resets the finder with the same map and recenters the cur_location
        """
        self.cur_location = ([int(self.dim / 2), int(self.dim / 2)])
        self.cur_location = tuple(self.cur_location)
        self.likelihood = np.ones(shape=(self.dim, self.dim))
        self.likelihood *= self.default_chance
        self.query_counter = np.zeros((self.dim, self.dim))
        self.cur_path_target = None

    def search_cell(self, coords):
        debug_print(f"Searching in spot [{coords}]", 8)
        self.query_counter[coords] += 1
        # searches the cell and moves the target if not found
        if self.landscape.query_tile(coords):
            # print(f"Target has been found in [{x},{y}]")
            return True
        self.bayes_update_on_miss(coords)
        if self.landscape.is_target_moving:
            self.bayes_update_on_move
        # print(self.likelihood)
        return False

    def bayes_update_on_miss(self, miss_coords):
        """Performs the bayesian update on a miss on a certain cell

            Parameters
            ----------
            miss_coords : (int, int)
                Coordinate tuple of where the miss observation occurred

            Returns
            -------
            float
                the new probability that is in the miss_coords spot
        """
        false_neg_chance = self.landscape.prob_map[miss_coords]
        original_belief = self.likelihood[miss_coords]
        new_belief = original_belief * false_neg_chance
        self.likelihood[miss_coords] = new_belief
        self.likelihood /= np.sum(self.likelihood)
        return new_belief

    def bayes_update_on_move(self):
        # Fetch the observation on boundry crossing from the landscape
        clue = self.landscape.get_last_transition()
        if clue is None:
            return
        target_move_vectors = Landscape.get_target_move_vectors()

        other_t_ids = np.zeros((self.dim, self.dim)) - 1
        num_moves_arr = np.zeros((self.dim, self.dim))
        for x in range(self.dim):
            for y in range(self.dim):
                coords = (x, y)
                t_id = self.landscape.t_id_map[coords]
                if t_id not in clue:
                    other_t_id = -1
                    continue
                if t_id == clue[0]:
                    other_t_id = clue[1]
                else:
                    other_t_id = clue[0]
                other_t_ids[coords] = other_t_id

                # Calculate the number of moves from (x,y) that match the
                # transition description
                neighbors = coords + target_move_vectors
                for neighbor in neighbors:
                    neighbor = tuple(neighbor)
                    if not self.in_bounds(neighbor):
                        continue
                    if self.landscape.t_id_map[neighbor] == other_t_id:
                        num_moves_arr[coords] += 1

        new_belief = np.zeros((self.dim, self.dim))
        for x in range(self.dim):
            for y in range(self.dim):
                coords = (x, y)
                # Get the t_id of the terrain we're on and the prev terrain
                t_id = self.landscape.t_id_map[coords]
                other_t_id = other_t_ids[coords]
                if other_t_id == -1:
                    continue

                poss_prev_locations = coords - target_move_vectors

                for neighbor in poss_prev_locations:
                    neighbor = tuple(neighbor)
                    if not self.in_bounds(neighbor):
                        continue
                    # neighbor is
                    if self.landscape.t_id_map[neighbor] != other_t_id:
                        # Filter out wrong t_id
                        continue
                    num_trans = num_moves_arr[neighbor]
                    new_belief[coords] += ((1 / num_trans) *
                                           self.likelihood[neighbor])

        self.likelihood = new_belief
        self.likelihood /= np.sum(self.likelihood)

    def move_on_path(self):
        # TODO implement path walking
        pos = self.cur_location
        target = self.cur_path_target
        if pos == target:
            return
        elif pos[0] < target[0]:
            self.cur_location = (pos[0] + 1, pos[1])
            return
        elif pos[0] > target[0]:
            self.cur_location = (pos[0] - 1, pos[1])
            return
        elif pos[1] < target[1]:
            self.cur_location = (pos[0], pos[1] + 1)
            return
        elif pos[1] > target[1]:
            self.cur_location = (pos[0], pos[1] - 1)
            return

    def search_target(self,
                      rule_num,
                      search_approach,
                      target_moving_arg=False):
        """Runs a certain algorithm to search for the target on a certain map
        """

        search_approach = search_approach.lower()
        total_steps = 0
        self.landscape.is_target_moving = target_moving_arg

        # Rule 1 -> likelihood that the target is in a cell
        # Rule 2 -> likelihood that the target is found in a cell
        if rule_num == 1:

            def score_matrix():
                return self.likelihood
        elif rule_num == 2:

            def score_matrix():
                return np.multiply(self.likelihood,
                                   1 - self.landscape.prob_map)
        else:
            error_print("Invalid rule number", 0)
            return -1

        # def coords_to_chance(coords):
        #     coords = tuple(coords)
        #     if not self.in_bounds(coords):
        #         return -1
        #     scores = score_matrix()
        #     return scores[coords]

        def best_global_cell():
            index = np.argmax(score_matrix())
            index = np.unravel_index(index, (self.dim, self.dim))
            return index

        def best_close_cell():
            '''Smarter algorithm that weighs in distance'''
            # TODO write this
            scores = np.copy(score_matrix())
            dists = np.zeros((self.dim, self.dim))
            for x in range(self.dim):
                for y in range(self.dim):
                    coords = (x, y)
                    dist = cell_dist(coords, self.cur_location)
                    dists[coords] = dist + 1

            # dists -= self.dim
            # dists = np.arctan(dists)
            # dists *= -(1/pi)
            # dists += 1/2
            # scores = np.multiply(scores, dists)
            scores = np.divide(scores, dists)

            index = np.argmax(scores)
            index = np.unravel_index(index, (self.dim, self.dim))
            return index

        # Set the decide_path and agent_search algorithm
        if search_approach == 'global':
            # No pathing always searches the best global
            def decide_path_global():
                self.cur_path_target = None
                return

            def agent_search_global():
                coords = best_global_cell()
                return self.search_cell(coords)

            decide_path = decide_path_global
            agent_search = agent_search_global
        elif search_approach == 'path_simple':
            # Travels to the best cell then searches it
            def decide_path_simple():
                if self.cur_path_target is None:
                    self.cur_path_target = best_global_cell()
                if self.cur_location == self.cur_path_target:
                    self.cur_path_target = None

            def agent_search_simple():
                return self.search_cell(self.cur_location)

            decide_path = decide_path_simple
            agent_search = agent_search_simple
        elif search_approach == 'path_smart':

            def decide_path_smart():
                if self.cur_path_target is None:
                    # TODO replace best_global_cell() with scoring func
                    self.cur_path_target = best_close_cell()
                if self.cur_location == self.cur_path_target:
                    self.cur_path_target = None

            def agent_search_smart():
                # debug_print(f'Searching: {self.cur_location}', 5)
                return self.search_cell(self.cur_location)

            decide_path = decide_path_smart
            agent_search = agent_search_smart

        target_found = False
        while not target_found:
            total_steps += 1
            # Sets the path to none if no movement needed
            decide_path()
            if self.cur_path_target is None:
                target_found = agent_search()
            else:
                self.move_on_path()
        return total_steps

    def in_bounds(self, coords):
        return self.landscape.in_bounds(coords)

    def run_trials(self, num_trials, search_rule):
        total_steps = 0
        for __ in range(0, num_trials):
            self.reset_all()
            target_found = False
            while not target_found:
                target_found = search_rule()
                total_steps += 1
        return total_steps / num_trials

    def p_state(self):
        print(self.likelihood)
        print('Current Path Target')
        print(self.cur_path_target)
        print('Current Position')
        print(self.cur_location)
Example #16
0
	def __init__(self, size=200, r1=3, r2=5, r3=10, r4=10, load_filename=None):
		self.landscape = Landscape(size, size, self, r1, r2, r3, r4, load_filename)
		if not load_filename:
			self.agents = set()
			for i in range(100): #200
				self.add_agent(Agent(self.landscape, self))
Example #17
0
def parallel_settlements(grid):

    # generate a random seed, use it and store it

    random_seed = round(np.random.random() * 1000000)
    np.random.seed(random_seed)
    file_seed = open(directorySettlements + subpath + 'randomSeeds.txt', 'a')
    file_seed.write(
        str(scenario['interactionW']) + "," + str(grid) + "," +
        str(random_seed) + '\n')
    file_seed.close()

    # read the previously generated landscape object (the grid)

    lscape = Landscape()
    lscape.pkl_import(path=directoryLandscapes + 'landscape' + str(grid) +
                      '.pkl')

    # start with an empty list of distributions

    settlements = []

    # loop over multiple distributions

    for distribution in range(0, nDistributions):

        # print message to keep track of the progress

        print("Generating settlement " + str(distribution) + " on grid " +
              str(grid))

        # sample the random number of individuals

        if nIndividualsMin < nIndividualsMax:
            n_individuals = np.random.randint(low=nIndividualsMin,
                                              high=nIndividualsMax)
        else:
            n_individuals = nIndividualsMin

        # new settlement object

        settlements.append(
            Settlement(interaction_w=interactionW, landscape=lscape))

        # set the response of the species to the different variables

        for index, label in enumerate(varLabel):
            settlements[distribution].set_weight(label=label,
                                                 weight=varWeight[index])

        # place the individuals in the grid using gibbs sampling

        settlements[distribution].gibbs(n_individuals=n_individuals,
                                        n_iterations=n_individuals *
                                        nSelections)

        # save the distribution

        settlements[distribution].export_to_pkl(
            path=directorySettlements + subpath + 'settlement' + str(grid) +
            '_' + str(distribution) + ".pkl")
Example #18
0
from debug_render import QuadtreeRender
from engine import Engine
from landscape import Landscape
from rocket import Rocket

engine = Engine()
engine.global_scale = 0.1
engine.add_static_object(Landscape())
engine.add_game_object(QuadtreeRender(engine.quadtree))
engine.add_dynamic_object(Rocket())

engine.loop()
Example #19
0
 def __init__(self, complexity=8, width=1000, height=800, margin=100):
     world = Landscape(terrain=[
         ground(margin, margin, width - margin, height - margin)
         for i in range(complexity)
     ])
     self.board = Simulator(world, width=width, height=height)
Example #20
0
        print(f"t = {t:4.32}, alive = {len(agentList.agentList)}\n{bMap}")

    if PAUSE:
        # Print nice statistics and await input
        # Empty input == continue to next event
        print(nice_statistics(agentList, t))
        repeatInput = True
        while repeatInput:
            uInput = input(f"Input t={t}> ")
            repeatInput = interpret(uInput, agentList, calendar, landscape,
                                    calendar.now())


rng = RNG(SEED)
eventList = EventCalendar()
landscape = Landscape(ROWS, COLUMNS, rng=rng)
agentList = AgentList(AGENTS, landscape, eventList, rng=rng)

eventList.set_preevent(preoperation, landscape, eventList)
eventList.set_postevent(postoperation, landscape, eventList, agentList)

## Pre simulation ##
print(f"Seed: {SEED}")
print(nice_statistics(agentList, 0))
init_map = str_map(landscape, showSugar=SHOW_SUGAR)

## Simulation ##
eventList.run(MAX_T)

## Post simulation ##
t = eventList.now()
Example #21
0
from landscape import Landscape
from sprite import FrameSprite
from Rain import Rain
from Client import Client
from time import sleep

volcano = FrameSprite("volcano",
                      shift=(5, 0),
                      num_frames=3,
                      update_time=1000,
                      color_map={
                          "*": (105, 105, 105),
                          "@": (255, 0, 0)
                      })
rain = Rain("rain", zval=100)
background = Landscape()

name = "weather-led-test" if background.test else "weather-led"
client = Client(name, "https://central-socket.herokuapp.com/")


def onWeatherChange(weather):
    if (isinstance(weather, list)):
        weather = weather[0]
    if weather == 'hot':
        background.add_sprite(volcano)
    elif weather == 'cold':
        background.remove_sprite(volcano)

    if weather == 'rainy':
        background.add_sprite(rain)
Example #22
0
import matplotlib.pyplot as plt
import matplotlib.animation as an
from forager import Forager
from landscape import Landscape
from foraging import foraging, display


def update(_):
    global l, f
    if not f.is_dead:
        foraging(l, f)
    return display(l, f),


l = Landscape(30, 30, 15)
f = Forager(0, 0)

fig = plt.figure(figsize=(6, 6))
ax = fig.add_axes([0, 0, 1, 1], frameon=False, aspect=1)

animation = an.FuncAnimation(fig, update, interval=1, blit=True, frames=200)
plt.show()

print('Total move = %d' % f.total_move)
print('Total eaten = %d' % f.total_eaten)
Example #23
0
 def reset_all(self):
     """Resets the finder with a new map and recenters the cur_location
     """
     self.landscape = Landscape(self.dim)
     self.reset_finder()
Example #24
0
if __name__ == "__main__":
    #global printers, landscapes, OSCSERVER_IP

    print("waiting 10 secs")
    time.sleep(10)

    print("MAIN program start\n")

    # get my IP address
    import os
    f = os.popen('ifconfig eth0 | grep inet')
    s = f.read()
    #print( s )
    OSCSERVER_IP = s.split()[1]

    landscapes["megalopoli"] = Landscape("megalopoli")
    landscapes["montagna"] = Landscape("montagna")
    landscapes["isola"] = Landscape("isola")
    landscapes["citta"] = Landscape("citta")
    landscapes["scogliera"] = Landscape("scogliera")
    landscapes["generici"] = Landscape("generici")
    print()

    # printer stuff
    try:
        printers.append(Printer("/dev/usb/lp0"))
        print("Printer 'lp0' recognized")
    except:
        print("Unable to create the 'pl0' printer")

    try:
Example #25
0
from landscape import Landscape
from simulator import Simulator

world = Landscape(
    terrain=[[200, 200, 400, 400], [400, 400, 600, 600], [600, 100, 800, 400]])
demo = Simulator(world)
demo.interactive()
Example #26
0
from forager import Forager
from landscape import Landscape
from foraging import eat, is_moving, move, foraging

x = 2
y = 2
nb_patches = 0
x_forager = 0
y_forager = 0
landscape = Landscape(x, y, nb_patches)
forager = Forager(x_forager, y_forager)


def test_eat():
    forager.stock = Forager.STOCK_MAX - Forager.EAT_MAX_BY_DAY + 2
    landscape.land[x_forager, y_forager] = Forager.EAT_MAX_BY_DAY
    eat(landscape, forager)
    assert landscape.land[x_forager, y_forager] == 2
    assert forager.stock == Forager.STOCK_MAX
    forager.stock = Forager.STOCK_MAX - Forager.EAT_MAX_BY_DAY - 2
    landscape.land[x_forager, y_forager] = Forager.EAT_MAX_BY_DAY
    eat(landscape, forager)
    assert landscape.land[x_forager, y_forager] == 0
    assert forager.stock == Forager.STOCK_MAX - 2


def test_is_moving():
    landscape.land[x_forager, y_forager] = 0
    assert is_moving(landscape, forager)
    landscape.land[x_forager, y_forager] = Forager.EAT_MAX_BY_DAY - 1
    forager.stock = 0
Example #27
0
from flask import Flask, render_template, request, redirect, session, url_for
import numpy as np

from Treehacks_recommendation import *
from visualisation import *
from landscape import Landscape
from Preprocessing import *

# setup flask
app = Flask(__name__)
app.secret_key = b'_5#y2L"F4Q8z\n\xec]/'
main_input = ""

# set up the model
lsr = Landscape("stsb-distilbert-base")
sentence = None
text_units = None


@app.route('/', methods=["GET", "POST"])
def startpage():
    if request.method == 'POST':
        session['inputText'] = request.form['inputText']
        # print(input_list)
        session['outputText'] = textsummary(session['inputText'])
        return redirect(url_for('analyze'))
    return render_template('interface.html')


@app.route('/text')
def analyze():
Example #28
0
import pygame

from settings import Settings
from landscape import Landscape
from dinosaur import Dinosaur

pygame.init()
canvas = pygame.display.set_mode(Settings.screen_size)

landscape = Landscape(canvas)
dinosaur = Dinosaur(canvas, landscape)

clock = pygame.time.Clock()

done = False
while not done:
    canvas.fill((0, 0, 0))
    landscape.draw()
    dinosaur.draw()
    pygame.display.flip()
    landscape.update()
    clock.tick(10)
Example #29
0
from landscape import Landscape
from simulator import Simulator
from math import pi, sqrt

world = Landscape(
    terrain=[[150, 200, 350, 400], [400, 400, 600, 600], [600, 200, 800, 400]])
demo = Simulator(world)

right = pi / 2
left = -pi / 2
straight = 0

demo.explore(401,
             401,
             moves=[[right, 5], [left, 100], [right, 100], [right, 250],
                    [right, 250], [right, 400], [right, 300], [right, 200],
                    [right, 200], [right, 250], [right, 100], [right, 250],
                    [straight, 150], [right, 80], [right,
                                                   150], [straight, 150],
                    [straight, 100], [pi / 4, 30], [right, 100], [right, 50],
                    [right, 250], [right, 200], [right, 300], [right, 200],
                    [right, 200], [right, 250], [right, 100], [right, 250],
                    [straight, 150], [right, 80], [right,
                                                   150], [straight, 150],
                    [right, 100], [right, 100], [right, 200], [left, 20],
                    [right, 20], [left, 20], [right, 20], [left, 20],
                    [right, 20], [left, 25], [left,
                                              sqrt(200**2 + 200**2)],
                    [right, 20], [right, 20], [right, 20]])

demo.interactive()