def toilet_dist(floor, path_dists, paths):
    ppt = defaultdict(int)
    toilet_centers = set([
        floor.room_centers[ID] for ID, name in floor.room_names.items()
        if name == 'toilet'
    ])
    ctr = {c: ID for ID, c in floor.room_centers.items()}
    has_bathroom = set(['1', '2', 'PK', 'K'])
    needs_bathroom = [
        ID for ID, name in floor.room_names.items() if name not in has_bathroom
    ]

    total_path_length = 0
    n = 0
    for ID in needs_bathroom:
        c = floor.room_centers[ID]
        path = pathing.min_path(path_dists[c], paths[c], toilet_centers)
        load = floor.population * (floor.room_sizes[ID] / floor.area)
        # load = floor.population * floor.room_sizes[ID] / len(floor.rooms)
        n += load
        total_path_length += path_length(floor, path)
        ppt[path[-1]] += load

    # for load, path in pathing.closest_paths(floor, path_dists, paths, vert_options=toilet_centers):
    #     total_path_length += load * path_length(floor, path)
    #     n += load
    foo = mean(list(v / floor.room_sizes[ctr[c]] for c, v in ppt.items()))
    return (total_path_length / n), foo
Esempio n. 2
0
    def get_average_fitness(self):
        """Get the per-generation average fitness."""
        avg_fitness = []
        for stats in self.generation_statistics:
            scores = []
            for fitness in stats.values():
                scores.extend(fitness)
            avg_fitness.append(mean(scores))

        return avg_fitness
Esempio n. 3
0
 def post_evaluate(self, population, species, best):
     fit_mean = mean([c.fitness for c in population])
     fit_std = stdev([c.fitness for c in population])
     print('Population\'s average fitness: {0:3.5f} stdev: {1:3.5f}'.format(
         fit_mean, fit_std))
     print('Best fitness: {0:3.5f} - size: {1!r} - species {2} - id {3}'.
           format(best.fitness, best.size(), best.species_id, best.ID))
     print('Species length: {0:d} totaling {1:d} individuals'.format(
         len(species), sum([len(s.members) for s in species])))
     print('Species ID       : {0!s}'.format([s.ID for s in species]))
     print('Species size     : {0!s}'.format(
         [len(s.members) for s in species]))
     print('Species age      : {0}'.format([s.age for s in species]))
Esempio n. 4
0
def get_species_fitness(population, null_value=''):
    all_species = set()
    for gen_data in population.generation_statistics:
        all_species = all_species.union(gen_data.keys())

    max_species = max(all_species)
    species_fitness = []
    for gen_data in population.generation_statistics:
        member_fitness = [gen_data.get(sid, []) for sid in range(1, max_species + 1)]
        fitness = []
        for mf in member_fitness:
            if mf:
                fitness.append(mean(mf))
            else:
                fitness.append(null_value)
        species_fitness.append(fitness)

    return species_fitness
def window_area(floor):
    class_rooms = set(['computer lab', 'tutoring', 'title 1', 'work', \
                        'team', 'library', 'tutoring', 'conference', 'resource', \
                        '2', '1', 'pk', 'k', 'art', 'music', 'life skills',
                        'faculty', 'library', 'administration', 'cafeteria'])
    foo = []
    for rid, verts in floor.rooms.items():
        if floor.room_names[rid].lower() not in class_rooms:
            continue

        total = 0
        outside = 0
        for i, j in pairwise(verts):
            d = floor.edge[i][j]
            total += d['length']
            outside += d['length'] * d['outside']
        foo.append(outside / total)

    return mean(foo)
Esempio n. 6
0
def species_mean_fitness(species):
    return mean([m.fitness for m in species.members])
Esempio n. 7
0
def create_hallways(floor,
                    iters=10,
                    alpha=12,
                    k=10,
                    pheromone_decay=.1,
                    fe_weight=.5,
                    start_pheromone=0,
                    verbose=False,
                    firescapes=False):
    max_width = 12
    min_width = 5
    intitialize(floor, start_pheromone)
    # print(fe_weight)
    # fe_weight = 1
    # Main loop.
    for step in range(iters):
        calculate_loads(floor, fe_weight, True)
        normalize_loads(floor)

        pheromone_values = []  # for logging

        for i, j, data in floor.edges(data=True):
            if not (data['between_fixed'] or data['outside']
                    ):  #if not (data['between_fixed'] or data['outside']):
                data['pheromone'] = (1 - pheromone_decay) * data[
                    'pheromone'] + k * data['load_normalized']
                pheromone_values.append(data['pheromone'])
                if data['pheromone'] > 0:  # and not data['inner']:
                    data['weight'] = data['length'] / (
                        (1 + data['pheromone'])**alpha)

        if verbose:
            print("step %i, mean phero=%f, min=%f, max=%f" % \
                (step, mean(pheromone_values), min(pheromone_values), max(pheromone_values)))
            print("step %i, mean phero=%f, min=%f, max=%f" % \
                (step, mean(pheromone_values), min(pheromone_values), max(pheromone_values)))

    entrances = create_entrances(
        floor)  # Create entrances based on those paths to exit
    floor.entrances = entrances

    calculate_loads(floor, fe_weight, firescapes)

    # Now that entrances are created. Find path to main one.
    path_dists, paths = pathing.all_paths(floor, weight='weight')

    if not firescapes:
        for i, j, d in floor.edges_iter(data=True):
            d['entrance_laod'] = 0

    # for load, path in pathing.closest_paths(floor, path_dists, paths, entrances):
    #     if len(path) > 1:
    #         add_load(floor, path, key='entrance_load', load=load)

    for load, path in pathing.closest_paths(floor, path_dists, paths,
                                            entrances[:1]):
        add_load(floor, path, key='entrance_load', load=load)
    for i, j, d in floor.edges_iter(data=True):
        d['load'] = max(d['load'], d['entrance_load'])

    # print(c)
    derp(floor)
    ########
    # # TODO explain.
    # for ID, face in floor.rooms.items():
    #     vc = floor.room_centers[ID]
    #     # print(list(floor.inner_edges(ID)))
    #     edge_with_door = max(floor.inner_edges(ID), key=lambda et: et[2]['load'])
    #     vd = edge_with_door[0] if edge_with_door[1] == vc else edge_with_door[1] # vert for door
    #     for v1, v2, data in floor.inner_edges(ID):
    #         if v2 != vc and data['load'] < load_for_doorway:
    #             data['load'] = 0
    #             data['weigh'] = data['length']

    #     s = sum(floor.edge[vc][j_]['load'] for j_ in face if floor.has_edge(vc, j_))
    #     jmax = max((floor.edge[vc][j_]['load'], j_) for j_ in face if floor.has_edge(vc, j_))[1]

    #     for j in face:
    #         if j != jmax and floor.has_edge(vc, j):
    #             floor.edge[vc][j]['load'] =0 maps
    # ########

    # max_laod = max(d['load'] for i, j,d in floor.edges_iter(data=True))
    load_to_width = 1  #, max_width / max_laod

    # Convert loads into hallway dimensions.
    for i, j, d in floor.edges(data=True):
        if d['load'] > 0:
            d['width'] = min(max_width,
                             max(min_width, d['load'] * load_to_width))
        else:
            d['width'] = 0
Esempio n. 8
0
    def from_genome(cls, genome, firescapes=False, view=None, cache=True):
        if genome.phenotype is not None and cache:
            return genome.phenotype
        G = genome_to_graph(genome)  # First create a graph representation.
        pos = nx.spectral_layout(G)  # Create with spectral layout of graph.
        scale_offset(pos, dx=75, dy=75, scale=600)
        fix_overlapping(pos)  # Prevent overlapping points.
        center(pos, dimensions=(750, 750))
        pos = physics_layout(G, pos, view)  # Apply physics simulation.

        center(pos, dimensions=(750, 750))
        if 'concave_alpha' in genome.attribute_genes:
            a = genome.attribute_genes['concave_alpha'].value
        else:
            a = 40

        cells, debug_data = voronoi_cells(
            pos, genome.node_genes, a)  # Room walls by voronoi tesselation.
        vert_to_id = defaultdict(
            lambda: len(vert_to_id))  # Map vertices to global indexes.
        rooms = defaultdict(list)
        vert_to_room = defaultdict(set)
        room_names = dict()
        room_centers = dict()
        edges = []

        no_outside = set()

        for ID, verts in cells.items():
            gene = genome.node_genes[ID]
            # print(gene.name)
            if gene.name == 'empty' or gene.name == 'playground':
                no_outside.update(set([vert_to_id[vert] for vert in verts]))
                if gene.name == 'empty':
                    continue

            center_v = polygon.center(verts)
            center_i = vert_to_id[center_v]
            room_centers[ID] = center_i
            vert_to_room[center_i].add(ID)
            room_names[ID] = gene.name

            # if gene.name == 'playground':
            #     continue

            for i, vert in enumerate(verts):
                vid = vert_to_id[
                    vert]  # voronoi points are integers and thus hashable.
                rooms[ID].append(vid)

                vert_to_room[vid].add(ID)
                if gene.name != 'playground':
                    edges.append((vid, vert_to_id[verts[i - 1]], {
                        'inner': False
                    }))
                edges.append((vid, center_i, {
                    'inner': True,
                    'directed': None
                }))

        vertices = sorted(vert_to_id.keys(), key=lambda v: vert_to_id[v])
        floor = cls(vertices,
                    dict(rooms),
                    room_names,
                    vert_to_room,
                    room_centers,
                    entrances=[])
        floor.debug_data = debug_data  # temporary

        for i, j, data in edges:  # add edges.
            floor.add_edge(i, j, **data)

        floor.calc_outisde_edges(no_outside)

        # Remove edges that connect centers to outside
        # for ri, vc in floor.room_centers.items():
        #     if room_names[ri] in ['cafeteria', 'library', 'gym']:
        #         continue
        #     verts = rooms[ri]
        #     out = [v for v in verts if v in floor.outside_verts]
        #     if len(out) == len(verts):
        #         continue
        #     for v in out:
        #         if floor.has_edge(vc, v):
        #             floor.remove_edge(vc, v)

        # for v in floor.outside_verts:
        #     for ri in vert_to_room[v]:
        #         if room_names[ri] not in ['cafeteria', 'library', 'gym'] and \
        #             len(room_centers[ri]):
        #             vc = room_centers[ri]
        #             floor.remove_edge(v, vc)

        # new_polygons = []
        # for ID, face in floor.rooms:
        #     polygon = [floor.vertices[vi] for vi in face]
        #     clipped = poylgon.clip(polygon, floor.hallway_geometry)
        #     new_polygons.append(clipped)

        # self.topologize(new_polygons)
        """ Prevent adjacency requirements from having a hallway between them.
        """
        for conn in genome.conn_genes.values():
            if conn.fixed:
                room1_id = conn.in_node_id
                room2_id = conn.out_node_id
                edge = floor.get_rooms_edge(room1_id, room2_id)
                if edge:
                    i, j, data = edge
                    data['between_fixed'] = True
                else:
                    raise InvalidContraintException()

        alpha = genome.attribute_genes['hallway_alpha'].value
        decay = genome.attribute_genes['hallway_decay'].value
        if 'fe_weight' in genome.attribute_genes:
            fe_weight = genome.attribute_genes['fe_weight'].value
        else:
            fe_weight = .2
        create_hallways(floor, alpha=alpha, pheromone_decay=decay, iters=10, fe_weight=fe_weight,\
                        verbose=False, firescapes=firescapes)

        for i, j, d in floor.edges(data=True):
            if d['between_fixed'] and d['width']:
                raise InvalidContraintException()

        cx = mean([x for x, y in floor.vertices])
        cy = mean([y for x, y in floor.vertices])
        x1, y1 = floor.vertices[floor.entrances[0]]
        angle = -math.atan2(y1 - cy, x1 - cx) + math.pi / 2
        floor.vertices = [
            geometry.rotate_point((cx, cy), p, angle) for p in floor.vertices
        ]

        floor.add_adjacent_room_edges([(c.in_node_id, c.out_node_id)
                                       for c in genome.conn_genes.values()
                                       if c.fixed])
        smooth(floor)
        floor.hallway_geometry = create_geometry(floor)
        floor.stats = fps.calculate_all(floor)
        return floor