Пример #1
0
class PatternEnding(namedtuple("PatternEnding",
                               "pattern end_states num_seen")):
    """A computed ending for a single pattern.
    """
    pass
Пример #2
0
        return group

    def _collect_perimeter(self, env, old_perimeter, group):
        new_perimeter = []
        for s in old_perimeter:
            for child in _get_children(env, s):
                if child not in self.state_group:
                    self.state_group[child] = group
                    new_perimeter.append(child)

        return new_perimeter


# A Node is sortable by its distance from the connected set.
Node = namedtuple.namedtuple("Node", "g s")


class CycleGator(object):
    def __init__(self, k=2):
        """Creates a new aggregator with max perimeter <= k.
        """
        assert k >= 2
        self.k = k

    def get_connected(self, env, s):
        """Returns all states that are able
        to visit another state with k steps.
        """
        self.env = env
        self.parent_memory = ParentMemory()
Пример #3
0
def find_model(models, mark):
    """Finds the model with the given mark.
    """
    for model in models:
        if model.mark == mark:
            return model

    return None

def _chars(start, end):
    """Returns a string with chars the from [start-end] set.
    """
    return "".join(chr(i) for i in range(ord(start), ord(end) + 1))

Style = namedtuple.namedtuple("Style", "weight is_unit")
STYLE_FIXED = Style(WEIGHT_FIXED, False)
STYLE_SMALL_FISH = Style(WEIGHT_LIGHT, True)
STYLE_BIG_FISH = Style(WEIGHT_HEAVY, True)
STYLE_LIGHT = Style(WEIGHT_LIGHT, False)
STYLE_HEAVY = Style(WEIGHT_HEAVY, False)

STYLE_MARKS = {
        STYLE_FIXED: "#",
        STYLE_SMALL_FISH: "+0123456789",
        STYLE_BIG_FISH: "*",
        STYLE_LIGHT: _chars("a", "z"),
        STYLE_HEAVY: _chars("A", "Z"),
        }

Пример #4
0
from pylib.namedtuple import namedtuple
from soko import mazing

Task = namedtuple("Task", "level_filename spec")
TASKS = None

def get_tasks():
    if TASKS is None:
        _define_tasks()
    return TASKS

def _add(level_filename, spec):
    TASKS.append(Task(level_filename, spec))

def get_measured_solvers():
    solvers = [
        "astar",
        #"macroastar",
        #"macroastar,hweight=2",
        #"pgastar",
        #"pgastar,hweight=2",
        #"pgastar,hweight=5",
        #"relaxastar",
        #"relaxastar,one_way=True,greedy_on_exact=True",
        #"relaxastar,hweight=1.2,one_way=True,greedy_on_exact=True",
        #"relaxastar,hweight=2,one_way=True,greedy_on_exact=True",
        #"relaxpgastar,hweight=1.2,one_way=True,greedy_on_exact=True",
        #"relaxpgastar,hweight=2,one_way=True,greedy_on_exact=True",
        #"ida",
        #"ida,one_way=True",
Пример #5
0
import errno
import time
import cPickle as pickle
import re

from pylib import disk
from pylib.namedtuple import namedtuple

RESULTS_PATH = "../export/results.p"
SOLUTION_PATH_TEMPLATE = "../export/solutions/%(level_filename)s_%(spec)s"
SANITIZE_PATTERN = re.compile(r"[^a-zA-Z0-9()_=,-]")

Result = namedtuple("Result", "solved length cost num_visited")

def store_result(task, result):
    timestamp = int(time.time())
    record = (timestamp, tuple(task), tuple(result))
    _store_record(record)

def _store_record(record):
    records = get_records()
    records.append(record)
    disk.store_content(RESULTS_PATH, pickle.dumps(records))

def get_records():
    try:
        records = pickle.load(disk.open(RESULTS_PATH))
    except IOError, e:
        if e.errno == errno.ENOENT:
            records = []
Пример #6
0
from pylib.namedtuple import namedtuple
from pylib import v2, cache

Action = namedtuple("Action", "pre effect")

class Extender(object):
    def reset(self, start_s):
        """Resets itself for a new reachability analysis.
        It returns the effects of the start state
        as a list of (value, variable) pairs.
        """
        raise NotImplementedError

    def get_new_actions(self, reachable, new_values):
        """Returns actions that become newly possible.
        """
        raise NotImplementedError

    def get_reached_goal(self, start_s, reachable):
        """Returns the reached goal or None.
        """
        raise NotImplementedError


class GroundAction(object):
    """An immutable ground action.
    """
    def __init__(self, action, tile):
        self.action = action
        self.tile = tile
Пример #7
0
        # The macro_action.cmd stores the end state of the macro.
        macros = []
        for cost, end_s in self.partition.get_macro_edges(s):
            macros.append(Action(end_s, cost))

        return macros

    def predict(self, s, macro_a):
        return macro_a.get_cmd()

    def __getattr__(self, name):
        return getattr(self.env, name)


# The edges are sortable by cost needed to reach s.
Edge = namedtuple("Edge", "cost s")

class RadiusPartition(object):
    """Limits the macro reach by a radius of a cube.
    States outside the radius are reported as the end states.
    """
    def __init__(self, env):
        self.env = env
        self.radius = 2

    def get_macro_edges(self, s):
        """Returns edges to the reachable states outside
        the current cluster.
        """
        start_coords = self._get_coords(s)
Пример #8
0
        tools = _ExpandTools(cost_fn)
        if self.config.rollout:
            self.expander = _RolloutExpander(tools)
        else:
            self.expander = _ChildExpander(tools)

    def solve(self, env, s=None):
        if s is None:
            s = env.init()

        self.expander.tools.set_env(env)
        return _find_path(env, s, self.expander)


Node = namedtuple.namedtuple("Node", "f h g s prev_node a")


def _create_node(env, s, g, prev_node, a, cost_fn):
    """Returns a named tuple
    with a proper __cmp__.
    The node __cmp__ compares (f, h, g) values.
    A better node would have smaller (f, h, g) values.
    """
    h = env.estim_cost(s)
    f = cost_fn(g, h)
    return Node(f, h, g, s, prev_node, a)


def _find_path(env, s, expander):
    """Computes the shortest path from s by A*.
Пример #9
0
                if an unpreferred action has to be followed.
"""
DEFAULT_CONFIG = dict(
    estim_limit=False,
    exact_h=True,
    one_way=False,
    greedy_on_exact=False,
    admissible=True,
    hweight=1,
    unprefpenalty=0,
    glimit=3,
    greduce=1,
    rollout=False,
)

Config = namedtuple("Config", " ".join(DEFAULT_CONFIG.keys()))

SOLVERS = dict(
    ida=ida.Solver,
    astar=astar.Solver,
    steer=steering.SteeringSolver,
    rbfs=rbfs.RbfsSolver,
    rida=rbfs.IdaSolver,
    mc=mc.McSolver,
    percept=PerceptSolver,
)

PREFIXES = (
    ("macro", MacroEnv),
    ("hyper", HyperEnv),
    ("relaxed", RelaxedEnv),