Ejemplo n.º 1
0
def mazeMaker(dim, p):
    finalPath = []

    arr = [['0' for i in range(dim)] for j in range(dim)] 
    arr[0][0] = "s"
    arr[dim-1][dim-1] = "g"

    count = 0
    for row in arr:
        for i, ele in enumerate(row):
            if ele != "s" and ele != "g" and int(ele) == 0:
                if random.randrange(0, 100, 1)/100 < p:
                    row[i] = "x"
                    count += 1

    sol = Solution(arr, (0, 0), "strat1", fireStartLoc)
    algoResult = sol.dfs()
    backtrack_info = algoResult[0]
    if backtrack_info != {}:
        finalPath = sol.create_solution(backtrack_info, (0, 0))
    if finalPath == []:
        arr = mazeMaker(dim, p)

    writeGame(arr, GAMEFILE)
    writeGame(arr, CLEANFILE)
    writeGame(arr, FIREFILE)
    return arr
Ejemplo n.º 2
0
 def optimizedTabou(self,start,size):
     tabou = []
     ltabou = []
     s = self.glouton1(start)
     i = 0
     while i != 100:
         i = i + 1
         neighbors,fct = self.generateNeighborsTabou(s.getChemin(),ltabou)
         index = fct.index(min(fct))            
         newSol = neighbors[index]
         tabou.append(Solution(newSol,fct[index]))
         ltabou.append(newSol)
         if len(ltabou) == size:
             lst = [tabou[j].getFct() for j in range(len(tabou))]
             index = lst.index(min(lst))
             x = tabou[index]
             y = tabou[index].getChemin()
             tabou = []
             ltabou = []
             tabou.append(x)
             ltabou.append(y)
             
         s = Solution(newSol,fct[index])
     lst = [tabou[j].getFct() for j in range(len(tabou))]
     index = lst.index(min(lst))
     return tabou[index]
Ejemplo n.º 3
0
def main():
    root = TreeNode(1)
    root.left = TreeNode(2)
    root.left.left = TreeNode(3)
    root.left.right = TreeNode(4)
    root.right = TreeNode(5)
    root.right.right = TreeNode(6)

    solution = Solution()
    solution.flatten(root)
    printFlattenTree(root)

    print '----'

    root2 = TreeNode(1)
    solution.flatten(root2)
    printFlattenTree(root2)

    print '----'

    root3 = TreeNode(1)
    root3.right = TreeNode(2)
    root3.right.left = TreeNode(3)
    root3.right.right = TreeNode(4)
    root3.right.right.right = TreeNode(5)
    solution.flatten(root3)
    printFlattenTree(root3)

    print '----'

    solution.flatten(None)
    printFlattenTree(None)
Ejemplo n.º 4
0
    def runIteration(self):
        if self.current_temperature > 1.0:

            # Create a new solution depending on the current solution,
            # i.e. a neighbour
            neighbour = Solution(
                self.objective_function,
                1,  # Minimisation
                self.getRandomNeighbour(self.current_solution))

            # Get its energy (cost function)
            self.getEnergy(neighbour)

            # Accept the neighbour or not depending on the acceptance probability
            if self.acceptanceProbability(
                    neighbour.getObjective()) > self.system_random.uniform(
                        0, 1):
                self.current_solution = copy.deepcopy(neighbour)

            # The neighbour is better thant the current element
            if self.best_solution.getObjective(
            ) > self.current_solution.getObjective():
                self.best_solution = copy.deepcopy(self.current_solution)

            # Log the current states
            self.logCurrentState()

            # Cool the system
            self.current_temperature = self.cooling_schedule()
Ejemplo n.º 5
0
 def greedy(self,r):
     for i in range(len(C)):
         l = Solution([Population.CO[i]])
         l.seed_greedy(0,r)
         self.pop.append(l)
     self.pop.sort(key = lambda l : l.dis)        
     self.rm_dup()    
Ejemplo n.º 6
0
 def HookeJeevesMove(self):
 	
     currentPoint = self.history[self.iIter]
 	bestPoints = list()
     for i in range(len(currentPoint.DV)):
         newDV = list()
         for j in range(len(currentPoint.DV)):
             if i == j:
                 newDV.append(currentPoint.DV[j] + self.stepSize[j])
             else:
                 newDV.append(currentPoint.DV[j])
         newPoint = Solution(Solution.getName(),newDV)
         if (not self.isTabu(newPoint)) and (not newPoint.isValid):
             self.addIfNotDominated(newPoint,bestPoints)
             self.removeDominatedPoints(bestPoints)
         newDV = list()
         for j in range(len(currentPoint.DV)):
             if i == j:
                 newDV.append(currentPoint.DV[j] - self.stepSize[j])
             else:
                 newDV.append(currentPoint.DV[j])
         newPoint = Solution(Solution.getName(),newDV)
         if (not self.isTabu(newPoint)) and (not newPoint.isValid):
             self.addIfNotDominated(newPoint,bestPoints)
             self.removeDominatedPoints(bestPoints)
 	self.iIter += 1
 	self.iLocal += 1
 	nextPoint = self.selectRandom(bestPoints)
 	self.history.append(nextPoint)
 	bestPoints.remove(nextPoint)
 	for remainingPoints in bestPoints:
 		self.addIfNotDominated(remainingPoint,self.IM)
 	self.removeDominatedPoints(self.IM)
 	self.nextMoveHookeJeeves = False
Ejemplo n.º 7
0
    def test_clear(self):
        poissonForm = PoissonFormulation.PoissonFormulation(2, True)
        poissonBF = poissonForm.bf()
        mesh = MeshFactory.MeshFactory_rectilinearMesh(poissonBF, [1.0, 1.0],
                                                       [2, 3], 4)
        s = Solution.Solution_solution(mesh)

        x = Function.Function_xn(1)
        one = Function.Function_constant(1)
        zero = Function.Function_constant(0)
        phi = poissonForm.phi(
        )  # VarPtr for main, scalar-valued variable in Poisson problem
        psi = poissonForm.psi()  # VarPtr for gradient of psi, vector-valued

        s = Solution.Solution_solution(mesh)
        s.projectOntoMesh({
            phi.ID(): x,
            psi.ID(): Function.Function_vectorize(one, zero)
        })
        s.addSolution(s, 1.0, [phi.ID()])
        self.assertNotEqual(
            0.0, s.L2NormOfSolution(0))  # not zero since addSolution
        s.clear()
        self.assertIsNotNone(
            s)  #make sure some object still exists since should be in tact
        self.assertEqual(
            0, s.L2NormOfSolution(0))  # zero since zero solutions now
Ejemplo n.º 8
0
 def test_case1(self):
     testclass = Solution.Solution()
     spec = Solution.TreeNode(5)
     spec.left = Solution.TreeNode(2)
     spec.right = Solution.TreeNode(-3)
     #testclass.findFrequentTreeSum(spec)
     self.assertEqual(testclass.findFrequentTreeSum(spec), [2, -3, 4])
Ejemplo n.º 9
0
 def tabou(self, a):
     tabou = []
     ltabou = []
     s = self.glouton1()
     i = 0
     while i != 100:
         i = i + 1
         neighbors, fct = self.generateNeighborsTabou(
             s.getInstance(), ltabou)
         if (len(fct) == 0):
             break
         index = fct.index(max(fct))
         newSol = neighbors[index]
         tabou.append(Solution(newSol, fct[index]))
         ltabou.append(newSol)
         if len(ltabou) == a:
             lst = [tabou[j].getValeur() for j in range(a)]
             index = lst.index(max(lst))
             x = tabou[index]
             tabou = []
             ltabou = []
             tabou.append(x)
             ltabou.append(x.getInstance())
         s = Solution(newSol, fct[index])
     lst = [tabou[j].getValeur() for j in range(len(tabou))]
     index = lst.index(max(lst))
     return tabou[index]
Ejemplo n.º 10
0
def main():
    root = TreeNode(1)
    root.left = TreeNode(2)
    root.right = TreeNode(2)
    root.left.right = TreeNode(3)
    root.right.right = TreeNode(3)
    s = Solution()
    print s.isSymmetric(root)
Ejemplo n.º 11
0
def main():
    solution = Solution()

    height = [1, 1]
    print(solution.maxArea(height))

    height = [1, 2]
    print(solution.maxArea(height))
Ejemplo n.º 12
0
def main():
    root = TreeNode(1)
    root.left = TreeNode(2)
    root.right = TreeNode(2)
    root.left.right = TreeNode(3)
    root.right.right = TreeNode(3)
    s = Solution()
    print s.isSymmetric(root)
Ejemplo n.º 13
0
        def buildSolution(self, branchInfo):
            # 验证 编译 锁
            lock_file = self.__checkLock()
            if lock_file == '':
                logger.error('另一个打包脚本正在运行...')
                return {'success': False, 'error': '另一个打包脚本正在运行...'}

            logger.info(branchInfo.programName + '/' + branchInfo.branchTag + '编译开始')
            logger.info("Name: %s" % branchInfo.programName)
            logger.info("Tag: %s" % branchInfo.branchTag)

            working_dir = getLocalDir(branchInfo.programName) + '/' + branchInfo.branchTag
            if branchInfo.programName == 'updater':
                try:
                    sol = Solution.Solution(working_dir, 'Updater.sln', False, 'Release')
                    sol.buildSolution(True, ['tlupdater'])
                    os.remove(lock_file)
                    if sol.status() == 3: # error
                        return {'success': False, 'error': 'build error %s/%s' % (branchInfo.programName, branchInfo.branchTag)}
                    elif sol.status() == 2: # finished
                        return {'success': True, 'error': 'build successfully %s/%s' % (branchInfo.programName, branchInfo.branchTag)}
                except Exception as e:
                    os.remove(lock_file)
                    return {'success':False, 'error': e.message}

            elif branchInfo.programName == 'daemon':
                try:
                    sol = Solution.Solution(working_dir, 'daemon.sln', False, "Deploy_Release")
                    sol.buildSolution(True, ['daemon'])
                    os.remove(lock_file)
                    if sol.status() == 3: # error
                        return {'success': False, 'error': 'build error %s/%s' % (branchInfo.programName, branchInfo.branchTag)}
                except Exception as e:
                    os.remove(lock_file)
                    return {'success':False, 'error': e.message}
            elif branchInfo.programName == 'quoter':
                try:
                    sol = Solution.Solution(working_dir, 'quoter.sln', False, "Deploy_Release")
                    sol.buildSolution(True, ['XtQuoter'])
                    os.remove(lock_file)
                    if sol.status() == 3: # error
                        return {'success': False, 'error': 'build error %s/%s' % (branchInfo.programName, branchInfo.branchTag)}
                except Exception as e:
                    os.remove(lock_file)
                    return {'success':False, 'error': e.message}
            elif branchInfo.programName == 'XtTradeClient':
                try:
                    sol = Solution.Solution(working_dir, 'XtTradeClient.full.sln', False, "Deploy_Release")
                    sol.buildSolution(True, ['XtTradeClient'])
                    os.remove(lock_file)
                    if sol.status() == 3: # error
                        return {'success': False, 'error': 'build error %s/%s' % (branchInfo.programName, branchInfo.branchTag)}
                except Exception as e:
                    os.remove(lock_file)
                    return {'success':False, 'error': e.message}
            logger.info(branchInfo.programName + '/' + branchInfo.branchTag + '编译完成')
            return {'success': True, 'error': 'build successfully %s/%s' % (branchInfo.programName, branchInfo.branchTag)}
Ejemplo n.º 14
0
def main():
    solution = Solution()

    root5 = TreeNode(1)
    root5.left = TreeNode(2)
    root5.right = TreeNode(3)
    root5.left.left = TreeNode(4)
    root5.left.right = TreeNode(5)
    print 'The count is :', solution.countNodes(root5)

    root6 = TreeNode(1)
    root6.left = TreeNode(2)
    root6.right = TreeNode(3)
    root6.left.left = TreeNode(4)
    root6.left.right = TreeNode(5)
    root6.right.left = TreeNode(6)
    print 'The count is :', solution.countNodes(root6)

    root7 = TreeNode(1)
    root7.left = TreeNode(2)
    root7.right = TreeNode(3)
    root7.left.left = TreeNode(4)
    root7.left.right = TreeNode(5)
    root7.right.left = TreeNode(6)
    root7.right.right = TreeNode(7)
    print 'The count is :', solution.countNodes(root7)

    root8 = TreeNode(1)
    root8.left = TreeNode(2)
    root8.right = TreeNode(3)
    root8.left.left = TreeNode(4)
    root8.left.right = TreeNode(5)
    root8.right.left = TreeNode(6)
    root8.right.right = TreeNode(7)
    root8.left.left.left = TreeNode(8)
    root8.left.left.right = TreeNode(9)
    root8.left.right.left = TreeNode(10)
    root8.left.right.right = TreeNode(11)
    print 'The count is :', solution.countNodes(root8)

    root = TreeNode(1)
    print 'The count is :', solution.countNodes(root)

    root2 = TreeNode(1)
    root2.left = TreeNode(2)
    print 'The count is :', solution.countNodes(root2)

    root3 = TreeNode(1)
    root3.left = TreeNode(2)
    root3.right = TreeNode(3)
    print 'The count is :', solution.countNodes(root3)

    root4 = TreeNode(1)
    root4.left = TreeNode(2)
    root4.right = TreeNode(3)
    root4.left.left = TreeNode(4)
    print 'The count is :', solution.countNodes(root4)
Ejemplo n.º 15
0
 def psuedogreedy(self, r):
     for i in range(len(C)):
         l = Solution([Population.CO[i]])
         l.seed_psuedogreedy(0, r)
         self.pop.append(l)
     self.pop.sort(key = lambda l : l.dis)        
     self.rm_dup() 
     for j in range(len(self.pop)):
         print self.pop[j]
Ejemplo n.º 16
0
 def read(self, data_type):
     directory = os.getcwd() + r'/csv/'
     filename = r'priority_queue.csv'
     access_type = 'r'
     serial_list = read(directory, filename, access_type)
     for element in serial_list:
         if data_type is Solution:
             new_solution = Solution()
             new_solution.process_csv(element[0])
             self.insert(new_solution, eval(element[1]))
    def process_csv(self, module):
        # print(module)
        self.anomaly_type = module[0]
        self.train_size = module[1]

        self.solution_tuple_list = []

        for solution_tuple in eval(module[2]):
            slt = Solution()
            slt.process_csv(solution_tuple[0])
            self.solution_tuple_list.append(
                (slt, solution_tuple[1], solution_tuple[2]))
Ejemplo n.º 18
0
        def cleanSolution(self, branchInfo):
            # 验证 编译 锁
            lock_file = self.__checkLock()
            if lock_file == '':
                logger.error('另一个打包脚本正在运行...')
                return {'success': False, 'error': '另一个打包脚本正在运行...'}

            sln_file = ''
            root_path = getLocalDir(branchInfo.programName) + '/' + branchInfo.branchTag
            if branchInfo.programName == 'updater':
                sln_file = 'Updater.sln'
            elif branchInfo.programName == 'daemon':
                sln_file = 'daemon.sln'
            elif branchInfo.programName == 'quoter':
                sln_file = 'quoter.sln'
            elif branchInfo.programName == 'XtTradeClient':
                sln_file = 'XtTradeClient.full.sln'
            if sln_file == '':
                if branchInfo.programName != '':
                    logger.error('program \"', branchInfo.programName, '\" does not exists')
                    os.remove(lock_file)
                    return {'success': False, 'error': 'program \"' + branchInfo.programName + '\" does not exists'}
                else:
                    os.remove(lock_file)
                    return {'success': False, 'error': 'program name is not set'}
            logger.info('%s/%s clean start' % (branchInfo.programName, branchInfo.branchTag))
            try:
                if branchInfo.programName == 'updater':
                    try:
                        sol = Solution.Solution(root_path, sln_file, True, "Release")
                        os.remove(lock_file)
                        if sol.status() == 3: # error
                            return {'success': False, 'error': 'clean error %s/%s' % (branchInfo.programName, branchInfo.branchTag)}
                    except Exception as e:
                        os.remove(lock_file)
                        return {'success': False, 'error': e.message}

                else:
                    try:
                        sol  = Solution.Solution(root_path, sln_file, True, self.build_configuration)
                        os.remove(lock_file)
                        if sol.status() == 3: # error
                            return {'success': False, 'error': 'clean error %s' % (branchInfo.programName, branchInfo.branchTag)}
                    except Exception as e:
                        os.remove(lock_file)
                        return {'success': False, 'error': e.message}
                logger.info('%s/%s clean end' % (branchInfo.programName, branchInfo.branchTag))
                return {'success': True, 'error': 'Clean %s succeeds' % sln_file}
            except Exception as e:
                os.remove(lock_file)
                logger.error('%s/%s: %s' %(branchInfo.programName, branchInfo.branchTag, e.message))
                return {'success': False, 'error': 'clean %s fails' % sln_file}
Ejemplo n.º 19
0
def main():
    solution = Solution()
    testCases = [
        [],
        [1, 2],
        [1, 2, 3],
        [1, 2, 3, 4],
        [1, 2, 3, 4, 5],
        [1, 2, 3, 4, 5, 6],
    ]
    for t in testCases:
        p = solution.swapPairs(makeList(t))
        printList(p)
Ejemplo n.º 20
0
 def Vk(self,s,k):
     if k == 0:
         x0 = self.two_opt(s.getChemin())
         # print("2-opt")
         return Solution(x0,self.fonctionObjectif(x0))
     if k == 1:
         x1 = self.three_opt(s.getChemin())
         # print("3-opt")
         return Solution(x1,self.fonctionObjectif(x1))
     if k == 2:
         x2 = self.four_opt(s.getChemin())
         # print("4-opt")
         return Solution(x2,self.fonctionObjectif(x2))
Ejemplo n.º 21
0
def main():

    if (len(sys.argv) < 2):
        print("Please provide the input filepath as the argument")
        sys.exit()

    input_file = sys.argv[1]

    input = readFromFile(input_file)

    #Get answer
    solution = Solution(input)
    print(solution.findClosestPair())
Ejemplo n.º 22
0
def main():
    solution = Solution()

    print(listProduct([""], ["a", "b", "c"]))

    digits = "111111"
    print(solution.letterCombinations(digits))


    digits = "111112"
    print(solution.letterCombinations(digits))

    digits = "234"
    print(solution.letterCombinations(digits))
Ejemplo n.º 23
0
 def mutation(self,ind,fct,typeOfMutation):
     n = len(ind)
     if typeOfMutation == "descente":
         return self.descenteVPop(Solution(ind,fct))
     
     if typeOfMutation == "inversion":
         l = self.two_opt(ind)
         return Solution(l,self.fonctionObjectif(l))
     if typeOfMutation == "permutation":
         i = random.randint(0, n-2)
         j = random.randint(i+1, n-1)
         lst = ind.copy()
         lst[i],lst[j] = lst[j],lst[i]
         return Solution(lst,self.fonctionObjectif(lst)) 
Ejemplo n.º 24
0
 def tabou(self,start):
     tabou = [] #Solution
     ltabou = [] #chemin
     s = self.glouton1(start)
     i = 0
     while i != 100:
         i = i + 1
         neighbors,fct = self.generateNeighborsTabou(s.getChemin(),ltabou)
         index = fct.index(min(fct))            
         newSol = neighbors[index]
         tabou.append(Solution(newSol,fct[index]))
         ltabou.append(newSol)
         s = Solution(newSol,fct[index])
     lst = [tabou[j].getFct() for j in range(len(tabou))]
     index = lst.index(min(lst))
     return tabou[index]
Ejemplo n.º 25
0
def main():
    with open('testcase.txt', "r") as f:
        lines = f.readlines()
    i = 0
    passall = True
    while i < len(lines) :
        line = lines[i]
        nums = stringToIntegerList(line)
        if (nums == "null") :
            nums = None
        #print nums
        line = lines[i+1]
        #print line
        expected = int(line.replace("\n",""))
        
        ret = Solution.Solution().singleNumber(nums)
        #print expected
        #print ret
        if (expected != ret) :
            if (nums is None) :
                strnums = 'null'
            else:
                strnums = integerListToString(nums)
            print "[Fail]" + strnums + ";" + str(ret) + ";" + str(expected)
            passall = False
            break

        i = i + 2
        #print out

    if passall == True :
        print "[Success]Your solution passed all " + str(len(lines)/2) + " test cases!"
Ejemplo n.º 26
0
 def recuit(self,start):
     T0 = 10
     Tmin = 1e-2
     kmax = 1e4
     
     T = T0
     k = 0
     s = self.glouton1(start).getChemin()
     
     # calcul de l'énergie initiale du système (la distance initiale à minimiser)
     Ec = self.fonctionObjectif(s)
     N =  len(s)
     while T > Tmin:
             # choix de deux villes différentes au hasard
             i = random.randint(1,N-1)
             j = random.randint(1,N -1)
             if i == j: continue
             
             # création de la fluctuation et mesure de l'énergie
             s = self.fluctuation(s,i,j) 
             Ef = self.fonctionObjectif(s)   
             Ec, s = self.metropolis(s,T,Ef,Ec,i,j)
             
 
             # application de la loi de refroidissement    
             k += 1
             T = T0*np.exp(-k/kmax)
     
     return Solution(s,self.fonctionObjectif(s))
Ejemplo n.º 27
0
 def Vk(self, s, k):
     if k == 0:
         x0 = self.hamming1(s.getInstance())
         while self.poids(x0) > self.capacite:
             x0 = self.hamming1(s.getInstance())
         return Solution(x0, self.fctObj(x0))
     if k == 1:
         x1 = self.hamming2(s.getInstance())
         while self.poids(x1) > self.capacite:
             x1 = self.hamming1(s.getInstance())
         return Solution(x1, self.fctObj(x1))
     if k == 2:
         x2 = self.hamming3(s.getInstance())
         while self.poids(x2) > self.capacite:
             x2 = self.hamming1(s.getInstance())
         return Solution(x2, self.fctObj(x2))
Ejemplo n.º 28
0
    def mutation(self, ind, fct, typeOfMutation):
        n = len(ind)
        if typeOfMutation == "descente":
            return self.descenteVNS(Solution(ind, fct))

        if typeOfMutation == "permutation":
            i = random.randint(0, n - 2)
            j = random.randint(i + 1, n - 1)
            lst = ind.copy()
            lst[i], lst[j] = lst[j], lst[i]
            while self.poids(lst) > self.capacite:
                i = random.randint(0, n - 2)
                j = random.randint(i + 1, n - 1)
                lst = ind.copy()
                lst[i], lst[j] = lst[j], lst[i]
            return Solution(lst, self.fctObj(lst))
Ejemplo n.º 29
0
    def __init__(self):
        self.design = Solution.Solution()
        self.design.convert_design_to_string()
        self.design.save_current_design_as_input()
        self.design.evaluate_design()

        self.candidate_design = copy.deepcopy(self.design)
Ejemplo n.º 30
0
 def geneticAlgorithm(self,mutationType):
     p0 = self.generatePopulation()
     p = p0
     t = 0
     while t != 50:
         
         crossOverList = self.selectAnyType(p[0], p[1], "crossOver")
         b = len(crossOverList[0])
         childs = []
         for i in range(0,len(crossOverList[0])-1,2):
             childs.append(self.crossOver(crossOverList[0][i], crossOverList[0][i+1])[0])
             childs.append(self.crossOver(crossOverList[0][i], crossOverList[0][i+1])[1])
         mutationList = self.selectAnyType(p[0], p[1], "mutation")
         a = len(mutationList[0])
         # print("before adding mut " + str(p[0]))
         for i in range(a):
             mutated = self.mutation(mutationList[0][i], mutationList[1][i], mutationType)
             p[0].append(mutated.getChemin())
             p[1].append(mutated.getFct())
         for i in range(b):
             p[0].append(childs[i])
             p[1].append(self.fonctionObjectif(childs[i]))          
         p = self.selectAnyType(p[0], p[1])
         t += 1 
     index = p[1].index(min(p[1]))
     return Solution(p[0][index], p[1][index])
     
     
     
     
     
Ejemplo n.º 31
0
def rk4(theta0, omega0, step=0.1, stop=10, start=0, name="runge_kutta"):
    def omega_prime(theta):
        """
        :return: derivative of omega with respect to time at some point theta
        """
        return -(g / l) * theta

    def theta_prime(omega):
        """
        :return: derivative of theta with respect to time at some point omega
        """
        return omega
    t = np.arange(start, stop, step)
    n = int((stop - start)/step)
    omega = np.zeros(n)
    theta = np.zeros(n)
    omega[0], theta[0] = omega0, theta0
    for i in range(n-1):
        # calculate next omega
        o1 = omega_prime(theta[i])
        o2 = omega_prime(theta[i] + o1 * step / 2)
        o3 = omega_prime(theta[i] + o2 * step / 2)
        o4 = omega_prime(theta[i] + o3 * step)
        omega[i + 1] = omega[i] + (step/6)*(o1 + 2*o2 + 2*o3 + o4)

        # calculate next theta
        t1 = theta_prime(omega[i])
        t2 = theta_prime(omega[i] + t1 * step / 2)
        t3 = theta_prime(omega[i] + t2 * step / 2)
        t4 = theta_prime(omega[i] + t3 * step)
        theta[i + 1] = theta[i] + (step/6)*(t1 + 2 * t2 + 2 * t3 + t4)

    # calculate energy
    e = 0.5*m*l*l*(omega**2 + (g/l)*theta**2)
    return Solution(t, theta, omega, e, name=name)
Ejemplo n.º 32
0
	def setSolution(self, end, iterations, branchingSum, expandedNodes, visited, time_elapsed):
		itr = self.end
		path = []
		c = 0
		
		while True:
			if itr:
				path.append(itr)
				itr = itr.getFather()
			else:
				path.reverse()
				
				if(len(path) == 1 and end == path[0]):
					path.pop()
				cost = 0
				for j in range(0, len(path)-1):
					for i in range(0, len(self.graph[path[j]])):
						if self.graph[path[j]][i][0] == path[j + 1]:
							cost = cost + self.graph[path[j]][i][1]	
				
				if iterations == 0:
					branchFactor = 0
				else:
					branchFactor = branchingSum/iterations
				
				self.solution = Solution(path, cost, expandedNodes, branchFactor, len(visited), time_elapsed, iterations)
				break	
				
		return self.solution		
Ejemplo n.º 33
0
 def test_setUseCondensedSolve(self):
     poissonForm = PoissonFormulation.PoissonFormulation(2, True)
     poissonBF = poissonForm.bf()
     mesh = MeshFactory.MeshFactory_rectilinearMesh(poissonBF, [1.0, 1.0],
                                                    [2, 3], 4)
     s = Solution.Solution_solution(mesh)
     s.setUseCondensedSolve(False)  # if no exception, then successful test
Ejemplo n.º 34
0
 def test_Solution(self):
     poissonForm = PoissonFormulation.PoissonFormulation(2, True)
     poissonBF = poissonForm.bf()
     mesh2 = MeshFactory.MeshFactory_rectilinearMesh(
         poissonBF, [1.0, 1.0], [2, 3], 4)
     s = Solution.Solution_solution(mesh2)
     self.assertIsNotNone(s)  #make sure some object exists
Ejemplo n.º 35
0
def main():
    solution = Solution()

    strs = [-1, 0, 1, 2, -1, -4]
    print(solution.threeSum(strs))

    strs = [3, 0, -2, -1, 1, 2]
    print(solution.threeSum(strs))

    strs = [0, 0, 0, 0]
    print(solution.threeSum(strs))

    strs = [0, 0, 0, 0, 0, 0]
    print(solution.threeSum(strs))
    strs = [7, -10, 7, 3, 14, 3, -2, -15, 7, -1, -7, 6, -5, -1, 3, -13, 6, -15, -10, 14, 8, 5, -10, -1, 1, 1, 11, 6, 8,
            5, -4, 0, 3, 10, -12, -6, -2, -6, -6, -10, 8, -5, 12, 10, 1, -8, 4, -8, -8, 2, -9, -15, 14, -11, -1, -8, 5,
            -13, 14, -2, 0, -13, 14, -12, 12, -13, -3, -13, -12, -2, -15, 4, 8, 4, -1, -6, 11, 11, -7, -12, -2, -8, 10,
            -3, -4, -6, 4, -14, -12, -5, 0, 3, -3, -9, -2, -6, -15, 2, -11, -11, 8, -11, 8, -7, 8, 14, -5, 4, 10, 3, -1,
            -15, 10, -6, -11, 13, -5, 1, -15]
Ejemplo n.º 36
0
def main():
    solution = Solution()

    l = ListNode.generate([1, 2, 3, 4, 5])
    res = solution.removeNthFromEnd(l, 2)
    res.tranverseListNoe()

    print("******")
    l = ListNode.generate([1, 2])
    res = solution.removeNthFromEnd(l, 1)
    res.tranverseListNoe()

    print("******")
    l = ListNode.generate([1, 2])
    res = solution.removeNthFromEnd(l, 2)
    res.tranverseListNoe()

    print("******")
    l = ListNode.generate([1, 2, 3])
    res = solution.removeNthFromEnd(l, 3)
    res.tranverseListNoe()
Ejemplo n.º 37
0
 def PatternMove(self):
     
 	currentPoint = self.history[self.iIter]
 	lastPoint = self.history[self.iIter-1]
     # find out last move
     lastMove = list()
     for i in range(len(currentPoint.DV)):
         lastMove.append(currentPoint.DV[i] - lastPoint.DV[i])
     # recreate last move to current design vector
     nextDV = list()
     for i in range(len(currentPoint.DV)):
         nextDV.append(currentPoint.DV[i] + lastMove[i])
     
 	newPoint = Solution(Solution.getName(),nextDV)
 	newPoint.evaluate()
     
 	if newPoint.dominate(currentPoint):
 		self.iIter += 1
 		self.iLocal += 1
 		self.history.append(newPoint)
 		return True
 	return False
Ejemplo n.º 38
0
 def createChild(self,parent):
     """ create a candidate child """
     
     i = self.P.index(parent)
     a = i
     b = i
     c = i
     while i == a or i == b or i == c or a == b or a == c or b == c:
         a = random.randint(0,len(self.P)-1)
         b = random.randint(0,len(self.P)-1)
         c = random.randint(0,len(self.P)-1)
     mateDV = self.mate(self.P[a],self.P[b],self.P[c])
     if self.debug:
         for DV in mateDV:
             print str(DV)
     childDV = self.crossover(self.P[i],DV)
     return Solution(Solution.getName(),childDV)        
Ejemplo n.º 39
0
def main():
    solution = Solution()

    strs = ["123456", "124546"]
    print(solution.longestCommonPrefix(strs))
Ejemplo n.º 40
0
def main():
    solution = Solution()

    strs = [-1, 2, 1, -4]
    target = 1
    print(solution.threeSumClosest(strs, target))
Ejemplo n.º 41
0
def main(maxiter,featureset):
    import sys
    print 'Number of arguments:', len(sys.argv), 'arguments.'
    print 'Argument List:', str(sys.argv)
    maxiter = int(sys.argv[-2])
    featureset = int(sys.argv[-1])
    sys.path
    sys.path.append(".") 
    import Solution as sl
    import numpy as np
    learner = sl.perceptron(maxiter,featureset)
    labels = []
    labels.append(learner['otrain'][:,0])
    labels.append(learner['ptrain'])
    match = sum(learner['otrain'][:,0] == learner['ptrain'])
    #print '*******************'
    #print 'Training accuracy is: {0:.3f}%'.format(match*1.0/len(learner['otrain'])*100.0)
    #print '*******************'

    #########################################
    ##### now run validation
    vdata = np.array(readfile("./validation.txt"))
    nvdata = vdata.shape[0]
    # get rid of ? missing data
    contatr = np.array([1,2,7,10,13,14])
    attrlist = np.array(range(len(vdata[0])))
    for i in contatr:
        dum = vdata[vdata[:,i]!=np.array('?'),i]
        vdata[vdata[:,i]==np.array('?'),i] = np.mean(dum.astype(np.float))
    disatr = list(set(attrlist)-set(contatr))
    for i in disatr:
        dum = max(set(list(vdata[:,i])), key=list(vdata[:,i]).count)
        vdata[vdata[:,i]==np.array('?'),i] = np.array(dum)
    print "is there missing data: ", sum(sum(vdata[:,:15]==np.array('?')))
    ori_v_label = vdata[:,-1];
    ori_v_label_bool = np.zeros((vdata.shape[0],1))-1
    ori_v_label_bool[ori_v_label==np.array('+')] = 1
    newdatafeatset = sl.getfeature(learner['thres'],vdata[:,:15],featureset,disatr,contatr) # no label col
    predv = np.sign(np.sum(np.tile(learner['alphaa']*learner['y'],(1,nvdata))*np.dot(learner['X'],newdatafeatset.T),axis=0))
    match = sum(predv == ori_v_label_bool[:,0])
    labels.append(ori_v_label_bool[:,0])
    labels.append(predv)
    #print '*******************'
    #print 'validation accuracy is: {0:.3f}%'.format(match*1.0/nvdata*100.0)
    #print '*******************'


    ##########################################
    ##### now run test
    tdata = np.array(readfile("./test.txt"))
    ntdata = tdata.shape[0]
    # get rid of ? missing data
    contatr = np.array([1,2,7,10,13,14])
    attrlist = np.array(range(len(tdata[0])))
    for i in contatr:
        dum = tdata[tdata[:,i]!=np.array('?'),i]
        tdata[tdata[:,i]==np.array('?'),i] = np.mean(dum.astype(np.float))
    disatr = list(set(attrlist)-set(contatr))
    for i in disatr:
        dum = max(set(list(tdata[:,i])), key=list(tdata[:,i]).count)
        tdata[tdata[:,i]==np.array('?'),i] = np.array(dum)
    print "is there missing data: ", sum(sum(tdata[:,:15]==np.array('?')))
    ori_t_label = tdata[:,-1];
    ori_t_label_bool = np.zeros((tdata.shape[0],1))-1
    ori_t_label_bool[ori_v_label==np.array('+')] = 1
    newdatafeatset = sl.getfeature(learner['thres'],tdata[:,:15],featureset,disatr,contatr) # no label col
    predt = np.sign(np.sum(np.tile(learner['alphaa']*learner['y'],(1,ntdata))*np.dot(learner['X'],newdatafeatset.T),axis=0))
    match = sum(predt == ori_t_label_bool[:,0])
    #print '*******************'
    #print 'test accuracy is: {0:.3f}%'.format(match*1.0/ntdata*100.0)
    #print '*******************'
    labels.append(ori_t_label_bool[:,0])
    labels.append(predt)

    if labels == None or len(labels) != 6:
	print '\nError: Perceptron Return Value.\n' 
    else:
	eval(labels[0],labels[1],labels[2],labels[3],labels[4],labels[5])
Ejemplo n.º 42
0
from Solution import *

sol = Solution()
print sol.canWinNim(4)
Ejemplo n.º 43
0
import sys
sys.path
sys.path.append("/home/he72/STAT590/hw2") 
import Solution as sl
import numpy as np
learner = sl.perceptron(10,1)
labels = []
labels.append(learner['otrain'])
labels.append(learner['ptrain'])

sys.argv=['5','2']
execfile('./Check.py')

import os
import sys
sys.path.append("/home/he72/STAT590/hw2")
import numpy as np
import Check as Ck
data = np.array(Ck.readfile("/home/he72/STAT590/hw2/train.txt"))

# get rid of ? missing data
contatr = np.array([1,2,7,10,13,14]) 
attrlist = np.array(range(len(data[0])))
for i in contatr:
    dum = data[data[:,i]!=np.array('?'),i]
    data[data[:,i]==np.array('?'),i] = np.mean(dum.astype(np.float))
    disatr = list(set(attrlist)-set(contatr))
for i in disatr:
        dum = max(set(list(data[:,i])), key=list(data[:,i]).count)
        data[data[:,i]==np.array('?'),i] = np.array(dum)
print "is there missing data: ", sum(sum(data[:,:15]==np.array('?')))
Ejemplo n.º 44
0
def main():
    solution = Solution()

    s = "([{}]))"
    print(solution.isValid(s))
Ejemplo n.º 45
0
def main():
    solution = Solution()

    strs = [1, 0, -1, 0, -2, 2]
    target = 0
    print(solution.fourSum(strs, target))
	def test_answers_1(self):
		self.assertEqual(Solution.answer(2,3,14), "Ambiguous")
		self.assertEqual(Solution.answer(19,19,3), "03/19/19") #needed to return the string, not just print it
Ejemplo n.º 47
0
def Create_Solution(App, Row, Col, Unrolling_Vec, Blocking_Vec, IO_Buffers, DFG_Lat):

    Possible_Solution = Solution()
    Possible_Solution.Loop_Vec = Get_Loop_Vec(App) 
    Possible_Solution.SCGRA_Row = Row
    Possible_Solution.SCGRA_Col = Col
    Possible_Solution.SCGRA_Size = Row * Col
    Possible_Solution.Loop_Unrolling_Vec = copy.copy(Unrolling_Vec)
    Possible_Solution.DFG_Lat = DFG_Lat
    Possible_Solution.In_Buffer = IO_Buffers[0]
    Possible_Solution.Out_Buffer = IO_Buffers[1]
    Possible_Solution.In_Addr_Buffer = IO_Buffers[2]
    Possible_Solution.Out_Addr_Buffer = IO_Buffers[3]
    Possible_Solution.Inst_Mem = Get_Min_Inst_Mem(DFG_Lat)
    Possible_Solution.Loop_Blocking_Vec = copy.copy(Blocking_Vec)

    Possible_Solution.Update_HW_Cost()
    DFG_Num = Get_SB_Num(Unrolling_Vec, Blocking_Vec)
    Block_Num = Get_SB_Num(Blocking_Vec, Get_Loop_Vec(App))
    Loop_Transfer_Vec = Get_Loop_Transfer_Vec(App, Unrolling_Vec, Blocking_Vec)
    Possible_Solution.Update_Lat(DFG_Num, Block_Num, Loop_Transfer_Vec)
    Possible_Solution.Update_Power()
    Possible_Solution.Update_EDP()
    Solution_Str = Possible_Solution.Get_Syllabus()
    return Possible_Solution