Пример #1
0
    def __init__(self, start, target, allow_diagonals, World):
        self.start = Node(start, target, 0, None, World, False,
                          allow_diagonals)
        self.target = Node(target, target, 0, None, World, False,
                           allow_diagonals)
        self.reached = False
        self.stack = [self.start]
        self.visited = []
        self.path = []

        while (not (self.start.is_accessible())):
            stdout.write("\033[;1m" + "\033[1;31m")
            stdout.write('START Tile have no children, choose another one ! ')
            stdout.write("\033[0;0m")
            start = int(input("New START Tile --->  "))
            self.start = Node(start, target, 0, None, World, False,
                              allow_diagonals, True)
        while (not (self.target.is_accessible())):
            stdout.write("\033[;1m" + "\033[1;31m")
            stdout.write('TARGET Tile have no children, choose another one ! ')
            stdout.write("\033[0;0m")
            target = int(input("New TARGET Tile --->  "))
            self.target = Node(target, target, 0, None, World, False,
                               allow_diagonals, True)

        self.path = [self.start.tile_pos]
        self.costs = [0]
Пример #2
0
    def __init__(self, start, target, allow_diagonals, World):
        self.start = Node(start, target, 0, None, World,
                          False, allow_diagonals)
        self.target = Node(target, target, -1, None, World,
                           False, allow_diagonals)

        self.open_nodes = [self.start]
        self.closed_nodes = []

        self.last_node = None

        self.reached = False
        self.available_tiles = World.list_available_tiles()

        while (not(self.start.is_accessible())):
            stdout.write("\033[;1m" + "\033[1;31m")
            stdout.write('START Tile have no children, choose another one ! ')
            stdout.write("\033[0;0m")
            start = int(input("New START Tile --->  "))
            self.start = Node(start, target, 0, None, World,
                              False, allow_diagonals)
        while (not(self.target.is_accessible())):
            stdout.write("\033[;1m" + "\033[1;31m")
            stdout.write('TARGET Tile have no children, choose another one ! ')
            stdout.write("\033[0;0m")
            target = int(input("New TARGET Tile --->  "))
            self.target = Node(target, target, -1, None, World,
                               False, allow_diagonals)

        self.path = [self.start.tile_pos]
        self.costs = [0]
    def test_testcase5(self):
        """
        测试用例如下:
        implementation: s0 -but?-> s1, s1 -liq!-> s2, s1 -choc!-> s3
        specification: s0 -but?-> s1, s0 -but?-> s2, s1 -liq!-> s3, s2 -but?-> s4, s4 -choc!-> s5
        :return: None
        """
        # implementation
        imp_root = Node(None, State("s0"))
        node1 = Node(Action("but", ActionEnum.INPUT), State("s1"))
        node2 = Node(Action("liq", ActionEnum.OUTPUT), State("s2"))
        node3 = Node(Action("choc", ActionEnum.OUTPUT), State("s3"))
        imp_root.children = [node1]
        node1.children = [node2, node3]
        imp = LTSTree(imp_root)

        # specification
        spec_root = Node(None, State("s0"))
        node1 = Node(Action("but", ActionEnum.INPUT), State("s1"))
        node2 = Node(Action("but", ActionEnum.INPUT), State("s2"))
        spec_root.children = [node1, node2]
        node3 = Node(Action("liq", ActionEnum.OUTPUT), State("s3"))
        node1.children = [node3]
        node4 = Node(Action("but", ActionEnum.INPUT), State("s4"))
        node2.children = [node4]
        node5 = Node(Action("liq", ActionEnum.OUTPUT), State("s5"))
        node4.children = [node5]
        spec = LTSTree(spec_root)

        self.assertFalse(imp.io_conform(spec),
                         msg="Error, test result: io conform!")
Пример #4
0
 def decode_headers(self, bitStream: 'BitStream', char_size: int):
     if bitStream.read(1).bin == '1':
         encoded_char: str = bitStream.read(char_size).bin
         int_char: int = int(encoded_char, 2)
         return Node(symbol=chr(int_char)[0], count=1)
     else:
         left = self.decode_headers(bitStream, char_size)
         right = self.decode_headers(bitStream, char_size)
         return Node(left=left, right=right, count=1)
Пример #5
0
def test_position_validity():
    for i in range(1000):
        rdn = random.random()
        if rdn > 0.5:
            pos = -1 * (random.randint(1, 1000))
            node = Node(State.DEAD, pos)
            assert (node.valid_node == False)
        else:
            pos = random.randint(1, 1000)
            node = Node(State.DEAD, pos)
            assert (node.valid_node == True)
Пример #6
0
def test_state_validity():
    for i in range(1000):
        rdn = random.random()
        if rdn > 0.5:
            state = random.choice(State.ALLOWED_)
            node = Node(state, 0)
            assert (node.valid_node == True)
        else:
            state = random.randint(-1000, 1000)
            if state in State.ALLOWED_:
                pass
            else:
                node = Node(state, 0)
                assert (node.valid_node == False)
Пример #7
0
    def setUp(self):
        self.cluster_patch = patch('lib.cluster.Cluster')
        #self.view_patch = patch('lib.view.CliView')

        real_stdoup = sys.stdout
        sys.stdout = StringIO()

        self.addCleanup(patch.stopall)
        self.addCleanup(reset_stdout)

        self.MockCluster = self.cluster_patch.start()
        #self.MockView = self.view_patch.start()
        Cluster._crawl = classmethod(lambda self: None)
        Cluster._callNodeMethod = classmethod(
            lambda self, nodes, method_name, *args, **kwargs:
            {"test":IOError("test error")})

        n = Node("172.99.99.99")
        Cluster.getNode = classmethod(
            lambda self, key: [n])

        pd = PrefixDict()
        pd['test'] = 'test'

        Cluster.getPrefixes = classmethod(lambda self: pd)

        self.rc = RootController()
Пример #8
0
def url(request, project, env):
    from lib.node import Node
    from lib.common import Common

    result = ""

    n = Node(project, env)
    ip = []
    for row in n.get():
        if row['hostname'].startswith("Controltier"):
            continue
        ip.append(row['hostname'])

    for vrow in Validation.objects.filter(project=project).values():
        for server in ip:
            if vrow['url'].startswith("ip"):
                url = re.sub("ip", server, vrow['url'])
                return_code = Common().get_return_code(url, vrow['port'])
                result += """
                <tr>
                    <th>{url}</th>
                    <th>{return_code}</th>
                </tr>
                """.format(
                    url=url,
                    return_code=return_code,
                )

    return HttpResponse(result)
Пример #9
0
    def add_node(self, node_name, children=None):
        if node_name in self.nodes:
            raise GraphDuplicateNodeNameError(
                "Attempting to create a duplicately-named node in the same graph."
            )

        self.nodes[node_name] = Node(node_name, children)
Пример #10
0
    def getInfoMock(self, return_value):
        Node._infoCInfo.return_value = return_value
        Node._infoTelnet.return_value = return_value

        n = Node("127.0.0.1")

        return n
Пример #11
0
def test_outofbounds():
    env = World(10, 10, 0.2)
    free_tiles = env.list_available_tiles()
    new_node = [Node(i, 84, 0, None, env) for i in free_tiles]

    for elem in new_node:
        assert (elem.tile_pos >= 0 and elem.tile_pos <= (env.L * env.H))
Пример #12
0
def test_availability():
    env = World(10, 10, 0.2)
    free_tiles = env.list_available_tiles()

    new_node = [Node(i, 84, 0, None, env) for i in free_tiles]

    for elem in new_node:
        assert (env.w[elem.tile_pos] != 1)
Пример #13
0
 def addXmlNode(self, homeId, nodeId, xmlNode):
     for n in self._nodes:
         if n.homeId == homeId and n.nodeId == nodeId:
             self._log.write(LogLevel.Warning, self, "Node {0} on homeId {1} from xml config file allready exist, abording add.".format(nodeId,  homeId))
             return None
     node = Node(self,  homeId,  nodeId, xmlNode)
     self._nodes.append(node)
     self._log.write(LogLevel.Info, self, "Node {0} on homeId {1} added from xml config file.".format(nodeId,  homeId))
Пример #14
0
    def prepare(self):
        """Create a router with its nodes."""
        debug('Creating {}:'.format(self.role), self.name)
        self.nodes = []
        for hypervisor in self.hypervisors:
            if self.deployment.high_available:
                suffix = self.suffixes[self.hypervisors.index(hypervisor)]
                self.nodes.append(Node(self, hypervisor, suffix))
            else:
                self.nodes.append(Node(self, hypervisor))
                break

        for i, node in enumerate(self.nodes):
            if len(self.nodes) == 2:
                node.peer_node = self.nodes[(i + 1) % 2]
                if i == 1:
                    node.is_secondary = True
    def test_testcase2(self):
        """
        测试用例如下:
        implementation: s0 -but?-> s1, s1 -liq!-> s2
        specification: s0 -but?-> s1, s1 -liq!-> s2, s1 -choc-> s3
        :return: None
        """
        # implementation
        imp_root = Node(None, State("s0"))
        node1 = Node(Action("but", ActionEnum.INPUT), State("s1"))
        node2 = Node(Action("liq", ActionEnum.OUTPUT), State("s2"))
        imp_root.children = [node1]
        node1.children = [node2]
        imp = LTSTree(imp_root)

        # specification
        spec_root = Node(None, State("s0"))
        node1 = Node(Action("but", ActionEnum.INPUT), State("s1"))
        node2 = Node(Action("liq", ActionEnum.OUTPUT), State("s2"))
        node3 = Node(Action("choc", ActionEnum.OUTPUT), State("s3"))
        spec_root.children = [node1]
        node1.children = [node2, node3]
        spec = LTSTree(spec_root)

        self.assertTrue(imp.io_conform(spec), msg="io not conform")
 def test_testcase1(self):
     """
     测试用例如下:
     implementation:s0 -act1?-> s1
     specification: s0 -act1?-> s1
     :return: None
     """
     imp_root = Node(None, State("s0"))
     imp_root.children = [
         Node(Action("act1", ActionEnum.INPUT), State("s1"))
     ]
     spec_root = Node(None, State("s0"))
     spec_root.children = [
         Node(Action("act1", ActionEnum.INPUT), State("s1"))
     ]
     imp = LTSTree(imp_root)
     spec = LTSTree(spec_root)
     self.assertTrue(imp.io_conform(spec), msg="io not conform")
Пример #17
0
    def copyNode(self, node):
        """Copy a node object add it on manager list nodes and set it not include.
           Return the new node object.
        """
#        newNode = copy.copy(node)
#        newNode.homeId = 0
        nodeId = self.getFirstFreeNodeIdBeforeInclude()
        newNode = Node(self,  0,  nodeId, node.GetXmlData)
        newNode.ClearAddingNode()
        newNode.Reset()
        self._nodes.append(newNode)
        self._log.write(LogLevel.Info, self, "Manager create new node by copy node {0}.{1}.".format(node.homeId, node.nodeId))
        return newNode
Пример #18
0
    def get_node_tree(self, frequencies: List['Node']) -> 'Node':
        priority_queue = PriorityQueue(frequencies)

        while True:
            left_node = priority_queue.get_and_remove_first_element()
            right_node = priority_queue.get_and_remove_first_element()

            parent = Node(left=left_node, right=right_node)

            if (len(priority_queue) == 0):
                return parent

            priority_queue.add(parent)
Пример #19
0
    def __initUI(self):
        self.pack(side=LEFT, fill="both", expand=True)

        self._canvas = Canvas(self,bg=WHITE,bd=0, highlightthickness=0)
        self._canvas.pack(fill="both", expand=True, padx=5, pady=5)
        
        self.item = None
        self.previous = (0,0)
        self._canvas.bind('<Button-1>',self.mouse_event)
        self._canvas.bind('<B1-Motion>',self.drag)
        self._canvas.bind('<ButtonRelease-1>',self.end_drag)
        self._parent.bind("<Key>",self.key_event)
        nodeList = get_variable("nodeList")
        
        A = Node(self._canvas,"A",1000,150,20,30)
        C = Node(self._canvas,"C",25,100,100,30)
        D = Node(self._canvas,"D",20,200,100,30)
        E = Node(self._canvas,"E",24,300,100,30)
        F = Node(self._canvas,"F",22,400,20,30)
        H = Node(self._canvas,"H",16,180,200,30)
        I = Node(self._canvas,"I",17,450,200,30)
        K = Node(self._canvas,"K",11,250,250,30)
        B = Node(self._canvas,"B",0,150,250,30)

        A.add_child(C,17)
        A.add_child(D,12)
        A.add_child(E,15)
        A.add_child(F,20)
        
        D.add_child(E,8)
        D.add_child(H,10)

        E.add_child(I,4)
        E.add_child(K,5)

        H.add_child(K,1)
        H.add_child(B,18)

        K.add_child(B,8)
        nodeList = [A,C,D,E,F,H,K,I,B]

        set_variable("nodeList",nodeList)
Пример #20
0
def test_uniqueness():
    env = World(10, 10, 0.2)
    free_tiles = env.list_available_tiles()
    nodes = [Node(i, 84, 0, None, env) for i in free_tiles]

    # list of positions
    pos = []
    for elem in nodes:
        pos.append(elem.tile_pos)

    # check uniqueness
    seen = set()
    uniqueness = not any(k in seen or seen.add(k) for k in pos)

    assert (uniqueness == True)
Пример #21
0
    def __initNodes(self, map):
        self.nodes = []

        for x in range(self.pNum):
            self.nodes.append([])
            for y in range(self.pNum):
                startPos = (x * self.pWidth, y * self.pHeight)
                nodeState = 0

                if map == maps.zebra:
                    nodeState = states.empty if y % 2 == 0 else states.wall

                elif map == maps.windows:
                    pLast = self.pNum - 1
                    if (x + 1) % 3 == 0 and y != pLast:
                        nodeState = states.empty
                    elif (y % 2 == 0 or y == pLast) and (x, y) not in [
                        (0, 0), (1, 0), (pLast, pLast - 1),
                        (pLast - 1, pLast - 1)
                    ]:
                        nodeState = states.wall

                elif map == maps.coolerWindows:
                    if (x + 1) % 3 == 0:
                        nodeState = states.empty
                    elif y % 2 == 0:
                        if 0 in [x % 6, (x - 1) % 6]:
                            nodeState = states.wall
                    else:
                        if 0 in [(x + 3) % 6, (x + 2) % 6]:
                            nodeState = states.wall

                elif map == maps.yourComputerWillCrash:
                    if (x, y) != (0, 0) or (y != self.pNum or x != self.pNum):
                        if x % 4 == 0 and y == 0:
                            nodeState = states.empty
                        elif x % 2 == 0 and y <= x:
                            nodeState = states.wall

                        if (y + 2) % 4 == 0 and x == 0:
                            nodeState = states.empty
                        elif y % 2 == 0 and y > x:
                            nodeState = states.wall

                self.nodes[-1].append(
                    Node(startPos, (self.pWidth, self.pHeight),
                         state=nodeState))
Пример #22
0
def create_point_list():
    A = Node(None,"A",1000,150,20,30)
    C = Node(None,"C",25,100,100,30)
    D = Node(None,"D",20,200,100,30)
    E = Node(None,"E",24,300,100,30)
    F = Node(None,"F",22,400,20,30)
    H = Node(None,"H",16,180,200,30)
    I = Node(None,"I",17,450,200,30)
    K = Node(None,"K",11,250,250,30)
    B = Node(None,"B",0,150,250,30)

    A.add_child(C,17)
    A.add_child(D,12)
    A.add_child(E,15)
    A.add_child(F,20)
    
    D.add_child(E,8)
    D.add_child(H,10)

    E.add_child(I,4)
    E.add_child(K,5)

    H.add_child(K,1)
    H.add_child(B,18)

    K.add_child(B,8)
    nodeList = [A,C,D,E,F,H,K,I,B]
    pointList = {}
    for node in nodeList:
        name = node._nameNode
        heuristic = float(node._heuristic)
        distanceTo = {}

        for child in node._childNodes:
            distanceTo[child["Node"]._nameNode] = float(child["cost"])

        pointList[name] = NodeALG(name,heuristic,distanceTo)
    
    return pointList
Пример #23
0
    def create_node(self,e):
        nodeList = get_variable("nodeList")
        properties = get_variable("properties")

        #check position
        x = e.x
        y = e.y
        for item in nodeList:
            iX = item._x
            iY = item._y
            if( x > iX - 20 and x < iX + 50 and y > iY - 20 and y < iY + 50):
                return
        
        #create new node
        newNode = Node(self._canvas,"",0,x-15,y-15,30)
        nodeList.append(newNode)
        properties.target_node(newNode)
Пример #24
0
    def create_new_child(self):
        if(self.target == None):
            return

        nodeList = get_variable("nodeList")
        children = self.target._childNodes
        x = None
        y = None
        if(children == []):
            x = self.target._x + 20
            y = self.target._y + 80
        else:
            x = children[-1]["Node"]._x + 50
            y = children[-1]["Node"]._y
        
        newChild = Node(self.target._canvas,"",0,x,y,30)
        nodeList.append(newChild)
        self.target.add_child(newChild,0)
        self.target_node(newChild)
Пример #25
0
    def _registerNode(self, ip_port):
        """
        Instantiate and return a new node

        If cannot instantiate node, return None.
        Creates a new node if:
           1) node.key doesn't already exist
           2) node.key exists but existing node is not alive
        """
        try:
            ip, port = ip_port
        except Exception as e:
            print "ip_port is expected to be a tuple of len 2, " + \
                "instead it is of type %s and str value of %s"%(type(ip_port)
                                                                , str(ip_port))
            return None

        try:
            node_key = Node.createKey(ip, port)
            if node_key in self.nodes:
                existing = self.nodes[node_key]
            else:
                existing = None

            if not existing or not existing.alive:
                new_node = Node(ip,
                                port,
                                use_telnet=self.use_telnet,
                                user=self.user,
                                password=self.password)

                if existing and not new_node.alive:
                    new_node = existing
            self.updateNode(new_node)

            return new_node
        except:
            return None
Пример #26
0
    def __init__(self,
                 epochs,
                 population,
                 infectProb,
                 healProb,
                 deathProb,
                 World,
                 n_infected=1,
                 spreadRange=1):
        self.epochs = epochs
        self.hardstop = 0
        self.spreadRange = spreadRange
        self.population = population
        self.infectProb = infectProb
        self.healProb = healProb
        self.deathProb = deathProb
        self.world = World

        self.worldHistory = []
        self.n_infected = n_infected
        self.has_spread = False

        self.nodes = dict()
        self.deaths_n = 0
        self.healthy = []
        self.cured = []
        self.infected = []
        self.dead = []

        free_tiles = World.list_available_tiles()
        free_tiles_n = len(free_tiles)

        if not (isinstance(population, int)):
            print(
                ColorsBook.WARNING +
                "Careful, population has to be an INT : forcing it at closest number"
                + ColorsBook.ENDC)
            population = int(population)

        if population > free_tiles_n:
            print(
                ColorsBook.WARNING +
                "Careful, population higher than allocated space : forcing it at maximum"
                + ColorsBook.ENDC)
            population = free_tiles_n

        if population < 0:
            print(
                ColorsBook.WARNING +
                "Careful, population can't be negative : forcing it at random number"
                + ColorsBook.ENDC)
            population = random.randint(1, free_tiles_n)

        self.population = population

        if epochs <= 0 or not (isinstance(epochs, int)):
            print(
                ColorsBook.FAIL +
                "Negative or Zero number of EPOCHS is not allowed, terminating..."
                + ColorsBook.ENDC)
            sys.exit()

        if (infectProb or healProb or deathProb) < 0 or (infectProb or healProb
                                                         or deathProb) > 1:
            print(
                ColorsBook.FAIL +
                "Probabilities not included between [0, 1] interval, terminating..."
                + ColorsBook.ENDC)
            sys.exit()

        if (spreadRange > 1):
            print(ColorsBook.WARNING +
                  "Careful, spreading range unsupported, forcing it at 1" +
                  ColorsBook.ENDC)
            self.spreadRange = 1

        elif (spreadRange < 0):
            print(ColorsBook.WARNING +
                  "Careful, spreading range unsupported, forcing it at 0" +
                  ColorsBook.ENDC)
            self.spreadRange = 0

        elif (not (isinstance(spreadRange, int))):
            print(
                ColorsBook.WARNING +
                "Careful, spreading range unsupported (should be int), forcing to random choice between 0 and 1"
                + ColorsBook.ENDC)
            self.spreadRange = round(random.random())

        if (n_infected < 0):
            print(
                ColorsBook.WARNING +
                "Careful, initial number of infected can't be negative, forcing it at 1"
                + ColorsBook.ENDC)
            self.n_infected = 1

        elif (not (isinstance(n_infected, int))):
            print(
                ColorsBook.WARNING +
                "Careful, initial number of infected must be int, forcing it at closest int"
                + ColorsBook.ENDC)
            self.n_infected = int(n_infected)

        # Generates Nodes at random available spot
        for i in range(self.population):
            random.shuffle(free_tiles)
            picked_spot = free_tiles.pop()
            self.world.pos_matrix[picked_spot] = State.UNAFFECTED
            self.nodes[picked_spot] = Node(State.UNAFFECTED, picked_spot)
Пример #27
0
    def search(self, game, chain_move=False, action=None):
        self.game = game
        self.root = Node()
        root_expansion = True

        # 128 MCTS Iterations
        for i in range(128):
            node = self.root
            clone = game.clone()
            # Search for a Leaf node
            while node.is_not_leaf():
                node = node.select_child()
                clone.play_action(node.action)
                clone.flip_perspective()

            # Get the policy and Value from the Neural Network
            policy, value = self.net.predict(clone.state)
            policy = _add_dirichlet_noise(policy)
            value = value.flatten()[0]

            # Finalize the list of valid moves based on the current position
            if not chain_move or not root_expansion:
                valid_moves = clone.remove_reverse_moves()
                if clone.attack_move_available(valid_moves):
                    valid_moves = clone.remove_non_attacks(valid_moves)
            else:
                valid_moves = clone.remove_except_current(action)
                valid_moves = clone.remove_non_attacks(valid_moves)
            root_expansion = False

            # Normalize the Policy
            # Zero out invalid moves
            # Make all probabilities sum up to 1
            for idx, move in enumerate(valid_moves):
                if move[4] == 0:
                    policy[0][idx] = 0
            policy_sum = sum(policy[0])
            if policy_sum > 0:
                policy[0] /= policy_sum

            # Expand Node Based on the policy
            node.expand_node(valid_moves, policy_vector=policy[0])

            # Checks if game is over
            w = clone.check_game_over()

            # Back Propagate values up the tree
            while node is not None:
                w = -w
                value = -value
                node.back_prop(w, value)
                node = node.parent

        best_n = 0
        best_n_idx = 0

        for idx, child in enumerate(self.root.children):
            if child.N > best_n:
                best_n = child.N
                best_n_idx = idx

        # Return the estimated best action
        return self.root.children[
            best_n_idx].action, self.root.children, game.get_valid_moves()
Пример #28
0
 def get_frequencies(self, file_content: str) -> List['Nodes']:
     return [
         Node(count=count, symbol=elem)
         for elem, count in Counter(file_content).most_common()
     ]
Пример #29
0
 def getInfoMock(self, return_value):
     Node.info = mock.Mock()
     n = Node("127.0.0.1")
     return n
 def insert(self, movie_score, movie_title):
     if self.head is None:
         self.head = Node(movie_score, movie_title)
         return self.head.depth
     else:
         return self.head.insert(movie_score, movie_title)