Esempio n. 1
0
def dijkstra_shortest_path(graph: AdjacentListGraph, start: SPVertice,
                           end: SPVertice) -> Tuple[int, List[SPVertice]]:
    visited = set()
    for v in graph.vertices:
        v.shortest_path_estimate = inf
    start.shortest_path_estimate = 0
    q = bintrees.RBTree()
    for v in graph.vertices:
        q.insert(v, v.shortest_path_estimate)
    while not q.is_empty():
        u, current_sp_eta = q.min_item()
        q.remove(u)
        visited.add(u)
        if u == end:
            shortest_path = [u]
            while u.previous:
                u = u.previous
                shortest_path.append(u)
            return end.shortest_path_estimate, list(reversed(shortest_path))
        for adj_v, w in graph[u].items():
            if adj_v in visited:
                continue
            if adj_v.shortest_path_estimate > current_sp_eta + w:
                adj_v.previous = u
                q.remove(adj_v)
                adj_v.shortest_path_estimate = current_sp_eta + w
                q.insert(adj_v, adj_v.shortest_path_estimate)
    return inf, []
Esempio n. 2
0
def a_star(
        graph: AdjacentListGraph,
        start: PlaneVertice,
        end: PlaneVertice,
        h_function: Callable = h_euclid_dist
) -> Tuple[int, List[PlaneVertice]]:
    visited = set()
    start.shortest_path_estimate = 0
    q = bintrees.RBTree()
    for v in graph.vertices:
        q.insert(v, v.shortest_path_estimate)
    while not q.is_empty():
        u, _ = q.min_item()
        q.remove(u)
        visited.add(u)
        if u == end:
            shortest_path = [u]
            while u.previous:
                u = u.previous
                shortest_path.append(u)
            return end.shortest_path_estimate, list(reversed(shortest_path))
        for adj_v, w in graph[u].items():
            if adj_v in visited:
                continue
            if adj_v.shortest_path_estimate > u.shortest_path_estimate + w:
                adj_v.previous = u
                q.remove(adj_v)
                adj_v.shortest_path_estimate = u.shortest_path_estimate + w
                q.insert(adj_v,
                         adj_v.shortest_path_estimate + h_function(adj_v, end))
    return inf, []
Esempio n. 3
0
File: 9.py Progetto: oc0de/pyEPI
def dijkstra_shortest_path(s, t):
    # Initialization of the distance of starting point.
    s.distance_with_fewest_edges = DistanceWithFewestEdges(0, 0)
    node_set = bintrees.RBTree([(s, None)])

    while node_set:
        # Extracts the minimum distance vertex from heap.
        u = node_set.pop_min()[0]
        if u.id == t.id:
            break

        # Relax neighboring vertices of u.
        for v in u.edges:
            v_distance = u.distance_with_fewest_edges.distance + v.distance
            v_num_edges = u.distance_with_fewest_edges.min_num_edges + 1
            new_distance = DistanceWithFewestEdges(v_distance, v_num_edges)
            if v.vertex.distance_with_fewest_edges > new_distance:
                node_set.discard(v.vertex)
                v.vertex.pred = u
                v.vertex.distance_with_fewest_edges = new_distance
                node_set.insert(v.vertex, None)

    def output_shortest_path(v):
        if v:
            output_shortest_path(v.pred)
            print(v.id)

    # Outputs the shortest path with fewest edges.
    output_shortest_path(t)
Esempio n. 4
0
    def projection_L1ball(self, v):
        """Find the projection of a vector onto the L1 ball. See for reference
        'Efficient projections onto L1-ball for learning in high dimensions'
        Duchi , Schwartz, Singer. SECTION 4, Figure 2.
        Parameters
        -------------------
        v : vector to be projected
        Returns
        -------------------
        w : projection on v onto the L1 ball of radius z
        """

        vector_copy = np.abs(v)
        keys_ar = np.unique(vector_copy)
        r = map(lambda k: (np.where(k == vector_copy)[0]).sum(), keys_ar)
        r = list(r)
        # r = np.where(j == vector_copy)[0].sum()
        # print("where ", r)
        # r = map(lambda k: len(np.where(k == vector_copy)[0]), keys_ar)
        # print("where2 ", r)
        n_elements = np.cumsum(r[::-1])[::-1]  # r di cui abbiamo bisogno
        s_sum = keys_ar * r
        cum_sum = np.cumsum(s_sum[::-1])[::-1]

        dictionary = {}
        for i in range(len(keys_ar)):
            dictionary[keys_ar[i]] = [n_elements[i], cum_sum[i]]

        rb_tree = bintrees.RBTree(dictionary)
        theta = self._pivotsearch(rb_tree, rb_tree._root, 0., 0.)

        return np.clip(vector_copy - theta, a_min=0, a_max=np.inf) * np.sign(v)
Esempio n. 5
0
def OBJECTIVE(measure):
    """
    produces the objective LineData()s RBTree arrangement
    given the dictionary of interval measures;
    N levels => N+1 LineData()s (verify?)
    """
    def sweep(x):
        Xminus = np.cumsum(x)
        total = Xminus[-1]
        Xplus = total - Xminus
        X = Xplus - Xminus
        return X

    # prepare constants kappa and alpha
    PREALPHA = np.array([0.] + [w for f, w in measure.items()])
    ALPHA = sweep(PREALPHA)

    PREKAPPA = np.array([0.] + [f * w for f, w in measure.items()])
    KAPPA = sweep(PREKAPPA)

    Cz = bintrees.RBTree()
    ff = [f for f in measure] + [np.inf]  # should be in order
    for f, alpha, kappa in zip(ff, ALPHA, KAPPA):
        Cz.insert(-f, LineData(alpha, kappa))

    return Cz
Esempio n. 6
0
 def act(*args):
     global t
     h, card = t.max_item()
     # print(card)
     policy[p] = card.uid
     if card.update_card_limit(p.w) == 0:
         t.remove(h)
     t = T.RBTree(t.items())
     return h, card
def generate_first_k_a_b_sqrt2(k):
    candidates = bintrees.RBTree([(ABSqrt2(0, 0), None)])
    result = []
    while len(result) < k:
        next_smallest = candidates.pop_min()[0]
        result.append(next_smallest.val)
        candidates[ABSqrt2(next_smallest.a + 1, next_smallest.b)] = None
        candidates[ABSqrt2(next_smallest.a, next_smallest.b + 1)] = None
    return result
Esempio n. 8
0
def generate_first_k_a_b_sqrt2(k):
    tree = bintrees.RBTree()
    tree.insert(AB(0, 0), None)
    result = []
    for i in range(k):
        cand = tree.pop_min()[0]
        result.append(cand.val)
        tree.insert(AB(cand.a + 1, cand.b), None)
        tree.insert(AB(cand.a, cand.b + 1), None)
    return result
Esempio n. 9
0
def generate_first_k_a_b_sqrt2(k: int) -> List[float]:
    candidate = bintrees.RBTree([(Pairing(0, 0), None)])
    res = []

    while len(res) < k:
        min_pair, _ = candidate.pop_min()
        res.append(min_pair.val)
        candidate.insert(Pairing(min_pair.a + 1, min_pair.b), None)
        candidate.insert(Pairing(min_pair.a, min_pair.b + 1), None)
    return res
Esempio n. 10
0
def trapezoid_tree(trap_dict):
    # for trapezoid containment query DS
    tree = bintrees.RBTree()

    for I in trap_dict:
        a, b = I
        L1, L2 = trap_dict[I]

        tree[a] = (a, b, L1, L2)

    return tree
Esempio n. 11
0
def generate_first_k_a_b_sqrt2(k: int) -> List[float]:
    # Initial for 0 + 0 * sqrt(2).
    candidates = bintrees.RBTree([Number(0,0), None]) 
    result: List[float] = []
    while len(result) < k: 
        next_smallest = candidates.pop_min()[0]
        result.append(next_smallest.val)
        # Adds the next two numbers derived 
        candidates[Number(next_smallest.a + 1, next_smallest.b)] = None 
        candidates[Number(next_smallest.a, next_smallest.b + 1)] = None 
    return result
Esempio n. 12
0
def find_closest_elements_in_sorted_arrays(sorted_arrays):

    min_distance_so_far = float('inf')

    # stores array iterators in each entry.
    iters = bintrees.RBTree()

    for idx, sorted_array in enumerate(sorted_arrays):
        it = iter(sorted_array)

        print("it: ", it)

        first_min = next(it, None)

        print("first_min: ", first_min)

        print("idx: ", idx)
        print("sorted_array: ", sorted_array)

        if first_min is not None:
            iters.insert((first_min, idx), it)

            print("iters: ", iters)

    print("\n")
    while True:

        min_value, min_idx = iters.min_key()

        print("min_value: ", min_value)
        print("min_idx: ", min_idx)

        max_value = iters.max_key()[0]

        print("max_value: ", max_value)

        min_distance_so_far = min(max_value - min_value, min_distance_so_far)

        print("min_distance_so_far: ", min_distance_so_far)

        it = iters.pop_min()[1]

        print("iters: ", iters)

        next_min = next(it, None)
        print("next_min: ", next_min)

        # return if some array has no remaining elements.
        if next_min is None:
            return min_distance_so_far
        iters.insert((next_min, min_idx), it)
        print("iters: ", iters)
        print("\n")
Esempio n. 13
0
def generate_first_k_a_b_sqrt2(k):
    # Initial for 0 + 0 * sqrt(2).
    candidates = bintrees.RBTree([(ABSqrt2(0, 0), None)])

    result = []
    while len(result) < k:
        next_smallest = candidates.pop_min()[0]
        result.append(next_smallest)
        # Adds the next two numbers derived from next_smallest.
        candidates[ABSqrt2(next_smallest.a + 1, next_smallest.b)] = None
        candidates[ABSqrt2(next_smallest.a, next_smallest.b + 1)] = None
    return result
def SEGMENT(S, T):
    """ sorted points into queues hanging from an indexed segment """
    segment = bintrees.RBTree()

    for i, s in enumerate(S):
        q = ensure_key(s, segment)
        q.P.append(i)

    for j, t in enumerate(T):
        q = ensure_key(t, segment)
        q.Q.append(j)

    return segment
Esempio n. 15
0
def generate_first_k_a_b_sqrt2(k):
    tree = bintrees.RBTree()
    tree.insert(0, (0, 0))
    res = []

    def f(a, b):
        return a + b * 2**0.5

    while len(res) < k:
        v, pair = tree.pop_min()
        res.append(v)
        tree.insert(f(pair[0] + 1, pair[1]), (pair[0] + 1, pair[1]))
        tree.insert(f(pair[0], pair[1] + 1), (pair[0], pair[1] + 1))
    return res
def get_most_visited_pages(it, k):
    next_page = next(it, None)
    rbt = bintrees.RBTree()
    num_elements = 0
    while next_page:
        if next_page in rbt:
            rbt[next_page] += 1
        else:
            if num_elements == k:
                rbt.min_key()  #remove the min key
            else:
                rbt[next_page] = 1
                num_elements += 1
        next_page = next(it, None)
    return rbt
Esempio n. 17
0
def find_closest_in_three_sorted_arrays(sorted_arrays):
    min_distance_so_far = float('inf')
    iters = bintrees.RBTree()
    for idx, sorted_array in enumerate(sorted_arrays):
        it = iter(sorted_array)
        first_min = next(it, None)
        if first_min is not None:
            iters.insert((first_min, idx), it)
    while True:
        min_value, min_idx = iters.min_key()
        max_value = iters.max_key()[0]
        min_distance_so_far = min(max_value - min_value, min_distance_so_far)
        it = iters.pop_min()[1]
        next_min = next(it, None)
        if next_min is None:
            return min_distance_so_far
        iters.insert((next_min, min_idx), it)
def generate_first_k_a_b_sqrt2(k):

    # initial for 0 + 0 * sqrt(2).
    candidates = bintrees.RBTree([(Number(0, 0), None)])

    result = []
    while len(result) < k:
        next_smallest = candidates.pop_min()[0]

        print("candidates: ", candidates)
        print("next_smallest: ", next_smallest.val)

        result.append(next_smallest.val)
        # adds the next two numbers derived from next_smallest.
        candidates[Number(next_smallest.a + 1, next_smallest.b)] = None
        candidates[Number(next_smallest.a, next_smallest.b + 1)] = None

    return result
def find_closest_elements_in_sorted_arrays(sorted_arrays):
    min_so_far = float("inf")
    iters = bintrees.RBTree()
    for idx, sorted_array in enumerate(sorted_arrays):
        it = iter(sorted_array)
        first_min = next(it, None)
        if first_min is not None:
            iters.insert((first_min, idx), it)

    while True:
        min_value, min_idx = iters.min_key()
        max_value, _ = iters.max_key()
        min_so_far = min(min_so_far, max_value - min_value)
        it = iters.pop_min()[1]
        next_min = next(it, None)
        if next_min is None:
            return min_so_far
        iters.insert((next_min, min_idx), it)
def find_closest_elements_in_sorted_arrays(sorted_arrays):
    iters = bintrees.RBTree()
    for i, s in enumerate(sorted_arrays):
        it = iter(s)
        v = next(it, None)
        if not v is None:
            iters.insert((v, i), it)
    dist = float('inf')
    while True:
        pair, it = iters.pop_min()
        min_v, arr_i = pair
        max_v = iters.max_key()[0]
        dist = min(dist, max_v - min_v)
        next_v = next(it, None)
        if next_v is None:
            return dist
        else:
            iters.insert((next_v, arr_i), it)
    return 0
Esempio n. 21
0
def calculate_view_from_above(A):
    class Endpoint:
        def __init__(self, is_left, line):
            self.is_left = is_left
            self.line = line

        def __lt__(self, other):
            return self.value() < other.value()

        def value(self):
            return self.line.left if self.is_left else self.line.right

    sorted_endpoints = sorted([Endpoint(True, a)
                               for a in A] + [Endpoint(False, a) for a in A])
    result = []
    prev_xaxis = sorted_endpoints[0].value()  # Leftmost end point.
    prev = None
    active_line_segments = bintrees.RBTree()
    for endpoint in sorted_endpoints:
        if active_line_segments and prev_xaxis != endpoint.value():
            active_segment = active_line_segments.max_item()[1]
            if prev is None:  # Found first segment.
                prev = LineSegment(prev_xaxis, endpoint.value(),
                                   active_segment.color, active_segment.height)
            else:
                if (prev.height == active_segment.height
                        and prev.color == active_segment.color
                        and prev_xaxis == prev.right):
                    prev = prev._replace(right=endpoint.value())
                else:
                    result.append(prev)
                    prev = LineSegment(prev_xaxis, endpoint.value(),
                                       active_segment.color,
                                       active_segment.height)
        prev_xaxis = endpoint.value()

        if endpoint.is_left:  # Left end point.
            active_line_segments[endpoint.line.height] = endpoint.line
        else:  # Right end point.
            del active_line_segments[endpoint.line.height]

    # Output the remaining segment (if any).
    return result + [prev] if prev else result
def find_closest_elements_in_sorted_arrays(sorted_arrays):
    min_distance_so_far = float('inf')
    # Stores array iterators in each entry.
    iters = bintrees.RBTree()
    for idx, sorted_array in enumerate(sorted_arrays):
        it = iter(sorted_array)
        first_min = next(it, None)
        if first_min is not None:
            iters.insert((first_min, idx), it)

    while True:
        min_value, min_idx = iters.min_key()
        max_value = iters.max_key()[0]
        min_distance_so_far = min(max_value - min_value, min_distance_so_far)
        it = iters.pop_min()[1]
        next_min = next(it, None)
        # Return if some array has no remaining elements.
        if next_min is None:
            return min_distance_so_far
        iters.insert((next_min, min_idx), it)
Esempio n. 23
0
def dijkstra_shortest_paths(graph: AdjacentListGraph, start: SPVertice):
    visited = set()
    for v in graph.vertices:
        v.shortest_path_estimate = inf
    start.shortest_path_estimate = 0
    q = bintrees.RBTree()
    for v in graph.vertices:
        q.insert(v, v.shortest_path_estimate)
    while not q.is_empty():
        u, current_sp_eta = q.min_item()
        q.remove(u)
        visited.add(u)
        for adj_v, w in graph[u].items():
            if adj_v in visited:
                continue
            if adj_v.shortest_path_estimate > current_sp_eta + w:
                adj_v.previous = u
                q.remove(adj_v)
                adj_v.shortest_path_estimate = current_sp_eta + w
                q.insert(adj_v, adj_v.shortest_path_estimate)
def find_closest_elements_in_sorted_arrays(sorted_arrays):
    min_dist_so_far = float('inf')
    iters = bintrees.RBTree()
    # you need i, to tell you what idx you're coming from down below
    for i, sorted_arr in enumerate(sorted_arrays):
        it = iter(sorted_arr)
        first_min = next(it, None)
        if first_min is not None:
            it.insert((first_min, i), it)
    while True:
        min_val, min_idx = iters.min_key()
        max_val = iters.max_key()[0]
        min_dist_so_far = min(max_val - min_val, min_dist_so_far)
        it = iters.pop_min()[1]
        next_min = next(it, None)
        # if one is done, you've already exhausted finding the min between the 3
        if next_min is None:
            return min_dist_so_far
        iters.insert((next_min, min_idx), it)
    return 0
Esempio n. 25
0
def MEASURE(segment, length, rbound=None):
    if rbound is not None:
        lbound = length
    else:
        lbound = 0.
        rbound = length

    # bintree instead of dict so that it is enumerated in sorted order
    measure = bintrees.RBTree()

    posts = [lbound] + [y for y, q in segment.iter_items()] + [rbound]
    intervals = zip(posts[:-1], posts[1:])

    deltas = [0] + [len(q.P) - len(q.Q) for y, q in segment.iter_items()]
    F = np.cumsum(deltas)

    for (a, b), f in zip(intervals, F):
        measure.setdefault(f, 0.)
        measure[f] += b - a

    return measure
def find_closest_elem_in_sorted_arrays(sorted_arrays):
    min_distance_so_far = float('inf')

    iters = bintrees.RBTree()
    for idx, s_arr in enumerate(sorted_arrays):
        it = iter(s_arr)
        first_min = next(it, None)
        if first_min is not None:
            iters.insert((first_min, idx), it)

    while True:
        min_val, min_idx = iters.min_key()
        max_val = iters.max_key()[0]
        min_distance_so_far = min(max_val - min_val, min_distance_so_far)

        min_itr = iters.pop_min()[1]
        next_min = next(min_itr, None)

        if next_min is None:
            return [min_val] + [key[0] for key in iters.keys()]

        iters.insert((next_min, min_idx), min_itr)
def find_closest_elements_in_sorted_arrays(sorted_arrays):
    min_distance_so_far = float('inf')
    tree = bintrees.RBTree()
    for idx, sorted_array in enumerate(sorted_arrays):
        tree.insert((sorted_array[0], idx), 0)

    result = []
    while len(tree) == 3:
        result = []
        min_value, aidx = tree.min_key()  # O(k)
        max_value, aidx = tree.max_key()  # O(k)
        if min_distance_so_far > max_value - min_value:
            min_distance_so_far = max_value - min_value
            result = []
            for node in tree:
                result.append(node[0])
        key, idx = tree.pop_min()  # O(k)
        next_min, arr_idx = key
        if idx + 1 < len(sorted_arrays[arr_idx]):
            tree.insert((sorted_arrays[arr_idx][idx + 1], arr_idx),
                        idx + 1)  # O(k)
    return (min_distance_so_far, result)
Esempio n. 28
0
def closest_entry_in_3_arrays(sorted_arrays):
    bst = bintrees.RBTree()
    for idx, sorted_array in enumerate(sorted_arrays):
        array_iter = iter(sorted_array)
        min_value = next(array_iter, None)
        if min_value is not None:
            bst.insert((min_value, idx), array_iter)

    best_min_distance_so_far = float('inf')
    while True:
        min_key, min_iter = bst.min_item()
        max_key, max_iter = bst.max_item()
        min_distance_now = max_key[0] - min_key[0]
        best_min_distance_so_far = min(best_min_distance_so_far,
                                       min_distance_now)
        bst.pop_min()
        next_value = next(min_iter, None)
        if next_value is None:
            return best_min_distance_so_far
        bst.insert((next_value, min_key[1]), min_iter)

    return best_min_distance_so_far
def find_closest_elements_in_sorted_arrays(sorted_arrays):
    min_dist_so_far = float('inf')
    iters = bintrees.RBTree()
    for idx, array in enumerate(sorted_arrays):
        it = iter(array)
        first_min = next(it, None)
        if first_min:
            # first_min is inserted with idx as tuple
            # to differentiate duplicate elements among sorted arrays
            iters.insert((first_min, idx), it)

    while True:
        print_tree(iters)
        min_value, min_idx = iters.min_key()
        max_value = iters.max_key()[0]
        min_dist_so_far = min(max_value - min_value, min_dist_so_far)
        it = iters.pop_min()[1]
        next_min = next(it, None)
        if next_min is None:
            return min_dist_so_far
        # next_min is inserted with min_idx as tuple
        # to differentiate duplicate elements among sorted arrays
        iters.insert((next_min, min_idx), it)
Esempio n. 30
0
def Astar(start, end):

    open = bintrees.RBTree()
    in_open = {}
    d[start] = Nod(heuristic(start))
    d[start].f = 0
    d[start].g = 0
    open.insert((d[start].f, start), d[start].f)
    in_open[start] = 1

    while len(open) > 0:

        best = open.pop_min()
        current = best[0][1]
        del in_open[current]

        if current == end:
            return make_path(current)

        successors = expand(current)
        #For any in the expansion list
        for adj in successors:
            if adj not in d:
                d[adj] = Nod(heuristic(adj))

            now_g = d[current].g + 1
            if now_g < d[adj].g:

                d[adj].last = current
                d[adj].g = now_g
                d[adj].f = d[adj].g + d[adj].h

                if adj not in in_open:
                    open.insert((d[adj].f, adj), d[adj].f)
                    in_open[adj] = 1

    return "Nu solution"