def _code_map(state: PushState) -> PushState: if state["exec"].is_empty() or state["code"].is_empty(): return Token.revert e = state["exec"].pop() c = state["code"].pop() if not isinstance(c, CodeBlock): c = CodeBlock(c) else: c = c.copy() l1 = [CodeBlock(JitInstructionRef("code_from_exec"), item, e) for item in c] l2 = [JitInstructionRef("code_combine") for _ in c[1:]] state["exec"].push(CodeBlock.from_list(l1 + [JitInstructionRef("code_wrap")] + l2)) return state
def from_json_str(cls, json_str: str, instruction_set: InstructionSet): """Create a PushSolution from a JSON string.""" solution_dict = json.loads(json_str) return cls( CodeBlock.from_json_str( json.dumps(solution_dict["program"], separators=(',', ':')), instruction_set ), solution_dict["output_types"] )
def _code_combine(a: Atom, b: Atom) -> Tuple[CodeBlock]: if isinstance(a, CodeBlock) and isinstance(b, CodeBlock): return CodeBlock.from_list(list(b.copy()) + list(a.copy())), elif isinstance(b, CodeBlock): result = b.copy() result.append(a) return result, elif isinstance(a, CodeBlock): result = a.copy() result.append(b) return result, else: return CodeBlock(a, b),
def _code_insert(code1, code2, ndx) -> Union[Token, Tuple[Atom]]: if isinstance(code1, CodeBlock): code1 = code1.copy(True) else: code1 = CodeBlock(code1) if isinstance(code2, CodeBlock): code2 = code2.copy(True) if code1.size() == 0: code1.append(code2) return code1, ndx = abs(ndx) % code1.size() return code1.insert_code_at_point(code2, ndx),
def to_code_block(self) -> CodeBlock: """Translate into nested CodeBlocks. These CodeBlocks can be considered the Push program representation of the Genome which can be executed by a PushInterpreter and evaluated by an Evaluator. """ plushy_buffer = [] for atom in self: plushy_buffer.append(atom) if isinstance(atom, Instruction) and atom.code_blocks > 0: plushy_buffer.append(Opener(atom.code_blocks)) push_buffer = [] while True: # If done with plush but unclosed opens, recur with one more close. if len(plushy_buffer) == 0 and _has_opener(push_buffer): plushy_buffer.append(Closer()) # If done with plush and all opens closed, return push. elif len(plushy_buffer) == 0: return CodeBlock.from_list(push_buffer) else: atom = plushy_buffer[0] # If next instruction is a close, and there is an open. if isinstance(atom, Closer) and _has_opener(push_buffer): ndx, opener = [(ndx, el) for ndx, el in enumerate(push_buffer) if isinstance(el, Opener)][-1] post_open = push_buffer[ndx + 1:] pre_open = push_buffer[:ndx] if opener.count == 1: push_buffer = pre_open + [post_open] else: opener.dec() push_buffer = pre_open + [post_open, opener] # If next instruction is a close, and there is no open. elif not isinstance(atom, Closer): push_buffer.append(atom) del plushy_buffer[0]
def test_load_program(self, state: PushState, atoms): prog = CodeBlock.from_list([atoms["5"], atoms["5"], atoms["add"]]) state.load_program(prog) assert state.size() == 1 assert len(state["exec"].top()) == 3
def test_genome_bad_init(self, atoms): with pytest.raises(ValueError): Genome(CodeBlock.from_list([atoms["5"], [atoms["5"], atoms["add"]]]))
def _code_but_last(x) -> Tuple[Atom]: if isinstance(x, CodeBlock) and len(x) > 1: return CodeBlock.from_list(x[:-1]), return Token.revert
def _code_reverse(code): if not isinstance(code, CodeBlock): return code, return CodeBlock.from_list(list(code[::-1])),
import math import sys from pyshgp.push.atoms import Literal, CodeBlock, InstructionMeta from pyshgp.push.interpreter import DEFAULT_INTERPRETER from pyshgp.push.types import Char, PushInt, PushStr # 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] }
def simple_program(atoms): return CodeBlock.from_list([atoms["5"], atoms["5"], atoms["add"]])
def load_program(name, interpreter) -> CodeBlock: with open("tests/resources/programs/" + name + ".json") as f: return CodeBlock.from_json_str(f.read(), interpreter.instruction_set)
def load_program(name: str) -> CodeBlock: with open("tests/resources/programs/" + name + ".json") as f: return CodeBlock.from_json_str(f.read(), i_set)
def test_set_program(self, unevaluated_individual): with pytest.raises(AttributeError): unevaluated_individual.program = CodeBlock.from_list([])