def compute_value(grid, goal, cost): value = get_init_value_grid(grid, goal, MAX_COST) policy = get_init_policy(grid, goal) change = OrderedSet() change |= (get_neighbors(grid, goal)) while change: current_cell = change.pop() stochastic_cost, optimal_direction = get_min_cost( grid, value, current_cell) if stochastic_cost + cost < value[current_cell[0]][current_cell[1]]: value[current_cell[0]][current_cell[1]] = stochastic_cost + cost policy[current_cell[0]][current_cell[1]] = optimal_direction neighbors = get_neighbors(grid, current_cell) change |= (neighbors) return value, policy
def compute_value(grid, goal, cost): value = get_init_value_grid(grid, goal, 99) policy = get_init_policy(grid, goal) change = OrderedSet() change |= (get_neighbors(grid, goal)) while change: current_cell = change.pop(last=False) min_cost, min_direction = get_min_cost(grid, value, current_cell) if min_cost + cost < value[current_cell[0]][current_cell[1]]: value[current_cell[0]][current_cell[1]] = min_cost + cost policy[current_cell[0]][current_cell[1]] = min_direction neighbors = get_neighbors(grid, current_cell) change |= (neighbors) for row in policy: print(row) for row in value: print(row) return value
class KBucket(object): def __init__(self, rangeLower, rangeUpper, ksize): self.range = (rangeLower, rangeUpper) self.nodes = OrderedDict() self.replacementNodes = OrderedSet() self.touchLastUpdated() self.ksize = ksize def touchLastUpdated(self): self.lastUpdated = time.time() def getNodes(self): return self.nodes.values() def split(self): midpoint = (self.range[0] + self.range[1]) / 2 one = KBucket(self.range[0], midpoint, self.ksize) two = KBucket(midpoint + 1, self.range[1], self.ksize) for node in self.nodes.values(): bucket = one if node.long_id <= midpoint else two bucket.nodes[node.id] = node return (one, two) def removeNode(self, node): if node.id not in self.nodes: return # delete node, and see if we can add a replacement del self.nodes[node.id] if len(self.replacementNodes) > 0: newnode = self.replacementNodes.pop() self.nodes[newnode.id] = newnode def hasInRange(self, node): return self.range[0] <= node.long_id <= self.range[1] def isNewNode(self, node): return node.id not in self.nodes def addNode(self, node): """ Add a C{Node} to the C{KBucket}. Return True if successful, False if the bucket is full. If the bucket is full, keep track of node in a replacement list, per section 4.1 of the paper. """ if node.id in self.nodes: del self.nodes[node.id] self.nodes[node.id] = node elif len(self) < self.ksize: self.nodes[node.id] = node else: self.replacementNodes.push(node) return False return True def depth(self): sp = shared_prefix([n.id for n in self.nodes.values()]) return len(sp) def head(self): return self.nodes.values()[0] def __getitem__(self, id): return self.nodes.get(id, None) def __len__(self): return len(self.nodes)