예제 #1
0
파일: conftest.py 프로젝트: nayabur/pyshgp
def atoms(instr_set):
    return {
        "5": Literal(value=5, push_type=PushInt),
        "1.2": Literal(value=1.2, push_type=PushFloat),
        "true": Literal(value=True, push_type=PushBool),
        "add": instr_set["int_add"].meta(),
        "sub": instr_set["int_sub"].meta(),
        "if": instr_set["exec_if"].meta(),
        "close": Closer()
    }
예제 #2
0
def atoms(instr_set):
    return {
        "5": Literal(5),
        "1.2": Literal(1.2),
        "true": Literal(True),
        "add": instr_set["int_add"],
        "sub": instr_set["int_sub"],
        "if": instr_set["exec_if"],
        "close": Closer()
    }
예제 #3
0
파일: code.py 프로젝트: bmetevier/pyshgp
def _exec_do_count(state: PushState) -> Union[Token, PushState]:
    if state["exec"].is_empty() or state["int"].is_empty():
        return Token.revert
    if state["int"].top() < 1:
        return Token.revert
    code = state["exec"].pop()
    count = state["int"].pop()
    state["exec"].push(
        CodeBlock(Literal(0), Literal(count - 1),
                  JitInstructionRef("exec_do_range"), code))
    return state
예제 #4
0
def _exec_do_count(state: PushState) -> Union[Token, PushState]:
    if state["exec"].is_empty() or state["int"].is_empty():
        return Token.revert
    if state["int"].top() < 1:
        return Token.revert
    code = state["exec"].pop()
    count = state["int"].pop()
    state["exec"].push(CodeBlock([
        Literal(value=0, push_type=PushInt),
        Literal(value=count - 1, push_type=PushInt),
        InstructionMeta(name="exec_do_range", code_blocks=1),
        code
    ]))
    return state
예제 #5
0
파일: code.py 프로젝트: bmetevier/pyshgp
def _exec_do_times(state: PushState) -> PushState:
    if state["exec"].is_empty() or state["int"].is_empty():
        return Token.revert
    if state["int"].top() < 1:
        return Token.revert
    code = state["exec"].pop()
    times = state["int"].pop()
    state["exec"].push(
        CodeBlock(Literal(0), Literal(times - 1),
                  JitInstructionRef("exec_do_range"),
                  CodeBlock(
                      JitInstructionRef("int_pop"),
                      code,
                  )))
    return state
예제 #6
0
def _deserialize_atoms(lst, instr_set: InstructionSet):
    type_lib = instr_set.type_library
    atoms = []
    for atom_spec in lst:
        atom = None
        if isinstance(atom_spec, list):
            atom = CodeBlock(_deserialize_atoms(atom_spec, instr_set))
        else:
            atom_type = atom_spec["a"]
            if atom_type == "close":
                atom = Closer()
            elif atom_type == "lit":
                push_type = type_lib[atom_spec["t"]]
                value = push_type.coerce(atom_spec["v"])
                atom = Literal(value=value, push_type=push_type)
            elif atom_type == "input":
                atom = Input(input_index=atom_spec["i"])
            elif atom_type == "instr":
                instr = instr_set[atom_spec["n"]]
                atom = InstructionMeta(name=instr.name,
                                       code_blocks=instr.code_blocks)
            else:
                raise ValueError("bad atom spec {s}".format(s=atom_spec))
        atoms.append(atom)
    return atoms
예제 #7
0
def test_input_instructions():
    in_state = PushState.from_dict({"inputs": [7, "x"], "exec": []})
    ex_state = PushState.from_dict({"inputs": [7, "x"], "exec": [Literal(7)]})
    DEFAULT_INTERPRETER.state = in_state
    DEFAULT_INTERPRETER.evaluate_atom(make_input_instruction(0))
    ac_state = DEFAULT_INTERPRETER.state
    assert ex_state == ac_state
    assert len(in_state.inputs) == 2

    in_state = PushState.from_dict({"inputs": [7, "x"], "exec": []})
    ex_state = PushState.from_dict({"inputs": [7, "x"], "exec": [Literal("x")]})
    DEFAULT_INTERPRETER.state = in_state
    DEFAULT_INTERPRETER.evaluate_atom(make_input_instruction(1))
    ac_state = DEFAULT_INTERPRETER.state
    assert ex_state == ac_state
    assert len(in_state.inputs) == 2
예제 #8
0
 def test_missing_close_genome_to_codeblock(self, atoms):
     gn = Genome([
         atoms["true"], atoms["if"], atoms["1.2"], atoms["close"],
         atoms["5"]
     ])
     cb = gn.to_code_block()
     assert cb[0] == Literal(True)
     assert isinstance(cb[1], Instruction)
     assert isinstance(cb[2], CodeBlock)
예제 #9
0
 def test_missing_close_genome_to_codeblock(self, atoms):
     gn = Genome([
         atoms["true"], atoms["if"], atoms["1.2"], atoms["close"],
         atoms["5"]
     ])
     cb = genome_to_code(gn)
     assert cb[0] == Literal(value=True, push_type=PushBool)
     assert isinstance(cb[1], InstructionMeta)
     assert isinstance(cb[2], CodeBlock)
예제 #10
0
def _code_do_times(state: PushState) -> PushState:
    if state["code"].is_empty() or state["int"].is_empty():
        return Token.revert
    if state["int"].top() < 1:
        return Token.revert
    code = state["code"].pop()
    times = state["int"].pop()
    state["exec"].push(CodeBlock([
        Literal(value=0, push_type=PushInt),
        Literal(value=times - 1, push_type=PushInt),
        InstructionMeta(name="code_from_exec", code_blocks=1),
        CodeBlock([
            InstructionMeta(name="int_pop", code_blocks=0),
            code,
        ]),
        InstructionMeta(name="code_do_range", code_blocks=0)
    ]))
    return state
예제 #11
0
파일: genome.py 프로젝트: bmetevier/pyshgp
    def random_erc(self) -> Literal:
        """Materialize a random ERC generator into a Literal and return it.

        Returns
        -------
        pushgp.push.atoms.Literal
            A Literal whose value comes from running a ERC generator function.

        """
        erc_value = np.random.choice(self.erc_generators)()
        return Literal(erc_value)
예제 #12
0
파일: code.py 프로젝트: bmetevier/pyshgp
def _exec_do_range(state: PushState) -> Union[Token, PushState]:
    if state["exec"].is_empty() or len(state["int"]) < 2:
        return Token.revert
    to_do = state["exec"].pop()
    destination_ndx = state["int"].pop()
    current_ndx = state["int"].pop()

    increment = 0
    if current_ndx < destination_ndx:
        increment = 1
    elif current_ndx > destination_ndx:
        increment = -1

    if not increment == 0:
        state["exec"].push(
            CodeBlock(Literal(current_ndx + increment),
                      Literal(destination_ndx),
                      JitInstructionRef("exec_do_range"), to_do))
    state["int"].push(current_ndx)
    state["exec"].push(to_do)
    return state
예제 #13
0
def _exec_do_range(state: PushState) -> Union[Token, PushState]:
    if state["exec"].is_empty() or len(state["int"]) < 2:
        return Token.revert
    to_do = state["exec"].pop()
    destination_ndx = state["int"].pop()
    current_ndx = state["int"].pop()

    increment = 0
    if current_ndx < destination_ndx:
        increment = 1
    elif current_ndx > destination_ndx:
        increment = -1

    if not increment == 0:
        state["exec"].push(CodeBlock([
            Literal(value=current_ndx + increment, push_type=PushInt),
            Literal(value=destination_ndx, push_type=PushInt),
            InstructionMeta(name="exec_do_range", code_blocks=1),
            to_do
        ]))
    state["int"].push(current_ndx)
    state["exec"].push(to_do)
    return state
예제 #14
0
def infer_literal(val: Any, type_library: PushTypeLibrary) -> Literal:
    """Make a literal by inferring the PushType of the value.

    Parameters
    ----------
    val : Any
        Any value to try and make a Literal out of.
    type_library : PushTypeLibrary
        The library of PushTypes which a Literal can be made of.

    Returns
    -------
    Literal
        The Literal object which holds the value and the corresponding PushType.

    """
    return Literal(value=val,
                   push_type=type_library.push_type_of(
                       val, error_on_not_found=True))
예제 #15
0
def iterate(state: PushState, *, vec_type: PushType,
            el_type: PushType) -> Union[Token, PushState]:
    vec_type_name = vec_type.name
    el_type_name = el_type.name
    if state[vec_type_name].is_empty() or state["exec"].is_empty():
        return Token.revert
    vec = state[vec_type_name].pop()
    if len(vec) == 0:
        state["exec"].pop()
        return state
    elif len(vec) == 1:
        state[el_type_name].push(vec[0])
        return state
    else:
        top_exec = state["exec"].top()
        state["exec"].push(
            InstructionMeta(name=vec_type_name + "_iterate", code_blocks=1))
        state["exec"].push(
            Literal(value=vec_type.coerce(vec[1:]), push_type=vec_type))
        state["exec"].push(top_exec)
        state[el_type_name].push(vec[0])
        return state
예제 #16
0
파일: genome.py 프로젝트: bmetevier/pyshgp
    def __init__(self,
                 instruction_set: InstructionSet,
                 literals: Sequence[Union[Literal, Any]],
                 erc_generators: Sequence[Callable],
                 distribution: DiscreteProbDistrib = "proportional"):
        self.instruction_set = instruction_set
        self.literals = [
            lit if isinstance(lit, Literal) else Literal(lit)
            for lit in literals
        ]
        self.erc_generators = erc_generators

        if distribution == "proportional":
            self.distribution = (DiscreteProbDistrib().add(
                "instruction", len(instruction_set)).add(
                    "close",
                    sum([i.code_blocks for i in instruction_set.values()
                         ])).add("literal",
                                 len(literals)).add("erc",
                                                    len(erc_generators)))
        else:
            self.distribution = distribution
예제 #17
0
 def test_extra_close_genome_to_codeblock(self, atoms):
     gn = Genome(
         [atoms["close"], atoms["5"], atoms["close"], atoms["close"]])
     cb = genome_to_code(gn)
     assert len(cb) == 1
     assert cb[0] == Literal(value=5, push_type=PushInt)
예제 #18
0
 def test_extra_close_genome_to_codeblock(self, atoms):
     gn = Genome(
         [atoms["close"], atoms["5"], atoms["close"], atoms["close"]])
     cb = gn.to_code_block()
     assert len(cb) == 1
     assert cb[0] == Literal(5)
예제 #19
0
 def f(state: PushState) -> Sequence[Literal]:
     input_value = state.inputs[ndx]
     if isinstance(input_value, Atom):
         return input_value,
     return Literal(input_value),
예제 #20
0
    def test_with_code_inserted_at_point(self):
        code_block = CodeBlock([
            CodeBlock([
                Literal(value="A", push_type=PushStr),
                Literal(value="B", push_type=PushStr)
            ]),
            Literal(value="C", push_type=PushStr)
        ])
        code = Literal(value="Z", push_type=PushStr)

        assert code_block.with_code_inserted_at_point(code, 0) == CodeBlock([
            code,
            CodeBlock([
                Literal(value="A", push_type=PushStr),
                Literal(value="B", push_type=PushStr)
            ]),
            Literal(value="C", push_type=PushStr)
        ])

        assert code_block.with_code_inserted_at_point(code, 1) == CodeBlock([
            CodeBlock([
                code,
                Literal(value="A", push_type=PushStr),
                Literal(value="B", push_type=PushStr)
            ]),
            Literal(value="C", push_type=PushStr)
        ])

        assert code_block.with_code_inserted_at_point(code, 2) == CodeBlock([
            CodeBlock([
                Literal(value="A", push_type=PushStr), code,
                Literal(value="B", push_type=PushStr)
            ]),
            Literal(value="C", push_type=PushStr)
        ])

        assert code_block.with_code_inserted_at_point(code, 3) == CodeBlock([
            CodeBlock([
                Literal(value="A", push_type=PushStr),
                Literal(value="B", push_type=PushStr), code
            ]),
            Literal(value="C", push_type=PushStr)
        ])

        assert code_block.with_code_inserted_at_point(code, 4) == CodeBlock([
            CodeBlock([
                Literal(value="A", push_type=PushStr),
                Literal(value="B", push_type=PushStr)
            ]), code,
            Literal(value="C", push_type=PushStr)
        ])

        assert code_block.with_code_inserted_at_point(code, 5) == CodeBlock([
            CodeBlock([
                Literal(value="A", push_type=PushStr),
                Literal(value="B", push_type=PushStr)
            ]),
            Literal(value="C", push_type=PushStr), code
        ])

        assert code_block.with_code_inserted_at_point(code, 100) == CodeBlock([
            CodeBlock([
                Literal(value="A", push_type=PushStr),
                Literal(value="B", push_type=PushStr)
            ]),
            Literal(value="C", push_type=PushStr), code
        ])
예제 #21
0
import math
import sys

from pyshgp.push.atoms import Literal, CodeBlock, InstructionMeta
from pyshgp.push.types import Char, PushInt, PushStr, BoolVector, IntVector, FloatVector, CharVector, StrVector, \
    PushIntVector

# Shorthand
L = lambda v, t: Literal(value=v, push_type=t)
IM = lambda nm, cb: InstructionMeta(name=nm, code_blocks=cb)
CB = lambda *args: CodeBlock(list(args))

SPECS = [
    # COMMON
    {
        "instr": "bool_pop",
        "in": {"bool": [True, False]},
        "ex": {"bool": [True]}
    },
    {
        "instr": "int_dup",
        "in": {"int": [101]},
        "ex": {"int": [101, 101]}
    },
    {
        "instr": "float_dup_times",
        "in": {"int": [3], "float": [1.23]},
        "ex": {"int": [], "float": [1.23, 1.23, 1.23]}
    },
    {
        "instr": "bool_dup_times",
예제 #22
0
def _make_code(x: Any, push_type: PushType) -> Tuple[Atom]:
    if isinstance(x, Atom):
        return x,
    else:
        return Literal(value=x, push_type=push_type),
예제 #23
0
def test_infer_literal():
    lib = PushTypeLibrary()
    assert infer_literal(5, lib) == Literal(value=5, push_type=PushInt)
    assert infer_literal(False, lib) == Literal(value=False,
                                                push_type=PushBool)
    assert infer_literal("", lib) == Literal(value="", push_type=PushStr)
예제 #24
0
파일: code.py 프로젝트: bmetevier/pyshgp
def _make_code(x: Any) -> Tuple[Atom]:
    if isinstance(x, Atom):
        return x,
    else:
        return Literal(x),