Ejemplo n.º 1
0
def project_test(func):
    if isinstance(func, backend.Function):
        V = func.function_space()
        u = backend.TrialFunction(V)
        v = backend.TestFunction(V)
        M = backend.assemble(backend.inner(u, v) * backend.dx)
        proj = backend.Function(V)
        backend.solve(M, proj.vector(), func.vector())
        return proj
    else:
        return func
Ejemplo n.º 2
0
def project_test(func):
    if isinstance(func, backend.Function):
        V = func.function_space()
        u = backend.TrialFunction(V)
        v = backend.TestFunction(V)
        M = backend.assemble(backend.inner(u, v)*backend.dx)
        proj = backend.Function(V)
        backend.solve(M, proj.vector(), func.vector())
        return proj
    else:
        return func
Ejemplo n.º 3
0
def annotate_split(bigfn, idx, smallfn, bcs):
    fn_space = smallfn.function_space().collapse()
    test = backend.TestFunction(fn_space)
    trial = backend.TrialFunction(fn_space)
    eq_lhs = backend.inner(test, trial)*backend.dx

    diag_name = "Split:%s:" % idx + hashlib.md5(str(eq_lhs) + "split" + str(smallfn) + str(bigfn) + str(idx) + str(random.random())).hexdigest()

    diag_deps = []
    diag_block = libadjoint.Block(diag_name, dependencies=diag_deps, test_hermitian=backend.parameters["adjoint"]["test_hermitian"], test_derivative=backend.parameters["adjoint"]["test_derivative"])

    solving.register_initial_conditions([(bigfn, adjglobals.adj_variables[bigfn])], linear=True, var=None)

    var = adjglobals.adj_variables.next(smallfn)
    frozen_expressions_dict = expressions.freeze_dict()

    def diag_assembly_cb(dependencies, values, hermitian, coefficient, context):
        '''This callback must conform to the libadjoint Python block assembly
        interface. It returns either the form or its transpose, depending on
        the value of the logical hermitian.'''

        assert coefficient == 1

        expressions.update_expressions(frozen_expressions_dict)
        value_coeffs=[v.data for v in values]
        eq_l = eq_lhs

        if hermitian:
            adjoint_bcs = [utils.homogenize(bc) for bc in bcs if isinstance(bc, backend.DirichletBC)] + [bc for bc in bcs if not isinstance(bc, backend.DirichletBC)]
            if len(adjoint_bcs) == 0: adjoint_bcs = None
            return (adjlinalg.Matrix(backend.adjoint(eq_l), bcs=adjoint_bcs), adjlinalg.Vector(None, fn_space=fn_space))
        else:
            return (adjlinalg.Matrix(eq_l, bcs=bcs), adjlinalg.Vector(None, fn_space=fn_space))
    diag_block.assemble = diag_assembly_cb

    rhs = SplitRHS(test, bigfn, idx)

    eqn = libadjoint.Equation(var, blocks=[diag_block], targets=[var], rhs=rhs)

    cs = adjglobals.adjointer.register_equation(eqn)
    solving.do_checkpoint(cs, var, rhs)

    if backend.parameters["adjoint"]["fussy_replay"]:
        mass = eq_lhs
        smallfn_massed = backend.Function(fn_space)
        backend.solve(mass == backend.action(mass, smallfn), smallfn_massed)
        assert False, "No idea how to assign to a subfunction yet .. "
        #assignment.dolfin_assign(bigfn, smallfn_massed)

    if backend.parameters["adjoint"]["record_all"]:
        smallfn_record = backend.Function(fn_space)
        assignment.dolfin_assign(smallfn_record, smallfn)
        adjglobals.adjointer.record_variable(var, libadjoint.MemoryStorage(adjlinalg.Vector(smallfn_record)))
Ejemplo n.º 4
0
    def _forward_solve(self, lhs, rhs, func, bcs, **kwargs):
        if self.assemble_system:
            A, b = backend.assemble_system(lhs, rhs, bcs)
        else:
            A = backend.assemble(lhs)
            b = backend.assemble(rhs)
            [bc.apply(A, b) for bc in bcs]

        if self.ident_zeros_tol is not None:
            A.ident_zeros(self.ident_zeros_tol)

        backend.solve(A, func.vector(), b, *self.forward_args,
                      **self.forward_kwargs)
        return func
Ejemplo n.º 5
0
def main():
    #Generate 4 kartu
    listCards = generateCards() #listCard[suit][num]

    listNb = []
    for x in listCards:
        listNb.append(x[1])

    #Sort descending
    sortedCards = sorted(listCards, key=lambda x:x[1], reverse=True)
    listNb = []
    for x in sortedCards:
        listNb.append(x[1])

    op = engine.solusiOp(listNb, listOp)

    solusi = engine.solve(listNb, listOp)

    strSolusi = ''.join(solusi)
    
    if eval(strSolusi) == 24:
        print('Solusi ditemukan')
        print(strSolusi)
    else:
        print('Solusi tidak ditemukan')
        print(strSolusi + ' = ' + str(eval(strSolusi)))

    cgui.cardGUI(listCards, op, strSolusi)

    return 0
Ejemplo n.º 6
0
def wrap_solve(A, x, b, solver_parameters):
    '''Make my own solve, since solve(A, x, b) can't handle other solver_parameters
    like linear solver tolerances'''

    # Comment. Why does list_lu_solver_methods() not return, a, uhm, list?
    lu_solvers = ["lu", "mumps", "umfpack", "spooles", "superlu", "superlu_dist", "pastix", "petsc"]

    if backend.__name__ == "dolfin":
        # dolfin's API for expressing linear_solvers and preconditioners has changed in 1.4. Here I try
        # to support both.
        method = solver_parameters.get("linear_solver", "default")
        pc = solver_parameters.get("preconditioner", "default")

        if "nonlinear_solver" in solver_parameters or "newton_solver" in solver_parameters:
            nonlinear_solver = solver_parameters.get("nonlinear_solver", "newton")
            sub_options = nonlinear_solver + "_solver"

            if sub_options in solver_parameters:
                newton_options = solver_parameters[sub_options]

                method = newton_options.get("linear_solver", method)
                pc = newton_options.get("preconditioner", pc)

        # We get passed in a Function, turn it into a Vector
        x = x.vector()
        if method in lu_solvers or method == "default":
            if method == "lu": method = "default"
            solver = backend.LUSolver(method)

            if "lu_solver" in solver_parameters:
                solver.parameters.update(solver_parameters["lu_solver"])

            solver.solve(A, x, b)
            return
        else:
            solver = backend.KrylovSolver(method, pc)

            if "krylov_solver" in solver_parameters:
                solver.parameters.update(solver_parameters["krylov_solver"])

            solver.solve(A, x, b)
            return
    else:
        backend.solve(A, x, b, solver_parameters=solver_parameters)
        return
Ejemplo n.º 7
0
def search():
    url = variable1.get()
    result = 'Error'
    try:
        result = backend.solve(url)
    except:
        pass
    print(result)
    labelvar.set(result)
    return ''
Ejemplo n.º 8
0
    def place(self, val):
        row, col = self.selected
        if self.cubes[row][col].value == 0:
            self.cubes[row][col].set(val)
            self.update_model()

            if valid(self.model, val, (row, col)) and solve(self.model):
                return True
            else:
                self.cubes[row][col].set(0)
                self.cubes[row][col].set_temp(0)
                self.update_model()
                return False
Ejemplo n.º 9
0
def solve(*args, **kwargs):
    """This solve routine wraps the real Dolfin solve call. Its purpose is to annotate the model,
    recording what solves occur and what forms are involved, so that the adjoint and tangent linear models may be
    constructed automatically by pyadjoint.

    To disable the annotation, just pass :py:data:`annotate=False` to this routine, and it acts exactly like the
    Dolfin solve call. This is useful in cases where the solve is known to be irrelevant or diagnostic
    for the purposes of the adjoint computation (such as projecting fields to other function spaces
    for the purposes of visualisation).

    The overloaded solve takes optional callback functions to extract adjoint solutions.
    All of the callback functions follow the same signature, taking a single argument of type Function.

    Keyword Args:
        adj_cb (function, optional): callback function supplying the adjoint solution in the interior.
            The boundary values are zero.
        adj_bdy_cb (function, optional): callback function supplying the adjoint solution on the boundary.
            The interior values are not guaranteed to be zero.
        adj2_cb (function, optional): callback function supplying the second-order adjoint solution in the interior.
            The boundary values are zero.
        adj2_bdy_cb (function, optional): callback function supplying the second-order adjoint solution on
            the boundary. The interior values are not guaranteed to be zero.

    """
    ad_block_tag = kwargs.pop("ad_block_tag", None)
    annotate = annotate_tape(kwargs)
    if annotate:
        tape = get_working_tape()

        solve_block_type = SolveVarFormBlock
        if not isinstance(args[0], ufl.equation.Equation):
            solve_block_type = SolveLinearSystemBlock

        sb_kwargs = solve_block_type.pop_kwargs(kwargs)
        sb_kwargs.update(kwargs)
        block = solve_block_type(*args, ad_block_tag=ad_block_tag, **sb_kwargs)
        tape.add_block(block)

    with stop_annotating():
        output = backend.solve(*args, **kwargs)

    if annotate:
        if hasattr(args[1], "create_block_variable"):
            block_variable = args[1].create_block_variable()
        else:
            block_variable = args[1].function.create_block_variable()
        block.add_output(block_variable)

    return output
Ejemplo n.º 10
0
def solve(*args, **kwargs):
    """This solve routine wraps the real Dolfin solve call. Its purpose is to annotate the model,
    recording what solves occur and what forms are involved, so that the adjoint and tangent linear models may be
    constructed automatically by libadjoint.

    To disable the annotation, just pass :py:data:`annotate=False` to this routine, and it acts exactly like the
    Dolfin solve call. This is useful in cases where the solve is known to be irrelevant or diagnostic
    for the purposes of the adjoint computation (such as projecting fields to other function spaces
    for the purposes of visualisation)."""

    # First, decide if we should annotate or not.
    to_annotate = utils.to_annotate(kwargs.pop("annotate", None))
    if to_annotate:
        linear = annotate(*args, **kwargs)

    # Avoid recursive annotation
    flag = misc.pause_annotation()
    try:
        ret = backend.solve(*args, **kwargs)
    except:
        raise
    finally:
        misc.continue_annotation(flag)

    if to_annotate:
        # Finally, if we want to record all of the solutions of the real forward model
        # (for comparison with a libadjoint replay later),
        # then we should record the value of the variable we just solved for.
        if backend.parameters["adjoint"]["record_all"]:
            if isinstance(args[0], ufl.classes.Equation):
                unpacked_args = compatibility._extract_args(*args, **kwargs)
                u = unpacked_args[1]
                adjglobals.adjointer.record_variable(
                    adjglobals.adj_variables[u], libadjoint.MemoryStorage(adjlinalg.Vector(u))
                )
            elif isinstance(args[0], compatibility.matrix_types()):
                u = args[1].function
                adjglobals.adjointer.record_variable(
                    adjglobals.adj_variables[u], libadjoint.MemoryStorage(adjlinalg.Vector(u))
                )
            else:
                raise libadjoint.exceptions.LibadjointErrorInvalidInputs("Don't know how to record, sorry")

    return ret
Ejemplo n.º 11
0
def main():
    #Membaca file input
    Nb = f.openFile(sys.argv[1])

    #Mengubah string menjadi list of char
    listNb = Nb.split(' ')

    #Mengubah list of char menjadi list of integer sesuai nilai kartu
    listNb = engine.cardsToNb(listNb)

    strSolusi = ''.join(engine.solve(listNb, listOp))
    #Validasi apakah solusi bernilai 24
    if eval(strSolusi) == 24:
        print(strSolusi)
    else:
        print('Solusi tidak ditemukan.')

    #Mengeluarkan file output
    f.writeFile(sys.argv[2], strSolusi)

    return 0
Ejemplo n.º 12
0
 def _forward_solve(self, lhs, rhs, func, bcs):
     backend.solve(lhs == rhs, func, bcs, *self.forward_args,
                   **self.forward_kwargs)
     return func
Ejemplo n.º 13
0
import backend

print('Input 4 numbers separated by space, then press enter:')
while (1):
    print(backend.solve(input().split(' ')))
Ejemplo n.º 14
0
import backend
import sys

r = open(sys.argv[1], "r")
w = open(sys.argv[2], "w")

for l in r:
	w.write(backend.solve(l.split(' ')))
	w.write("\n")
Ejemplo n.º 15
0
def main():

    # initialize the pg module
    pg.init()
    pg.font.init()

    # load and set the logo
    pg.display.set_caption("24 Solver - Greedy")

    # create a surface on screen that has the size of 240 x 180
    screen = pg.display.set_mode((720, 480))

    # load asset
    card = pg.transform.smoothscale(pg.image.load("ass/cards/blue_back.png"),
                                    (140, 210))
    # bgd_image = pg.image.load("ass/cards/back_cards-07.png")

    # blit image(s) to screen
    # screen.blit(bgd_image, (0, 0))  # first background
    # instead of blitting the background image you could fill it
    # (uncomment the next line to do so)
    screen.fill(pg.Color('gray25'))

    screen.blit(pg.transform.rotate(card, 90), (50, 300))

    # update the screen to make the changes visible (fullscreen update)
    pg.display.flip()

    # define a variable to control the main loop
    running = True

    # array of cards ID, div by 13 = 0 clubs; 1 diamond; 2 heart; 3 spades
    card_arr = [i + 1 for i in range(52)]

    # shuffle card
    for i in range(52):
        ran = random.randint(0, 51)
        card_arr[i], card_arr[ran] = card_arr[ran], card_arr[i]

    current_num = []
    min_num = []

    # main loop
    while running:
        # event handling, gets all event from the eventqueue
        for event in pg.event.get():
            # only do something if the event if of type QUIT
            keyinput = pg.key.get_pressed()
            # exit on corner 'x' click or escape key press
            if keyinput[pg.K_ESCAPE]:
                raise SystemExit
            elif event.type == pg.QUIT:
                # change the value to False, to exit the main loop
                running = False

            if event.type == pg.MOUSEBUTTONDOWN:
                x, y = event.pos
                card_pos = pg.Rect(50, 300, 210, 140)

                if card_pos.collidepoint(x, y):
                    if not card_arr:
                        running = False
                        break

                    for i in range(4):
                        current_num.append(card_arr.pop())
                        min_num.append(current_num[i])
                        while min_num[i] > 13:
                            min_num[i] -= 13

                    myfont = pg.font.SysFont('Roboto', 24)
                    mystr = backend.solve(min_num)
                    textsurface = myfont.render(
                        "Expression: " + mystr + " = " +
                        str(round(eval(mystr), 2)), True, pg.Color('grey80'))
                    screen.fill(pg.Color("gray25"), (300, 330, 350, 40))
                    screen.blit(textsurface, (300, 330))

                    myfont = pg.font.SysFont('Roboto', 16)
                    mystr = str(len(card_arr))
                    textsurface = myfont.render("Card(s) remaining: " + mystr,
                                                True, pg.Color('grey80'))
                    screen.fill(pg.Color("gray25"), (300, 370, 350, 40))
                    screen.blit(textsurface, (300, 370))

                    screen.blit(
                        pg.transform.smoothscale(
                            pg.image.load("ass/cards/" +
                                          str(current_num.pop(0)) + ".png"),
                            (140, 210)), (50, 50))
                    screen.blit(
                        pg.transform.smoothscale(
                            pg.image.load("ass/cards/" +
                                          str(current_num.pop(0)) + ".png"),
                            (140, 210)), (210, 50))
                    screen.blit(
                        pg.transform.smoothscale(
                            pg.image.load("ass/cards/" +
                                          str(current_num.pop(0)) + ".png"),
                            (140, 210)), (370, 50))
                    screen.blit(
                        pg.transform.smoothscale(
                            pg.image.load("ass/cards/" +
                                          str(current_num.pop(0)) + ".png"),
                            (140, 210)), (530, 50))
                    pg.display.flip()

                    min_num = []
Ejemplo n.º 16
0
def annotate_split(bigfn, idx, smallfn, bcs):
    fn_space = smallfn.function_space().collapse()
    test = backend.TestFunction(fn_space)
    trial = backend.TrialFunction(fn_space)
    eq_lhs = backend.inner(test, trial) * backend.dx

    key = "{}split{}{}{}{}".format(eq_lhs, smallfn, bigfn, idx,
                                   random.random()).encode('utf8')
    diag_name = "Split:%s:" % idx + hashlib.md5(key).hexdigest()

    diag_deps = []
    diag_block = libadjoint.Block(
        diag_name,
        dependencies=diag_deps,
        test_hermitian=backend.parameters["adjoint"]["test_hermitian"],
        test_derivative=backend.parameters["adjoint"]["test_derivative"])

    solving.register_initial_conditions(
        [(bigfn, adjglobals.adj_variables[bigfn])], linear=True, var=None)

    var = adjglobals.adj_variables.next(smallfn)
    frozen_expressions_dict = expressions.freeze_dict()

    def diag_assembly_cb(dependencies, values, hermitian, coefficient,
                         context):
        '''This callback must conform to the libadjoint Python block assembly
        interface. It returns either the form or its transpose, depending on
        the value of the logical hermitian.'''

        assert coefficient == 1

        expressions.update_expressions(frozen_expressions_dict)
        value_coeffs = [v.data for v in values]
        eq_l = eq_lhs

        if hermitian:
            adjoint_bcs = [
                utils.homogenize(bc)
                for bc in bcs if isinstance(bc, backend.DirichletBC)
            ] + [bc for bc in bcs if not isinstance(bc, backend.DirichletBC)]
            if len(adjoint_bcs) == 0: adjoint_bcs = None
            return (adjlinalg.Matrix(backend.adjoint(eq_l), bcs=adjoint_bcs),
                    adjlinalg.Vector(None, fn_space=fn_space))
        else:
            return (adjlinalg.Matrix(eq_l, bcs=bcs),
                    adjlinalg.Vector(None, fn_space=fn_space))

    diag_block.assemble = diag_assembly_cb

    rhs = SplitRHS(test, bigfn, idx)

    eqn = libadjoint.Equation(var, blocks=[diag_block], targets=[var], rhs=rhs)

    cs = adjglobals.adjointer.register_equation(eqn)
    solving.do_checkpoint(cs, var, rhs)

    if backend.parameters["adjoint"]["fussy_replay"]:
        mass = eq_lhs
        smallfn_massed = backend.Function(fn_space)
        backend.solve(mass == backend.action(mass, smallfn), smallfn_massed)
        assert False, "No idea how to assign to a subfunction yet .. "
        #assignment.dolfin_assign(bigfn, smallfn_massed)

    if backend.parameters["adjoint"]["record_all"]:
        smallfn_record = backend.Function(fn_space)
        assignment.dolfin_assign(smallfn_record, smallfn)
        adjglobals.adjointer.record_variable(
            var, libadjoint.MemoryStorage(adjlinalg.Vector(smallfn_record)))
Ejemplo n.º 17
0
 def _assembled_solve(self, lhs, rhs, func, bcs, **kwargs):
     for bc in bcs:
         bc.apply(rhs)
     backend.solve(lhs, func.vector(), rhs, **kwargs)
     return func