Ejemplo n.º 1
0
    def is_grounded(self):
        R = self.resolution
        ground_layer = [
            Pos(x, 0, y) for x in range(R) for z in range(R)
            if self.matrix[x, 0, z] == FillState.Full
        ]
        if len(ground_layer) == 0:
            return False

        full_unvisited = Set()
        for x in range(R):
            for y in range(R):
                for z in range(R):
                    if self.matrix[x, y, z] == FillState.Full:
                        full_unvisited.add(Pos(x, y, z))

        core = Set([pos for pos in full_unvisited if pos.y == 0])
        boundary = Set([
            pos for pos in self.neighbors(core)
            if pos in full_unvisited and pos not in core
        ])
        while boundary:
            for pos in boundary:
                core.add(pos)
                full_unvisited.remove(pos)
            boundary = Set([
                pos for pos in self.neighbors(core)
                if pos in full_unvisited and pos not in core
            ])
        return not bool(full_unvisited)
Ejemplo n.º 2
0
 def pos_neighbors(coords):
     vals = [-1, 0, 1]
     deltas = [
         Vec(dx, dy, dz) for dx in vals for dy in vals for dz in vals
     ]
     nbrs = Set([
         coords + delta for delta in deltas
         if (not delta.is_zero()) and self.is_coord_valid(coords +
                                                          delta)
     ])
     return nbrs
 def __and__(self, other):
     """
     Implements the '&' operator.
     In order to intersect two object sets successfully one of the following
     conditions must be met:
         1. Both of the object sets must contain objects
         2. Object sets must have identical schema
     """
     if self.schema == other.schema:
         intersection = Set.__and__(self, other)
         intersection.schema = self.schema
         return intersection
     else:
         raise TypeError('Unsupported operand (&). Object sets do not ' +
                         'have the same schema')
Ejemplo n.º 4
0
 def __and__(self, other):
     """
     Implements the '&' operator.
     In order to intersect two object sets successfully one of the following
     conditions must be met:
         1. Both of the object sets must contain objects
         2. Object sets must have identical schema
     """
     if self.schema == other.schema:
         intersection = Set.__and__(self, other)
         intersection.schema = self.schema
         return intersection
     else:
         raise TypeError('Unsupported operand (&). Object sets do not ' +
                         'have the same schema')
Ejemplo n.º 5
0
def graph_search(problem, priority_func, heuristic=None):

    # start fringe (state, actions, cost)
    """
    :param problem: problem
    :param priority_func: func(Fringe) returns int
    :param heuristic: func(state, problem)
    :return: actions for the problem
    :rtype: list
    """
    goal_fringe = fringe = Fringe(problem.getStartState(), [], 0, 0)

    # closed set
    closed = Set()

    # all possible states
    from util import PriorityQueueWithFunction
    fringe_queue = PriorityQueueWithFunction(priority_func)
    fringe_queue.push(fringe)

    while not fringe_queue.isEmpty():
        # pop
        fringe = fringe_queue.pop()

        # goal test
        if problem.isGoalState(fringe.state):
            goal_fringe = fringe
            break

        # closed set
        if contains(closed, fringe.state):
            continue
        closed.add(fringe.state)

        # expand
        for successor in problem.getSuccessors(fringe.state):
            next_state, action, cost = successor
            expanded_fringe = Fringe(next_state, fringe.actions[:],
                                     fringe.cost_backward + cost, 0)
            expanded_fringe.actions.append(action)
            if heuristic is not None:
                expanded_fringe.cost_forward = heuristic(
                    expanded_fringe.state, problem)

            # push
            fringe_queue.push(expanded_fringe)

    return goal_fringe.actions if goal_fringe is not None else []
Ejemplo n.º 6
0
def split_data(new_split = True):
  if new_split:
    A_files = glob.glob("{}/*-T1_resliced.nii.gz".format(A_dir))
    subjects = Set()
    for A_file in A_files:
      subjects.add(get_subject_id(A_file))

    B_files = glob.glob("{}/*-color_fa.nii.gz".format(B_dir))
    N = len(B_files)
    indexes = np.random.permutation(N)
    train_indexes = indexes[0 : int(N*0.7)]
    val_indexes = indexes[int(N*0.7)+1 : int(N*0.8)]
    test_indexes = indexes[int(N*0.8)+1 : N]

    def  save_split(split, files, ids):
      outputfile = "{}/{}_volumes.txt".format(destination_dir, split)
      rlt_files = []
      with open(outputfile, 'w') as f:
        for i in ids:
          if get_subject_id(files[i]) in subjects:
            rlt_files.append(files[i])
            f.write("{}\n".format(files[i]))
      return rlt_files

    train_files = save_split("train", B_files, train_indexes)
    val_files = save_split("val", B_files, val_indexes)
    test_files = save_split("test", B_files, test_indexes)
  else:
    def read_split(split):
      filename = "{}/{}_volumes.txt".format(destination_dir, split)
      with open(filename, 'r') as f:
        content = f.readlines()
      rlt_files = []
      for line in content:
        rlt_files.append(line)
      return rlt_files

    train_files = read_split("train")
    val_files = read_split("val")
    test_files = read_split("test")

  return train_files, val_files, test_files
Ejemplo n.º 7
0
	def __hash__(self):
		""" Use the hash funtion from Set,
		I'm not sure that it works for collections with multiple elements.

		>>> hash(frozenbag()) == hash(frozenbag((0,)))
		False
		>>> hash(frozenbag('a')) == hash(frozenbag(('aa')))
		False
		>>> hash(frozenbag('a')) == hash(frozenbag(('aaa')))
		False
		>>> hash(frozenbag('a')) == hash(frozenbag(('aaaa')))
		False
		>>> hash(frozenbag('a')) == hash(frozenbag(('aaaaa')))
		False
		>>> hash(frozenbag('ba')) == hash(frozenbag(('ab')))
		True
		>>> hash(frozenbag('badce')) == hash(frozenbag(('dbeac')))
		True
		"""
		return Set._hash(self)
Ejemplo n.º 8
0
def generate_test_class_type(g):
    """
    :param g: rdflib graph
    :return:
    """
    classes_set = Set()
    try:
        # for rdf_type, _ in g.subject_objects(predicate=RDF.type):
        # for _, rdf_type in g.subject_objects(predicate=RDFS.Class):
        for rdf_type in g.subjects(predicate=RDF.type, object=OWL.Class):
            classes_set.add(rdf_type)
        tests = []
        for c in classes_set:
            t = "%s type Class" % c
            print(t)
            tests.append(t)
        return tests
    except Exception as e:
        dolog("error in generating themis class_type tests")
        dolog(str(e))
Ejemplo n.º 9
0
    __and__ = Set.__and__
    __or__ = Set.__or__
    __sub__ = Set.__sub__
    __xor__ = Set.__xor__

    issubset = __le__
    issuperset = __ge__
    union = __or__
    intersection = __and__
    difference = __sub__
    symmetric_difference = __xor__

    isdisjoint = Set.isdisjoint

Set.register(PSet)
Hashable.register(PSet)

_EMPTY_PSET = PSet(pmap())


def pset(iterable=(), pre_size=8):
    """
    Creates a persistent set from iterable. Optionally takes a sizing parameter equivalent to that
    used for :py:func:`pmap`.

    >>> s1 = pset([1, 2, 3, 2])
    >>> s1
    pset([1, 2, 3])
    """
    if not iterable:
Ejemplo n.º 10
0
    __and__ = Set.__and__
    __or__ = Set.__or__
    __sub__ = Set.__sub__
    __xor__ = Set.__xor__

    issubset = __le__
    issuperset = __ge__
    union = __or__
    intersection = __and__
    difference = __sub__
    symmetric_difference = __xor__

    isdisjoint = Set.isdisjoint

Set.register(PSet)
Hashable.register(PSet)

_EMPTY_PSET = PSet(pmap())


def pset(iterable=(), pre_size=8):
    """
    Creates a persistent set from iterable. Optionally takes a sizing parameter equivalent to that
    used for :py:func:`pmap`.

    >>> s1 = pset([1, 2, 3, 2])
    >>> s1
    pset([1, 2, 3])
    """
    if not iterable:
Ejemplo n.º 11
0
        x in self
        """
        return _intervals(self.wrapped)

    def reversed_intervals(self):
        """Iterator over the reverse of intervals()"""
        return _reversed_intervals(self.wrapped)

    def __reversed__(self):
        for start, end in self.reversed_intervals():
            for i in range(end - 1, start - 1, -1):
                yield i


Sequence.register(IntSet)
Set.register(IntSet)


def _new_maybe_empty_interval(start, end):
    if end <= start:
        return ()
    return _new_interval(start, end)


_START = 0
_END = 1
_SIZE = 2
_PREFIX = 3
_MASK = 4
_LEFT = 5
_RIGHT = 6
Ejemplo n.º 12
0
)

# Force scans to ensure __new__ is set correctly
# FIXME: This shouldn't be necessary!
NSArray.__new__ = nsarray_new
NSMutableArray.__new__ = nsmutablearray_new
NSMutableArray.alloc().init()
# NSMutableSet.set()

NSSet = lookUpClass("NSSet")
NSMutableSet = lookUpClass("NSMutableSet")

try:
    from collections import Set

    Set.register(NSSet)
except:
    Set = (set, frozenset, NSSet)


def nsset_isdisjoint(self, other):
    for item in self:
        if item in other:
            return False
    return True


def nsset_union(self, *other):
    result = NSMutableSet()
    result.unionSet_(self)
    for val in other:
Ejemplo n.º 13
0
        x in self
        """
        return _intervals(self.wrapped)

    def reversed_intervals(self):
        """Iterator over the reverse of intervals()"""
        return _reversed_intervals(self.wrapped)

    def __reversed__(self):
        for start, end in self.reversed_intervals():
            for i in range(end - 1, start - 1, -1):
                yield i


Sequence.register(IntSet)
Set.register(IntSet)


def _new_maybe_empty_interval(start, end):
    if end <= start:
        return ()
    return _new_interval(start, end)


_START = 0
_END = 1
_SIZE = 2
_PREFIX = 3
_MASK = 4
_LEFT = 5
_RIGHT = 6
Ejemplo n.º 14
0
    ('__rmul__', nsarray_mul),
)

# Force scans to ensure __new__ is set correctly
# FIXME: This shouldn't be necessary!
NSArray.__new__ = nsarray_new
NSMutableArray.__new__ = nsmutablearray_new
NSMutableArray.alloc().init()
#NSMutableSet.set()

NSSet = lookUpClass('NSSet')
NSMutableSet = lookUpClass('NSMutableSet')

try:
    from collections import Set
    Set.register(NSSet)
except:
    Set = (set, frozenset, NSSet)


def nsset_isdisjoint(self, other):
    for item in self:
        if item in other:
            return False
    return True


def nsset_union(self, *other):
    result = NSMutableSet()
    result.unionSet_(self)
    for val in other:
Ejemplo n.º 15
0
 def __hash__(self):
     return Set._hash(self)