Skip to content

Commit

Permalink
refactoring
Browse files Browse the repository at this point in the history
  • Loading branch information
KevinCortacero committed Nov 29, 2024
1 parent 76c262c commit 40a1322
Show file tree
Hide file tree
Showing 29 changed files with 376 additions and 395 deletions.
34 changes: 19 additions & 15 deletions src/kartezio/callback.py
Original file line number Diff line number Diff line change
@@ -1,24 +1,21 @@
from abc import ABC
from datetime import datetime
from enum import Enum
from uuid import uuid4
from typing import Dict
from uuid import uuid4

import matplotlib.pyplot as plt
import numpy as np

from kartezio.core.helpers import Observer
from kartezio.components.genotype import Genotype
from kartezio.core.decoder import Decoder
from kartezio.utils.directory import Directory
from kartezio.core.helpers import Observer
from kartezio.enums import JSON_ELITE
from kartezio.utils.directory import Directory
from kartezio.utils.io import JsonSaver
from kartezio.utils.json_handler import json_write



import matplotlib.pyplot as plt


def timestamp(ms=True):
dt = datetime.now()
if ms:
Expand All @@ -34,9 +31,10 @@ def eventid():
return f"{timestamp()}-{uuid()}".replace(" ", "-")



class Event:
def __init__(self, iteration: int, name: str, content: Dict, force: bool=False):
def __init__(
self, iteration: int, name: str, content: Dict, force: bool = False
):
self.iteration = iteration
self.name = name
self.content = content
Expand Down Expand Up @@ -179,23 +177,27 @@ def on_new_parent(self, iteration, event_content):

def on_evolution_end(self, iteration, event_content):
self._add_new_line(iteration, event_content)
print(f"{self.filename} saved. {len(self.data)} lines, last = {self.data[-1]}")
print(
f"{self.filename} saved. {len(self.data)} lines, last = {self.data[-1]}"
)
data = np.array(self.data)
plt.figure()
plt.plot(data[:, 0], data[:, 1])
plt.plot(data[:, 0], data[:, 2])
plt.savefig(f"{self.filename}.png")


class CallbackSaveElite(Callback):
def __init__(self, filename, dataset, preprocessing, fitness):
super().__init__()
self.filename = filename
self.dataset = dataset.__to_dict__()
self.decoder = None
self.preprocessing = preprocessing.__to_dict__() if preprocessing else None
self.preprocessing = (
preprocessing.__to_dict__() if preprocessing else None
)
self.fitness = fitness.__to_dict__()

def set_decoder(self, decoder: Decoder):
self.decoder = decoder.__to_dict__()

Expand All @@ -205,10 +207,12 @@ def on_new_parent(self, iteration, event_content):
"iteration": iteration,
"dataset": self.dataset,
"elite": {
"chromosomes": {k: v.tolist() for k, v in elite._chromosomes.items()}
"chromosomes": {
k: v.tolist() for k, v in elite._chromosomes.items()
}
},
"preprocessing": self.preprocessing,
"decoder": self.decoder,
"fitness": self.fitness,
}
json_write(self.filename, json_data, indent=None)
json_write(self.filename, json_data, indent=None)
20 changes: 17 additions & 3 deletions src/kartezio/components/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ class Component(ABC):
Abstract base class for representing a Component in the CGP framework.
This class provides basic functionalities for components.
"""

def __init__(self):
"""
Initialize a Component instance.
Expand Down Expand Up @@ -48,11 +49,22 @@ class UpdatableComponent(Component, Observer, ABC):
Inherits from Component and Observer to enable both observation and update capabilities, making it suitable
for scenarios where a component's internal state must be adjusted during the evolutionary process.
"""

def __init__(self):
"""
Initialize an UpdatableComponent instance.
"""
super().__init__()
self.n_iterations = None
self.stored = None

def compile(self, n_iterations: int):
self.n_iterations = n_iterations
self.stored = self._precompute()

@abstractmethod
def _precompute(self):
pass


class Components:
Expand Down Expand Up @@ -114,15 +126,17 @@ def display():
pprint(Components._registry)



class Node(Component, ABC):
"""
Abstract base class for a Node in the CGP framework.
"""

pass


def register(component_group: type, component_name: str, replace: bool = False):
def register(
component_group: type, component_name: str, replace: bool = False
):
"""
Register a component to the Components registry.
Expand Down Expand Up @@ -163,4 +177,4 @@ def load_component(component_class: type, json_data: Dict) -> Component:
Returns:
Component: An instance of the component created from the given data.
"""
return component_class.__from_dict__(json_data)
return component_class.__from_dict__(json_data)
2 changes: 1 addition & 1 deletion src/kartezio/components/dataset.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@

import numpy as np

from kartezio.core.components.base import Component
from kartezio.components.base import Component
from kartezio.utils.json_handler import json_read, json_write


Expand Down
1 change: 0 additions & 1 deletion src/kartezio/components/endpoint.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,4 +38,3 @@ def __from_dict__(cls, dict_infos: Dict) -> "Endpoint":
dict_infos["name"].lower().replace(" ", "_"),
**dict_infos["args"]
)

13 changes: 6 additions & 7 deletions src/kartezio/components/genotype.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,6 @@
from kartezio.components.base import Component


import copy
import numpy as np
from typing import Dict

class Genotype(Component):
"""
Represents the genotype for Cartesian Genetic Programming (CGP).
Expand Down Expand Up @@ -81,8 +77,12 @@ def __from_dict__(cls, dict_infos: Dict) -> "Genotype":
Returns:
Genotype: A new Genotype instance created from the given dictionary.
"""
assert "chromosomes" in dict_infos, "Expected 'chromosomes' key in dictionary."
assert "outputs" in dict_infos["chromosomes"], "Expected 'outputs' key in 'chromosomes' dictionary."
assert (
"chromosomes" in dict_infos
), "Expected 'chromosomes' key in dictionary."
assert (
"outputs" in dict_infos["chromosomes"]
), "Expected 'outputs' key in 'chromosomes' dictionary."
n_outputs = len(dict_infos["chromosomes"]["outputs"])
genotype = cls(n_outputs)
for key, value in dict_infos["chromosomes"].items():
Expand All @@ -97,4 +97,3 @@ def clone(self) -> "Genotype":
Genotype: A cloned instance of the genotype.
"""
return copy.deepcopy(self)

14 changes: 8 additions & 6 deletions src/kartezio/components/initializer.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,16 +2,16 @@
from typing import Dict

from kartezio.components.base import register
from kartezio.core.decoder import Adapter
from kartezio.components.genotype import Genotype
from kartezio.core.decoder import Adapter
from kartezio.mutation.base import Mutation


"""
@register(Mutation, "all_random")
class RandomInit(Mutation):
"""
'''
Can be used to initialize genome (genome) randomly
"""
'''
@classmethod
def __from_dict__(cls, dict_infos: Dict) -> "Mutation":
Expand All @@ -32,9 +32,11 @@ def mutate(self, genotype):
return genotype
def random(self):
genotype = self.adapter.new()
genotype = self.adapter.new_genotype()
return self.mutate(genotype)
"""


@register(Mutation, "copy")
class CopyGenotype(Mutation):
Expand All @@ -51,7 +53,7 @@ def mutate(self, genotype):


@register(Mutation, "all_random_poly")
class MutationAllRandomPoly(Mutation):
class RandomInit(Mutation):
"""
Can be used to initialize genome (genome) randomly
"""
Expand Down
7 changes: 2 additions & 5 deletions src/kartezio/components/library.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,10 @@
import numpy as np
from tabulate import tabulate

from kartezio.components.base import Node, Components, Component, register
from kartezio.components.base import Component, Components, Node, register
from kartezio.core.types import KType



class Primitive(Node, ABC):
"""
Primitive function called inside the CGP Graph.
Expand All @@ -22,12 +21,10 @@ def __init__(self, inputs: List[KType], output: KType, n_parameters: int):
self.arity = len(inputs)
self.n_parameters = n_parameters



@classmethod
def __from_dict__(cls, dict_infos: Dict) -> "Primitive":
return Components.instantiate("Primitive", dict_infos["name"])


class Library(Component, ABC):
def __init__(self, rtype):
Expand Down
8 changes: 0 additions & 8 deletions src/kartezio/components/primitive.py

This file was deleted.

Loading

0 comments on commit 40a1322

Please sign in to comment.