Esempio n. 1
0
 def addOpenningTag(self, tag):
     if self.root.state == 'empty':
         self.root.state = 'open'
         self.root.openningTag = tag
         if tag.type == 'empty':
             self.root.state = 'close'
             self.root.closingTag = tag
         return
     elif self.root.state == 'close' or (self.root.state == 'text'
                                         and self.root.openningTag.type
                                         == 'no'):
         rootBranch1 = node()
         rootBranch1.state = 'close'
         rootBranch1.openningTag = self.root.openningTag
         rootBranch1.listOfText = self.root.listOfText
         rootBranch1.closingTag = self.root.closingTag
         rootBranch1.listOfNodes = self.root.listOfNodes
         self.root = node()
         self.root.state = 'passed'
         rootBranch2 = node()
         rootBranch2.state = 'open'
         rootBranch2.openningTag = tag
         if tag.type == 'empty':
             rootBranch2.state = 'close'
             rootBranch2.closingTag = tag
         self.root.listOfNodes.append(rootBranch1)
         self.root.listOfNodes.append(rootBranch2)
     else:
         self.root.state = 'passed'
         self.addOpenningSubtree(self.root, tag)
Esempio n. 2
0
def testcase():
    head = node(1)
    head.next = node(2)
    head.next.next = node(3)
    head.next.next.next = node(4)
    head.next.next.next.next = node(5)

    sol = Solution(head)
    sol.print_list(sol.reverse_list())
Esempio n. 3
0
 def addNode(self, data):
     if self.getHead() == None:
         self.setHead(node(data))
     else:
         currentNode = self.getHead()
         while(currentNode.getNext() != None):
             currentNode = currentNode.getNext()
         currentNode.setNext(node(data))
     return "Added a new node:" + str(data)
Esempio n. 4
0
	def iniGameBoard(self):
		for i in range(0,len(self.board)):
			col=[]
			for j in range(0,len(self.board[0])):
				if self.board[i][j]!=0 :
					col.append(node(domain,(-1,-1),i,j,value=self.board[i][j]))
				else:
					col.append(node(domain,(-1,-1),i,j))
			self.gameBoard.append(col)
			col=[]
Esempio n. 5
0
 def append(self, data):
     ''' puts data at the end of a list'''
     if self.isEmpty():
         self.front = node(data)
         self.back = self.front
         self.size += 1
     else:
         # create a node with data in it and call it 'temp'
         temp = node(data)
         temp.set_prev(self.front)
         # the new node's (temp) prev becomes the last element in the list
         # the back node's next becomes the newly created node
         self.back.set_next(temp)
         self.back = temp  # updating the back to temp
         self.size += 1
 def __init__(self,
              address=('localhost', 5001 + 1),
              id=1,
              init_address=('localhost', 5000),
              timeout=3):
     threading.Thread.__init__(self)
     self.node = node(address, self.__class__.__name__, id, init_address)
Esempio n. 7
0
def DT_Learn(data, attrs, pData):
    if data.__len__() == 0:
        return mostCommon(pData)
    else:
        if Control_1(data):
            return mostCommon(data)
        else:
            if attrs.__len__() == 0:
                return mostCommon(data)
            else:
                # calcolo il guadagno e scelgo l'attribbuto che realizza il massimo guadagno
                listattr = list(attrs.keys())
                earning = gain(data, listattr)
                i = np.argmax(earning)
                A = listattr[i]
                # calcolo la classe del nodo cioè la classe più presente nel dataset corrente
                classe, num = np.unique(data['Y'], return_counts=True)
                i = np.argmax(num)
                y = classe[i]
                # creo il nuovo nodo
                newNode = node()
                newNode.setAttribute(A)
                newNode.setY(y)

                val = attrs[A]
                newattrs = copy.deepcopy(attrs)
                newattrs.pop(A)
                for i in val:
                    data2 = data.where(data[A] == i).dropna()
                    nodo = DT_Learn(data2, newattrs, data)
                    newNode.setChild(nodo, i)
                return newNode
Esempio n. 8
0
def mostCommon(data):
    NewNode = node()
    val, num = np.unique(data['Y'], return_counts=True)
    i = np.argmax(num)
    NewNode.setY(val[i])
    NewNode.leaf = True
    return NewNode
Esempio n. 9
0
def test3():
    tree = node()
    root = tree
    #first child
    firstChild = root.addNode("seq")
    if firstChild == None:
        print ("error creating seq node")
        print("test 3: failed :-(")
        return None
        
    tempN = firstChild.addNode("seq")
    if tempN == None:
        print ("error creating seq node")
    else:
        tempN.setAttrib("probability","0.1 0.5")
        
    tempN = firstChild.addNode("seq")
    if tempN == None:
        print ("error creating seq node")
    else:
        tempN.setAttrib("probability","0.1 0.5")
        
    tempN = firstChild.addNode("loop")
    if tempN == None:
        print ("error creating loop node")
    else:
        tempN.setAttrib("probability","0.1 0.5")
        
    tempN = firstChild.addNode("par")
    if tempN == None:
         print ("error creating parallel node")
    else:
        tempN.setAttrib("probability","0.1 0.5")
        
    tempN = firstChild.addNode("tsk")
    if tempN == None:
        print ("error creating tsk node")
    else:
        tempN.setAttrib("probability","0.1 0.5")
        
    tempN = firstChild.addNode("sel")
    if tempN == None:
        print ("error creating selector node")
    else:
        tempN.setAttrib("probability","0.1 0.5")
    
    #iterate over firstChild children:
    firstChildList = firstChild.getChildren()
    count = 0
    for childNode in firstChildList:
        count += 1
    if count == 6:
        print("test 3: success! please check the file test3.xml - every tag need to have the same attrib.")
    else:
        print("test 3: failed :-(")
    
    #print the tree we built from scratch to xml file.
    #please check the file- every tag need to have the same attrib.
    root.treeToXml("tests/test3.xml")
Esempio n. 10
0
 def addClosingTag(self, tag):
     if self.root.state == 'empty':
         self.root.state = 'close'
         self.root.closingTag = tag
     elif self.root.state == 'close':
         rootBranch1 = node()
         rootBranch1.state = 'close'
         rootBranch1.openningTag = self.root.openningTag
         rootBranch1.listOfText = self.root.listOfText
         rootBranch1.closingTag = self.root.closingTag
         rootBranch1.listOfNodes = self.root.listOfNodes
         self.root = node()  # clear root
         self.root.state = 'close'
         self.root.closingTag = tag
         self.root.listOfNodes.append(rootBranch1)
     else:
         self.addClosingSubtree(self.root, tag, 0)
Esempio n. 11
0
    def __init__(self, profondeurMax, nbChildMax, board):
        self.profondeurMax = profondeurMax
        self.nbChildMax = nbChildMax
        self.root = node(None, 0, self.profondeurMax, 0, board)
        self.propagate(self.root)

        self.root.heuristic = self.MinMax(self.root)
        self.info()
 def __init__(self,
              address=('localhost', 5000),
              id=0,
              init_address=None,
              timeout=3):
     threading.Thread.__init__(self)
     self.node = node(address, self.__class__.__name__, id, init_address)
     self.grill = True  # As maquinas...
     self.fryer = True
     self.bottle = True
Esempio n. 13
0
def mainFromScrath(argv):
    # Twhile True:
    # print("please chose a number between 1-5")
    # create the tree root
    tree = node()
    # create a new seq child
    child = tree.addNode("seq")
    # add attribute to the new node
    child.setAttrib("probability", "0.78, 0.2, 0.1, 0.9")
    # write the tree to xml file
    tree.treeToXml(argv)
Esempio n. 14
0
def graph_generator(filename):
    pyramid = open(filename)
    pyramid = [line.strip('\n').split(' ') for line in pyramid]
    #print pyramid
    graph = []
    for r, row in enumerate(pyramid):  #Creates nodes
        graph.append([])
        for element in row:
            if element[0] == '0':
                graph[r].append(node(-int(element[1:])))
            else:
                graph[r].append(node(-int(element)))

    for r in range(0, len(graph) - 1):  #Updates neighbors
        for e in range(0, len(graph[r])):
            graph[r][e].neighbors = [graph[r + 1][e], graph[r + 1][e + 1]]

    graph[0][0].distance = graph[0][0].value

    return graph
Esempio n. 15
0
def graph_generator(filename):
	pyramid = open(filename)
	pyramid = [line.strip('\n').split(' ') for line in pyramid]
	#print pyramid
	graph = []
	for r, row in enumerate(pyramid): #Creates nodes
		graph.append([])
		for element in row:
			if element[0] == '0':
				graph[r].append(node(-int(element[1:])))
			else:
				graph[r].append(node(-int(element)))
	
	for r in range(0, len(graph)-1): #Updates neighbors
		for e in range(0, len(graph[r])):
			graph[r][e].neighbors = [graph[r+1][e], graph[r+1][e+1]]

	graph[0][0].distance = graph[0][0].value

	return graph
Esempio n. 16
0
 def addOpenningSubtree(self, subTree, tag):
     if len(subTree.listOfNodes) == 0:
         newNode = node()
         newNode.state = 'open'
         newNode.openningTag = tag
         if tag.type == 'empty':
             newNode.state = 'close'
             newNode.closingTag = tag
         subTree.listOfNodes.append(newNode)
         return
     if subTree.listOfNodes[-1].state == 'text' or subTree.listOfNodes[
             -1].state == 'close':
         newNode = node()
         newNode.state = 'open'
         newNode.openningTag = tag
         if tag.type == 'empty':
             newNode.state = 'close'
             newNode.closingTag = tag
         subTree.listOfNodes.append(newNode)
         return
     self.addOpenningSubtree(subTree.listOfNodes[-1], tag)
Esempio n. 17
0
 def addTextSubtree(self, subTree, text):
     if len(subTree.listOfNodes) == 0:
         subTree.state = 'text'
         subTree.listOfText.append(text)
         return
     if subTree.listOfNodes[-1].state == 'close':
         newNode = node()
         newNode.state = 'text'
         newNode.listOfText.append(text)
         subTree.listOfNodes.append(newNode)
         return
     self.addTextSubtree(subTree.listOfNodes[-1], text)
Esempio n. 18
0
 def __init__(self,
              address=('localhost', 5001 + 2),
              id=2,
              init_address=('localhost', 5000),
              timeout=3):
     threading.Thread.__init__(self)
     self.node = node(address, self.__class__.__name__, id, init_address)
     self.plates = Queue.Queue(
     )  # QUEUE de pratos(menus) que tem para fazer
     self.permitions = Queue.Queue(
     )  # QUEUE das permissões (vindas o Restaurante) que tem, para consequentemente cozinhar
     self.cook = threading.Thread(target=self.cooking)
Esempio n. 19
0
    def completeGraph(self):
        # Method that create a complete graph. It return a list of objects node.

        nodesList = []  # Create an empty list
        nodeT = self.N  # Define the total number of nodes
        positions = self.load_positions()
        max_pos = self.max_dist(positions)
        for i in range(nodeT):
            nodesList.append(
                node([(x, self.distance(positions, x, i) / max_pos)
                      for x in range(nodeT) if x != i]))
        # Append an object node, that is connected with all the other nodes except itself, at each iteration
        return nodesList
Esempio n. 20
0
def test1():

    tree = node()
    root = tree
    #first child
    newChild = root.addNode("par")  #parallel
    #notice that the childlist start from zero.
    child = root.getChild(0)
    #compare by instance id:
    if newChild.comparTo(child) == True:
        print("test 1: success!")
    else:
        print("test 1: failed :-(")
Esempio n. 21
0
	def __init__(self):
		self.graph = {
		'A': [edge('B',5),edge('C',4)],
		'B': [edge('A',5),edge('F',10)],
		'C': [edge('A',4),edge('D',8)],
		'D': [edge('C',8),edge('F',2),edge('E',3)],
		'E': [edge('D',3),edge('G',2)],
		'F': [edge('B',10),edge('D',2),edge('G',3),edge('H',8)],
		'G': [edge('E',2),edge('F',3),edge('H',1)],
		'H': [edge('G',1),edge('F',8)]}
	
		self.meta=state('H')
		self.initialNode = node(state('A'),None,None,0)
Esempio n. 22
0
 def prepend(self, data):
     '''puts data at the end of a list'''
     if self.isEmpty():
         self.append(data)
     else:
         # create a node with data in it and call it 'temp'
         temp = node(data)
         temp.setNext(self.back)
         # the new node's (temp) next becomes the first element in the list
         # teh front node's prev becomes the newly created node
         self.front.setPrev(temp)
         self.front = temp  # updating the back to temp
         self.size += 1
Esempio n. 23
0
def test1():
    
    tree = node()
    root = tree
    #first child
    newChild = root.addNode("par")#parallel
    #notice that the childlist start from zero.
    child = root.getChild(0)
    #compare by instance id:
    if newChild.comparTo(child) == True :
        print("test 1: success!")
    else:
        print("test 1: failed :-(")
Esempio n. 24
0
 def addText(self, text):
     if self.root.state == 'empty' or self.root.state == 'text':
         self.root.state = 'text'
         self.root.listOfText.append(text)
         return
     elif self.root.state == 'close' or (self.root.state == 'text'
                                         and self.root.openningTag.type
                                         == 'no'):
         rootBranch1 = node()
         rootBranch1.state = 'close'
         rootBranch1.openningTag = self.root.openningTag
         rootBranch1.listOfText = self.root.listOfText
         rootBranch1.closingTag = self.root.closingTag
         rootBranch1.listOfNodes = self.root.listOfNodes
         self.root = node()
         self.root.state = 'passed'
         rootBranch2 = node()
         rootBranch2.state = 'text'
         rootBranch2.listOfText.append(text)
         self.root.listOfNodes.append(rootBranch1)
         self.root.listOfNodes.append(rootBranch2)
     else:
         self.addTextSubtree(self.root, text)
Esempio n. 25
0
 def __init__(self, fileName=None ,root=None):
     if fileName != None:
         tree = etree.parse(fileName)
     #if we don't get a file to parse
     if root == None:
         self.root = tree.getroot()
     else:
         self.root= root
         
     #hold the name of the file.
     self.fileName = fileName
     #create a root node- type plan
     self.rootNode = node(self.root,self,self.root.tag)
     #update the whole tree- create the wrap for the whole tree.
     self._getUpdateTree()
Esempio n. 26
0
 def insert(self, data, old_node):
     '''inserts a node between two other nodes in a list'''
     if self.isEmpty():
         self.append(data)
     else:
         if old_node == None:
             return None
         else:
             # create a node with data in it and call it 'temp
             temp = node(data)
             # set that node (temp) prev to the node already in the list
             temp.setPRev(old_node)
             temp.setNext(old_node.getNext())
             # set 'temp's next to the next of teh node already in the lsit
             old_node.setNext(temp)  # set 'temp' as the old node's next
             temp.getNext().setPrevious(temp)
    def add(self, item):
        current = self.head
        previous = None
        stop = False
        while current != None and not stop:
            if current.getData() > item:
                stop = True
            else:
                previous = current
                current = current.getNext()

        temp = node(item)
        if previous == None:
            temp.setNext(self.head)
            self.head = temp
        else:
            temp.setNext(current)
            previous.setNext(temp)
Esempio n. 28
0
 def __init__(self, address=('localhost', 5001+3), id=3, init_address=('localhost', 5000), timeout=3):
     threading.Thread.__init__(self)
     self.node = node(address, self.__class__.__name__, id, init_address)
     self.deliveries = {}        # Dicionario pa guardar o ID : ADDR do cliente
Esempio n. 29
0
 def test_str(self):
     test_object = str(node(3,None))
     self.assertEqual('3',test_object)
Esempio n. 30
0
 def test_node(self):
     test_object = node(3,None).item
     self.assertEqual(3,test_object)
Esempio n. 31
0
def test17():

    tree = node()
    root = tree
    #first child
    firstChild = root.addNode("par")
    if firstChild == None:
        print("error creating parallel node")
        print("test 17: failed :-(")
        return None
    dist_succ = _createUniformDist(2, 5)
    dist_fail = _createUniformDist(6, 10)

    firstChild.DEBUGchild = True
    for j in range(3):
        tempN = firstChild.addNode("seq")
        if tempN == None:
            print("error creating seq node")

        for i in range(5):
            if ((j == 1) and (i == 2)):
                tempN1 = tempN.addNode("seq")
                tempN.DEBUGchild = True
                tempN1.DEBUGchild = True
                if tempN1 == None:
                    print("error creating seq node")
                else:
                    for i in range(4):
                        tempN2 = tempN1.addNode("tsk")
                        if tempN2 == None:
                            print("error creating seq node")
                        else:
                            tempN2.setProbTable([0.8, 0.5])
                            for i in range(2):
                                dist_fail = _createUniformDist(6, 10 - i)
                                tempN2.addDistToSuccTable(dist_succ)
                                tempN2.addDistToFailTable(dist_fail)
                            tempN2.setAttrib(
                                "Successdistribution",
                                tempN2._distTableToString(
                                    tempN2.distTableSucc))
                            tempN2.setAttrib(
                                "Failuredistribution",
                                tempN2._distTableToString(
                                    tempN2.distTableFail))
                            tempN2.setDebug("True 100")

            else:
                tempN1 = tempN.addNode("tsk")
                if tempN1 == None:
                    print("error creating seq node")
                else:
                    tempN1.setProbTable([0.7, 0.5])
                    for i in range(2):
                        tempN1.addDistToSuccTable(dist_succ)
                        tempN1.addDistToFailTable(dist_fail)

                    tempN1.setAttrib(
                        "Successdistribution",
                        tempN1._distTableToString(tempN1.distTableSucc))
                    tempN1.setAttrib(
                        "Failuredistribution",
                        tempN1._distTableToString(tempN1.distTableFail))

    #iterate over firstChild children:
    firstChildList = firstChild.getChildren()
    node.debugMode = False
    for i in range(5):
        firstChild.run(0)
    root.treeToXml("output/test17.xml")

    print "phase 2"
    node.debugMode = True
    for i in range(5):
        firstChild.run(0)
    root.treeToXml("output/test17.xml")

    count = 0
    for childNode in firstChildList:
        count += 1
    if count == 3:
        print(
            "test 17: success! please check the file test4.xml - every tag need to have the same attrib."
        )
    else:
        print("test 17: failed :-(")
Esempio n. 32
0
def test15():
  
    tree = node()
    root = tree
    #first child
    firstChild = root.addNode("par")
    if firstChild == None:
        print ("error creating seq node")
        print("test 15: failed :-(")
        return None
    dist_succ = _createUniformDist(2,5)
    dist_fail = _createUniformDist(6,10)   
    
    firstChild.DEBUGchild = True 
    for j in range(3): 
      tempN = firstChild.addNode("seq")
      if tempN == None:
	  print ("error creating seq node")
      
      for i in range(5):
          if ((j==1) and (i==2)):
              tempN1 = tempN.addNode("seq")
              tempN.DEBUGchild = True
              tempN1.DEBUGchild = True
              if tempN1 == None:
                  print ("error creating seq node")
              else:                
                  for i in range(4):
                      tempN2 = tempN1.addNode("tsk")
                      if tempN2 == None:
                          print ("error creating seq node")
                      else:
                          tempN2.setProbTable([0.8, 0.5])
                          for i in range(2):
                              dist_fail = _createUniformDist(6,10-i)  
                              tempN2.addDistToSuccTable(dist_succ)
                              tempN2.addDistToFailTable(dist_fail)
                          tempN2.setAttrib("Successdistribution",tempN2._distTableToString(tempN2.distTableSucc))
                          tempN2.setAttrib("Failuredistribution",tempN2._distTableToString(tempN2.distTableFail))
                          tempN2.setDebug("True 100")
                              
          else:
              tempN1 = tempN.addNode("tsk")
              if tempN1 == None:
                  print ("error creating seq node")
              else:
                  tempN1.setProbTable([0.7, 0.5])
                  for i in range(2):
                      tempN1.addDistToSuccTable(dist_succ)
                      tempN1.addDistToFailTable(dist_fail)
                      
                  tempN1.setAttrib("Successdistribution",tempN1._distTableToString(tempN1.distTableSucc))
                  tempN1.setAttrib("Failuredistribution",tempN1._distTableToString(tempN1.distTableFail))
             
	    
        

    
    #iterate over firstChild children: 

    node.debugMode = False
    for i in range(5):
        firstChild.run(0)
    root.treeToXml("output/test15a.xml") 
    print("test 15.1: success! please check the file test15a.xml - every tag need to have the same attrib.")
    node.debugMode = True
    for i in range(5):
        firstChild.run(0)
    root.treeToXml("output/test15b.xml") 
    print("test 15.2: success! please check the file test15b.xml - every tag need to have the same attrib.")
Esempio n. 33
0
def test6():
    tree = node()
    root = tree
    #first child
    firstChild = root.addNode("par")
    if firstChild == None:
        print ("error creating par node")
        print("test 7: failed :-(")
        return None
    dist_succ = _createUniformDist(2,5)
    dist_fail = _createUniformDist(6,10)   
    
    firstChild.DEBUGchild = True 
    for j in range(3): 
      if j==0:  
          tempN = firstChild.addNode("seq")
          if tempN == None:
              print ("error creating seq node")
      if j==1:  
          tempN = firstChild.addNode("sel")
          if tempN == None:
              print ("error creating sel node")
      if j==2:  
          tempN = firstChild.addNode("loop")
          if tempN == None:
              print ("error creating seq node")        
      
      for i in range(5):
          if ((j==1) and (i==2)):
              tempN1 = tempN.addNode("seq")
              tempN.DEBUGchild = True
              tempN1.DEBUGchild = True
              if tempN1 == None:
                  print ("error creating seq node")
              else:                
                  for i in range(4):
                      tempN2 = tempN1.addNode("tsk")
                      if tempN2 == None:
                          print ("error creating seq node")
                      else:
                          tempN2.setProbTable([0.1, 0.5])
                          for i in range(2):
                              dist_fail = _createUniformDist(6,10-i)  
                              tempN2.addDistToSuccTable(dist_succ)
                              tempN2.addDistToFailTable(dist_fail)
                          tempN2.setAttrib("Successdistribution",tempN2._distTableToString(tempN2.distTableSucc))
                          tempN2.setAttrib("Failuredistribution",tempN2._distTableToString(tempN2.distTableFail))
                          tempN2.setDebug("True 100")

                              
          else:
              tempN1 = tempN.addNode("tsk")
              if tempN1 == None:
                  print ("error creating seq node")
              else:
                  tempN1.setProbTable([0.3, 0.5])
                  for i in range(2):
                      tempN1.addDistToSuccTable(dist_succ)
                      tempN1.addDistToFailTable(dist_fail)
                      
                  tempN1.setAttrib("Successdistribution",tempN1._distTableToString(tempN1.distTableSucc))
                  tempN1.setAttrib("Failuredistribution",tempN1._distTableToString(tempN1.distTableFail))
          if j==2:
              break
	    
        

    
    #iterate over firstChild children: 
    firstChildList = firstChild.getChildren()
    node.debugMode = False
    for i in range(5):
        firstChild.run(0)
    root.treeToXml("output/test4.xml") 
    
    print "phase 2"
    node.debugMode = True
    for i in range(5):
        firstChild.run(0)
    root.treeToXml("output/test5.xml") 
    
        
        
    count = 0
    for childNode in firstChildList:
        count += 1
    if count == 3:
        print("test 6: success! please check the file test4.xml - every tag need to have the same attrib.")
    else:
        print("test 6: failed :-(")
Esempio n. 34
0
        Outside.remove(Node[i].index)
"""
"""
j = 0
    for j in range(len(Cluster[i].nodes_idx)):
        if (Cluster[i].nodes_idx[j] not in Assigned_Nodes):
            Assigned_Nodes.append(Cluster[i].nodes_idx[j])
"""
"""
Cluster[i].Nodes.append(Cluster[i].centroid.index)

Cluster[i].nodes_idx.append(Cluster[i].centroid.index)
"""

#Create Node set
Node = [node(i, (deliv_517["Longitude"][i], deliv_517["Latitude"][i]), deliv_517["Delivery Volume"][i], deliv_517["Adj Nodes"][i]) for i in range(len(deliv_517))]

#Establish set Outside, which tracks the nodes that are not assigned to a cluster
Outside = []

i = 0
for i in range(len(Node)):
    Outside.append(Node[i].index)

#Create set that tracks the nodes that have been assigned to a cluster
Assigned_Nodes = []

#Cluster Initialization
#The last three nodes are the facilities. We are using them as the initial nodes in order to build the algorithm.
#Clusters take a Node object that will be the centroid, a target weight for the cluster, and a capacity.
Cluster = [cluster(Node[i], target_weight, deliv_517["Delivery Volume"][i]) for i in range(465,468)]
Esempio n. 35
0
        if (Node[Node[Outside[i]].adj_nodes[j]].isOutside == True):
            n_outside += 1
    Node[Outside[i]].reachability = n_outside/len(Outside)
"""
#%%
#Import node and cluster class objects
from Node import node
from Cluster import cluster
from Reachable_Extensible import get_reach_and_ext
from Best_Reach_Ext import best_reach_ext_nodes, best_reach_ext_clusters
from Assign_and_Update import assign_and_update
from Decision_Criteria import priority_weight, priority_card

#Create Node set
Node = [
    node(i, (delivs["Longitude"][i], delivs["Latitude"][i]),
         delivs["Delivery Volume"][i], delivs["Adj Nodes"][i])
    for i in range(len(delivs))
]

#Establish set Outside, which tracks the nodes that are not assigned to a cluster
Outside = [Node[i].index for i in range(len(Node))]

#Create set that tracks the nodes that have been assigned to a cluster
Assigned_Nodes = []

#Cluster Initialization:

#Clusters take a Node object that will be the centroid, a balance target for the cluster, and a capacity.
#This line creates 3 clusters with the facilities as the central locations.
Cluster = [
    cluster(Node[i], delivs["Delivery Volume"][i], 999999999)
Esempio n. 36
0
def test7():

    tree = node()
    root = tree
    #first child
    firstChild = root.addNode("par")
    if firstChild == None:
        print("error creating seq node")
        print("test 7: failed :-(")
        return None
    dist_succ = _createUniformDist(2, 5)
    dist_fail = _createUniformDist(6, 10)

    for j in range(3):
        tempN = firstChild.addNode("seq")
        if tempN == None:
            print("error creating seq node")

        for i in range(5):
            if ((j == 1) and (i == 2)):
                tempN1 = tempN.addNode("seq")
                if tempN1 == None:
                    print("error creating seq node")
                else:
                    for i in range(4):
                        tempN2 = tempN1.addNode("tsk")
                        if tempN2 == None:
                            print("error creating seq node")
                        else:
                            tempN2.setAttrib("time", "1")
                            tempN2.setAttrib("succ", "T")
                            #tempN2.setTime(0)
                            #tempN2.setSucc(False)
                            tempN2.setProbTable([0.8, 0.5])
                            for i in range(2):
                                tempN2.addDistToSuccTable(dist_succ)
                                tempN2.addDistToFailTable(dist_fail)
                            tempN2.setAttrib("Successdistribution",
                                             tempN2.distTableSucc)
                            tempN2.setAttrib("Failuredistribution",
                                             tempN2.distTableFail)

            else:
                tempN1 = tempN.addNode("tsk")
                if tempN1 == None:
                    print("error creating seq node")
                else:
                    tempN1.setAttrib("time", "1")
                    tempN1.setAttrib("succ", "T")
                    #tempN1.setTime(0)
                    #tempN1.setSucc(False)
                    tempN1.setProbTable([0.7, 0.5])
                    for i in range(2):
                        tempN1.addDistToSuccTable(dist_succ)
                        tempN1.addDistToFailTable(dist_fail)

                    tempN1.setAttrib("Successdistribution",
                                     tempN1.distTableSucc)
                    tempN1.setAttrib("Failuredistribution",
                                     tempN1.distTableFail)

    #iterate over firstChild children:
    firstChildList = firstChild.getChildren()
    for i in range(5):
        firstChild.run(0)
    count = 0
    for childNode in firstChildList:
        count += 1
    if count == 3:
        print(
            "test 7: success! please check the file output/test4.xml - every tag need to have the same attrib."
        )
    else:
        print("test 7: failed :-(")

    #print the tree we built from scratch to xml file.
    #please check the file- every tag need to have the same attrib.
    root.treeToXml("output/test4.xml")
Esempio n. 37
0
def test7():
  
    tree = node()
    root = tree
    #first child
    firstChild = root.addNode("par")
    if firstChild == None:
        print ("error creating seq node")
        print("test 7: failed :-(")
        return None
    dist_succ = _createUniformDist(2,5)
    dist_fail = _createUniformDist(6,10)   
    
    
    for j in range(3): 
      tempN = firstChild.addNode("seq")
      if tempN == None:
	  print ("error creating seq node")
	  
      for i in range(5):
          if ((j==1) and (i==2)):
              tempN1 = tempN.addNode("seq")
              if tempN1 == None:
                  print ("error creating seq node")
              else:
                  for i in range(4):
                      tempN2 = tempN1.addNode("tsk")
                      if tempN2 == None:
                          print ("error creating seq node")
                      else:
                          tempN2.setAttrib("time","1")
                          tempN2.setAttrib("succ","T")
                          #tempN2.setTime(0)
                          #tempN2.setSucc(False)
                          tempN2.setProbTable([0.8, 0.5])
                          for i in range(2):
                              tempN2.addDistToSuccTable(dist_succ)
                              tempN2.addDistToFailTable(dist_fail)
                          tempN2.setAttrib("Successdistribution",tempN2.distTableSucc)
                          tempN2.setAttrib("Failuredistribution",tempN2.distTableFail)    
                              
          else:
              tempN1 = tempN.addNode("tsk")
              if tempN1 == None:
                  print ("error creating seq node")
              else:
                  tempN1.setAttrib("time","1")
                  tempN1.setAttrib("succ","T")
                  #tempN1.setTime(0)
                  #tempN1.setSucc(False)
                  tempN1.setProbTable([0.7, 0.5])
                  for i in range(2):
                      tempN1.addDistToSuccTable(dist_succ)
                      tempN1.addDistToFailTable(dist_fail)
                      
                  tempN1.setAttrib("Successdistribution",tempN1.distTableSucc)
                  tempN1.setAttrib("Failuredistribution",tempN1.distTableFail) 
             
	    
        

    
    #iterate over firstChild children: 
    firstChildList = firstChild.getChildren()
    for i in range(5):
        firstChild.run(0)
    count = 0
    for childNode in firstChildList:
        count += 1
    if count == 3:
        print("test 7: success! please check the file output/test4.xml - every tag need to have the same attrib.")
    else:
        print("test 7: failed :-(")
    
    #print the tree we built from scratch to xml file.
    #please check the file- every tag need to have the same attrib.
    root.treeToXml("output/test4.xml")
Esempio n. 38
0
def test3():
    tree = node()
    root = tree
    #first child
    firstChild = root.addNode("seq")
    if firstChild == None:
        print("error creating seq node")
        print("test 3: failed :-(")
        return None

    tempN = firstChild.addNode("seq")
    if tempN == None:
        print("error creating seq node")
    else:
        tempN.setAttrib("probability", "0.1 0.5")

    tempN = firstChild.addNode("seq")
    if tempN == None:
        print("error creating seq node")
    else:
        tempN.setAttrib("probability", "0.1 0.5")

    tempN = firstChild.addNode("loop")
    if tempN == None:
        print("error creating loop node")
    else:
        tempN.setAttrib("probability", "0.1 0.5")

    tempN = firstChild.addNode("par")
    if tempN == None:
        print("error creating parallel node")
    else:
        tempN.setAttrib("probability", "0.1 0.5")

    tempN = firstChild.addNode("tsk")
    if tempN == None:
        print("error creating tsk node")
    else:
        tempN.setAttrib("probability", "0.1 0.5")

    tempN = firstChild.addNode("sel")
    if tempN == None:
        print("error creating selector node")
    else:
        tempN.setAttrib("probability", "0.1 0.5")

    #iterate over firstChild children:
    firstChildList = firstChild.getChildren()
    count = 0
    for childNode in firstChildList:
        count += 1
    if count == 6:
        print(
            "test 3: success! please check the file test3.xml - every tag need to have the same attrib."
        )
    else:
        print("test 3: failed :-(")

    #print the tree we built from scratch to xml file.
    #please check the file- every tag need to have the same attrib.
    root.treeToXml("tests/test3.xml")
Esempio n. 39
0
def minimax(board, player, moves_ahead, first_player
            ):  #creates nodes for start board and return best next move
    m = 0

    curr_node = node(board, [], [], [], "MAX", True, True, False,
                     -1)  #creates parent node

    first_move = True
    while (
        (curr_node.parent != []) or (first_move == True)
    ):  #in this loop it creates each nodes children until reached to given depth (moves_ahead)

        first_move = False
        if (curr_node.level == "MIN"):  #assigns player depending on level
            if (player == 'w'):
                p = 'b'
            else:
                p = 'w'
        else:
            if (player == 'w'):
                p = 'w'
            else:
                p = 'b'

        if (curr_node.level == "MAX"
            ):  #assigns level depending on parent node's level
            l = "MIN"
        else:
            l = "MAX"
        new_states = movegen(
            curr_node.state,
            player)  #gets the new moves from current given move

        while (len(new_states) > 0):  #creates children nodes
            state = new_states.pop(0)
            new_node = node(state, curr_node, [], [], l, False, False, False,
                            -1)
            curr_node.children.append(new_node)

        for c in range(len(curr_node.children)):
            if (c != len(curr_node.children) - 1):
                curr_node.children[c].right = curr_node.children[c + 1]
        curr_children = copy.copy(curr_node.children)

        #assigns next node
        if (m + 1 >= moves_ahead):  #if depth is reached
            for i in curr_node.children:  #leaves are found
                i.visited = True
                i.isleaf = True
            if (curr_node.right !=
                []):  #goes to the node on the right if exists
                curr_node = curr_node.right
                if (curr_node.visited == True):  #finds node that wasnt visited
                    found = False
                    while (curr_node.visited == True):
                        if (curr_node.visited == False and curr_node != []):
                            found = True
                            curr_node = curr_node.right
                            curr_node.visited = True
                            break
                    if (found == False):  #if not found goes back to the parent
                        curr_node = curr_node.parent
                else:
                    curr_node.visited = True
            else:
                if (curr_node.parent.isfirst == False
                    ):  #if we are back at the top get out of the loop
                    curr_node = curr_node.parent
                else:
                    curr_node = curr_node.parent
                    break
        else:  #if depth hasnt reached

            if (len(curr_children) > 0):  #get first child if exists
                curr_node = curr_children.pop(0)
                curr_node.visited = True
            else:  #if not go right
                if (curr_node.right != []):
                    curr_node = curr_node.right
                    curr_node.visited = True
                else:
                    if (curr_node.isfirst == True):
                        break
                    if (curr_node.parent.isfirst == False):
                        curr_node = curr_node.parent
                    else:
                        curr_node = curr_node.parent
                        break

        m += 1

    return (get_best_move(curr_node, player, first_player, moves_ahead))
Esempio n. 40
0
                    return True
        current_stack.pop()
        unvisited.append(a_node)
        return False


#Read in names

participants = open('olive.txt')
participants = [names.strip('\n').split(' ') for names in participants]
graph = []
for names in participants:  #Creates nodes with name and family members
    for name in names:
        family = names[:]
        family.remove(name)
        graph.append(node(name, family))

#Create unvisited list

unvisited = graph

#Traverse and see path:

bag = []
traversal(unvisited[random.randint(0,
                                   len(unvisited) - 1)],
          bag)  #Selects random participant to start with to organize
bag.append(bag[0])  #Appends first person to the end as well
bag = [x.name for x in bag]
for x in range(len(bag) - 1):
    print bag[x] + ' -> ' + bag[x + 1]