예제 #1
0
 def __add_recently(self, key, val):
     node = Node(key, val)
     self.cache.add_last(node)
     self.map[key] = node
예제 #2
0
 def test_node_gets_present_time_as_updated_time_on_insertion(self):
     now = time_now()
     node = Node(0, set(), **temp_info)
     self.assertAlmostEqual(now, node.get_update_time(), places=0)
예제 #3
0
def make_density_split_node(node, N, feature_indices):
    """
    Selects dimension and threshold where node is to be split up

    :param node: Node
        Node to be split

    :param N: int
        Number of training instances

    :param feature_indices: array-like of shape (D_try, )
        Contains feature indices to be considered in the present split

    :return: tuple
        Tuple of left and right children nodes (to be placed on the stack)

    """
    n, D = node.data.shape
    m, M = node.box
    v = np.prod(M - m)
    if v <= 0:
        raise ValueError("Zero volume (should not happen)")

    # Find best feature j (among 'feature_indices') and best threshold t for the split
    e_min = float("inf")
    j_min, t_min = None, None

    for j in feature_indices:
        # Duplicate feature values have to be removed because candidate thresholds are
        # the midpoints of consecutive feature values, not the feature value itself
        dj = np.sort(np.unique(node.data[:, j]))
        # Compute candidate thresholds
        tj = (dj[1:] + dj[:-1]) / 2

        # Compute Leave-One-Out error of resulting children nodes for each candidate threshold
        for t in tj:
            # Compute number of instances in left and right children
            nl = np.sum(node.data[:, j] <= t)
            nr = n - nl
            # Compute volume of left and right nodes
            vl = t / (M[j] - m[j])  # vl = v * t / (M[j] - m[j])
            vr = 1.0 - vl  # vr = v - vl
            # Notice actual volumes are commented. These differ by the constant factor v.

            if vl == 0 or vr == 0:
                continue
            # Compute LOO errors
            el = (nl / (N * vl)) * (nl / N - 2.0 * ((nl - 1) / (n - 1)))
            er = (nr / (N * vr)) * (nr / N - 2.0 * ((nr - 1) / (n - 1)))

            # Choose best threshold that minimizes sum of LOO error
            loo_error = el + er
            if loo_error < e_min:
                e_min = loo_error
                j_min = j
                t_min = t

    # Create children
    left = Node()
    right = Node()

    # Initialize 'left' and 'right' with the data subsets and bounding boxes
    # according to the optimal split found above
    left.data = node.data[node.data[:, j_min] <= t_min, :]
    left.box = m.copy(), M.copy()
    left.box[1][j_min] = t_min

    right.data = node.data[node.data[:, j_min] > t_min, :]
    right.box = m.copy(), M.copy()
    right.box[0][j_min] = t_min

    node.left = left
    node.right = right
    node.feature = j_min
    node.threshold = t_min

    return left, right
예제 #4
0
def find_nth_to_last(root, nth):
    if root is None or nth < 0:
        return None
    p2 = root
    for x in xrange(0, nth):
        p2 = p2.next
        if p2 is None:
            return None
    p1 = root
    while p2.next is not None:
        p1 = p1.next
        p2 = p2.next
    return p1


root = Node(0)
root.append_to_tail(1)
root.append_to_tail(2)
root.append_to_tail(3)
root.append_to_tail(4)
root.append_to_tail(5)
root.append_to_tail(6)
root.append_to_tail(7)
root.append_to_tail(8)
root.append_to_tail(9)

print_nodes(root)
nth = 2
node = find_nth_to_last(root, nth)
print "%s to last: %s" % (nth, node.data)
예제 #5
0
    def test_hash_and_queue_changes_in_a_complex_tree(self):
        update_queue = set()

        root = Node(randomPK, update_queue)
        root_child1 = Node(getRandomPK(), update_queue)
        root_child2 = Node(getRandomPK(), update_queue)
        root_child1_child1 = Node(getRandomPK(), update_queue)
        root_child1_child2 = Node(getRandomPK(), update_queue)
        root_child2_child1 = Node(getRandomPK(), update_queue)
        root_child2_child2 = Node(getRandomPK(), update_queue)
        root_child1_child1_child1 = Node(getRandomPK(), update_queue)

        all_nodes = [locals()[x] for x in locals().keys() if 'root' in x]

        # Each new node announces its presence in the update queue
        self.assertSetEqual(update_queue, set([x._pk for x in all_nodes]))

        update_queue = set()
        for x in all_nodes:
            x._update_hash_queue = update_queue


        #start creating relationships
        old_root_hash = root.get_sync_hash()
        old_root_child1_hash = root_child1.get_sync_hash()
        root.add_child(root_child1)
        self.assertSetEqual(update_queue, set([root._pk, root_child1._pk]))
        new_root_hash = root.get_sync_hash()
        new_root_child1_hash = root_child1.get_sync_hash()

        self.assertTrue(TestNodeCore.check_sync_hash_old_new(old_root_hash, new_root_hash, False, True, False))
        self.assertTrue(TestNodeCore.check_sync_hash_old_new(old_root_child1_hash, new_root_child1_hash, True, True, True))

        root_child1.add_child(root_child1_child1)
        self.assertSetEqual(update_queue, set([root._pk, root_child1._pk, root_child1_child1._pk]))

        root.add_child(root_child2)
        self.assertSetEqual(update_queue, set([root._pk, root_child1._pk, root_child1_child1._pk, root_child2._pk]))

        #create complete relationship
        root_child1.add_child(root_child1_child2)
        root_child2.add_child(root_child2_child1)
        root_child2.add_child(root_child2_child2)
        root_child1_child1.add_child(root_child1_child1_child1)

        self.assertEqual(root._number_of_children(), 2)
        self.assertEqual(root_child1._number_of_children(), 2)
        self.assertEqual(root_child2._number_of_children(), 2)
        self.assertEqual(root_child1_child1._number_of_children(), 1)
        self.assertEqual(root_child1_child2._number_of_children(), 0)
        self.assertEqual(root_child2_child1._number_of_children(), 0)
        self.assertEqual(root_child2_child2._number_of_children(), 0)

        self.assertEqual(len(update_queue), 8)

        self.assertIn(root_child1_child1_child1, root_child1_child1._children)

        # test that changing a child's description, changes its hash and adds self
        # pk in the update queue

        update_queue.remove(root_child2_child2._pk)
        old_sync_hash = root_child2_child2.get_sync_hash()
        root_child2_child2.something = "Sometihng"
        new_sync_hash = root_child2_child2.get_sync_hash()
        self.assertIn(root_child2_child2._pk, update_queue)
        self.assertTrue(TestNodeCore.check_sync_hash_old_new(
            old_sync_hash, new_sync_hash, False, False, True))
예제 #6
0
def nfa2regex(nfa):
    if not nfa.isValid():
        raise AutomataError(
            'NFA must be in a valid state to be converted to a regex.')

    network = NetworkNFA(nfa)

    if DEBUG:
        print('START', network)

# Take care of multi-terminals
# if len(network.terminals) > 1:
##    end = Node('qf')
# network.addNode(end)
# for i in copy(network.terminals):
##      network.addDelta(i, '', end)
# network.remTerminal(i)
# network.addTerminal(end)

# Add a dummy start and end nodes
    start = Node('qs')
    network.addNode(start)
    network.addDelta(start, '', network.start)
    network.start = start

    end = Node('qf')
    network.addNode(end)
    for i in network.terminals:
        network.addDelta(i, '', end)
        network.remTerminal(i)
    network.addTerminal(end)
    if DEBUG:
        print('Dummies added: ', network)

    # Collapse connections
    for src in network.nodes:
        delta_temp = network.getDelta(src)
        for dest in network.nodes:
            chars = []
            for input in delta_temp:
                if input and dest in delta_temp[input]:
                    chars.append(input)

            if len(chars):
                for c in chars:
                    delta_temp[c].remove(dest)
                    if len(delta_temp[c]) == 0:
                        del delta_temp[c]

                if len(chars) > 1:
                    chars = '(' + '+'.join(chars) + ')'
                else:
                    chars = '+'.join(chars)
                network.addDelta(src, chars, dest)
    if DEBUG:
        print('Collapsed: ', network)

    # Collect pliable nodes
    pliableNodes = list(network.nodes)
    pliableNodes.remove(network.start)
    for n in network.terminals:
        pliableNodes.remove(n)

    # Build a distance-from-terminal table
    nodeFinalDist = {}
    maxDist = len(network.nodes)**len(network.nodes)  # Lazy
    for n in network.nodes:
        nodeFinalDist[n] = maxDist

    nodeFinalDist[network.terminals[0]] = 0
    toProcess = list(network.nodes)
    toProcess.remove(network.terminals[0])

    while len(toProcess):
        for node in toProcess:
            dests = network.getDelta(node).values()
            if len(dests) == 0:
                dests = set([])
            else:
                dests = reduce(set.union, network.getDelta(node).values())

            if len(dests) == 0:
                toProcess.remove(node)
            else:
                minDist = min([nodeFinalDist[i] for i in dests])
                if minDist != maxDist:
                    nodeFinalDist[node] = minDist + 1
                    toProcess.remove(node)

    # Sort pliable nodes by distance from terminal
    pliableNodes.sort(key=lambda x: nodeFinalDist[x], reverse=True)
    if DEBUG:
        print('Pliables: ', pliableNodes)

    for node in pliableNodes:
        # Remove Node
        network.remNode(node)

        # Save delta
        delta = copy(network.getDelta(node))

        # Convert loops to regex
        loops = []
        for input in delta:
            if node in delta[input]:
                if len(input):
                    loops.append(input)
        loopRegex = '+'.join(loops)
        if len(loopRegex) > 1 and not (loopRegex[0] == '('
                                       and loopRegex[-1] == ')'):
            loopRegex = '(' + loopRegex + ')*'
        elif len(loopRegex) >= 1:
            loopRegex = loopRegex + '*'

        # Remove loops
        for input in copy(delta):
            if delta[input] == set([node]):
                del delta[input]
            elif node in delta[input]:
                delta[input].remove(node)

        # Search lambda-closure equivalence
        if '' in delta and (len(delta) != 1 or len(delta['']) != 1):
            eligible = []
            for dest in delta['']:
                delta_temp = network.getDelta(dest)
                if '' in delta_temp and node in delta_temp['']:
                    eligible.append(dest)

            if len(eligible):
                replaceNode(network, node, eligible[0])
                continue

        # Remove delta
        try:
            del network._deltas[node]
        except KeyError:  # No deltas remaining, had only loops
            continue

        if DEBUG:
            print('Working on connections: ', node, delta)
        # Check all possible connections through this node
        deltas_temp = copyDeltas(network._deltas)
        for src in deltas_temp:
            for input in deltas_temp[src]:
                tempDeltaDest = network.getDelta(src)[input]
                if node in tempDeltaDest:
                    tempDeltaDest.remove(node)
                    if len(tempDeltaDest) == 0:
                        network.remDelta(src, input)

                    for input2 in delta:
                        for dest in delta[input2]:
                            if not (src == dest and
                                    (input + loopRegex + input2) == ''):
                                network.addDelta(src,
                                                 input + loopRegex + input2,
                                                 dest)
                                if DEBUG:
                                    print('New Delta:', src, input, loopRegex,
                                          input2, dest, network)

    # Extract common prefix/suffix
    branches = network.getDelta(network.start).keys()
    if len(branches) == 1:
        regex = branches[0]
    else:
        prefix = commonprefix(branches)
        suffix = commonsuffix(branches)
        branches = [
            i[len(prefix):-len(suffix)] if len(suffix) else i[len(prefix):]
            for i in branches
        ]
        branches.sort(key=len)
        if len(prefix) or len(suffix):
            regex = prefix + \
                '(' + '+'.join([i or LAMBDA for i in branches]) + ')' + suffix
        else:
            regex = '+'.join([i or LAMBDA for i in branches]) or PHI

    return regex
예제 #7
0
        root1 = root1.next
        mult *= 10
    num2 = 0
    mult = 1
    while root2 is not None:
        num2 += root2.data * mult
        root2 = root2.next
        mult *= 10
    result = num1 + num2
    print "%s + %s = %s" % (num1, num2, result)
    result_list = None
    for x in str(result)[::-1]:
        if result_list is None:
            result_list = Node(x)
        else:
            result_list.append_to_tail(x)
    return result_list


root1 = Node(3)
root1.append_to_tail(1)
root1.append_to_tail(5)
root1.append_to_tail(6)

root2 = Node(5)
root2.append_to_tail(9)
root2.append_to_tail(2)

result = sum_linked_lists(root1, root2)
print_nodes(result)
예제 #8
0
파일: graph.py 프로젝트: triplrrr/pystruct
 def __init__(self, names=list()):
     self.nodes = dict()
     for name in names:
         self.nodes[name] = Node()
예제 #9
0
import context
import torch
from base import TreeParams, Node
from settings import arg, constants
from game import card_to_string, card_tools
from tree import tree_builder, TreeCFR, tree_visulizer, tree_strategy_sl

params = TreeParams()
params.root_node = Node()
params.root_node.board_string = arg.board_string
params.root_node.board = card_to_string.string_to_cards(arg.board_string)
params.root_node.street = arg.street
params.root_node.current_player = constants.players.P1
params.root_node.bets = arg.IntTensor([100, 100]).to(arg.device)
root = tree_builder.build_tree(params)

starting_range = torch.zeros([constants.players_count, constants.card_count],
                             dtype=arg.dtype).to(arg.device)
starting_range[0] = card_tools.get_uniform_range(params.root_node.board)
starting_range[1] = card_tools.get_uniform_range(params.root_node.board)

tree_cfr = TreeCFR()
tree_cfr.run_cfr(root, starting_range)

tree_visulizer.draw_tree(root)

tree_strategy_sl.save_strategy(root)
예제 #10
0
 def init_first_food(self):
     food_img = Node(img_path=GameConfig.first_food_img)
     point = self.find_point()
     food = Food(node=food_img, point=point)
     self.food = food
예제 #11
0
from base import Node, print_nodes


def find_loop_start(node):
    nodes = {}
    while node is not None:
        if node not in nodes:
            nodes[node] = 1
        else:
            return node
        node = node.next


root = Node('A')
root.append_to_tail('B')
root.append_to_tail('C')
root.append_to_tail('D')
root.append_to_tail('E')
root.next.next.next.next.next = root.next.next

loop_start = find_loop_start(root)
print loop_start.data
예제 #12
0
from base import Node, print_nodes


def remove_duplicates(root):
    n = root
    prev = None
    d = {}
    while n is not None:
        if n.data in d:
            prev.next = n.next
        else:
            d[n.data] = 1
            prev = n
        n = n.next


root = Node(4)
root.append_to_tail(5)
root.append_to_tail(8)
root.append_to_tail(7)
root.append_to_tail(8)
root.append_to_tail(10)
root.append_to_tail(8)
root.append_to_tail(10)

print_nodes(root)
remove_duplicates(root)
print_nodes(root)
예제 #13
0
파일: binary.py 프로젝트: swstack/algos
 def populate(self):
     self.root = Node(self.array[0])
     for item in self.array[1:]:
         self._recursive_populate(self.root, item)
예제 #14
0
if __name__ == '__main__':
    import math
    from base import FE, Node, Transform, BoundCon, LineLoad, localX
    from postprocess import PostProcess

    class BeamFE(FE, PostProcess):
        pass

    fixed = BoundCon(Dx=0., Dy=0., Dz=0., Rx=0., Ry=0., Rz=0.)
    pinned = BoundCon(Dx=0., Dy=0., Dz=0.)
    free = BoundCon()

    prof = Properties(Area=10., Ixx=100., Iyy=200., Izz=300.)
    mat = Material(E=30E6, G=12E6, nu=0.4, Density=7850.)

    n1 = Node(0., 0., 0., boundCon=fixed)
    n4 = Node(0., 0., 100., boundCon=free)
    n3 = Node(100., 0., 100., boundCon=free)
    n2 = Node(100., 0., 0., boundCon=fixed)

    b1 = Beam(n1, n4, mat, prof)
    b2 = Beam(n2, n3, mat, prof)
    b3 = Beam(n3, n2, mat, prof)

    fe = BeamFE((n1, n2, n3, n4), (b1, b2, b3))

    fe.validate()

    fe.linkNodes()
    fe.assembleElementK()
    fe.assembleElementM()
예제 #15
0
 def setUp(self):
     public_key, private_key = rsa.newkeys(512)
     self.voting_node = Node(public_key, private_key)
     self.VotingComputer(self.voting_node)
예제 #16
0
 def setUp(self):
     (public_key, private_key) = rsa.newkeys(512)
     self.node = Node(public_key, private_key)
     self.node_mapping = {str(public_key): self.node}