Exemple #1
0
    def __init__(self):
        Node.__init__(self, HmiAudNode.__name__)
        # self._log.log_to_screen()
        self.ipc.subs(
            {
                IpcTopic.AUD__AUDIO: self.on_event,
            })
        self.set_timeout(0.05)

        self.msg_queue = queue.Queue()
        self.player = Aplay()
        self.player.adjust_volume(10)
    def __init__(self, listOfNodeLabels=[], listOfEdges=[]):
        super(Graph, self).__init__()
        if len(listOfNodeLabels) != 0:
            if type(listOfNodeLabels[0]) == str: nodes = [Node(labelstr) for labelstr in listOfNodeLabels if type(labelstr) == str]
            elif type(listOfNodeLabels[0]) == int: nodes = [Node(labelint) for labelint in listOfNodeLabels if type(labelint) == int]
            elif type(listOfNodeLabels[0]) == Node: nodes = [node for node in listOfNodeLabels if type(node) == Node]
            if len(nodes) == len(listOfNodeLabels): self.nodes = nodes
            else: self.nodes = []
        else: self.nodes = []
        self.edges = []

        if len(listOfEdges) != 0:
            edges = []
            if type(listOfEdges[0]) == Edge: edges = [edge for edge in listOfEdges if type(edge) == Edge]
            elif len(listOfEdges[0]) == 2 and type(listOfEdges[0]) == list and type(listOfEdges[0][0]) == str and type(listOfEdges[0][1]) == str:
                edges = []
                for edge in listOfEdges:
                    nodeStart = self.get_node_by_label(edge[0])
                    nodeDest  = self.get_node_by_label(edge[1])
                    if nodeStart != None and nodeDest != None : edges.append(Edge(nodeStart, nodeDest))
                if len(edges) == len(listOfEdges): self.edges = edges
            elif len(listOfEdges[0]) == 3 and type(listOfEdges[0]) == list and type(listOfEdges[0][0]) == str and type(listOfEdges[0][1]) == str and (type(listOfEdges[0][2]) == int or type(listOfEdges[0][2]) == float):
                edges = []
                for edge in listOfEdges:
                    nodeStart = self.get_node_by_label(edge[0])
                    nodeDest  = self.get_node_by_label(edge[1])
                    if nodeStart != None and nodeDest != None : edges.append(Edge(nodeStart, nodeDest, capacity=edge[2]))
                if len(edges) == len(listOfEdges): self.edges = edges
            elif len(listOfEdges[0]) == 3 and type(listOfEdges[0]) == list and type(listOfEdges[0][2]) == int and type(listOfEdges[0][2]) == int and type(listOfEdges[0][2]) == int or type(listOfEdges[0][2]) == float:
                edges = []
                for edge in listOfEdges:
                    nodeStart = self.get_node_by_label(edge[0])
                    nodeDest  = self.get_node_by_label(edge[1])
                    if nodeStart != None and nodeDest != None : edges.append(Edge(nodeStart, nodeDest, capacity=edge[2]))
            elif len(listOfEdges[0]) == 4 and (type(listOfEdges[0]) == list) and (type(listOfEdges[0][0]) == str) and (type(listOfEdges[0][1]) == str) and (type(listOfEdges[0][2]) == int or type(listOfEdges[0][2]) == float) and (type(listOfEdges[0][3]) == int or type(listOfEdges[0][3]) == float):
                edges = []
                for edge in listOfEdges:
                    nodeStart = self.get_node_by_label(edge[0])
                    nodeDest  = self.get_node_by_label(edge[1])
                    if nodeStart != None and nodeDest != None : edges.append(Edge(nodeStart, nodeDest, capacity=edge[2], flow=edge[3]))
            elif len(listOfEdges[0]) == 4 and type(listOfEdges[0]) == list and (type(listOfEdges[0][2]) == int) and (type(listOfEdges[0][2]) == int) and (type(listOfEdges[0][2]) == int or type(listOfEdges[0][2]) == float) and (type(listOfEdges[0][3]) == int or type(listOfEdges[0][3]) == float):
                edges = []
                for edge in listOfEdges:
                    nodeStart = self.get_node_by_label(edge[0])
                    nodeDest  = self.get_node_by_label(edge[1])
                    if nodeStart != None and nodeDest != None : edges.append(Edge(nodeStart, nodeDest, capacity=edge[2], flow=edge[3]))

        self.nodestable = {}
        for node in self.nodes :
            self.nodestable[node.get_label()] = []
Exemple #3
0
def get_graph_1():
    graph = Graph()
    node_a = Node(1)
    node_b = Node(2)
    node_c = Node(3)
    node_d = Node(4)
    node_e = Node(5)

    graph.set_bidirectional_neighbor(node_a, node_b, 40)
    graph.set_bidirectional_neighbor(node_b, node_e, 20)

    graph.set_bidirectional_neighbor(node_a, node_c, 30)
    graph.set_bidirectional_neighbor(node_c, node_d, 10)
    graph.set_bidirectional_neighbor(node_d, node_e, 30)

    graph.add_nodes([node_a, node_b, node_c, node_d, node_e])

    return graph, node_a, node_e
Exemple #4
0
def parse(fpath):
    """Parse the data and return the root node.
    
    :param fpath: Path to the scenario file
    :type fpath: basestring

    :return Root element of the parse tree.
    :rtype lib.types.Node
    """

    try:
        with open(fpath) as f:
            lines = f.readlines()
    except IOError:
        print 'Cannot open %s' % fpath
        exit()

    root = Node('root', None, 0)
    parent = root

    for line in lines:
        line = line.rstrip()

        if _line_empty(line):
            continue

        indent = _get_indent(line)

        if indent == parent.indent:
            if parent is root:
                root.add_child(line, indent)
        if indent == previous.indent:
            previous.parent.add_child(line, indent)
        if indent > previous.indent:
            previous.add_child(line, indent)

        print '%s%s%s' % (line, (40 - len(line)) * ' ', indent if indent else "")

    for child in root.children:
        print child

    return root
Exemple #5
0
def solution(L1, L2):
    n = L = None
    prev = None
    val = 0
    carry = 0
    for n1, n2 in zip(L1, L2):
        sum = n1.d + n2.d + carry
        val = sum % 10
        carry = sum // 10
        new_node = Node(val)
        if L is None:
            L = new_node
        else:
            prev.next = new_node
        prev = new_node

    if carry != 0:
        prev.next = Node(carry)

    return L
Exemple #6
0
 def addLast(self, newElem):
     newNode = Node.node(
         newElem)  #creating the new node that will be inserted
     lastNode = None
     nodeIt = self._rootNode.getNextNode()  #auxiliary node
     while (nodeIt !=
            None):  #moving along the list until we find the lsat position
         lastNode = nodeIt
         nodeIt = nodeIt.getNextNode()
     if (lastNode == None):
         self._rootNode.setNextNode(newNode)
     else:
         lastNode.setNextNode(newNode)
Exemple #7
0
    def insertAtEvaluation(self, newElem):

        newNode = Node.node(newElem)  #new node to be inserted
        posNode = None
        nodeIt = self._rootNode.getNextNode(
        )  #auxiliary node, which  is the next one after the root node
        if (nodeIt == None):  #checking if it is null
            self._rootNode.setNextNode(
                newNode)  #in that case, we simply place there our new node
        elif (nodeIt.getEvaluation() > newNode.getEvaluation()):
            newNode.setNextNode(nodeIt)
            self._rootNode.setNextNode(newNode)
        else:
            while (nodeIt != None):  #moving along the list
                posNode = nodeIt
                nodeIt = nodeIt.getNextNode()
                if (nodeIt == None):  #checking if it is null
                    posNode.setNextNode(newNode)
                    break
                elif (nodeIt.getEvaluation() > newNode.getEvaluation()):
                    newNode.setNextNode(nodeIt)
                    posNode.setNextNode(newNode)
                    break
Exemple #8
0
 def addFirst(self, newElem):
     newNode = Node.node(
         newElem)  #creating the new node with the 1-parameter constructor
     oldNode = self._rootNode.getNextNode()  #copy of the original top node
     self._rootNode.setNextNode(newNode)
     newNode.setNextNode(oldNode)
Exemple #9
0
 def __init__(self):
     self.setRootNode(Node.node())
Exemple #10
0
 def add_node (self, nodeOrLabel):
     if type(nodeOrLabel) == Node:
         self.nodes.append(nodeOrLabel)
     elif type(nodeOrLabel) == str:
         self.nodes.append(Node(nodeOrLabel))
                    except Exception as e:
                        print('EXCEPTION', first, n, prev)
                        raise e
                else:
                    print('!=', first.d, n.d)
                    prev = n
                n = n.next

            first = first.next

    while remove_dup(L):
        pass
    return L


L0 = Node(1)

L1 = Node(1)
[L1.append(x) for x in [1]]
L1E = Node(1)

L2 = Node(1)
[L2.append(x) for x in [2]]

L3 = Node(1)
[L3.append(x) for x in [2, 1, 2, 3, 1, 4]]

L3E = Node(1)
[L3E.append(x) for x in [2, 3, 4]]

Exemple #12
0
        val = sum % 10
        carry = sum // 10
        new_node = Node(val)
        if L is None:
            L = new_node
        else:
            prev.next = new_node
        prev = new_node

    if carry != 0:
        prev.next = Node(carry)

    return L


L01 = Node.from_list([1])
L02 = Node.from_list([1])
L0E = Node.from_list([2])

L11 = Node.from_list([5])
L12 = Node.from_list([5])
L1E = Node.from_list([0, 1])

L21 = Node.from_list([3, 1, 5])
L22 = Node.from_list([5, 9, 2])
L2E = Node.from_list([8, 0, 8])

L31 = Node.from_list([3, 1, 2])
L32 = Node.from_list([5, 9, 9])
L3E = Node.from_list([8, 0, 2, 1])
Exemple #13
0
from lib import Node
import json
import importlib
import socket

config = json.load(open('config.json'))

for name, server in config["servers"].iteritems():
	role = config["roles"][server["role"]]

	node = Node(server)
	node.values = dict(server.items() + { "name": name }.items())
	node.values["addresses"] = [ socket.gethostbyname(server["host"]) ]
	node.values["processes"] = [ dict(config["processes"][x].items() + { "name": x }.items()) for x in role["processes"] ]

	for name, plugin in config["plugins"].iteritems():
		module = importlib.import_module("plugins." + name)
		method = getattr(module, 'run')

		method(plugin, node)

	node.pprint()
Exemple #14
0
def main():

    #Try catch for opening file
    try:
        fileraw = open(sys.argv[1], 'r')
    except:
        print(Back.RED + " Error happened when opening the input file " +
              Style.RESET_ALL)  #error if problem with the input file
        exit(1)

    filelinelist = fileraw.read().split(
        '\n')  #spliting the input file by lines
    fileraw.close()

    observationListStart = []  #initial list of observations
    satelliteListStart = []  #initial list of satellites

    try:
        idcounter = 0

        for obscoord in re.sub('([OBS: ]|[()])', '',
                               filelinelist[0]).split(';'):
            idcounter += 1
            obscoordlist = list(map(int, obscoord.split(',')))
            observationListStart.append(
                Observation.observation(
                    idcounter, obscoordlist[0],
                    obscoordlist[1]))  #including observations
            #print("obs", idcounter, obscoordlist[0], obscoordlist[1])

        idcounter = 0

        for position in range(1, len(filelinelist)):
            idcounter += 1
            poscoordlist = list(
                map(
                    int,
                    re.sub('(SAT)\w+: {1}', '',
                           filelinelist[position]).split(';')))
            satelliteListStart.append(
                Satellite.satellite(idcounter, (idcounter), 0, "iddle",
                                    poscoordlist))  #including satellites
            #print("pos", idcounter, (idcounter), 0, "iddle", poscoordlist)

    except:
        print(Back.RED + " Object creation failed: Invalid file contents " +
              Style.RESET_ALL)  #error if the input file format is not correct
        exit(1)

    satelliteListGoal = []  #final list of satellites
    observationListGoal = []  #finallist of observations

    InitialNode = Node.node(None, satelliteListStart,
                            observationListStart)  #creating the initial node
    FinalNode = Node.node(None, satelliteListGoal,
                          observationListGoal)  #creating the final node
    astar = AStar.astar(
        InitialNode, FinalNode,
        sys.argv[2])  #creating A* object (sys.argv[2] is the heurtistic type)

    stdout_fileno = sys.stdout
    sys.stdout = open('{0}.output'.format(sys.argv[1]), 'w')
    statoutput = open('{0}.statistics'.format(sys.argv[1]), 'w')
    print("Overall time: ", astar.algorithm(), " seconds.",
          file=statoutput)  #calling the A* algorithm method          #CHECK!!!
    print("Overall cost: ", astar.getTotalCost(),
          file=statoutput)  #calling the A* algorithm method
    print("#Steps: ", len(astar.getPath(astar.getGoalNode())), file=statoutput)
    # print("#Expansions: ", astar.getCountExpansion(), file = statoutput)
    sys.stdout.close()
    sys.stdout = stdout_fileno
Exemple #15
0
def solution(L):
    prev = None
    for n in L:
        if n.next is None:
            break
        else:
            prev = n

    if prev is None:
        return L.d
    else:
        return prev.d


L0 = Node(1)

L1 = Node(1)
[L1.append(x) for x in [1]]

L2 = Node(1)
[L2.append(x) for x in [2]]

L3 = Node(2)
[L3.append(x) for x in [1, 1, 2, 3, 5, 4]]


@pytest.mark.parametrize("L, expected", [
    (L0, 1),
    (L1, 1),
    (L2, 1),
    def addAdjacentNodes(self, currentNode):
        satelliteList = currentNode.getListSatellites()  #list of satellites
        observationList = currentNode.getListObservations(
        )  #list of observations

        for satellite in satelliteList:  #this loop will make that all the satellites are in the same time (position
            if (satellite.getHasStartedMoving()):
                if (satellite.getPosition() >= 0
                        and satellite.getPosition() < 23):
                    satellite.setPosition(satellite.getPosition() + 1)
                elif (satellite.getPosition() >= 23
                      or satellite.getPosition() < 0):
                    satellite.setPosition(0)

            if (satellite.getIdNumber() == 1):
                print("{0}.".format(self.counter),
                      end='')  #printing current position
            self.counter = self.counter + 0.5

        for satellite in satelliteList:  #moving through the list of satellites to
            childNode = Node.node(currentNode)
            satellite.setHasStartedMoving(True)

            print("SAT{0}: ".format(satellite.getIdNumber()),
                  end='')  #printing SAT Id number

            if (
                    satellite.getPosition() > 11
            ):  #satellites can only do activies from 0 to 11       #CASE FOR POSITION > 11
                satellite.iddle(
                )  #the satellite performs the downlinking of the observation
                if (satellite.getIdNumber() == 1):
                    print("IDLE, ", end='')  #printing a comma if it is SAT1
                if (satellite.getIdNumber() == 2):
                    print("IDLE ")  #printing a new line if it is SAT2

                if (self.checkNode(childNode)
                    ):  #checking if the node has already been expanded
                    self.createChildNode(currentNode, childNode, satelliteList,
                                         observationList)
                continue  #it won't do anything during this time
            countObservations = 0  #auxiliary variable to count the number of observations

            for observation in observationList:  #moving through the list of observations

                #MEASURE

                #checking that the observation and the satellite are in the same position,also that the observation has not been measured,
                #that it has energy, and that is does not have an observation  that needs to be dowlinked
                if (satellite.getPosition() == observation.getPosition()
                        and not (observation.getMeasured()) and
                        satellite.getEnergy() >= satellite.states.measurement
                        and satellite.getObservation() == None):

                    if (satellite.getIdNumber() == 1):  # CASE for SAT 1
                        if (satellite.getBand() == observation.getBand()
                                or satellite.getBand() - 1
                                == observation.getBand()
                            ):  #it can access its current band an one below
                            satellite.measure(observation)  #measuring
                            self.setTotalCost(self.getTotalCost() +
                                              satellite.states.measurement
                                              )  #updating total cost

                            if (satellite.getIdNumber() == 1):
                                print("Measure O{0}, ".format(
                                    observation.getIdNumber()),
                                      end='')  #printing a comma if it is SAT1
                            if (satellite.getIdNumber() == 2):
                                print("Measure O{0} ".format(
                                    observation.getIdNumber())
                                      )  #printing a new line if it is SAT2

                            if (
                                    self.checkNode(childNode)
                            ):  #checking if the node has already been expanded
                                self.createChildNode(currentNode, childNode,
                                                     satelliteList,
                                                     observationList)
                                break  #it has already done an activity, so the rest do not need to be checked

                    if (satellite.getIdNumber() == 2):  #CASE for SAT 2
                        if (satellite.getBand() == observation.getBand()
                                or satellite.getBand() + 1
                                == observation.getBand()
                            ):  #it can access its current band an one above
                            satellite.measure(observation)  #measuring
                            self.setTotalCost(self.getTotalCost() +
                                              satellite.states.measurement
                                              )  #updating total cost

                            if (satellite.getIdNumber() == 1):
                                print("Measure O{0}, ".format(
                                    observation.getIdNumber()),
                                      end='')  #printing a comma if it is SAT1
                            if (satellite.getIdNumber() == 2):
                                print("Measure O{0} ".format(
                                    observation.getIdNumber())
                                      )  #printing a new line if it is SAT2

                            if (
                                    self.checkNode(childNode)
                            ):  #checking if the node has already been expanded
                                self.createChildNode(currentNode, childNode,
                                                     satelliteList,
                                                     observationList)
                                break  #it has already done an activity, so the rest do not need to be checked

                #DOWLINK

                elif (
                        satellite.getActivity() == "measurement"
                        and satellite.getEnergy() >= satellite.states.downlink
                ):  #the last activity performed by the satellite was "measure", so now it needs to downlink the observation
                    satellite.downlink(
                    )  #the satellite performs the downlinking of the observation
                    self.setTotalCost(
                        self.getTotalCost() +
                        satellite.states.downlink)  #updating total cost

                    if (satellite.getIdNumber() == 1):
                        print("Downlink O{0}, ".format(
                            observation.getIdNumber()),
                              end='')  #printing a comma if it is SAT1
                    if (satellite.getIdNumber() == 2):
                        print("Downlink O{0} ".format(observation.getIdNumber(
                        )))  #printing a new line if it is SAT2

                    if (self.checkNode(childNode)
                        ):  #checking if the node has already been expanded
                        self.createChildNode(currentNode, childNode,
                                             satelliteList, observationList)
                        break  #it has already done an activity, so the rest do not need to be checked

                #CHARGE

                #checking that there's no energy to perform some activity. As we are using "if else", this case will be executed if others haven't been executed before
                elif (satellite.getEnergy() < satellite.states.measurement
                      or satellite.getEnergy() < satellite.states.downlink):

                    satellite.charge()  #charging
                    self.setTotalCost(
                        self.getTotalCost() +
                        satellite.states.charge)  #updating total cost

                    if (satellite.getIdNumber() == 1):
                        print("Charge, ",
                              end='')  #printing a comma if it is SAT1
                    if (satellite.getIdNumber() == 2):
                        print("Charge ")  #printing a new line if it is SAT2

                    if (self.checkNode(childNode)
                        ):  #checking if the node has already been expanded
                        self.createChildNode(currentNode, childNode,
                                             satelliteList, observationList)
                        break  #it has already done an activity, so the rest do not need to be checked

                #TURN

                #it will turn into another band if it has enough energy, the previous activity was not "measurent" (it should downlink it), and there's no
                #observation that can be measured at the moment
                elif (
                        satellite.getEnergy() >= satellite.states.turn
                        and satellite.getActivity() != "measurement" and
                        satellite.getPosition() != observation.getPosition()
                        and satellite.getBand() != observation.getBand() and
                    ((satellite.getIdNumber() == 1
                      and satellite.getBand() - 1 != observation.getBand()) or
                     (satellite.getIdNumber() == 2
                      and satellite.getBand() + 1 != observation.getBand()))
                        and
                    ((satellite.getPosition() + 1 != observation.getPosition()
                      and not (observation.getMeasured())))):

                    satellite.turn()  #turning
                    self.setTotalCost(
                        self.getTotalCost() +
                        satellite.states.turn)  #updating total cost

                    if (satellite.getIdNumber() == 1):
                        print("Turn, ",
                              end='')  #printing a comma if it is SAT1
                    if (satellite.getIdNumber() == 2):
                        print("Turn ")  #printing a new line if it is SAT2

                    if (self.checkNode(childNode)
                        ):  #checking if the node has already been expanded
                        self.createChildNode(currentNode, childNode,
                                             satelliteList, observationList)
                        break  #it has already done an activity, so the rest do not need to be checked

                #IDLE

                #in any other case, it do nothing
                else:  #(satellite.getEnergy() >= satellite.states.turn and satellite.getActivity() != "measurement" and satellite.getPosition() != observation.getPosition()):
                    if (
                            countObservations == len(observationList) - 1
                    ):  #we only want it to be "iddle" if it's the last observation from the list (in IDDLE we are not including "break")
                        satellite.iddle()  #do nothing

                        if (satellite.getIdNumber() == 1):
                            print("IDLE, ",
                                  end='')  #printing a comma if it is SAT1
                        if (satellite.getIdNumber() == 2):
                            print("IDLE ")  #printing a new line if it is SAT2

                        if (self.checkNode(childNode)
                            ):  #checking if the node has already been expanded
                            self.createChildNode(currentNode, childNode,
                                                 satelliteList,
                                                 observationList)

                countObservations = countObservations + 1  #updaating auxiliary counter

        self.__openList.insertAtEvaluation(
            childNode
        )  #inserting the child node into the open list, taking into account its evaluation value
Exemple #17
0

def solution(L, E):
    prev = None
    for n in L:
        if n.d == E:
            if prev is None:
                L = L.next
            else:
                prev.next = n.next
            break
        prev = n
    return L


L0 = Node.from_list([1])

L1 = Node.from_list([1, 1])
L1E = Node.from_list([1])

L2 = Node.from_list([1, 2, 3, 4])
L2E = Node.from_list([1, 3, 4])

L3 = Node.from_list([1, 2, 3])
L3E = Node.from_list([1, 2])


@pytest.mark.parametrize("L, E, expected", [
    (L0, 0, L0),
    (L1, 1, L1E),
    (L2, 2, L2E),