示例#1
0
 def push(self, value):
     if self.top is None:
         self.top = Node(value)
     else:
         next = self.top
         self.top = Node(value)
         self.top.next = next
示例#2
0
    def insertAtEnd(self, value):
        if self.head is None:
            self.head = Node(value)
        else:
            node = self.head
            while node.next is not None:
                node = node.next

            node.next = Node(value)
示例#3
0
def main():
    parser = argparse.ArgumentParser(description='n-puzzle')
    parser.add_argument('-d',
                        '--distance-metric',
                        help='Distance function',
                        choices=['simple', 'manhattan', 'euclead'],
                        default='manhattan')
    parser.add_argument('-v',
                        '--verbose',
                        help='Verbose intermediate results',
                        action='store_true')
    parser.add_argument('-g',
                        '--greedy',
                        help='Use greedy algorithm',
                        action='store_true')
    parser.add_argument('-u',
                        '--uniform',
                        help='Use uniform cost',
                        action='store_true')
    parser.add_argument('file', help='input file')
    parser = parser.parse_args()

    try:
        data_parser = Parser(file_name=parser.file)
        node = Node(puzzle_data=data_parser.get_data(),
                    metric=parser.distance_metric,
                    print_inter_res=parser.verbose,
                    greedy=parser.greedy,
                    uniform_cost=parser.uniform)
        game = Game(start_node=node)
        game.solve()
        exit(0)
    except ValueError as error:
        print(error)
        exit(2)
示例#4
0
def createNodes():
    nodes = []
    for row in range(GRIDSIZEY):
        temp = []
        for col in range(GRIDSIZEX):
            temp.append(
                Node((col, row), white, CELLSIZEX, CELLSIZEY, GRIDX, GRIDY,
                     WIN, GRIDSIZEX, GRIDSIZEY))
        nodes.append(temp)
    return nodes
示例#5
0
def main():
    try:
        opts, args = getopt.getopt(sys.argv[1:], "f", ["file"])
    except getopt.error as msg:
        print(msg)
        print("It is necessary file :((")
        sys.exit(2)
    for arg in args:
        try:
            parser = Parser(file_name=arg)
            node = Node(puzzle_data=parser.get_data(), metric='simple')
            game = Game(start_node=node)
            game.solve()
            exit(0)
        except ValueError as error:
            print(error)
            exit(2)
    parser = Parser()
    node = Node(puzzle_data=parser.get_data(), metric='euclead')
    game = Game(start_node=node)
    game.solve()
示例#6
0
    def alphabeta(board: Board, node: Node, depth: int, alpha: float, beta: float, is_maximizer: bool) -> float:
        if (depth == 0 or board.phase == GamePhase.FINISHED):
            return AlphaBetaAgent.get_heuristic_value(board)

        if (is_maximizer):
            v: float = -999999
            deltas: List[Delta] = board.get_all_possible_deltas(Utils.get_player(board.round_num))
            for delta in deltas:
                child_node: Node = Node(node, delta)
                v = max(v, AlphaBetaAgent.alphabeta(board.get_next_board(delta), child_node, depth - 1, alpha, beta, False))
                alpha = max(alpha, v)
                if (beta <= alpha):
                    break
            return v
        else:
            v = 999999
            deltas: List[Delta] = board.get_all_possible_deltas(Utils.get_player(board.round_num))
            for delta in deltas:
                child_node: Node = Node(node, delta)
                v = min(v, AlphaBetaAgent.alphabeta(board.get_next_board(delta), child_node, depth - 1, alpha, beta, True))
                beta = min(beta, v)
                if beta <= alpha:
                    break
            return v
示例#7
0
    def _select(self, node: Node, total_num_simulations: int) -> Node:
        scores: List[Tuple[Node, float]] = []
        unexplored_nodes_score: float = Utils.UCB1(
            1, 2, total_num_simulations, MCTSAgent._EXPLORATION_MULTIPLIER)
        # A list of all deltas which have already been explored at least once. Therefore, they are nodes.
        children: List[Node] = node.children
        # A list of all valid deltas from the given board.
        deltas: List[Delta] = self._board.get_all_possible_deltas(
            Utils.get_player(self._board.round_num))

        if (len(children) > 0):
            for child in children:
                # Since some deltas have already been explored and are therefore included in 'children', remove them
                # from 'deltas' so that it only contains unexplored moves.
                deltas.remove(child.delta)
                scores.append((child,
                               Utils.UCB1(child.wins, child.num_simulations,
                                          total_num_simulations,
                                          MCTSAgent._EXPLORATION_MULTIPLIER)))

            # Since there are no unexplored options available, we'll set its score to -1 such that the algorithm won't
            # attempt to choose an unexplored option (since there are none).
            if len(deltas) == 0:
                unexplored_nodes_score = -1

            # Order by highest scoring nodes.
            scores = sorted(scores, key=lambda x: x[1], reverse=True)
            for child, score in scores:
                if (score > unexplored_nodes_score):
                    # This is to avoid re-exploring a leaf node that resulted in a win or loss. We want to explore new
                    # options. Otherwise we'd have wasted this simulation or back-propagated the same result twice.
                    if (self._board.get_next_board(
                            child.delta).phase == GamePhase.FINISHED):
                        continue
                    else:
                        return child
                else:
                    # We've now reached a (node : score) pair that has a lower score than all the unexplored moves.
                    # Therefore, stop iterating through existing nodes so we can instead select an unexplored move.
                    break

        random_delta: Delta = random.choice(deltas)
        new_child_node: Node = Node(node, random_delta)
        node.children.append(new_child_node)
        return new_child_node
示例#8
0
    def run(self):
        print(self._board)

        is_maximizer: bool = False
        while (self._board.phase != GamePhase.FINISHED):

            deltas: List[Delta] = self._board.get_all_possible_deltas(Utils.get_player(self._board.round_num))
            delta_scores: List[Tuple[Delta, float]] = []
            for delta in deltas:
                delta_scores.append((delta, AlphaBetaAgent.alphabeta(self._board.get_next_board(delta), Node(self._node, delta), 2, -9999, 9999, is_maximizer)))

            if (len(set([delta_score[1] for delta_score in delta_scores])) == 1):
                best_delta: Tuple[Delta, float] = random.choice(delta_scores)
            elif not is_maximizer:
                best_delta: Tuple[Delta, float] = max(delta_scores, key=lambda x:x[1])
            elif is_maximizer:
                best_delta: Tuple[Delta, float] = min(delta_scores, key=lambda x:x[1])

            self._board = self._board.get_next_board(best_delta[0])
            self._node = Node(self._node, best_delta[0])
            is_maximizer = not is_maximizer

            print("{:3}: {} ({})".format(self._board.round_num - 1, best_delta[0], best_delta[1]))
            print(self._board)
示例#9
0
 def __init__(self, data=None):
     if data is None:
         self.top = None
     else:
         self.top = Node(data)
         self.top.next = None
示例#10
0
Integrantes:
Valeria Rivera Muñoz; Codigo 1626837
Juan Felipe Gil Londoño; Codigo 1626055
Mateo Gregory Jiemenz; 1629431
"""
from Classes.Node import Node
from LoadingFiles.LoadMap import searchMap
from Searches.breadthSolve import *
from Searches.depthSolve import *
from Searches.iterativeDepthSolve import *

if __name__ == '__main__':

    map, playerPosition, boxes = searchMap()
    Max_tree_depth = 64
    node = Node(playerPosition, boxes, None, None, 0)

    breadthSolution = breadthSolveIterative(map, node, Max_tree_depth)
    breadthSolutionString = ""
    for decision in breadthSolution:
        breadthSolutionString = breadthSolutionString + decision
    print(breadthSolutionString)

    depthSolution = depthSolveIterative(map, node, Max_tree_depth)
    depthSolutionString = ""
    for decision in depthSolution:
        depthSolutionString = depthSolutionString + decision
    print(depthSolutionString)

    iterativeDepthSolution = iterativeDepthSolveIterative(
        map, node, Max_tree_depth)
示例#11
0
def topology_generator(microgrid, microgrid_SSH, base_voltage_list, busbar_list, linear_shunt_compensator_list,
                       substation_list, voltage_level_list,
                       generating_unit_list, regulating_control_list, power_transformer_list,
                       energy_consumer_list, power_transformer_end_list, breaker_list, ratio_tap_changer_list,
                       synchronous_machine_list, AC_lines_list):
    # Add elements in Node class, add them to node_list, find the terminals connected
    # and add them to terminalList in node

    answer = messagebox.showinfo("Topology Generator algorithm","Let's check how the topology algorithm works!")
    answer = messagebox.showinfo("Topology Generator algorithm","After a number of functions is defined, "
                                                                "the algorithm start. Let's continue.")

    terminal_list = []
    node_list = []
    for terminal in microgrid.findall('Terminal'):
        CN = terminal.find('Terminal.ConnectivityNode').attrib['resource']
        ID = terminal.get('ID')
        name = terminal.find('IdentifiedObject.name').text
        CE = terminal.find('Terminal.ConductingEquipment').attrib['resource']
        passed = False
        terminal_class = Terminal(ID, name, CE, CN, passed)
        terminal_list.append(terminal_class)

    for node in microgrid.findall('ConnectivityNode'):
        ID = node.get('ID')
        name = node.find('IdentifiedObject.name').text
        container = node.find('ConnectivityNode.ConnectivityNodeContainer').attrib['resource']
        node_class = Node(ID, name, container)

        for terminal in terminal_list:
            if ID == terminal.CN[1:]:
                node_class.add_terminal(terminal)

        node_list.append(node_class)

    # Add Conducting Equipment to list
    equipment_list = (busbar_list + linear_shunt_compensator_list + generating_unit_list + power_transformer_list +
                      energy_consumer_list + breaker_list + synchronous_machine_list + AC_lines_list)

    # Find the terminals connected to every CE and add them to terminalList of each component
    for ce in equipment_list:
        if (isinstance(ce, ACLine) or isinstance(ce, Breaker) or isinstance(ce, PowerTransformer)
                or isinstance(ce, SynchronousMachine) or isinstance(ce, LinearShuntCompensator)
                or isinstance(ce, BusBar) or isinstance(ce, EnergyConsumer)):
            for terminal in terminal_list:
                if ce.ID == terminal.CE[1:]:
                    ce.add_terminal(terminal)
    # for the generating unit, at first, the synchronous machine connected to it is found
    for ce in generating_unit_list:
        for machine in synchronous_machine_list:
            if ce.ID == machine.gen_unit[1:]:
                ce.terminalList = machine.terminalList

    # Define function to check if element is a Te
    def check_terminal(curr_node):
        return isinstance(curr_node, Terminal)

    # Define function to check if element is a CN
    def check_CN(curr_node):
        return isinstance(curr_node, Node)



    # Define function to check if element is a CE
    def check_CE(curr_node):
        return (isinstance(curr_node, ACLine) or isinstance(curr_node, Breaker) or isinstance(curr_node, GeneratingUnit)
                or isinstance(curr_node, PowerTransformer) or isinstance(curr_node, SynchronousMachine)
                or isinstance(curr_node, LinearShuntCompensator) or isinstance(curr_node, BusBar)
                or isinstance(curr_node, EnergyConsumer))

    # Define function that finds the node following the input node
    def find_next_node(curr_node, prev_node):
        if check_terminal(curr_node):
            if check_CE(prev_node):
                for cn in node_list:
                    if cn.ID == curr_node.CN[1:]:
                        next_node = cn
                        return next_node
            if check_CN(prev_node):
                for ce in equipment_list:
                    if ce.ID == curr_node.CE[1:]:
                        next_node = ce
                        return next_node
        if check_CN(curr_node):
            for te in terminal_list:
                if curr_node.ID == te.CN[1:] and not te.passed:
                    next_node = te
                    return next_node
        if check_CE(curr_node):
            for te in curr_node.terminalList:
                if not te.passed:
                    next_node = te
                    return next_node

    # Define function to check if there is a busbar connected to a CN
    # Returns true is it is connected to a busbar and false if it is not
    def bus_connected_to_CN(CN):
        next_terminal = find_next_node(CN, '')
        if not next_terminal:
            return False
        CE = find_next_node(next_terminal, CN)
        for busbar in busbar_list:
            if CE.ID == busbar.ID:
                return True
        return False

    # Define function that return the bus attached to the terminal, or false if there is none
    def bus_connected_to_te(terminal):
        for busbar in busbar_list:
            if terminal.CE[1:] == busbar.ID:
                return busbar
        return False

    # Define function to find out if in the list of terminals, a terminal il untraversed
    def is_untraversed(node):
        for terminal in node.terminalList:
            if not terminal.passed:
                return True
        return False

    # Define a function that check if CE is a breaker and returns true if terminal is open, false otherwise
    def is_open_breaker(CE):
        for breaker in breaker_list:
            if CE == breaker:
                if breaker.state == 'true':
                    return True
        return False

    # Initialize stacks
    CN_stack = deque([])  # to push a CN as soon as it is visited, pop when all terminals attached to this node are traversed
    CE_stack = deque([])  # to push a CE, as and when encountered
    everything_stack = deque([])  # to push all the visited nodes (CE, CN, Te)

    # Initialize variables to use
    starting_node = generating_unit_list[0]  # Select starting node as an end device
    curr_node = starting_node
    prev_node = 'empty'

    # Get next_node from function and define algorithm
    next_node = find_next_node(curr_node, prev_node)
    final_everything_stack = []
    final_CE_stack = []
    CE_list = []
    bus_flag = False
    flag = False
    answer = messagebox.showinfo(title="Topology Generator algorithm",message=( "The algorithm starts with the current node =", curr_node) )
    counter = 1
    continue_messages = True
    while not flag:
        if continue_messages:
            answer = messagebox.askyesno(title="Topology Generator algorithm", message=("Step number", counter,
                                         "current node = ", curr_node, " Do you want to continue?"))
            if answer == False:
                continue_messages=False
        counter += 1


        if len(everything_stack) == 0 or curr_node not in everything_stack:
            everything_stack.append(curr_node)   # Add element to everything_stack

        if check_terminal(curr_node): # If curr_node is a terminal
            curr_node.passed = True
            if check_CN(next_node):
                if not bus_connected_to_CN(next_node):  # if CN is not connected to a bus go to next node
                    prev_node = curr_node
                    curr_node = next_node
                    next_node = find_next_node(curr_node, prev_node)
                else:  # if CN is connected to bus, stop the algorithm at the busbar
                    bus_flag = True
                    node_flag = next_node
                    prev_node = curr_node
                    curr_node = next_node
                    next_node = find_next_node(curr_node, prev_node)
            elif check_CE(next_node):
                prev_node = curr_node
                curr_node = next_node
                next_node = find_next_node(curr_node, prev_node)
        # If the current node is a CN
        elif check_CN(curr_node):
            if len(CN_stack) == 0 or curr_node not in  CN_stack:#not CN_stack[-1] == curr_node:
                CN_stack.append(curr_node)  # Push in the CN stack
            if is_untraversed(curr_node):
                prev_node = curr_node
                curr_node = next_node
                next_node = find_next_node(curr_node, prev_node)
            else:  # if there is no untraversed terminal remaining and go to another CN
                final_CE_stack = CE_stack
                final_everything_stack =everything_stack
                CN_stack.pop()  # pop the current CN off the CN stack
                if len(CN_stack) != 0:  # if the stack is not empty
                    curr_node = CN_stack[-1]  # mark the next node as the CN on top of CN stack
                    prev_node = 'empty'
                    next_node = find_next_node(curr_node, prev_node)
                else:
                    # final_CE_stack.append(CE_stack)
                    final_CE_stack = CE_stack
                    final_everything_stack = everything_stack  # publish the CE_stack and everything_stack
                    flag = True

        # If the current node is a CE
        elif check_CE(curr_node):
            CE_stack.append(curr_node)  # Push in the CE stack
            if is_untraversed(curr_node) and not is_open_breaker(curr_node):
                prev_node = curr_node
                curr_node = next_node
                next_node = find_next_node(curr_node, prev_node)
            elif (not is_untraversed(curr_node) or is_open_breaker(curr_node)):
                final_CE_stack = CE_stack
                final_everything_stack =everything_stack  # publish the CE_stack, everything_stack
                prev_node = curr_node
                curr_node = CN_stack[-1]  # mark the next node as the CN on top of CN stack
                next_node = find_next_node(curr_node, prev_node)
                if len(CN_stack) == 0:  # if the stack is not empty
                    final_CE_stack = CE_stack
                    final_everything_stack = everything_stack  # publish the CE_stack and everything_stack
                    flag = True
            elif bus_flag:  # go back to the CN
                if not is_untraversed(node_flag):  # if the CN connected to the busbar has no other terminals connected
                    # end the algorithm publish the CE_stack, everything_stack
                    final_CE_stack = CE_stack
                    final_everything_stack = everything_stack
                    answer = messagebox.showinfo(title="Topology Generator algorithm",
                                                 message=("Algorithm finished at step number", counter,
                                                          "current node = ", curr_node))
                    flag = True
                else:  # if the CN has other terminals connected go back
                    curr_node = node_flag  # mark the next node as the CN on top of CN stack
                    prev_node = 'empty'
                    next_node = find_next_node(curr_node, prev_node)
                    bus_flag = False


    #print(curr_node)
    return final_everything_stack, final_CE_stack
示例#12
0
            else:
                self.LeftTree.insert(new_node)
        else:
            if self.RightTree is None:
                self.RightTree = Tree(new_node)
            else:
                self.RightTree.insert(new_node)

    def walk_tree(self):
        result = ""

        if self.LeftTree is not None:
            result = self.LeftTree.walk_tree()

        result += "{0}".format(self.NodeData.Value)

        if self.RightTree is not None:
            result += self.RightTree.walk_tree()

        return result


if __name__ == "__main__":
    node = Node(1)
    newTree = Tree(node)
    for i in range(2, 10):
        newTree.insert(Node(i))
    result_new = newTree.walk_tree()

    print(result_new)
示例#13
0
class AlphaBetaAgent():

    _board: Board
    _node: Node
    _init_node: Node = Node(None, None)

    def __init__(self, start_board: Board = None, seed: int = random.randint(0, 999999)):
        if (start_board == None):
            self._board = Board(None, 1, GamePhase.PLACEMENT)
        else:
            self._board = start_board

        self._node = self._init_node
        random.seed(seed)

    def run(self):
        print(self._board)

        is_maximizer: bool = False
        while (self._board.phase != GamePhase.FINISHED):

            deltas: List[Delta] = self._board.get_all_possible_deltas(Utils.get_player(self._board.round_num))
            delta_scores: List[Tuple[Delta, float]] = []
            for delta in deltas:
                delta_scores.append((delta, AlphaBetaAgent.alphabeta(self._board.get_next_board(delta), Node(self._node, delta), 2, -9999, 9999, is_maximizer)))

            if (len(set([delta_score[1] for delta_score in delta_scores])) == 1):
                best_delta: Tuple[Delta, float] = random.choice(delta_scores)
            elif not is_maximizer:
                best_delta: Tuple[Delta, float] = max(delta_scores, key=lambda x:x[1])
            elif is_maximizer:
                best_delta: Tuple[Delta, float] = min(delta_scores, key=lambda x:x[1])

            self._board = self._board.get_next_board(best_delta[0])
            self._node = Node(self._node, best_delta[0])
            is_maximizer = not is_maximizer

            print("{:3}: {} ({})".format(self._board.round_num - 1, best_delta[0], best_delta[1]))
            print(self._board)

    @staticmethod
    def alphabeta(board: Board, node: Node, depth: int, alpha: float, beta: float, is_maximizer: bool) -> float:
        if (depth == 0 or board.phase == GamePhase.FINISHED):
            return AlphaBetaAgent.get_heuristic_value(board)

        if (is_maximizer):
            v: float = -999999
            deltas: List[Delta] = board.get_all_possible_deltas(Utils.get_player(board.round_num))
            for delta in deltas:
                child_node: Node = Node(node, delta)
                v = max(v, AlphaBetaAgent.alphabeta(board.get_next_board(delta), child_node, depth - 1, alpha, beta, False))
                alpha = max(alpha, v)
                if (beta <= alpha):
                    break
            return v
        else:
            v = 999999
            deltas: List[Delta] = board.get_all_possible_deltas(Utils.get_player(board.round_num))
            for delta in deltas:
                child_node: Node = Node(node, delta)
                v = min(v, AlphaBetaAgent.alphabeta(board.get_next_board(delta), child_node, depth - 1, alpha, beta, True))
                beta = min(beta, v)
                if beta <= alpha:
                    break
            return v

    @staticmethod
    def get_heuristic_value(board: Board):
        num_white_pieces: int = len(board._get_player_squares(PlayerColor.WHITE))
        num_black_pieces: int = len(board._get_player_squares(PlayerColor.BLACK))
        return num_white_pieces - num_black_pieces
示例#14
0
 def __init__(self, value=None):
     if value is None:
         self.head = None
     else:
         self.head = Node(value)
node_list = []
for terminal in microgrid.findall('Terminal'):
    CN = terminal.find('Terminal.ConnectivityNode').attrib['resource']
    ID = terminal.get('ID')
    name = terminal.find('IdentifiedObject.name').text
    CE = terminal.find('Terminal.ConductingEquipment').attrib['resource']
    passed = False
    terminal_class = Terminal(ID, name, CE, CN, passed)
    terminal_list.append(terminal_class)

for node in microgrid.findall('ConnectivityNode'):
    ID = node.get('ID')
    name = node.find('IdentifiedObject.name').text
    container = node.find(
        'ConnectivityNode.ConnectivityNodeContainer').attrib['resource']
    node_class = Node(ID, name, container)

    for terminal in terminal_list:
        if ID == terminal.CN[1:]:
            node_class.add_terminal(terminal)

    node_list.append(node_class)

# Add Conducting Equipment to list
equipment_list = (busbar_list + linear_shunt_compensator_list +
                  generating_unit_list + power_transformer_list +
                  energy_consumer_list + breaker_list +
                  synchronous_machine_list + AC_lines_list)

# Find the terminals connected to every CE and add them to terminalList of each component
for ce in equipment_list: