Ejemplo n.º 1
0
def visualise_crossover(genomes: List[Genome], count=1, parent_mutation_count = 1):
    """
    pairs genomes, plots parents along with their children
    """
    if len(genomes) < 2:
        raise Exception("need at least 2 genomes to show cross over, num found: " + str(len(genomes)))

    for i in range(count):
        parent1 = copy.deepcopy(random.choice(genomes))
        parent2 = None

        found_unique_parent = False
        while not found_unique_parent:
            parent2 = copy.deepcopy(random.choice(genomes))
            found_unique_parent = parent1 != parent2

        child = cross.over(parent1, parent2)
        if not child.validate():
            print("invalid child")
            continue

        parent1_graph = get_graph_of(parent1, node_names="parent1", sub_graph=True, label= "parent 1")
        parent2_graph = get_graph_of(parent2, node_names="parent2", sub_graph= True, label= "parent 2")
        full_graph = get_graph_of(child, node_names="full", node_colour= "yellow")
        full_graph.subgraph(parent1_graph)
        full_graph.subgraph(parent2_graph)

        full_graph.view(directory=runs_manager.get_graphs_folder_path())
Ejemplo n.º 2
0
def visualise_traversal_dict(traversal_dict: Dict[int, List[int]]):
    g = Digraph(name="traversal_dict")

    for from_id in traversal_dict.keys():
        g.node(name=str(from_id))
        for to_id in traversal_dict[from_id]:
            g.node(name=str(to_id))
            g.edge(str(from_id), str(to_id))

    g.render(directory=runs_manager.get_graphs_folder_path(config.run_name),
             view=config.view_graph_plots,
             format="png")
Ejemplo n.º 3
0
def _log_imgs(generation: Generation) -> Dict[str, wandb.Image]:
    imgs = {}
    for root, _, files in os.walk(get_graphs_folder_path(config.run_name)):
        for file in files:
            if not file.endswith('.png'):
                continue

            for match in re.compile(r"_g[0-9]+_").finditer(str(file)):
                if match[0][2:-1] == str(generation.generation_number - 1):
                    name = 'best_pheno' if 'phenotype' in file else 'best_geno'
                    imgs[name] = wandb.Image(
                        Image.open(os.path.join(root, file)), file)

    return imgs
Ejemplo n.º 4
0
def visualise(pheno: neural_network,
              prefix="",
              suffix="",
              node_colour: Any = "white"):
    name = prefix + "blueprint_i" + str(
        pheno.blueprint.id) + "_phenotype" + suffix
    # print("saving:", name, "to",RunsManager.get_graphs_folder_path(config.run_name))
    graph = graphviz.Digraph(name=name, comment='phenotype')

    q: List[BaseLayer] = [pheno.model]
    _node_colour = node_colour if isinstance(node_colour,
                                             str) else node_colour(pheno.model)
    graph.node(pheno.model.name,
               pheno.model.get_layer_info(),
               fillcolor=_node_colour,
               style="filled")
    visited = set()

    while q:
        parent_layer = q.pop()

        if parent_layer.name not in visited:
            visited.add(parent_layer.name)

            child_layer: BaseLayer
            for child_layer in parent_layer.child_layers:
                _node_colour = node_colour if isinstance(
                    node_colour, str) else node_colour(child_layer)
                description = child_layer.get_layer_info()

                graph.node(child_layer.name,
                           child_layer.name + '\n' + description,
                           fillcolor=_node_colour,
                           style="filled")
                graph.edge(parent_layer.name, child_layer.name)

                q.append(child_layer)

    try:
        graph.render(directory=runs_manager.get_graphs_folder_path(
            config.run_name),
                     view=config.view_graph_plots,
                     format="png")

    except Exception as e:
        print(e)
Ejemplo n.º 5
0
def visualise_mutation(genomes: List[Genome],
                       mutator: Union[module_genome_mutator, blueprint_genome_mutator],
                       mutation_record: mutation_record, count=1, num_mutations=1):
    """
    samples genomes and plots them before and after mutation
    """

    for i in range(count):
        genome: Genome = random.choice(genomes)
        genome = copy.deepcopy(genome)

        before_graph = get_graph_of(genome, node_names="before")

        mutant_genome = mutator.mutate(genome, mutation_record)
        for i in range(num_mutations - 1):
            # print("mutated genome")
            mutant_genome = mutator.mutate(mutant_genome, mutation_record)
        # print("mutated genome")

        both_graph = get_graph_of(mutant_genome, node_names="after", append_graph=before_graph, node_colour="yellow")
        both_graph.view(directory=runs_manager.get_graphs_folder_path())
Ejemplo n.º 6
0
 def visualize(self):
     get_graph_of(self).render(
         directory=runs_manager.get_graphs_folder_path(config.run_name),
         view=config.view_graph_plots)
Ejemplo n.º 7
0
def visualise_blueprint_genome(genome: BlueprintGenome,
                               sample_map: Dict[int, int] = None,
                               parse_number=-1,
                               prefix=""):
    blueprint_graph = get_graph_of(
        genome,
        node_names="blueprint",
        sample_map=sample_map,
        node_colour=get_node_colour,
        graph_title_prefix=prefix + "blueprint_",
        graph_title_suffix=("_p" + str(parse_number) +
                            "_" if parse_number >= 0 else ""))
    module_ids = set()
    exception = None
    plotted_species = set()
    for bp_node_id in genome.get_fully_connected_node_ids():
        bp_node = genome.nodes[bp_node_id]
        if not isinstance(bp_node, BlueprintNode):
            continue
        species = bp_node.species_id
        if species in plotted_species:
            continue
        plotted_species.add(species)
        if bp_node.linked_module_id != -1:
            module_id = bp_node.linked_module_id
        elif species in sample_map.keys():
            module_id = sample_map[species]
        else:
            exception = Exception(
                "bp node is unmapped by both link and sample map: " +
                repr(bp_node) + " scp_id: " + repr(species),
                " sample map: " + repr(sample_map))
        sub_graph_label = "Species: " + str(species) + "\nModule: " + str(
            module_id)
        node_names = "module_" + str(species) + "_" + str(module_id)
        module = Singleton.instance.module_population[module_id]
        module_graph = get_graph_of(module,
                                    node_names=node_names,
                                    sub_graph=True,
                                    label=sub_graph_label,
                                    node_colour="cyan")
        blueprint_graph.subgraph(module_graph)

    if config.evolve_da:
        da: DAGenome = genome.get_da()
        da_graph = get_graph_of(da,
                                sub_graph=True,
                                node_names="da_nodes",
                                label="Augmentation Scheme " + repr(da.id),
                                node_colour="pink")
        blueprint_graph.subgraph(da_graph)
    try:
        blueprint_graph.render(directory=runs_manager.get_graphs_folder_path(
            config.run_name),
                               view=config.view_graph_plots,
                               format="png")
    except Exception as e:
        print(e)

    if exception is not None:
        raise exception