Пример #1
0
    def __init__(self, color_sch="default"):
        set_color_scheme(color_sch)
        self.color_scheme = color_sch

        self.ani = None

        self.bob_mass = init_bob_mass
        self.rod_length = init_rod_length
        self.dt = init_dt
        self.Om_d = init_Om_d
        self.F_d = init_F_d
        self.show_analytical = False
        self.dampening_index = init_dampening_index
        self.speed_index = init_speed_index
        self.initialized = False

        self.s = AxisSetup(self)
        self.s.plot_setup()

        self.aa_calc = AnimatedActors(self)
        self.aa_anal = AnimatedActors(self, "darkgreen")
        self.acts = (self.aa_calc, self.aa_anal)
        self.artists = None

        self.sol_runge_kutta = Solver(method="runge_kutta")
        self.sol_analytical = Solver(method="analytical")
        self.sol_dummy = Solver(method="dummy")

        self.solution = None
        self.solution_analytical = None
        self.angle_diffs = None
        self.energy_diffs = None

        self.plot_indexes = [0, 0]
Пример #2
0
    def test_hiddenSubset(self):
        problemFile = "Puzzles/Testing/test7.txt"
        g = Main.Grid()
        g.setup(problemFile)
        s = Solver.Solver()
        # Before
        self.assertEqual([1, 6, 9], g.getCell((4, 8)).possibleValues)
        s.hiddenSubsetHelper(g.getColumn((0, 8)), 2)
        # After
        self.assertEqual([1, 9], g.getCell((4, 8)).possibleValues)

        problemFile = "Puzzles/Testing/test8.txt"
        g = Main.Grid()
        g.setup(problemFile)
        s = Solver.Solver()
        # Before
        self.assertEqual([1, 2, 4, 5], g.getCell((8, 1)).possibleValues)
        self.assertEqual([2, 5, 6], g.getCell((8, 2)).possibleValues)
        s.hiddenSubset(g)
        # After
        self.assertEqual([2, 4, 5], g.getCell((8, 1)).possibleValues)
        self.assertEqual([2, 5], g.getCell((8, 2)).possibleValues)

        problemFile = "Puzzles/Testing/test9.txt"
        g = Main.Grid()
        g.setup(problemFile)
        s = Solver.Solver()
        # Before
        self.assertEqual([3, 4, 5, 6, 8], g.getCell((6, 4)).possibleValues)
        self.assertEqual([2, 4, 5, 6], g.getCell((7, 4)).possibleValues)
        s.hiddenSubset(g)
        # After
        self.assertEqual([4, 5, 8], g.getCell((6, 4)).possibleValues)
        self.assertEqual([2, 4, 5], g.getCell((7, 4)).possibleValues)
Пример #3
0
def UI():
    ## initialize the board
    print "Welcome to the sudoku solver. I'm going to give you an empty sudoku board in the file board.txt. Replace the dots with the numbers in your board."
    IO.initBoard()
    initMessage = 'Type "done" when you\'ve finished editing the text file. Type "new" to get a fresh board.: '
    invalidMessage = "This board is not a valid sudoku. Either a row, column or box has a duplicate value"
    poorFormatMessage = "You have mucked up the formatting of the board. Please fix it, or type new and start over."

    ##get the board and make sure it's valid and well formatted
    goodInput = False
    board = [[]]
    while goodInput == False:
        response = raw_input(initMessage)
        if response == "new":
            IO.initBoard()

        elif response == "done":
            board = IO.readBoard()
            if not IO.isWellFormatted(board):
                print poorFormatMessage
            elif not IsValid.isValidSudoku(board):
                print invalidMessage

            else:
                goodInput = True
    #solve the sudoku
    solution = Solver.solve(Solver.getState(board))
    if solution == None:
        print "I cannot solve this board!"
    else:
        print "Here is the solution"
        print IO.makeBoard(solution)
        print "I'll put it in the text file too."
        IO.writeSolution(board, solution)
Пример #4
0
def main():
    coffee = Body.ThermalBody(500)
    solver = Solver.Euler(0.5)

    def stop_condition(coffee):
        return coffee.temperature > sim.Ta * 1.1

    sim = Simulation.CoolingSim(stop_condition, solver, 293, 0.05, coffee)
    t, T = sim.get_results()
    plt.plot(t, T)

    coffee = Body.ThermalBody(500)
    solver = Solver.RK2(0.5)

    def stop_condition(coffee):
        return coffee.temperature > sim.Ta * 1.1

    sim = Simulation.CoolingSim(stop_condition, solver, 293, 0.05, coffee)
    t, T = sim.get_results()
    plt.plot(t, T)

    plt.title("OOP Cooling Curves")
    plt.xlabel("Time [s]")
    plt.ylabel("Temperature[K]")
    plt.legend(["Euler Curve", "RK2 Cooling Curve"])
Пример #5
0
def selectMethod(solver):
    print("1 - Backtracking")
    print("2 - Breadth First Search")
    print("3 - Depth First Search (limited)")
    print("4 - Ordered Search")
    print("5 - Greed Search")
    print("6 - A* Search")
    print("7 - IDA* Search")

    o = int(input("> "))
    enterObjective()
    if o == 1:
        solver = Backtracking(start, end)
    if o == 2:
        solver = Solver()  #BreadthFirst(start, end)
    if o == 3:
        solver = DepthFirst(start, end)
    if o == 4:
        solver = OrderedSearch(start, end)
    if o == 5:
        solver = GreedySearch(start, end)
    if o == 6:
        solver = AStar(start, end)
    if o == 7:
        solver = Solver()

    return solver
Пример #6
0
def extract_solve(model_path, file_path, show_extract=False):
    load_model = tf.keras.models.load_model(model_path)
    board = document_scanner.generate_board_df(file_path)
    board_raw = load_model(board.values)
    board_clean = np.argmax(board_raw, axis=1).reshape((9, 9))
    if show_extract:
        print(board_clean)
    Solver.run_solver(board_clean)
Пример #7
0
def solve_sudoku(path, print_unsolved=False):
    model = tf.keras.models.load_model('save_model\digreco_2')

    tiles = generate_board_tiles(path)
    board_raw = model(tiles)
    board_clean = np.argmax(board_raw, axis=1).reshape((9, 9))
    if print_unsolved:
        print(board_clean)
    Solver.run_solver(board_clean)
Пример #8
0
def main():
    domain = "http://localhost:8080"  # domain al que nos vamos a conectar
    pid = int(input("Ingrese el id del jugador: "))
    name = input("Ingrese el nombre del jugador: ")
    taquin.create_player(domain, pid, name)

    option = int(input("1) Single player, 2) Resolver un reto (Multiplayer), 3) Retar a un jugador, -1) salir\n"))
    while option != -1:
        if option == 1:
            size = int(input("Ingrese el tamaño N del tablero: "))
            matrix = taquin.generate_matrix(size)  # generamos una matriz de size * size
            board = Board(matrix, size, size-1, size-1)

            # -------------- PARA PROBAR 2x2 ------------
            #matrix = [[3, 1],
            #         [2, None]]

            #board = Board(matrix, 2, 1, 1)
            # -------------------------------------------

            # -------------- PARA PROBAR 3x3 ------------
            #matrix = [[1, 3, 4],
            #          [2, 5, 6],
            #          [7, 8, None]]

            #board = Board(matrix, 3, 2, 2)
            # -------------------------------------------
            while not board.is_solvable():
                matrix = taquin.generate_matrix(size)  # generamos una matriz de size * size
                board = Board(matrix, size, size - 1, size - 1)

            taquin.generateBoard(domain, matrix, size-1, size-1)   # mandamos la matriz para que se display en la pagina

            if board.is_solvable():
                print("El tablero SI se puede resolver")
                solver = Solver(board)
                movements = solver.solve()
                print("Movimientos: ", movements)
                if len(movements) != 0:
                    send_movements(domain, pid, movements)

            else:
                print("El tablero NO se puede resolver")

        elif option == 2:  # todavia no sirve
            taquin.get_challenge(domain, pid)
        elif option == 3:
            opponent = input("Ingrese el id del oponente: ")
            opponent = int(opponent)
            size = int(input("Ingrese el tamaño N del tablero: "))
            matrix_challenge = taquin.generate_matrix(size)
            taquin.challenge(domain, matrix_challenge, size-1, size-1, opponent)
            print("Reto enviado: ")
            print(matrix_challenge)

        option = int(input("1) Single player, 2) Resolver un reto (Multiplayer), 3) Retar a un jugador, -1) salir\n"))
Пример #9
0
def idle_func():
    global d_sim, win_id, p_vector, dt
    if d_sim:
        Solver.simulation_step(p_vector, dt)
    else:
        # get_from_UI() needs to be implemented
        remap_gui()

    glutSetWindow(win_id)
    glutPostRedisplay()
Пример #10
0
    def __init__(self):
        super().__init__()
        self.setupUi(self)
        self.setWindowFlags(Qt.FramelessWindowHint | Qt.WindowStaysOnTopHint)

        self.Solver = Solver()
        self.generateDB()

        self.setSlot()
        self.show()
Пример #11
0
    def explore_environment(self):
        paths = []
        robot_position = []
        robot_position.append(self.real_environment.robot)
        field_list = self.real_environment.field
        self.robot_knowledge_object.robotField.append(field_list)
        self.robot_knowledge_object.robotgoal.append(
            self.real_environment.goal)
        access_flag = 0
        self.robot_knowledge = self.knowledge_string(
            "field", self.robot_knowledge_object.robotField)
        self.robot_knowledge += self.knowledge_string(
            "goal", self.robot_knowledge_object.robotgoal)
        temp_str = ""
        while access_flag == 0:

            temp_str = self.knowledge_string("robot", robot_position)
            self.robot_knowledge += temp_str
            self.robot_knowledge_object.addKnowledge(self.robot_knowledge)
            solver_object = Solver.Solver()
            solver_object.solver()
            path = solver_object.solution
            if (solver_object.solution.__len__() != 0):
                check = self.check_obstacle(solver_object.solution)

                if check == -1:
                    paths.append((path, robot_position))
                    access_flag = -1
                else:
                    robot_position.clear()
                    robot_position.append([solver_object.solution[check]])
                    paths.append((path[:check + 2], path[check + 1]))
                    self.robot_knowledge = self.robot_knowledge.replace(
                        temp_str, "")

            else:
                paths.append(((-1, -1, -1), (-1, -1, -1)))
                break
        robot_position.clear()
        robot_position.append(self.real_environment.robot)
        real_robot_position = self.knowledge_string("robot", robot_position)
        self.robot_knowledge = self.robot_knowledge.replace(
            temp_str, real_robot_position)
        self.robot_knowledge_object.addKnowledge(self.robot_knowledge)

        if (solver_object.solution.__len__() != 0):
            solver_object = Solver.Solver()
            solver_object.solver()
            path = solver_object.solution
            paths.append((path, (0, 0, 0)))
        else:
            paths.append(((-1, -1, -1), (-1, -1, -1)))
            print("unsatisfied")
        return paths
Пример #12
0
def main():
    m = v.Model()
    m.createNodes()
    m.createDistanceMatrix()
    m.createTimeMatrix()
    m.sortNodes()
    sol = v.Solution()

    print()
    #print("******Solution******")
    b.BestFitTime(sol, m.allNodes, m.time_matrix)
    sol.CalculateMaxTravelTime(m)
    #sol.ReportSolution()

    #print("******TSP Improvement******")
    for i in range(0, len(sol.trucks)):
        if len(sol.trucks[i].nodesOnRoute) < 2:
            continue
        sol.trucks[i] = t.MinimumInsertions(sol.trucks[i], m.time_matrix)
    sol.CalculateMaxTravelTime(m)
    #sol.ReportSolution()

    #print("******Improved Fleet Utilization******")
    im.improveFleetUtilization(sol, m)
    sol.CalculateMaxTravelTime(m)
    #sol.ReportSolution()

    bestSol = cloneSolution(sol)

    while timeit.default_timer() - start_time <= 300.0:

        #print("******VND classic******")
        solv = Solver2(m, sol)
        sol = solv.solve(start_time)
        sol.CalculateMaxTravelTime(m)
        #sol.ReportSolution()

        if sol.max_travel_time < bestSol.max_travel_time:
            bestSol = cloneSolution(sol)

        #print("******VND modified******")
        solv = Solver(m, sol)
        sol = solv.solve(start_time)
        sol.CalculateMaxTravelTime(m)
        #sol.ReportSolution()

        if sol.max_travel_time < bestSol.max_travel_time:
            bestSol = cloneSolution(sol)

    print("******Best Solution******")
    bestSol.ReportSolution()
    extractSolution(bestSol)
 def vError(self, v):
     '''The error function used in a Search method for finding an initial
     velocity that gives a trajectory that reaches the desired height.
     
     Parameters
     -----
     v : float
         The velocity whose error is being calculated.
         
     Returns
     -----
     float
         The difference between the calculated height and the desired height.
     '''
     step=0.01
     
     skull = Body.GravBody(Vector.Vector(x=0,y=0,z=v),Vector.Vector(x=0,y=0,z=self.startHeight))
     solver = Solver.RK2(step,Physics.UniformGravity.diffEq)
     
     skullFlight = TrajectorySim(solver,Vector.Vector(x=0,y=0,z=self.g),skull,Physics.stopCondition)
     t,bodies = skullFlight.simulate()
     
     hGuess = bodies[-1].position.z
     
     return hGuess-self.desiredHeight  
def playGame():
    gameImage = screenGrab(bbox)
    imageTiles = getImageTiles(gameImage,3,3)
    matrix = initMatrix(3,3)

    print("Loading tiles...")
    importedImageTiles = loadTiles(filenames)
    print("Tiles loaded.")

    print("Creating matrix...")
    matrix = createMatrix(gameImage, importedImageTiles)
    print("Matrix created.")
    showMatrix(matrix)

    finalMatrix = getFinalMatrix(3,3)

    startNode = Node(matrix, (0,0), None, None)
    endNode = Node(finalMatrix, (3,3), None, None)

    print("Calculating shortest path...")
    totalPath = Solver.shortestPath(startNode, endNode)
    print("Shortest path calculated.")

    print("Total path length: ", len(totalPath))

    for node in reversed(totalPath):
        node.showMatrix()
        print()

    clickSolve(totalPath)
Пример #15
0
def project_solution(height, length, gs_x, gs_y, u_in, cc, au, av, ap, rho, mu):

    # Get Mesh
    u_grid, v_grid, p_grid = Preprocessing.gen_mesh(height, length, gs_x, gs_y)

    # Get Initial Values
    u, v, p = Preprocessing.initial_con(u_grid[0].shape[0], u_grid[1].shape[0], u=0., v=0., p=0.)

    # Get Boundary Conditions
    bc = Preprocessing.boundary_cond('velocity', 'velocity gradient', 'no slip', 'no slip', [u_in, None, None, None])

    # Create viewers
    p_viewer = Viewer.FlowContours(p, p_grid[0], p_grid[1], [0, 0, length, height], 'Pressure')
    x_v_viewer = Viewer.FlowContours(u, u_grid[0], u_grid[1], [0, 0, length, height], 'X Velocity')
    y_v_viewer = Viewer.FlowContours(v, v_grid[0], v_grid[1], [0, 0, length, height], 'Y Velocity')

    s = Solver.Solution(p, u, v, u_grid[0], v_grid[0], v_grid[1], u_grid[1], bc, cc, au, av, ap, rho, mu, p_viewer,
                        x_v_viewer, y_v_viewer)

    p = s.p_n[s.ni/2:-1, s.nj/2]
    dp = p[-1]-p[0]

    print 'dp/dx = ' + str(dp/(gs_x*(len(p)-1)))
    print 'max U = ' + str(s.u_n[s.ni/2:-1, s.nj/2].max())
    print 'max V = ' + str(s.v_n[s.ni/2:-1, s.nj/2].max())

    Viewer.keep_open()
Пример #16
0
    def test_isUnsolved(self):
        problemFile = "Puzzles/Testing/test1.txt"
        g = Main.Grid()
        g.setGrid(GameReader.getGridFromFile(problemFile))
        s = Solver.Solver()

        # Check for row duplicates
        g.setCell((1, 3), 7)
        with self.assertRaises(Solver.DuplicateError) as cm:
            s.isUnsolved(g)
        exception = cm.exception
        message = exception.message
        self.assertEqual("Row 1 contains a duplicate", message)
        g.setCell((1, 3), 0)

        # Check for column duplicates
        g.setCell((4, 0), 7)
        with self.assertRaises(Solver.DuplicateError) as cm:
            s.isUnsolved(g)
        exception = cm.exception
        message = exception.message
        self.assertEqual("Column 0 contains a duplicate", message)
        g.setCell((4, 0), 0)

        # Check for box duplicates
        g.setCell((1, 1), 8)
        with self.assertRaises(Solver.DuplicateError) as cm:
            s.isUnsolved(g)
        exception = cm.exception
        message = exception.message
        self.assertEqual("Box 0 contains a duplicate", message)
        g.setCell((1, 1), 0)

        # Check that check for 0s works properly
        self.assertTrue(s.isUnsolved(g))
Пример #17
0
def number_solutions(copy_s, row, col):

    num_solutions = 0

    if row == 8 and col == 8:
        return num_solutions + 1

    if col == 9:
        row = row + 1
        col = 0

    if copy_s[row][col] == 0:
        present = Solver.test_cell(copy_s, row, col)

        if 0 not in present:
            return 0

        while 0 in present:
            copy_s[row][col] = present.index(0)
            present[present.index(0)] = 1
            num_solutions += number_solutions(copy_s, row, col + 1)

        copy_s[row][col] = 0
        return num_solutions

    num_solutions += number_solutions(copy_s, row, col + 1)
    return num_solutions
Пример #18
0
    def run(self):
        #Report start
        self.reportProgamStarted()

        #Load PSLG
        self.reportMeshLoadingStarted()
        self.pslg = FemIo.loadEle(self.eleFilename)
        self.parameters.initialize(self.pslg)
        self.reportMeshLoadingFinished()

        #Create shape functions
        self.reportBuildingShapeFunctionsStarted()
        slopeFunctions = ShapeFunctions.buildShapeFunctionsForPslg(self.pslg)
        self.reportBuildingShapeFunctionsFinished()

        #Precompute matrices
        self.reportPrecomputingMatricesStarted()
        (G, A, BPrime) = Assembler.precomputeMatrices(slopeFunctions,
                                                      self.parameters)
        self.reportPrecomputingMatricesFinished()

        #Solve
        self.reportSolvingStarted()
        Solver.Solve(self.pslg, slopeFunctions, self.parameters, G, A, BPrime,
                     self.femFilename, self.releaseFilename)
        self.reportSolvingFinished()

        #Report finished
        self.reportProgamFinished()
Пример #19
0
    def __init__(self, neigh, iNumVars):
        self.upstream = []
        self.downstream = []

        self.neigh = neigh
        self.iNumVars = iNumVars
        self.Vars = Solver.Variable_Initialization(self, iNumVars)
Пример #20
0
    def __init__(self, parentWindow, parentGame, parentCanvas):
        self.parentWindow = parentWindow
        self.parentGame = parentGame
        self.parentCanvas = parentCanvas
        self.items = {}
        self.wordsFound = []
        self.language = parentWindow.language
        self.solver = parentWindow.solver
        self.graph = Graph(self.language)
        self.lettersList = self.graph.lettersList
        self.draw_hexagon(parentCanvas, 340, 95, 140)
        self.word = []
        self.dico = Dictionary(self.language)
        self.solver = Solver(self.graph, self.dico, self.lettersList,
                             self.solver)
        self.solutionSolver = self.solver.solution
        self.parentGame.insertListBox(self.solutionSolver)

        self.validationPolygon = parentCanvas.create_polygon(820,
                                                             0,
                                                             1030,
                                                             0,
                                                             1030,
                                                             180,
                                                             820,
                                                             180,
                                                             fill='')
def solve(size):
    solver = Solver.Solver(size)
    if solver.solve():
        return solver.solution()
        # solver.showStatistics()
    else:
        return 'No solution found'
Пример #22
0
    def post(self, request, filename, format=None):

        # .encode('utf-8').decode('utf-8-sig') will remove the \ufeff in the string when add string as value in
        # a dictionary.
        domain_file = request.data['domain'].encode('utf-8').decode(
            'utf-8-sig').lower()
        problem_file = request.data['problem'].encode('utf-8').decode(
            'utf-8-sig').lower()
        animation_file = request.data['animation'].encode('utf-8').decode(
            'utf-8-sig')

        # add url
        if "url" in request.data:
            url_link = request.data['url']
        else:
            url_link = "http://solver.planning.domains/solve"

        predicates_list = Domain_parser.get_domain_json(domain_file)
        plan = Plan_generator.get_plan(domain_file, problem_file, url_link)
        problem_dic = Problem_parser.get_problem_dic(problem_file,
                                                     predicates_list)

        object_list = Problem_parser.get_object_list(problem_file)
        animation_profile = json.loads(
            Animation_parser.get_animation_profile(animation_file,
                                                   object_list))
        stages = Predicates_generator.get_stages(plan, problem_dic,
                                                 problem_file, predicates_list)
        objects_dic = Initialise.initialise_objects(stages["objects"],
                                                    animation_profile)

        myfile = open('stagejson', 'w')

        # Write a line to the file
        myfile.write(json.dumps(stages))
        # Close the file
        myfile.close()

        myfile = open('objects_dic', 'w')

        # Write a line to the file
        myfile.write(json.dumps(objects_dic))
        # Close the file
        myfile.close()
        myfile = open('animation_profile', 'w')

        # Write a line to the file
        myfile.write(json.dumps(animation_profile))
        # Close the file
        myfile.close()

        result = Solver.get_visualisation_dic(stages, animation_profile,
                                              plan['result']['plan'],
                                              problem_dic)

        visualisation_file = Transfer.generate_visualisation_file(
            result, list(objects_dic.keys()), animation_profile,
            plan['result']['plan'])

        return Response(visualisation_file)
Пример #23
0
def manual_mode(a, b, c, d, x_0, y_0, beta, T, calculating_mod):
    N = 50

    if calculating_mod == "Ручной" or calculating_mod == "Авто":
        p_func, z_func, s_func = initialize_functions(a, b, c, d)

        p_func.tabulate(np.arange(0, T + T / N, T / N), "p_func_tabulated")
        z_func.tabulate(np.arange(0, T + T / N, T / N), "z_func_tabulated")
        s_func.tabulate(np.arange(0, T + T / N, T / N), "s_func_tabulated")

    p_interpolated = interpolated_function.InterpolatedFunction(
        "p_func_tabulated")
    z_interpolated = interpolated_function.InterpolatedFunction(
        "z_func_tabulated")
    s_interpolated = interpolated_function.InterpolatedFunction(
        "s_func_tabulated")

    p_interpolated.tabulate(np.arange(0, T + T / (N * 100), T / (N * 100)),
                            "p_func_interp_tabulated")
    z_interpolated.tabulate(np.arange(0, T + T / (N * 100), T / (N * 100)),
                            "z_func_interp_tabulated")
    s_interpolated.tabulate(np.arange(0, T + T / (N * 100), T / (N * 100)),
                            "s_func_interp_tabulated")

    integral_p = integral.Integral(p_interpolated)

    f_func = f_function.FFunction([beta, s_interpolated, z_interpolated, N])

    c1, c2 = Solver.solve(x_0, y_0, beta, T, N, p_interpolated, z_interpolated,
                          s_interpolated, integral_p, f_func)

    return c1, c2
Пример #24
0
def main():

    skull = Body.GravBody(5, 6.371 * 10**6, 8000.)
    solver = Solver.RK2(0.001)

    def stop_condition(skull):
        return skull.velocity > 0

    sim1 = Simulation.TrajectorySim(stop_condition, solver, skull)
    x, y = sim1.get_results()
    skull2 = Body.GravBody(5, 6.371 * 10**6, 8000.)
    sim2 = Simulation.InverseTrajectorySim(stop_condition, solver, skull2)
    a, b = sim2.get_results()

    plt.plot(x, y)
    plt.plot(a, b)
    plt.title("Skull Tosses")
    plt.xlabel("Time [s]")
    plt.ylabel("Height [m]")
    plt.legend(["Uniform Gravity", "Inverse Square Gravity"])

    plt.figure()
    varray = np.arange(0, 100, 0.5)
    harray = []
    for v in varray:
        skull3 = Body.GravBody(5, 6.371 * 10**6, v)
        sim3 = Simulation.InverseTrajectorySim(stop_condition, solver, skull3)
        result = sim3.get_results()
        harray.append(skull3.position)

    plt.plot(varray, harray)
    plt.title("Maximum Height vs. Initial Velocity")
    plt.xlabel("Initial Velocity [m/s]")
    plt.ylabel("Maximum Height [m]")
Пример #25
0
    def configuring(self):
        # Dataset configs:
        self.data_confs = Configs.Data_Configs(self.dataset_root,
                                               self.dataset_name, self.stage,
                                               self.mode).configuring()
        print 'data_confs', self.data_confs

        # Model configs:
        self.model_confs = Configs.Model_Configs(self.dataset_name,
                                                 self.stage).configuring()

        self.data_loaders, self.data_sizes = self.loadData(self.data_confs)
        self.net = self.loadModel()

        if torch.cuda.is_available():
            self.net = self.net.cuda()
            #self.net = torch.nn.DataParallel(self.net).cuda()
        print self.net

        if 'trainval' in self.mode:
            # Solver configs:
            self.solver_confs = Configs.Solver_Configs(
                self.dataset_name, self.data_loaders, self.data_sizes,
                self.net, self.stage, self.mode,
                self.data_confs).configuring()
            print 'solver_confs', self.solver_confs

            self.solver = Solver.Solver(self.net, self.model_confs,
                                        self.solver_confs)
Пример #26
0
def main():
    file_ids, data_dict, image_dict = load_data_from_folder()
    model = load_digit_classifier()
    correct_data = []
    for file_id in file_ids:
        image = image_dict[file_id]
        data = data_dict[file_id]
        warped = recognize_board(image)
        sudoku, sudoku_grid = rec_numbers_alt(warped, model)
        correct_data.append(evaluate_scanned(sudoku_grid, data))
        if Solver.sudoku_solve(sudoku_grid):
            Solver.Sudoku_grid(sudoku_grid)
        else:
            print("No solution exists")
    # total_evaluation() --> performed manually with output from below
    print(correct_data)
    print(file_ids)
Пример #27
0
 def test_hiddenSingles(self):
     problemFile = "Puzzles/Testing/test2.txt"
     g = Main.Grid()
     g.setup(problemFile)
     s = Solver.Solver()
     s.hiddenSingle(g)
     cell = g.getCell((2, 3))
     self.assertEqual(6, cell.getValue())
Пример #28
0
 def test_nakedSingle(self):
     problemFile = "Puzzles/Testing/test1.txt"
     g = Main.Grid()
     g.setup(problemFile)
     s = Solver.Solver()
     s.nakedSingle(g)
     cell = g.getCell((0, 4))
     self.assertEqual(3, cell.getValue())
Пример #29
0
def nextMove(board):
    cars = Solver.getCarArray(board)
    solution = Solver.solve(board, cars)
    
    mvs = []
    mvs.append(solution[0])
    while solution[1] != ():
        solution = solution[1]
        mvs.append(solution[0])
    board.incrementMoves()
    mvs.pop()           # Get rid of first move (no change).
    Solver.updateBoard(board, mvs.pop())
    board.clearBoard()
    board.drawGrid()
    board.drawCars()
    board.master.update()
    board.checkForWin()
Пример #30
0
def reduce_sudoku(s, difficulty):

    elements = list(range(81))
    random.shuffle(elements)

    while elements:
        row = elements[0] // 9
        col = elements[0] % 9
        temp = s[row][col]
        s[row][col] = 0
        elements = elements[1:]

        copy_s = [
            [0, 0, 0, 0, 0, 0, 0, 0, 0],
            [0, 0, 0, 0, 0, 0, 0, 0, 0],
            [0, 0, 0, 0, 0, 0, 0, 0, 0],
            [0, 0, 0, 0, 0, 0, 0, 0, 0],
            [0, 0, 0, 0, 0, 0, 0, 0, 0],
            [0, 0, 0, 0, 0, 0, 0, 0, 0],
            [0, 0, 0, 0, 0, 0, 0, 0, 0],
            [0, 0, 0, 0, 0, 0, 0, 0, 0],
            [0, 0, 0, 0, 0, 0, 0, 0, 0],
        ]

        for i in range(9):
            for j in range(9):
                copy_s[i][j] = s[i][j]

        Solver.initial_fill(copy_s)

        for line in copy_s:
            if 0 in line:
                num_solutions = number_solutions(copy_s, 0, 0)

                if num_solutions > 1:
                    s[row][col] = temp
                    if difficulty == 1:
                        return
                    if difficulty == 2 and len(elements) <= 40:
                        return
                    if difficulty == 3 and len(elements) <= 24:
                        return
                break

    return
Пример #31
0
def build_preconditioned_system(init, preconditioner, equation, x_nodes, t_steps, cfl=0.1, x_min=0., x_max=1., a=1.,
                                acc_space=8, acc_time=8, D=6, P=6, combinations=None, hotime=0):
    """
    Builds a linear system from simulation data using PDE-FIND and preconditions the matrix accordingly.
    Returns the preconditioned system matrix 'R', the corresponding response vector 'u_t', the inverse_transform
    to retrieve the original coefficients from the preconditioned system, the coefficient description and the
    simulation data 'domain' saved in the class 'FDgrid'.
    """

    domain = Solver.solve(x_nodes, t_steps, init, equation, cfl=cfl, a=a, x_min=x_min, x_max=x_max)  # run solver
    Solver.visualize(domain)  # visualize solution
    # apply PDE-FIND algorithm to generate the raw system
    u_t_raw, R_raw, rhs_description = Find.build_linear_system_FD(domain.grid[domain.i_ghost_l + 1:domain.i_ghost_r, :],
                                                                  domain.dt, domain.dx, D=D, P=P, acc_space=acc_space,
                                                                  acc_time=acc_time, order_combinations=combinations,
                                                                  high_order_time_derivs=hotime)
    R, u_t, inverse_transform = Find.precondition_problem(preconditioner, R_raw, u_t_raw)  # precondition the system
    return R, u_t, inverse_transform, rhs_description, domain
Пример #32
0
 def __init__(self, num_vars):
     self.num_vars = num_vars  # int
     self.node_vars_stable = []  # cycle -> node -> PropVarSet id
     self.node_vars_trans = []  # cycle -> node -> PropVarSet id
     self.node_vars_diff = []  # cycle -> node -> PropVarSet id
     self.prop_var_sets = {}  # id -> PropVarSet
     self.linear_gate_set = {}  # vars -> (vars...)
     self.linear_set_cache = {}  # (vars...) -> vars
     self.nonlin_gate_set = {}  # vars -> (vars...)
     self.nonlin_set_cache = {}  # (vars...) -> vars
     self.biased_cache = set()  # {vars...}
     self.biased_vars = set()  # {vars...}
     self.check_vars = {}  # labeled node -> prop
     self.assume_act = {}  # labeled node -> prop
     self.covering_top_vars = {}  # vars -> {vars...}
     self.covered_bot_vars = {}  # {vars...}
     self.vars_to_info = {}  # vars -> (cycle, node)
     self.solver = Solver(store_clauses=False, store_comments=True)
Пример #33
0
    def __init__(self, parent):
        Frame.__init__(self, parent)

        parent.title("HyperSudoku")

        # canvas that shows the HyperSudoku board
        self.sudokuGrid = PhotoImage(file="HyperSudokugrid.gif")
        canvas = Canvas(self, width=610, height=610)
        canvas.create_image(305, 305, image=self.sudokuGrid)
        canvas.pack(side='top')

        # buttons to change between frames
        button2 = Button(self,
                         text="XSudoku",
                         command=lambda: parent.change_frame(XSudoku),
                         width=20)
        button2.pack(side='bottom')
        button1 = Button(self,
                         text="Sudoku",
                         command=lambda: parent.change_frame(Sudoku),
                         width=20)
        button1.pack(side='bottom')

        # information text about the state the board is currently in / what user just did
        information = Label(self, text="")
        information.pack(side='bottom')

        # create Commands object with HyperSudoku parameters
        commands = Commands(solver=Solver.HyperSudokuSolver(),
                            canvas=canvas,
                            information=information,
                            sudokutype="HyperSudoku")

        # buttons to change the board
        completedbutton = Button(self,
                                 text="completed HyperSudoku",
                                 command=commands.completed_grid,
                                 width=20)
        completedbutton.pack(side='bottom')
        solvablebutton = Button(self,
                                text="solvable HyperSudoku",
                                command=commands.solvable_grid,
                                width=20)
        solvablebutton.pack(side='bottom')
        solvebutton = Button(self,
                             text="solve HyperSudoku",
                             command=commands.solve_grid,
                             width=20)
        solvebutton.pack(side='bottom')
        clearbutton = Button(self,
                             text="empty HyperSudoku",
                             command=commands.empty_grid,
                             width=20)
        clearbutton.pack(side='bottom')

        # start with an empty board
        commands.empty_grid()
def main(size):
    timeStat = TimeStatistics.TimeStatistics()
    timeStat.mark()
    solver = Solver.Solver(size)
    if solver.solve():
        solver.showBoard()
        # solver.showStatistics()
    else:
        print 'No solution found'
    timeStat.mark()
Пример #35
0
def solveSystem():
    mGuiSolve = Toplevel();
    mGuiSolve.geometry('500x700+200+200');
    mGuiSolve.title('Soluciones')
    text = Text(mGuiSolve)

    txt = ''
    A = matrizA[:]
    b = matrizB[:]
    N = dim
    gauss = Gauss(A,b,N)
    txt += gauss.all()
    
    A = matrizA[:]
    b = matrizB[:]
    N = dim
    
    solucion = Solver(A, b, N)
    txt += solucion.all()

    A = matrizA[:]
    b = matrizB[:]
    N = dim
    parlet =  parletreid(A, b, N)
    txt += str(parlet)
    
    A = matrizA[:]
    b = matrizB[:]
    N = dim
    aasentxt =  aasen(A, b, N)
    txt += str(aasentxt)
    
    A = matrizA[:]
    b = matrizB[:]
    N = dim
    hh =  HouseHolder(A, n, m, b)
    txt += str(hh.all())

    text.insert(INSERT, txt)
    text.insert(END, '....')
    text.place(x = 20, y = 20, width = 460, height = 660)
Пример #36
0
    def reduce_via_random(self, cutoff=81):
        temp = self.board
        existing = temp.get_used_cells()

        # sorting used cells by density heuristic, highest to lowest
        new_set = [(x,self.board.get_density(x)) for x in existing]
        elements= [x[0] for x in sorted(new_set, key=lambda x: x[1], reverse=True)]

        # for each cell in sorted list
        for cell in elements:
            original = cell.value

            # get list of other values to try in its place
            complement = [x for x in range(1,10) if x != original]
            ambiguous = False

            # check each value in list of other possibilities to try
            for x in complement:

                # set cell to value
                cell.value = x

                # create instance of solver
                s = Solver(temp)

                # if solver can fill every box and the solution is valid then
                # puzzle becomes ambiguous after removing particular cell, so we can break out
                if s.solve() and s.is_valid():
                    cell.value = original
                    ambiguous = True
                    break

            # if every value was checked and puzzle remains unique, we can remove it
            if not ambiguous:
                cell.value = 0
                cutoff -= 1

            # if we ever meet the cutoff limit we can break out
            if cutoff == 0:
                break
Пример #37
0
 def process(self,path):
     count = 0
     path = path.replace("\"", "")
     self.algo = 1
     for line in fileinput.input(files = (path)):
         if count == 0:
              self.algo = int(line[0])
         else:
             if " " in line:
                 cir = line.split( ' ' , 2)
                 pos = Position( float(cir[0]), float(cir[1]))
                 cir = Circle( pos , float(cir [2]))
                 self.cirkels.append(cir)
         count = count + 1 
     self.solver = Solver(self.algo, self.cirkels)
     self.intersections = self.solver.find_intersect()
     self.intersections[1] = self.intersections[1]*1000
Пример #38
0
def fill_sudoku(s, row, col):

    if row == 8 and col == 8:
        present = Solver.test_cell(s, row, col)
        s[row][col] = present.index(0)
        return True

    if col == 9:
        row = row + 1
        col = 0

    sequence = [1, 2, 3, 4, 5, 6, 7, 8, 9]
    random.shuffle(sequence)

    for i in range(9):
        s[row][col] = sequence[i]
        if valid_cell(s, row, col):
            if fill_sudoku(s, row, col + 1):
                return True

    s[row][col] = 0
    return False
Пример #39
0
        [0, 0, 0, 0, 0, 0, 0, 0, -1, 0, 1, -1, 0, 1, 0, 0, 0],
        [0, 0, 0, 0, 0, 0, 0, 0, 0, -1, 0, 1, 0, 0, 1, 0, 0],
        [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -1, 0, 0, 1, 0],
        [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -1, 0, -1, 1],
        [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -1, 0, -1],
    ]
)
#
##Branch source matrix
F = np.zeros((17, 1))
F[5, 0] = 1000
F[6, 0] = 1000
F[10, 0] = 1000
F[11, 0] = 1000

flux_nodal = Solver.solve_node_circuit(A, Yb, F)
flux_nodal_1 = Solver.solve_nodal_circuit(A, Yb, F)

B = np.array(
    [
        [-1, 0, 0, 0, 0, 0],
        [0, -1, 0, 0, 0, 0],
        [1, 0, 0, 0, 0, 0],
        [-1, 1, 0, 0, 0, 0],
        [0, -1, 0, 0, 0, 0],
        [1, 0, -1, 0, 0, 0],
        [0, 1, 0, -1, 0, 0],
        [0, 0, 1, 0, 0, 0],
        [0, 0, -1, 1, 0, 0],
        [0, 0, 0, -1, 0, 0],
        [0, 0, -1, 0, 1, 0],
Пример #40
0
 def test_one_number_string(self):
     """Tesf if string wiht one number returns its number"""
     cadena = "1"
     self.assertEqual(Solver.solve(cadena), cadena)
Пример #41
0
 def test_two_or_more_numbers_string(self):
     """Test the solver with a string of two or more numbers separated by comma"""
     cadena = "1,4,9,0,4,5"
     respuesta_esperada = 5
     self.assertEqual(Solver.solve(cadena), respuesta_esperada)
Пример #42
0
 def test_two_or_more_numbers_string_other_separator(self):
     """Test the solver with a string of two or more numbers separated by comma, ampersand or colon"""
     cadena = "1:6&9"
     respuesta_esperada = 7
     self.assertEqual(Solver.solve(cadena), respuesta_esperada)
Пример #43
0
 def test_solve_empty_string(self):
     """Test if  empty string returns 0"""
     self.assertEqual(Solver.solve(""), 0)
Пример #44
0
        # kspFp, Fp = PrecondSetup.FluidNonLinearSetup(Pressure, MU, u_k)
        # print "Inititial guess norm: ",  u.norm(PETSc.NormType.NORM_INFINITY)
        # #A,Q
        n = FacetNormal(mesh)
        b_t = TrialFunction(Velocity)
        c_t = TestFunction(Velocity)
        mat =  as_matrix([[b_k[1]*b_k[1],-b_k[1]*b_k[0]],[-b_k[1]*b_k[0],b_k[0]*b_k[0]]])
        aa = params[2]*inner(grad(b_t), grad(c_t))*dx(W.mesh()) + inner((grad(b_t)*u_k),c_t)*dx(W.mesh()) +(1./2)*div(u_k)*inner(c_t,b_t)*dx(W.mesh()) - (1./2)*inner(u_k,n)*inner(c_t,b_t)*ds(W.mesh())+kappa/Mu_m*inner(mat*b_t,c_t)*dx(W.mesh())
        ShiftedMass = assemble(aa)
        bcu.apply(ShiftedMass)
        ShiftedMass = CP.Assemble(ShiftedMass)
        kspF = NSprecondSetup.LSCKSPnonlinear(ShiftedMass)

        stime = time.time()

        u, mits,nsits = S.solve(A,b,u,params,W,'Direct',IterType,OuterTol,InnerTol,HiptmairMatrices,Hiptmairtol,KSPlinearfluids, Fp,kspF)
        Soltime = time.time()- stime
        MO.StrTimePrint("MHD solve, time: ", Soltime)
        Mits += mits
        NSits += nsits
        SolutionTime += Soltime

        u1, p1, b1, r1, eps= Iter.PicardToleranceDecouple(u,x,FSpaces,dim,"2",iter)
        p1.vector()[:] += - assemble(p1*dx)/assemble(ones*dx)
        u_k.assign(u1)
        p_k.assign(p1)
        b_k.assign(b1)
        r_k.assign(r1)
        uOld= np.concatenate((u_k.vector().array(),p_k.vector().array(),b_k.vector().array(),r_k.vector().array()), axis=0)
        x = IO.arrayToVec(uOld)
Пример #45
0
### python2.5 -i Tester.py

from Solver import *
#from Rubik import *
#from FCG import *
##from Cannibals import *
#from Donkey import *
#from Wheel import *
from LO import *
s = Solver()
#puzzle = FCG()
#puzzle = Cannibals()
#puzzle = Rubik()
#puzzle = Donkey()
puzzle = LO([1,1,1,1,1,1,1,1,1])
#print puzzle
p = puzzle

s.solve(puzzle)
#s.solve(puzzle, max_level = 10)
#s.solve(puzzle,True)

s.graph() 
#s.path(puzzle)

'''
p = Donkey(B=(1,2), V=((0,1),(1,0),(3,0),(4,0)), H = ((3,2),(3,3)), S = ((2,0),(2,1)), E = ((0,0),(0,3)))
print p

print "ORIGINAL POSITION\n" + str(p)
Пример #46
0
    def post(self):
	guestbook_name = self.request.get('guestbook_name',
                                          DEFAULT_GUESTBOOK_NAME)
        greetings_query = Greeting.query(
            ancestor=guestbook_key(guestbook_name)).order(-Greeting.date)
        greetings = greetings_query.fetch(1)
        
	s = [[0,0,0,0,0,0,0,0,0],
	     [0,0,0,0,0,0,0,0,0],
	     [0,0,0,0,0,0,0,0,0],
	     [0,0,0,0,0,0,0,0,0],
	     [0,0,0,0,0,0,0,0,0],
	     [0,0,0,0,0,0,0,0,0],
	     [0,0,0,0,0,0,0,0,0],
	     [0,0,0,0,0,0,0,0,0],
	     [0,0,0,0,0,0,0,0,0]]
	
	for i in range(0,81):
	    row = i // 9
	    col = i % 9
	    if sent_cells[i] != '':
		s[row][col] = int(sent_cells[i])
	    else:
		s[row][col] = 0
		
	for greeting in greetings:
	    for i in range(0,81):
		if sent_cells[i] == '0':
		    sent_cells[i] = str(self.request.get('e'+str(i/9)+str(i%9)))
	
	    """fname = 'Solutions.txt'
	    with open(fname) as f:
		content = f.readlines()
	
	    content = [x.strip('\n') for x in content] 
	    s = content[greeting.sudoku_id]"""
	    
	    Solver.initial_fill(s)
	    
	    for line in s:
		if 0 in line:
		    Solver.solve(s, 0, 0)
		    break
	    
	    for i in range(0,9):
		for j in range(0,9):
		    sol_cells[9*i+j] = str(s[i][j])
	    
	    flag = True
	    for i in range(0,81):
		if sol_cells[i] != sent_cells[i]:
		    flag = False
		    break
	
	
	template_values = {
	  'flag': flag,
	  'sol_cells': sol_cells,
	  }
	template = JINJA_ENVIRONMENT.get_template('result.html')
        self.response.write(template.render(template_values))
Пример #47
0
        else:
            AA, bb = assemble_system(maxwell+ns+CoupleTerm, (Lmaxwell + Lns) - RHSform,  bcs)
            A,b = CP.Assemble(AA,bb)
            F = A.getSubMatrix(u_is,u_is)
            kspF = NSprecondSetup.LSCKSPnonlinear(F)
        # if iter == 1:
            if iter == 1:
                u = b.duplicate()
        print ("{:40}").format("MHD assemble, time: "), " ==>  ",("{:4f}").format(toc()),  ("{:9}").format("   time: "), ("{:4}").format(time.strftime('%X %x %Z')[0:5])

        kspFp, Fp = PrecondSetup.FluidNonLinearSetup(Pressure, MU, u_k)

        print "Inititial guess norm: ", u.norm()
        stime = time.time()
        # ksp.solve(b, u)
        u,it1,it2 = S.solve(A,b,u,[NS_is,M_is],FSpaces,IterType,OuterTol,InnerTol,HiptmairMatrices,KSPlinearfluids,kspF,Fp)
        Soltime = time.time()- stime
        NSits += it1
        Mits +=it2
        SolutionTime = SolutionTime +Soltime

        u1, p1, b1, r1, eps= Iter.PicardToleranceDecouple(u,x,FSpaces,dim,"2",iter)
        p1.vector()[:] += - assemble(p1*dx)/assemble(ones*dx)
        u_k.assign(u1)
        p_k.assign(p1)
        b_k.assign(b1)
        r_k.assign(r1)
        # if eps > 100 and iter > 3:
        #     print 22222
        #     break
        uOld= np.concatenate((u_k.vector().array(),p_k.vector().array(),b_k.vector().array(),r_k.vector().array()), axis=0)
Пример #48
0
#! /usr/bin/python
"""
Created on Tue Feb 12 09:51:01 2013

@author: santiago
"""

from Classes import *
from Interpreter import *
from Solver import *
from utils import substract_1  
from write import write_vtk

simulation = Simulation()
simulation.read_solver_input('square.msh')
simulation.domain.read_mesh_file('square.msh')
simulation.domain.read_bc_file('square.bc')

interpreter = Interpreter()
equation = interpreter.build_QM_dirichlet_eq(simulation)

solver = Solver()
solution = solver.solve_spectral(simulation, equation)

nodes_coords = simulation.domain.nodes.coords
triangles = simulation.domain.elements.triangles.el_set
triangles = substract_1(triangles)
triangles = triangles[:, 1:]

write_vtk('square_from_OOP.vtk','this shit','',nodes_coords,\
            triangles,['SCALARS',['solution'],[solution[1]]])
Пример #49
0
def foo():
    m = 6


    errL2u =np.zeros((m-1,1))
    errH1u =np.zeros((m-1,1))
    errL2p =np.zeros((m-1,1))
    errL2b =np.zeros((m-1,1))
    errCurlb =np.zeros((m-1,1))
    errL2r =np.zeros((m-1,1))
    errH1r =np.zeros((m-1,1))



    l2uorder =  np.zeros((m-1,1))
    H1uorder =np.zeros((m-1,1))
    l2porder =  np.zeros((m-1,1))
    l2border =  np.zeros((m-1,1))
    Curlborder =np.zeros((m-1,1))
    l2rorder =  np.zeros((m-1,1))
    H1rorder = np.zeros((m-1,1))

    NN = np.zeros((m-1,1))
    DoF = np.zeros((m-1,1))
    Velocitydim = np.zeros((m-1,1))
    Magneticdim = np.zeros((m-1,1))
    Pressuredim = np.zeros((m-1,1))
    Lagrangedim = np.zeros((m-1,1))
    Wdim = np.zeros((m-1,1))
    iterations = np.zeros((m-1,1))
    SolTime = np.zeros((m-1,1))
    udiv = np.zeros((m-1,1))
    MU = np.zeros((m-1,1))
    level = np.zeros((m-1,1))
    NSave = np.zeros((m-1,1))
    Mave = np.zeros((m-1,1))
    TotalTime = np.zeros((m-1,1))
    
    nn = 2

    dim = 2
    ShowResultPlots = 'yes'
    split = 'Linear'

    MU[0]= 1e0
    for xx in xrange(1,m):
        print xx
        level[xx-1] = xx+ 0
        nn = 2**(level[xx-1])



        # Create mesh and define function space
        nn = int(nn)
        NN[xx-1] = nn/2
        # parameters["form_compiler"]["quadrature_degree"] = 6
        # parameters = CP.ParameterSetup()
        mesh = UnitCubeMesh(nn,nn,nn)

        order = 2
        parameters['reorder_dofs_serial'] = False
        Velocity = VectorFunctionSpace(mesh, "CG", order)
        Pressure = FunctionSpace(mesh, "CG", order-1)
        Magnetic = FunctionSpace(mesh, "N1curl", order)
        Lagrange = FunctionSpace(mesh, "CG", order)
        W = MixedFunctionSpace([Velocity, Pressure, Magnetic,Lagrange])
        # W = Velocity*Pressure*Magnetic*Lagrange
        Velocitydim[xx-1] = Velocity.dim()
        Pressuredim[xx-1] = Pressure.dim()
        Magneticdim[xx-1] = Magnetic.dim()
        Lagrangedim[xx-1] = Lagrange.dim()
        Wdim[xx-1] = W.dim()
        print "\n\nW:  ",Wdim[xx-1],"Velocity:  ",Velocitydim[xx-1],"Pressure:  ",Pressuredim[xx-1],"Magnetic:  ",Magneticdim[xx-1],"Lagrange:  ",Lagrangedim[xx-1],"\n\n"
        dim = [Velocity.dim(), Pressure.dim(), Magnetic.dim(), Lagrange.dim()]


        def boundary(x, on_boundary):
            return on_boundary

        u0, p0,b0, r0, Laplacian, Advection, gradPres,CurlCurl, gradR, NS_Couple, M_Couple = ExactSol.MHD3D(4,1)


        bcu = DirichletBC(Velocity,u0, boundary)
        bcb = DirichletBC(Magnetic,b0, boundary)
        bcr = DirichletBC(Lagrange,r0, boundary)

        # bc = [u0,p0,b0,r0]
        bcs = [bcu,bcb,bcr]
        FSpaces = [Velocity,Pressure,Magnetic,Lagrange]


        (u, b, p, r) = TrialFunctions(W)
        (v, c, q, s) = TestFunctions(W)
        kappa = 1.0
        Mu_m =10.0
        MU = 1.0/1
        IterType = 'Full'
        Split = "No"
        Saddle = "No"
        Stokes = "No"
        SetupType = 'python-class'
        F_NS = -MU*Laplacian+Advection+gradPres-kappa*NS_Couple
        if kappa == 0:
            F_M = Mu_m*CurlCurl+gradR -kappa*M_Couple
        else:
            F_M = Mu_m*kappa*CurlCurl+gradR -kappa*M_Couple
        params = [kappa,Mu_m,MU]

        MO.PrintStr("Seting up initial guess matricies",2,"=","\n\n","\n")
        BCtime = time.time()
        BC = MHDsetup.BoundaryIndices(mesh)
        MO.StrTimePrint("BC index function, time: ", time.time()-BCtime)
        Hiptmairtol = 1e-5
        HiptmairMatrices = PrecondSetup.MagneticSetup(Magnetic, Lagrange, b0, r0, Hiptmairtol, params)
 

        MO.PrintStr("Setting up MHD initial guess",5,"+","\n\n","\n\n")
        u_k,p_k,b_k,r_k = common.InitialGuess(FSpaces,[u0,p0,b0,r0],[F_NS,F_M],params,HiptmairMatrices,1e-10,Neumann=Expression(("0","0")),options ="New")
        b_t = TrialFunction(Velocity)
        c_t = TestFunction(Velocity)

        ones = Function(Pressure)
        ones.vector()[:]=(0*ones.vector().array()+1)
        # pConst = - assemble(p_k*dx)/assemble(ones*dx)
        p_k.vector()[:] += - assemble(p_k*dx)/assemble(ones*dx)
        x = Iter.u_prev(u_k,p_k,b_k,r_k)

        KSPlinearfluids, MatrixLinearFluids = PrecondSetup.FluidLinearSetup(Pressure, MU)
        kspFp, Fp = PrecondSetup.FluidNonLinearSetup(Pressure, MU, u_k)
        #plot(b_k)

        ns,maxwell,CoupleTerm,Lmaxwell,Lns = forms.MHD2D(mesh, W,F_M,F_NS, u_k,b_k,params,IterType,"CG",Saddle,Stokes)
        RHSform = forms.PicardRHS(mesh, W, u_k, p_k, b_k, r_k, params,"CG",Saddle,Stokes)

        bcu = DirichletBC(W.sub(0),Expression(("0.0","0.0","0.0")), boundary)
        bcb = DirichletBC(W.sub(2),Expression(("0.0","0.0","0.0")), boundary)
        bcr = DirichletBC(W.sub(3),Expression(("0.0")), boundary)
        bcs = [bcu,bcb,bcr]
        
        parameters['linear_algebra_backend'] = 'uBLAS'
        
        eps = 1.0           # error measure ||u-u_k||
        tol = 1.0E-4     # tolerance
        iter = 0            # iteration counter
        maxiter = 10       # max no of iterations allowed
        SolutionTime = 0
        outer = 0
        # parameters['linear_algebra_backend'] = 'uBLAS'

        # FSpaces = [Velocity,Magnetic,Pressure,Lagrange]

        if IterType == "CD":
            MO.PrintStr("Setting up PETSc "+SetupType,2,"=","\n","\n")
            Alin = MHDsetup.Assemble(W,ns,maxwell,CoupleTerm,Lns,Lmaxwell,RHSform,bcs+BC, "Linear",IterType)
            Fnlin,b = MHDsetup.Assemble(W,ns,maxwell,CoupleTerm,Lns,Lmaxwell,RHSform,bcs+BC, "NonLinear",IterType)
            A = Fnlin+Alin
            A,b = MHDsetup.SystemAssemble(FSpaces,A,b,SetupType,IterType)
            u = b.duplicate()


        u_is = PETSc.IS().createGeneral(range(Velocity.dim()))
        NS_is = PETSc.IS().createGeneral(range(Velocity.dim()+Pressure.dim()))
        M_is = PETSc.IS().createGeneral(range(Velocity.dim()+Pressure.dim(),W.dim()))
        OuterTol = 1e-5
        InnerTol = 1e-5
        NSits =0
        Mits =0
        TotalStart =time.time()
        SolutionTime = 0
        while eps > tol  and iter < maxiter:
            iter += 1
            MO.PrintStr("Iter "+str(iter),7,"=","\n\n","\n\n")
            AssembleTime = time.time()
            if IterType == "CD":
                MO.StrTimePrint("MHD CD RHS assemble, time: ", time.time()-AssembleTime)
                b = MHDsetup.Assemble(W,ns,maxwell,CoupleTerm,Lns,Lmaxwell,RHSform,bcs+BC, "CD",IterType)
            else:
                MO.PrintStr("Setting up PETSc "+SetupType,2,"=","\n","\n")
                if  Split == "Yes":
                    if iter == 1:
                        Alin = MHDsetup.Assemble(W,ns,maxwell,CoupleTerm,Lns,Lmaxwell,RHSform,bcs+BC, "Linear",IterType)
                        Fnlin,b = MHDsetup.Assemble(W,ns,maxwell,CoupleTerm,Lns,Lmaxwell,RHSform,bcs+BC, "NonLinear",IterType)
                        A = Fnlin+Alin
                        A,b = MHDsetup.SystemAssemble(FSpaces,A,b,SetupType,IterType)
                        u = b.duplicate()
                    else: 
                        Fnline,b = MHDsetup.Assemble(W,ns,maxwell,CoupleTerm,Lns,Lmaxwell,RHSform,bcs+BC, "NonLinear",IterType)
                        A = Fnlin+Alin
                        A,b = MHDsetup.SystemAssemble(FSpaces,A,b,SetupType,IterType)
                else:
                    AA, bb = assemble_system(maxwell+ns+CoupleTerm, (Lmaxwell + Lns) - RHSform,  bcs)
                    A,b = CP.Assemble(AA,bb)
            # if iter == 1:
            MO.StrTimePrint("MHD total assemble, time: ", time.time()-AssembleTime)
            
            u = b.duplicate()
            kspFp, Fp = PrecondSetup.FluidNonLinearSetup(Pressure, MU, u_k)
            print "Inititial guess norm: ",  u.norm(PETSc.NormType.NORM_INFINITY)            
            #A,Q
            if IterType == 'Full':
   
                n = FacetNormal(mesh)
                mat = as_matrix([[b_k[2]*b_k[2]+b[1]*b[1],-b_k[1]*b_k[0],-b_k[0]*b_k[2]],
                          [-b_k[1]*b_k[0],b_k[0]*b_k[0]+b_k[2]*b_k[2],-b_k[2]*b_k[1]],
                        [-b_k[0]*b_k[2],-b_k[1]*b_k[2],b_k[0]*b_k[0]+b_k[1]*b_k[1]]])
                a = params[2]*inner(grad(b_t), grad(c_t))*dx(W.mesh()) + inner((grad(b_t)*u_k),c_t)*dx(W.mesh()) +(1./2)*div(u_k)*inner(c_t,b_t)*dx(W.mesh()) - (1./2)*inner(u_k,n)*inner(c_t,b_t)*ds(W.mesh())+kappa/Mu_m*inner(mat*b_t,c_t)*dx(W.mesh())
                ShiftedMass = assemble(a)
                bcu.apply(ShiftedMass)
                ShiftedMass = CP.Assemble(ShiftedMass)
                kspF = NSprecondSetup.LSCKSPnonlinear(ShiftedMass)
            else:
                F = A.getSubMatrix(u_is,u_is)
                kspF = NSprecondSetup.LSCKSPnonlinear(F)
            stime = time.time()
            u, mits,nsits = S.solve(A,b,u,params,W,'Directclase',IterType,OuterTol,InnerTol,HiptmairMatrices,Hiptmairtol,KSPlinearfluids, Fp,kspF)
            Soltime = time.time()- stime
            MO.StrTimePrint("MHD solve, time: ", Soltime)
            Mits += mits
            NSits += nsits
            SolutionTime += Soltime
            
            u1, p1, b1, r1, eps= Iter.PicardToleranceDecouple(u,x,FSpaces,dim,"2",iter)
            p1.vector()[:] += - assemble(p1*dx)/assemble(ones*dx)
            u_k.assign(u1)
            p_k.assign(p1)
            b_k.assign(b1)
            r_k.assign(r1)
            uOld= np.concatenate((u_k.vector().array(),p_k.vector().array(),b_k.vector().array(),r_k.vector().array()), axis=0)
            x = IO.arrayToVec(uOld)



        XX= np.concatenate((u_k.vector().array(),p_k.vector().array(),b_k.vector().array(),r_k.vector().array()), axis=0)
        SolTime[xx-1] = SolutionTime/iter
        NSave[xx-1] = (float(NSits)/iter)
        Mave[xx-1] = (float(Mits)/iter)
        iterations[xx-1] = iter
        TotalTime[xx-1] = time.time() - TotalStart
#        dim = [Velocity.dim(), Pressure.dim(), Magnetic.dim(),Lagrange.dim()]
#
#        ExactSolution = [u0,p0,b0,r0]
#        errL2u[xx-1], errH1u[xx-1], errL2p[xx-1], errL2b[xx-1], errCurlb[xx-1], errL2r[xx-1], errH1r[xx-1] = Iter.Errors(XX,mesh,FSpaces,ExactSolution,order,dim, "DG")
#
#        if xx > 1:
#            l2uorder[xx-1] =  np.abs(np.log2(errL2u[xx-2]/errL2u[xx-1]))
#            H1uorder[xx-1] =  np.abs(np.log2(errH1u[xx-2]/errH1u[xx-1]))
#
#            l2porder[xx-1] =  np.abs(np.log2(errL2p[xx-2]/errL2p[xx-1]))
#
#            l2border[xx-1] =  np.abs(np.log2(errL2b[xx-2]/errL2b[xx-1]))
#            Curlborder[xx-1] =  np.abs(np.log2(errCurlb[xx-2]/errCurlb[xx-1]))
#
#            l2rorder[xx-1] =  np.abs(np.log2(errL2r[xx-2]/errL2r[xx-1]))
#            H1rorder[xx-1] =  np.abs(np.log2(errH1r[xx-2]/errH1r[xx-1]))
#
#
#
#
#    import pandas as pd
#
#
#
#    LatexTitles = ["l","DoFu","Dofp","V-L2","L2-order","V-H1","H1-order","P-L2","PL2-order"]
#    LatexValues = np.concatenate((level,Velocitydim,Pressuredim,errL2u,l2uorder,errH1u,H1uorder,errL2p,l2porder), axis=1)
#    LatexTable = pd.DataFrame(LatexValues, columns = LatexTitles)
#    pd.set_option('precision',3)
#    LatexTable = MO.PandasFormat(LatexTable,"V-L2","%2.4e")
#    LatexTable = MO.PandasFormat(LatexTable,'V-H1',"%2.4e")
#    LatexTable = MO.PandasFormat(LatexTable,"H1-order","%1.2f")
#    LatexTable = MO.PandasFormat(LatexTable,'L2-order',"%1.2f")
#    LatexTable = MO.PandasFormat(LatexTable,"P-L2","%2.4e")
#    LatexTable = MO.PandasFormat(LatexTable,'PL2-order',"%1.2f")
#    print LatexTable
#
#
#    print "\n\n   Magnetic convergence"
#    MagneticTitles = ["l","B DoF","R DoF","B-L2","L2-order","B-Curl","HCurl-order"]
#    MagneticValues = np.concatenate((level,Magneticdim,Lagrangedim,errL2b,l2border,errCurlb,Curlborder),axis=1)
#    MagneticTable= pd.DataFrame(MagneticValues, columns = MagneticTitles)
#    pd.set_option('precision',3)
#    MagneticTable = MO.PandasFormat(MagneticTable,"B-Curl","%2.4e")
#    MagneticTable = MO.PandasFormat(MagneticTable,'B-L2',"%2.4e")
#    MagneticTable = MO.PandasFormat(MagneticTable,"L2-order","%1.2f")
#    MagneticTable = MO.PandasFormat(MagneticTable,'HCurl-order',"%1.2f")
#    print MagneticTable




    import pandas as pd




    print "\n\n   Iteration table"
    if IterType == "Full":
        IterTitles = ["l","DoF","AV solve Time","Total picard time","picard iterations","Av Outer its","Av Inner its",]
    else:
        IterTitles = ["l","DoF","AV solve Time","Total picard time","picard iterations","Av NS iters","Av M iters"]
    IterValues = np.concatenate((level,Wdim,SolTime,TotalTime,iterations,Mave,NSave),axis=1)
    IterTable= pd.DataFrame(IterValues, columns = IterTitles)
    if IterType == "Full":
        IterTable = MO.PandasFormat(IterTable,'Av Outer its',"%2.1f")
        IterTable = MO.PandasFormat(IterTable,'Av Inner its',"%2.1f")
    else:
        IterTable = MO.PandasFormat(IterTable,'Av NS iters',"%2.1f")
        IterTable = MO.PandasFormat(IterTable,'Av M iters',"%2.1f")
    print IterTable
    print " \n  Outer Tol:  ",OuterTol, "Inner Tol:   ", InnerTol


    IterTable.to_latex("3d.tex")
    # # # if (ShowResultPlots == 'yes'):

#    plot(u_k)
#    plot(interpolate(u0,Velocity))
#
#    plot(p_k)
#
#    plot(interpolate(p0,Pressure))
#
#    plot(b_k)
#    plot(interpolate(b0,Magnetic))
#
#    plot(r_k)
#    plot(interpolate(r0,Lagrange))
#
#    interactive()

    interactive()
Пример #50
0
basePath = 'sweep'
aoaRange = [-6,-4,-2,0,2,4,6,8,10]

for aoa in aoaRange:
    ## Case setup will configure a directory for an OpenFoam run
    case = Utilities.caseSetup(folderPath='%s/test_%s'%(basePath,aoa), geometryPath='../test_dir/benchmarkAircraft.stl')


    ## This manages the STL file. This includes the option to scale and rotate the geometry.
    model = stlTools.SolidSTL(case.stlPath)
    ## Rotate the geometry to the correct aoa for the simulation
    model.setaoa(aoa, units='degrees')
    ## Save the Modified geometry to disk
    model.saveSTL(case.stlPath)


    ## Meshing will execute blockMeshDict and snappyHexMesh to create the mesh for simulation
    mesh = Meshing.mesher(case.dir, model)
    ## Run blockMesh to generate the simulation domain
    mesh.blockMesh()
    ## Used snappyHexMesh to refine the domain and subtract out regions around the geometry
    mesh.snappyHexMesh()
    ## Display the mesh in a Paraview preview window
    if preview:
        mesh.previewMesh()


    solver = Solver.solver(case.dir)
    if preview:
        ## Call the mesh function again, but Paraview will find the solver results in the case directory
        mesh.previewMesh()
        [0, 0, 1, 0, 0, 0],
        [0, 0, -1, 1, 0, 0],
        [0, 0, 0, -1, 0, 0],
        [0, 0, -1, 0, 1, 0],
        [0, 0, 0, -1, 0, 1],
        [0, 0, 0, 0, 1, 0],
        [0, 0, 0, 0, -1, 1],
        [0, 0, 0, 0, 0, -1],
        [0, 0, 0, 0, 1, 0],
        [0, 0, 0, 0, 0, 1],
    ]
)

#%%
A = np.load(r"D:\Anderson\Cloud_Drive\10_UFSC\01_Doutorado\10_Testes\15_Circuit\incidence.npy")
B, tree, co_tree = Solver.welsch(A)

Zb = np.load(r"D:\Anderson\Cloud_Drive\10_UFSC\01_Doutorado\10_Testes\15_Circuit\reluctance.npy")
F = np.load(r"D:\Anderson\Cloud_Drive\10_UFSC\01_Doutorado\10_Testes\15_Circuit\source.npy")
Yb = np.linalg.inv(Zb)

#%%
# ==============================================================================
# Nodal Solver
# ==============================================================================
start_time = time.time()
flux_nodal = Solver.solve_nodal_circuit(A, Yb, F)
nodal_time = time.time() - start_time

# ==============================================================================
# Mesh solver - B manually defined
Пример #52
0
clock=pygame.time.Clock()
hold = []


# -------- Main Program Loop -----------
while done==False:
        for event in pygame.event.get(): # User did something
            if event.type == pygame.QUIT: # If user clicked close
                done=True # Flag that we are done so we exit this loop
            if event.type == pygame.KEYDOWN: # If user wants to perform an action
                if event.key == pygame.K_e:
                    # Choose a random puzzle to solve
                    easypuzzle = random.choice(os.listdir("easypuzzles")) #change dir name if necessary
                    easypuzzle = "easypuzzles/" + easypuzzle
                    firstSnapshot = Sudoku_IO.loadPuzzle(easypuzzle)
                    Solver.solve(firstSnapshot, screen)    
                if event.key == pygame.K_h:
                    # Choose a random puzzle to solve
                    hardpuzzle = random.choice(os.listdir("hardpuzzles")) #change dir name if necessary
                    hardpuzzle = "hardpuzzles/" + hardpuzzle
                    firstSnapshot = Sudoku_IO.loadPuzzle(hardpuzzle)
                    Solver.solve(firstSnapshot, screen)
   
        # Limit to 20 frames per second
        clock.tick(10)
        # Go ahead and update the screen with what we've drawn.
        pygame.display.flip()
     
# If you forget this line, the program will 'hang' on exit.
pygame.quit ()
Пример #53
0
"""
Created on Jan 25, 2016

@author: John_2
"""
from Solver import *
from Directions import *

if __name__ == "__main__":
    print("running TTT minimax")

    solver = Solver()

    print(str(solver.search(solver.game.getGrid(), solver.game.getTurn())))
    solver.game.swapMove()  # always follows
    solver.game.printState()

    print(str(solver.search(solver.game.getGrid(), solver.game.getTurn())))
    solver.game.swapMove()  # always follows
    solver.game.printState()

    print(str(solver.search(solver.game.getGrid(), solver.game.getTurn())))
    solver.game.swapMove()  # always follows
    solver.game.printState()

    pass
Пример #54
0
[0,0,0,0,-1,0,-1,0,0,1,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,-1,0,0,-1,0,1,0,0,0,0],
[0,0,0,0,0,0,0,0,-1,0,1,-1,0,1,0,0,0],
[0,0,0,0,0,0,0,0,0,-1,0,1,0,0,1,0,0],
[0,0,0,0,0,0,0,0,0,0,0,0,-1,0,0,1,0],
[0,0,0,0,0,0,0,0,0,0,0,0,0,-1,0,-1,1],
[0,0,0,0,0,0,0,0,0,0,0,0,0,0,-1,0,-1]])

##Branch source matrix
F=np.zeros((17,1))
F[0,0]=1000
F[12,0]=1000
F[13,0]=1000
F[14,0]=1000
#
flux_nodal=Solver.solve_nodal_circuit(A,Yb, F)


#Ex Chua, pg 150
#A=np.array([
#[1,1,0,1,0,0,0,0],
#[0,-1,1,0,1,0,1,0],
#[0,0,0,0,0,0,-1,1],
#[-1,0,-1,0,0,1,0,0]])

#A=np.array([
#[1,1,0,0,0,0,-1],
#[-1,0,0,1,-1,0,0],
#[0,0,0,-1,0,1,0],
#[0,0,-1,0,1,-1,1]])
Пример #55
0
def foo():
    m = 7


    errL2u =np.zeros((m-1,1))
    errH1u =np.zeros((m-1,1))
    errL2p =np.zeros((m-1,1))
    errL2b =np.zeros((m-1,1))
    errCurlb =np.zeros((m-1,1))
    errL2r =np.zeros((m-1,1))
    errH1r =np.zeros((m-1,1))



    l2uorder =  np.zeros((m-1,1))
    H1uorder =np.zeros((m-1,1))
    l2porder =  np.zeros((m-1,1))
    l2border =  np.zeros((m-1,1))
    Curlborder =np.zeros((m-1,1))
    l2rorder =  np.zeros((m-1,1))
    H1rorder = np.zeros((m-1,1))

    NN = np.zeros((m-1,1))
    DoF = np.zeros((m-1,1))
    Velocitydim = np.zeros((m-1,1))
    Magneticdim = np.zeros((m-1,1))
    Pressuredim = np.zeros((m-1,1))
    Lagrangedim = np.zeros((m-1,1))
    Wdim = np.zeros((m-1,1))
    iterations = np.zeros((m-1,1))
    SolTime = np.zeros((m-1,1))
    udiv = np.zeros((m-1,1))
    MU = np.zeros((m-1,1))
    level = np.zeros((m-1,1))
    NSave = np.zeros((m-1,1))
    Mave = np.zeros((m-1,1))
    TotalTime = np.zeros((m-1,1))
    
    nn = 2

    dim = 2
    ShowResultPlots = 'yes'
    split = 'Linear'
    kappa = 0.01
    for yy in xrange(1,5):
        kappa = kappa*10
        for xx in xrange(1,m):
            print xx
            level[xx-1] = xx+ 2
            nn = 2**(level[xx-1])



            # Create mesh and define function space
            nn = int(nn)
            NN[xx-1] = nn/2
            # parameters["form_compiler"]["quadrature_degree"] = 6
            # parameters = CP.ParameterSetup()
            mesh = UnitSquareMesh(nn,nn)

            order = 1
            parameters['reorder_dofs_serial'] = False
            Velocity = VectorFunctionSpace(mesh, "CG", order)
            Pressure = FunctionSpace(mesh, "DG", order-1)
            Magnetic = FunctionSpace(mesh, "N1curl", order)
            Lagrange = FunctionSpace(mesh, "CG", order)
            W = MixedFunctionSpace([Velocity, Pressure, Magnetic,Lagrange])
            # W = Velocity*Pressure*Magnetic*Lagrange
            Velocitydim[xx-1] = Velocity.dim()
            Pressuredim[xx-1] = Pressure.dim()
            Magneticdim[xx-1] = Magnetic.dim()
            Lagrangedim[xx-1] = Lagrange.dim()
            Wdim[xx-1] = W.dim()
            print "\n\nW:  ",Wdim[xx-1],"Velocity:  ",Velocitydim[xx-1],"Pressure:  ",Pressuredim[xx-1],"Magnetic:  ",Magneticdim[xx-1],"Lagrange:  ",Lagrangedim[xx-1],"\n\n"
            dim = [Velocity.dim(), Pressure.dim(), Magnetic.dim(), Lagrange.dim()]


            def boundary(x, on_boundary):
                return on_boundary

            u0, p0,b0, r0, Laplacian, Advection, gradPres,CurlCurl, gradR, NS_Couple, M_Couple = ExactSol.MHD2D(4,1)


            bcu = DirichletBC(W.sub(0),u0, boundary)
            bcb = DirichletBC(W.sub(2),b0, boundary)
            bcr = DirichletBC(W.sub(3),r0, boundary)

            # bc = [u0,p0,b0,r0]
            bcs = [bcu,bcb,bcr]
            FSpaces = [Velocity,Pressure,Magnetic,Lagrange]


            (u, b, p, r) = TrialFunctions(W)
            (v, c, q, s) = TestFunctions(W)
            #kappa = 1.0
            MU = 1.0
            Mu_m =1e1
            IterType = 'Combined'

            F_NS = -MU*Laplacian+Advection+gradPres-kappa*NS_Couple
            if kappa == 0:
                F_M = Mu_m*CurlCurl+gradR -kappa*M_Couple
            else:
                F_M = Mu_m*kappa*CurlCurl+gradR -kappa*M_Couple
            params = [kappa,Mu_m,MU]


            # MO.PrintStr("Preconditioning MHD setup",5,"+","\n\n","\n\n")
            Hiptmairtol = 1e-5
            HiptmairMatrices = PrecondSetup.MagneticSetup(Magnetic, Lagrange, b0, r0, Hiptmairtol, params)


            MO.PrintStr("Setting up MHD initial guess",5,"+","\n\n","\n\n")
            u_k,p_k,b_k,r_k = common.InitialGuess(FSpaces,[u0,p0,b0,r0],[F_NS,F_M],params,HiptmairMatrices,1e-6,Neumann=Expression(("0","0")),options ="New", FS = "DG")
            #plot(p_k, interactive = True) 
            b_t = TrialFunction(Velocity)
            c_t = TestFunction(Velocity)
            #print assemble(inner(b,c)*dx).array().shape
            #print mat
            #ShiftedMass = assemble(inner(mat*b,c)*dx)
            #as_vector([inner(b,c)[0]*b_k[0],inner(b,c)[1]*(-b_k[1])])

            ones = Function(Pressure)
            ones.vector()[:]=(0*ones.vector().array()+1)
            # pConst = - assemble(p_k*dx)/assemble(ones*dx)
            p_k.vector()[:] += - assemble(p_k*dx)/assemble(ones*dx)
            x = Iter.u_prev(u_k,p_k,b_k,r_k)

            KSPlinearfluids, MatrixLinearFluids = PrecondSetup.FluidLinearSetup(Pressure, MU)
            kspFp, Fp = PrecondSetup.FluidNonLinearSetup(Pressure, MU, u_k)
            #plot(b_k)

            ns,maxwell,CoupleTerm,Lmaxwell,Lns = forms.MHD2D(mesh, W,F_M,F_NS, u_k,b_k,params,IterType,"DG")
            RHSform = forms.PicardRHS(mesh, W, u_k, p_k, b_k, r_k, params,"DG")


            bcu = DirichletBC(W.sub(0),Expression(("0.0","0.0")), boundary)
            bcb = DirichletBC(W.sub(2),Expression(("0.0","0.0")), boundary)
            bcr = DirichletBC(W.sub(3),Expression(("0.0")), boundary)
            bcs = [bcu,bcb,bcr]

            eps = 1.0           # error measure ||u-u_k||
            tol = 1.0E-4     # tolerance
            iter = 0            # iteration counter
            maxiter = 40       # max no of iterations allowed
            SolutionTime = 0
            outer = 0
            # parameters['linear_algebra_backend'] = 'uBLAS'

            # FSpaces = [Velocity,Magnetic,Pressure,Lagrange]

            if IterType == "CD":
                AA, bb = assemble_system(maxwell+ns, (Lmaxwell + Lns) - RHSform,  bcs)
                A,b = CP.Assemble(AA,bb)
                # u = b.duplicate()
                # P = CP.Assemble(PP)


            u_is = PETSc.IS().createGeneral(range(Velocity.dim()))
            NS_is = PETSc.IS().createGeneral(range(Velocity.dim()+Pressure.dim()))
            M_is = PETSc.IS().createGeneral(range(Velocity.dim()+Pressure.dim(),W.dim()))
            OuterTol = 1e-5
            InnerTol = 1e-5
            NSits =0
            Mits =0
            TotalStart =time.time()
            SolutionTime = 0
            while eps > tol  and iter < maxiter:
                iter += 1
                MO.PrintStr("Iter "+str(iter),7,"=","\n\n","\n\n")
                tic()
                if IterType == "CD":
                    bb = assemble((Lmaxwell + Lns) - RHSform)
                    for bc in bcs:
                        bc.apply(bb)
                    FF = AA.sparray()[0:dim[0],0:dim[0]]
                    A,b = CP.Assemble(AA,bb)
                    # if iter == 1
                    if iter == 1:
                        u = b.duplicate()
                        F = A.getSubMatrix(u_is,u_is)
                        kspF = NSprecondSetup.LSCKSPnonlinear(F)
                else:
                    AA, bb = assemble_system(maxwell+ns+CoupleTerm, (Lmaxwell + Lns) - RHSform,  bcs)
                    A,b = CP.Assemble(AA,bb)
                # if iter == 1:
                    if iter == 1:
                        u = b.duplicate()
                print ("{:40}").format("MHD assemble, time: "), " ==>  ",("{:4f}").format(toc()),  ("{:9}").format("   time: "), ("{:4}").format(time.strftime('%X %x %Z')[0:5])

                kspFp, Fp = PrecondSetup.FluidNonLinearSetup(Pressure, MU, u_k)
                print "Inititial guess norm: ", u.norm()
                
                #A,Q
                if IterType == 'Combined':
       
                    n = FacetNormal(mesh)
                    mat =  as_matrix([[b_k[1]*b_k[1],-b_k[1]*b_k[0]],[-b_k[1]*b_k[0],b_k[0]*b_k[0]]])
                    F = A.getSubMatrix(u_is,u_is)
                    a = params[2]*inner(grad(b_t), grad(c_t))*dx(W.mesh()) + inner((grad(b_t)*u_k),c_t)*dx(W.mesh()) +(1/2)*div(u_k)*inner(c_t,b_t)*dx(W.mesh()) - (1/2)*inner(u_k,n)*inner(c_t,b_t)*ds(W.mesh())+kappa/Mu_m*inner(mat*b_t,c_t)*dx(W.mesh())
                    ShiftedMass = assemble(a)
                    bcu.apply(ShiftedMass)
                    
                    kspF = NSprecondSetup.LSCKSPnonlinear(F)
                else:
                    F = A.getSubMatrix(u_is,u_is)
                    kspF = NSprecondSetup.LSCKSPnonlinear(F)

                stime = time.time()
                u, mits,nsits = S.solve(A,b,u,params,W,IterType,OuterTol,InnerTol,HiptmairMatrices,Hiptmairtol,KSPlinearfluids, Fp,kspF)
                Soltime = time.time()- stime
                Mits += mits
                NSits += nsits
                SolutionTime += Soltime
                
                u1, p1, b1, r1, eps= Iter.PicardToleranceDecouple(u,x,FSpaces,dim,"2",iter)
                p1.vector()[:] += - assemble(p1*dx)/assemble(ones*dx)
                u_k.assign(u1)
                p_k.assign(p1)
                b_k.assign(b1)
                r_k.assign(r1)
                uOld= np.concatenate((u_k.vector().array(),p_k.vector().array(),b_k.vector().array(),r_k.vector().array()), axis=0)
                x = IO.arrayToVec(uOld)



            XX= np.concatenate((u_k.vector().array(),p_k.vector().array(),b_k.vector().array(),r_k.vector().array()), axis=0)
            SolTime[xx-1] = SolutionTime/iter
            NSave[xx-1] = (float(NSits)/iter)
            Mave[xx-1] = (float(Mits)/iter)
            iterations[xx-1] = iter
            TotalTime[xx-1] = time.time() - TotalStart
            dim = [Velocity.dim(), Pressure.dim(), Magnetic.dim(),Lagrange.dim()]
    #
    #        ExactSolution = [u0,p0,b0,r0]
    #        errL2u[xx-1], errH1u[xx-1], errL2p[xx-1], errL2b[xx-1], errCurlb[xx-1], errL2r[xx-1], errH1r[xx-1] = Iter.Errors(XX,mesh,FSpaces,ExactSolution,order,dim, "DG")
    #
    #        if xx > 1:
    #            l2uorder[xx-1] =  np.abs(np.log2(errL2u[xx-2]/errL2u[xx-1]))
    #            H1uorder[xx-1] =  np.abs(np.log2(errH1u[xx-2]/errH1u[xx-1]))
    #
    #            l2porder[xx-1] =  np.abs(np.log2(errL2p[xx-2]/errL2p[xx-1]))
    #
    #            l2border[xx-1] =  np.abs(np.log2(errL2b[xx-2]/errL2b[xx-1]))
    #            Curlborder[xx-1] =  np.abs(np.log2(errCurlb[xx-2]/errCurlb[xx-1]))
    #
    #            l2rorder[xx-1] =  np.abs(np.log2(errL2r[xx-2]/errL2r[xx-1]))
    #            H1rorder[xx-1] =  np.abs(np.log2(errH1r[xx-2]/errH1r[xx-1]))




        import pandas as pd



    #    LatexTitles = ["l","DoFu","Dofp","V-L2","L2-order","V-H1","H1-order","P-L2","PL2-order"]
    #    LatexValues = np.concatenate((level,Velocitydim,Pressuredim,errL2u,l2uorder,errH1u,H1uorder,errL2p,l2porder), axis=1)
    #    LatexTable = pd.DataFrame(LatexValues, columns = LatexTitles)
    #    pd.set_option('precision',3)
    #    LatexTable = MO.PandasFormat(LatexTable,"V-L2","%2.4e")
    #    LatexTable = MO.PandasFormat(LatexTable,'V-H1',"%2.4e")
    #    LatexTable = MO.PandasFormat(LatexTable,"H1-order","%1.2f")
    #    LatexTable = MO.PandasFormat(LatexTable,'L2-order',"%1.2f")
    #    LatexTable = MO.PandasFormat(LatexTable,"P-L2","%2.4e")
    #    LatexTable = MO.PandasFormat(LatexTable,'PL2-order',"%1.2f")
    #    print LatexTable
    #
    #
    #    print "\n\n   Magnetic convergence"
    #    MagneticTitles = ["l","B DoF","R DoF","B-L2","L2-order","B-Curl","HCurl-order"]
    #    MagneticValues = np.concatenate((level,Magneticdim,Lagrangedim,errL2b,l2border,errCurlb,Curlborder),axis=1)
    #    MagneticTable= pd.DataFrame(MagneticValues, columns = MagneticTitles)
    #    pd.set_option('precision',3)
    #    MagneticTable = MO.PandasFormat(MagneticTable,"B-Curl","%2.4e")
    #    MagneticTable = MO.PandasFormat(MagneticTable,'B-L2',"%2.4e")
    #    MagneticTable = MO.PandasFormat(MagneticTable,"L2-order","%1.2f")
    #    MagneticTable = MO.PandasFormat(MagneticTable,'HCurl-order',"%1.2f")
    #    print MagneticTable
    #
    #
    #
    #
    #    import pandas as pd
    #



        print "\n\n   Iteration table"
        if IterType == "Full":
            IterTitles = ["l","DoF","AV solve Time","Total picard time","picard iterations","Av Outer its","Av Inner its",]
        else:
            IterTitles = ["l","DoF","AV solve Time","Total picard time","picard iterations","Av NS iters","Av M iters"]
        IterValues = np.concatenate((level,Wdim,SolTime,TotalTime,iterations,Mave,NSave),axis=1)
        IterTable= pd.DataFrame(IterValues, columns = IterTitles)
        if IterType == "Full":
            IterTable = MO.PandasFormat(IterTable,'Av Outer its',"%2.1f")
            IterTable = MO.PandasFormat(IterTable,'Av Inner its',"%2.1f")
        else:
            IterTable = MO.PandasFormat(IterTable,'Av NS iters',"%2.1f")
            IterTable = MO.PandasFormat(IterTable,'Av M iters',"%2.1f")
        print IterTable
        print " \n  Outer Tol:  ",OuterTol, "Inner Tol:   ", InnerTol
        
        IterTable.to_latex('Tables/IterType='+IterType+'_n='+str(m)+'_mu='+str(MU)+'_kappa='+str(kappa)+'_mu_m='+str(Mu_m)+'.tex')



        # # # if (ShowResultPlots == 'yes'):

    #    plot(u_k)
    #    plot(interpolate(u0,Velocity))
    #
    #    plot(p_k)
    #
    #    plot(interpolate(p0,Pressure))
    #
    #    plot(b_k)
    #    plot(interpolate(b0,Magnetic))
    #
    #    plot(r_k)
    #    plot(interpolate(r0,Lagrange))
    #
    #    interactive()

        interactive()
Пример #56
0
Файл: MHD.py Проект: wathen/PhD
            AA, bb = assemble_system(maxwell+ns+CoupleTerm, (Lmaxwell + Lns) - RHSform,  bcs)
            A,b = CP.Assemble(AA,bb)
            del AA
            F = assemble(fp)
            F = CP.Assemble(F)
            P = CP.Assemble(PP)
            # P = S.ExactPrecond(PP,Q,L,F,FSpaces)
            Mass = CP.Assemble(Q)

        uu = b.duplicate()

        OuterTol = 1e-6
        InnerTol = 1e-3

        tic()
        u,it1,it2 = S.solve(A,b,uu,P,[NS_is,M_is],FSpaces,IterType,OuterTol,InnerTol,Mass,L,F)
        time = toc()
        print time
        SolutionTime = SolutionTime +time
        print "Solve time >>>>>>", time
        print it1,it2
        NSits += it1
        Mits +=it2
        u, p, b, r, eps= Iter.PicardToleranceDecouple(u,x,FSpaces,dim,"2",iter)
        p.vector()[:] += - assemble(p*dx)/assemble(ones*dx)
        u_k.assign(u)
        p_k.assign(p)
        b_k.assign(b)
        r_k.assign(r)
        if eps > 100 and iter > 3:
            print 22222
Пример #57
0
class GUI(object):
    """description of class"""

    def __init__(self,master):
        # aanmaak list voor de ingelezen cirkels
        self.cirkels = []

        # de parent van deze GUI = root
        self.master = master
        
        # bottom en top frames om zo de layout wat te verbeteren
        self.top = Frame(master, bd=1,relief=SUNKEN,padx=1,pady=1)
        self.bottom = Frame(master, bd=1,relief=SUNKEN,padx=1,pady=1)
        self.top.pack(side=TOP,fill=BOTH, expand=True)
        self.bottom.pack(side=BOTTOM, fill=BOTH, expand=True)

        # top in nog meer frames opdelen links en rechts
        self.leftTOP = Frame(self.top, bd=1,relief=SUNKEN,padx=1,pady=1)
        self.rightTOP = Frame(self.top, bd=1,relief=SUNKEN,padx=1,pady=1)
        self.leftTOP.pack(side=LEFT,fill=BOTH, expand=True)
        self.rightTOP.pack(side=RIGHT,fill=BOTH, expand=True)

        # uitleg
        w = Label(self.rightTOP, text="Enter the path to to input file in the first field or use the browse input button"+"\n" +"Enter the path to the output file in the second field or use the browse output button" + "\n" + "push the START button to start processing")
        w.pack()

        # buttons 
        self.buttontext = StringVar()
        self.buttontext.set("START")
        self.startbutton = Button(master, textvariable=self.buttontext, command=self.clicked1,height = 2)
        
        self.buttontext1 = StringVar()
        self.buttontext1.set("Browse input")
        self.browsebutton = Button(master, textvariable=self.buttontext1,command=self.clicked2, height = 1)

        self.buttontext2 = StringVar()
        self.buttontext2.set("Browse output")
        self.browsebutton1 = Button(master, textvariable=self.buttontext2,command=self.clicked3, height = 1)
        
        self.startbutton.pack(in_= self.rightTOP)
        self.browsebutton.pack(in_= self.leftTOP)
        self.browsebutton1.pack(in_=self.leftTOP)

        self.inputframe = Frame(master,width=500, height=500, bd=1,relief=SUNKEN,padx=1,pady=1,bg="blue")
        self.inputframe.pack(in_= self.bottom, side = LEFT)
        
        self.outputframe = Frame(master,width=500, height=500, bd=1,relief=SUNKEN,padx=1,pady=1,bg="blue")
        self.outputframe.pack(in_= self.bottom, side = LEFT)

        #entry fields 
        self.entrytext = StringVar()
        self.inputEntry = Entry(master, textvariable=self.entrytext, width = 50).pack(in_= self.leftTOP)

        self.entrytext1 = StringVar()
        self.outputEntry = Entry(master, textvariable=self.entrytext1, width = 50).pack(in_= self.leftTOP)

    def output(self, path):
         if len(path) > 4 :
             file =  open(path,'w')
             if (self.algo == 3):
                 file.write("Dit Algoritme is niet ge"+"\i"+"mplementeerd")
                 file.close()
             else:
                 for inter in self.intersections[0]:
                     file.write(inter.to_string()+"\n")
                 file.write("\n" )
                 file.write("uitvoeringstijd in ms: " + str(self.intersections[1]))
                 file.close()


    def process(self,path):
        count = 0
        path = path.replace("\"", "")
        self.algo = 1
        for line in fileinput.input(files = (path)):
            if count == 0:
                 self.algo = int(line[0])
            else:
                if " " in line:
                    cir = line.split( ' ' , 2)
                    pos = Position( float(cir[0]), float(cir[1]))
                    cir = Circle( pos , float(cir [2]))
                    self.cirkels.append(cir)
            count = count + 1 
        self.solver = Solver(self.algo, self.cirkels)
        self.intersections = self.solver.find_intersect()
        self.intersections[1] = self.intersections[1]*1000

    def clicked1(self):
        self.process(self.entrytext.get())
        self.output(self.entrytext1.get())

        self.algoLabel = Label(self.master,text = "Het gebruikte algoritme is: " + str(self.algo))
        self.algoLabel.pack(in_= self.rightTOP)

        self.timeLabel = Label(self.master,text = "Het vinden van de snijpunten nam: " + str(self.intersections[1]) + " ms in beslag")
        self.timeLabel.pack(in_= self.rightTOP)

        cirkeltext = Text(self.inputframe)
        cirkeltext.insert(END,'Uw Cirkels:')
        cirkeltext.pack()

        fig = plt.gcf()
                
        count = 1
        for circle in self.cirkels:
            cirkeltext.insert(END,"\n" +str(count)+" => "+ circle.to_string())
            fig.gca().add_artist(circle.getPlot())
            count+=1

        intertext = Text(self.outputframe)
        intertext.insert(END,'De Snijpunten:')
        intertext.pack()
        
        count = 1
        for inter in self.intersections[0]:
            intertext.insert(END,"\n" +str(count)+" => "+ inter.to_string())
            count+=1
        self.cirkels.clear()
        self.intersections.clear()
        plt.show()
        self.master.update_idletasks()

    def clicked2(self):
        self.entrytext.set(askopenfilename())
    
    def clicked3(self):
        self.entrytext1.set(askopenfilename())

    def button_click(self, e):
        pass
Пример #58
0
def foo():
    m = 6
    mm = 5


    errL2u =np.zeros((m-1,1))
    errH1u =np.zeros((m-1,1))
    errL2p =np.zeros((m-1,1))
    errL2b =np.zeros((m-1,1))
    errCurlb =np.zeros((m-1,1))
    errL2r =np.zeros((m-1,1))
    errH1r =np.zeros((m-1,1))



    l2uorder =  np.zeros((m-1,1))
    H1uorder =np.zeros((m-1,1))
    l2porder =  np.zeros((m-1,1))
    l2border =  np.zeros((m-1,1))
    Curlborder =np.zeros((m-1,1))
    l2rorder =  np.zeros((m-1,1))
    H1rorder = np.zeros((m-1,1))

    NN = np.zeros((m-1,1))
    DoF = np.zeros((m-1,1))
    Velocitydim = np.zeros((m-1,1))
    Magneticdim = np.zeros((m-1,1))
    Pressuredim = np.zeros((m-1,1))
    Lagrangedim = np.zeros((m-1,1))
    Wdim = np.zeros((m-1,1))
    iterations = np.zeros((m-1,3*(mm-1)))
    SolTime = np.zeros((m-1,1))
    udiv = np.zeros((m-1,1))
    MU = np.zeros((m-1,1))
    level = np.zeros((m-1,1))
    NSave = np.zeros((m-1,1))
    Mave = np.zeros((m-1,1))
    TotalTime = np.zeros((m-1,1))
    KappaSave = np.zeros((mm-1,1))
    nn = 2

    dim = 2
    ShowResultPlots = 'yes'
    split = 'Linear'
    qq = -1
    MU[0]= 1e0
    kappa = 0.01
    qq = -1
    for yy in xrange(1,mm):
        kappa = kappa*10
        KappaSave[yy-1] = kappa
        IterTypes = ['Full','MD','CD']
        for kk in range(len(IterTypes)):
            qq += 1
            for xx in xrange(1,m):
                print xx
                level[xx-1] = xx+ 2
                nn = 2**(level[xx-1])



                # Create mesh and define function space
                nn = int(nn)
                NN[xx-1] = nn/2
                # parameters["form_compiler"]["quadrature_degree"] = 6
                # parameters = CP.ParameterSetup()
                mesh = UnitSquareMesh(nn,nn)

                order = 1
                parameters['reorder_dofs_serial'] = False
                Velocity = VectorFunctionSpace(mesh, "CG", order+1)
                Pressure = FunctionSpace(mesh, "CG", order)
                Magnetic = FunctionSpace(mesh, "N1curl", order)
                Lagrange = FunctionSpace(mesh, "CG", order)
                W = MixedFunctionSpace([Velocity, Pressure, Magnetic,Lagrange])
                # W = Velocity*Pressure*Magnetic*Lagrange
                Velocitydim[xx-1] = Velocity.dim()
                Pressuredim[xx-1] = Pressure.dim()
                Magneticdim[xx-1] = Magnetic.dim()
                Lagrangedim[xx-1] = Lagrange.dim()
                Wdim[xx-1] = W.dim()
                print "\n\nW:  ",Wdim[xx-1],"Velocity:  ",Velocitydim[xx-1],"Pressure:  ",Pressuredim[xx-1],"Magnetic:  ",Magneticdim[xx-1],"Lagrange:  ",Lagrangedim[xx-1],"\n\n"
                dim = [Velocity.dim(), Pressure.dim(), Magnetic.dim(), Lagrange.dim()]


                def boundary(x, on_boundary):
                    return on_boundary

                u0, p0,b0, r0, Laplacian, Advection, gradPres,CurlCurl, gradR, NS_Couple, M_Couple = ExactSol.MHD2D(4,1)


                bcu = DirichletBC(W.sub(0),u0, boundary)
                bcb = DirichletBC(W.sub(2),b0, boundary)
                bcr = DirichletBC(W.sub(3),r0, boundary)

                # bc = [u0,p0,b0,r0]
                bcs = [bcu,bcb,bcr]
                FSpaces = [Velocity,Pressure,Magnetic,Lagrange]


                (u, b, p, r) = TrialFunctions(W)
                (v, c, q, s) = TestFunctions(W)
                Mu_m =1e1
                MU = 1.0/1
            

                IterType = IterTypes[kk]
                Split = "No"
                Saddle = "No"
                Stokes = "No"

                F_NS = -MU*Laplacian+Advection+gradPres-kappa*NS_Couple
                if kappa == 0:
                    F_M = Mu_m*CurlCurl+gradR -kappa*M_Couple
                else:
                    F_M = Mu_m*kappa*CurlCurl+gradR -kappa*M_Couple
                params = [kappa,Mu_m,MU]


                # MO.PrintStr("Preconditioning MHD setup",5,"+","\n\n","\n\n")
                Hiptmairtol = 1e-5
                HiptmairMatrices = PrecondSetup.MagneticSetup(Magnetic, Lagrange, b0, r0, Hiptmairtol, params)


                MO.PrintStr("Setting up MHD initial guess",5,"+","\n\n","\n\n")
                u_k,p_k,b_k,r_k = common.InitialGuess(FSpaces,[u0,p0,b0,r0],[F_NS,F_M],params,HiptmairMatrices,1e-6,Neumann=Expression(("0","0")),options ="New", FS = "DG")
                #plot(p_k, interactive = True) 
                b_t = TrialFunction(Velocity)
                c_t = TestFunction(Velocity)
                #print assemble(inner(b,c)*dx).array().shape
                #print mat
                #ShiftedMass = assemble(inner(mat*b,c)*dx)
                #as_vector([inner(b,c)[0]*b_k[0],inner(b,c)[1]*(-b_k[1])])

                ones = Function(Pressure)
                ones.vector()[:]=(0*ones.vector().array()+1)
                # pConst = - assemble(p_k*dx)/assemble(ones*dx)
                p_k.vector()[:] += - assemble(p_k*dx)/assemble(ones*dx)
                x = Iter.u_prev(u_k,p_k,b_k,r_k)

                KSPlinearfluids, MatrixLinearFluids = PrecondSetup.FluidLinearSetup(Pressure, MU)
                kspFp, Fp = PrecondSetup.FluidNonLinearSetup(Pressure, MU, u_k)
                #plot(b_k)

                ns,maxwell,CoupleTerm,Lmaxwell,Lns = forms.MHD2D(mesh, W,F_M,F_NS, u_k,b_k,params,IterType,"DG",Saddle,Stokes)
                RHSform = forms.PicardRHS(mesh, W, u_k, p_k, b_k, r_k, params,"DG",Saddle,Stokes)

                bcu = DirichletBC(Velocity,Expression(("0.0","0.0")), boundary)
                bcb = DirichletBC(Magnetic,Expression(("0.0","0.0")), boundary)
                bcr = DirichletBC(Lagrange,Expression(("0.0")), boundary)
                bcs = [bcu,bcb,bcr]
                
                parameters['linear_algebra_backend'] = 'uBLAS'
                SetupType = 'Matrix'
                BC = MHDsetup.BoundaryIndices(mesh)
                
                eps = 1.0           # error measure ||u-u_k||
                tol = 1.0E-4     # tolerance
                iter = 0            # iteration counter
                maxiter = 40       # max no of iterations allowed
                SolutionTime = 0
                outer = 0
                # parameters['linear_algebra_backend'] = 'uBLAS'

                # FSpaces = [Velocity,Magnetic,Pressure,Lagrange]

                if IterType == "CD":
                    MO.PrintStr("Setting up PETSc "+SetupType,2,"=","\n","\n")
                    Alin = MHDsetup.Assemble(W,ns,maxwell,CoupleTerm,Lns,Lmaxwell,RHSform,bcs+BC, "Linear",IterType)
                    Fnlin,b = MHDsetup.Assemble(W,ns,maxwell,CoupleTerm,Lns,Lmaxwell,RHSform,bcs+BC, "NonLinear",IterType)
                    A = Fnlin+Alin
                    A,b = MHDsetup.SystemAssemble(FSpaces,A,b,SetupType,IterType)
                    u = b.duplicate()


                u_is = PETSc.IS().createGeneral(range(Velocity.dim()))
                NS_is = PETSc.IS().createGeneral(range(Velocity.dim()+Pressure.dim()))
                M_is = PETSc.IS().createGeneral(range(Velocity.dim()+Pressure.dim(),W.dim()))
                OuterTol = 1e-5
                InnerTol = 1e-5
                NSits =0
                Mits =0
                TotalStart =time.time()
                SolutionTime = 0
                while eps > tol  and iter < maxiter:
                    iter += 1
                    MO.PrintStr("Iter "+str(iter),7,"=","\n\n","\n\n")
                    AssembleTime = time.time()
                    if IterType == "CD":
                        MO.StrTimePrint("MHD CD RHS assemble, time: ", time.time()-AssembleTime)
                        b = MHDsetup.Assemble(W,ns,maxwell,CoupleTerm,Lns,Lmaxwell,RHSform,bcs+BC, "CD",IterType)
                    else:

                        MO.PrintStr("Setting up PETSc "+SetupType,2,"=","\n","\n")

#                        if iter == 1:
#                            Alin = MHDsetup.Assemble(W,ns,maxwell,CoupleTerm,Lns,Lmaxwell,RHSform,bcs+BC, "Linear",IterType)
#                            Fnlin,b = MHDsetup.Assemble(W,ns,maxwell,CoupleTerm,Lns,Lmaxwell,RHSform,bcs+BC, "NonLinear",IterType)
#                            A = Fnlin+Alin
#                            A,b = MHDsetup.SystemAssemble(FSpaces,A,b,SetupType,IterType)
#                            u = b.duplicate()
#                        else: 
#                            Fnline,b = MHDsetup.Assemble(W,ns,maxwell,CoupleTerm,Lns,Lmaxwell,RHSform,bcs+BC, "NonLinear",IterType)
#                            A = Fnlin+Alin
#                            A,b = MHDsetup.SystemAssemble(FSpaces,A,b,SetupType,IterType)
                        AA, bb = assemble_system(maxwell+ns+CoupleTerm, (Lmaxwell + Lns) - RHSform,  bcs)
                        A,b = CP.Assemble(AA,bb)
                    # if iter == 1:
                    MO.StrTimePrint("MHD total assemble, time: ", time.time()-AssembleTime)
                    
                    u = b.duplicate()
                    #A,Q
                    kspFp, Fp = PrecondSetup.FluidNonLinearSetup(Pressure, MU, u_k)
                    print "Inititial guess norm: ", u.norm()
                    if u.norm()>1e50:
                        iter = 10000
                        break
                    stime = time.time()
                    kspF = 0
                    u, mits,nsits = S.solve(A,b,u,params,W,'Direct',IterType,OuterTol,InnerTol,HiptmairMatrices,Hiptmairtol,KSPlinearfluids, Fp,kspF)
                    Soltime = time.time()- stime
                    Mits += mits
                    NSits += nsits
                    SolutionTime += Soltime
                    
                    u1, p1, b1, r1, eps= Iter.PicardToleranceDecouple(u,x,FSpaces,dim,"2",iter)
                    p1.vector()[:] += - assemble(p1*dx)/assemble(ones*dx)
                    u_k.assign(u1)
                    p_k.assign(p1)
                    b_k.assign(b1)
                    r_k.assign(r1)
                    uOld= np.concatenate((u_k.vector().array(),p_k.vector().array(),b_k.vector().array(),r_k.vector().array()), axis=0)
                    x = IO.arrayToVec(uOld)



                XX= np.concatenate((u_k.vector().array(),p_k.vector().array(),b_k.vector().array(),r_k.vector().array()), axis=0)

                iterations[xx-1,qq] = iter
                dim = [Velocity.dim(), Pressure.dim(), Magnetic.dim(),Lagrange.dim()]
    #
#        ExactSolution = [u0,p0,b0,r0]
#        errL2u[xx-1], errH1u[xx-1], errL2p[xx-1], errL2b[xx-1], errCurlb[xx-1], errL2r[xx-1], errH1r[xx-1] = Iter.Errors(XX,mesh,FSpaces,ExactSolution,order,dim, "DG")
#
#        if xx > 1:
#            l2uorder[xx-1] =  np.abs(np.log2(errL2u[xx-2]/errL2u[xx-1]))
#            H1uorder[xx-1] =  np.abs(np.log2(errH1u[xx-2]/errH1u[xx-1]))
#
#            l2porder[xx-1] =  np.abs(np.log2(errL2p[xx-2]/errL2p[xx-1]))
#
#            l2border[xx-1] =  np.abs(np.log2(errL2b[xx-2]/errL2b[xx-1]))
#            Curlborder[xx-1] =  np.abs(np.log2(errCurlb[xx-2]/errCurlb[xx-1]))
#
#            l2rorder[xx-1] =  np.abs(np.log2(errL2r[xx-2]/errL2r[xx-1]))
#            H1rorder[xx-1] =  np.abs(np.log2(errH1r[xx-2]/errH1r[xx-1]))
#
#
#
#
#    import pandas as pd
#
#
#
#    LatexTitles = ["l","DoFu","Dofp","V-L2","L2-order","V-H1","H1-order","P-L2","PL2-order"]
#    LatexValues = np.concatenate((level,Velocitydim,Pressuredim,errL2u,l2uorder,errH1u,H1uorder,errL2p,l2porder), axis=1)
#    LatexTable = pd.DataFrame(LatexValues, columns = LatexTitles)
#    pd.set_option('precision',3)
#    LatexTable = MO.PandasFormat(LatexTable,"V-L2","%2.4e")
#    LatexTable = MO.PandasFormat(LatexTable,'V-H1',"%2.4e")
#    LatexTable = MO.PandasFormat(LatexTable,"H1-order","%1.2f")
#    LatexTable = MO.PandasFormat(LatexTable,'L2-order',"%1.2f")
#    LatexTable = MO.PandasFormat(LatexTable,"P-L2","%2.4e")
#    LatexTable = MO.PandasFormat(LatexTable,'PL2-order',"%1.2f")
#    print LatexTable
#
#
#    print "\n\n   Magnetic convergence"
#    MagneticTitles = ["l","B DoF","R DoF","B-L2","L2-order","B-Curl","HCurl-order"]
#    MagneticValues = np.concatenate((level,Magneticdim,Lagrangedim,errL2b,l2border,errCurlb,Curlborder),axis=1)
#    MagneticTable= pd.DataFrame(MagneticValues, columns = MagneticTitles)
#    pd.set_option('precision',3)
#    MagneticTable = MO.PandasFormat(MagneticTable,"B-Curl","%2.4e")
#    MagneticTable = MO.PandasFormat(MagneticTable,'B-L2',"%2.4e")
#    MagneticTable = MO.PandasFormat(MagneticTable,"L2-order","%1.2f")
#    MagneticTable = MO.PandasFormat(MagneticTable,'HCurl-order',"%1.2f")
#    print MagneticTable
#



    import pandas as pd

    print iterations.shape[1]

    iter = ["P","MD","CD"]
    IterTitles = ["l","DoF"]
    for i in range(iterations.shape[1]/3):
        IterTitles += iter
    print IterTitles
    IterValues = np.concatenate((level,Wdim,iterations),axis=1)
    IterTable= pd.DataFrame(IterValues, columns = IterTitles)
    print IterTable.to_latex()
    print " \n  Outer Tol:  ",OuterTol, "Inner Tol:   ", InnerTol

    print KappaSave


    # # # if (ShowResultPlots == 'yes'):

#    plot(u_k)
#    plot(interpolate(u0,Velocity))
#
#    plot(p_k)
#
#    plot(interpolate(p0,Pressure))
#
#    plot(b_k)
#    plot(interpolate(b0,Magnetic))
#
#    plot(r_k)
#    plot(interpolate(r0,Lagrange))
#
#    interactive()

    interactive()
Пример #59
0
#===============================================================================
Zb=np.array([
[0.166666676666666,-0.0833333333333333,0,0],
[-0.0833333333333333,0.333333333333333,-0.0833333333333333,0],
[0,-0.0833333333333333,0.166666676666666,0],
[0,0,0,0.00000005]])


Yb=np.linalg.inv(Zb)


F=np.zeros((4,1))
F[3,0]=2500

Ac=np.array([
[-1,-1,0,0],
[0,1,-1,0],
[1,0,0,1],
[0,0,1,-1]])

B=np.array([
[-1,1,1,1]])
B=B.T


flux_nodal=Solver.solve_nodal_circuit(Ac,Yb, F)
#Bl,tree,co_tree=Solver.welsch(Ac)
#Bl=Bl.T
#flux_Bl=Solver.solve_mesh(Bl,Zb,F)
#flux_B=Solver.solve_mesh(B,Zb,F)