Ejemplo n.º 1
0
    def __init__(self, problem, tag, *args, **kwargs):
        self.problem = problem
        self.tag = tag
        opts = PETSc.Options()

        # Timestepping solver
        self.ts = PETSc.TS().create()
        self.ts_its = 0

        ts = self.ts
        ts.setIFunction(problem.evalFunction, problem.b_petsc)
        ts.setIJacobian(problem.evalJacobian, problem.A_petsc)
        ts.setSolution(problem.xx)
        ts.computeIFunction(0.0, problem.xx, problem.xxdot, problem.b_petsc)
        ts.computeIJacobian(0.0, problem.xx, problem.xxdot, 1.0,
                            problem.A_petsc)
        ts.setMonitor(TSMonitor(self))

        # Nonlinear solver
        self.snes = ts.getSNES()
        self.snes_its = 0
        self.snes.setMonitor(SNESMonitor(self))

        # Linear solver
        self.ksp = self.snes.getKSP()
        self.ksp_its = 0
        self.ksp.setMonitor(KSPMonitor(self))

        # and preconditioner
        self.pc = self.ksp.getPC()
Ejemplo n.º 2
0
def run_test(nx, ny, nz, samples, plot=False):
    ts = PETSc.TS().create()
    ts.setType('theta')
    ts.setTheta(1.0)
    ts.setTimeStep(0.01)
    ts.setTime(0.0)
    ts.setMaxTime(1.0)
    ts.setMaxSteps(10)
    eft = PETSc.TS.ExactFinalTime.STEPOVER
    ts.setExactFinalTime(eft)

    x = PETSc.Vec().createSeq(nx * ny * nz)
    ts.setSolution(x)
    app = AppCtx(nx, ny, nz)
    f = PETSc.Vec().createSeq(nx * ny * nz)
    ts.setIFunction(app.formFunction, f)
    ts.snes.setUseMF(1)
    ts.snes.ksp.setType('cg')
    ts.setFromOptions()
    ts.setUp()

    wt = 1e300
    for i in range(samples):
        app.formInitial(0, x)
        t1 = PETSc.Log.getTime()
        ts.solve(x)
        t2 = PETSc.Log.getTime()
        wt = min(wt, t2 - t1)

    if plot and pylab:
        app.plot(ts.time, x)

    return wt
Ejemplo n.º 3
0
 def setUp(self):
     self.ts = PETSc.TS()
     self.ts.createPython(MyTS(), comm=PETSc.COMM_SELF)
     ctx = self.ts.getPythonContext()
     self.assertEqual(getrefcount(ctx), 3)
     self.assertEqual(ctx.log['create'], 1)
     self.nsolve = 0
Ejemplo n.º 4
0
 def setUp(self):
     self.ts = PETSc.TS().create(PETSc.COMM_SELF)
     ptype = PETSc.TS.ProblemType.NONLINEAR
     self.ts.setProblemType(ptype)
     self.ts.setType(self.TYPE)
     if PETSc.ScalarType().dtype.char in 'fF':
         snes = self.ts.getSNES()
         snes.setTolerances(rtol=1e-6)
Ejemplo n.º 5
0
def help(args=None):
    import sys, shlex
    # program name
    try:
        prog = sys.argv[0]
    except Exception:
        prog = getattr(sys, 'executable', 'python')
    # arguments
    if args is None:
        args = sys.argv[1:]
    elif isinstance(args, str):
        args = shlex.split(args)
    else:
        args = [str(a) for a in args]
    # import and initialize
    import petsc4py
    petsc4py.init([prog, '-help'] + args)
    from petsc4py import PETSc
    # help dispatcher
    COMM = PETSc.COMM_SELF
    if 'vec' in args:
        vec = PETSc.Vec().create(comm=COMM)
        vec.setSizes(0)
        vec.setFromOptions()
        vec.destroy()
    if 'mat' in args:
        mat = PETSc.Mat().create(comm=COMM)
        mat.setSizes([0, 0])
        mat.setFromOptions()
        mat.destroy()
    if 'pc' in args:
        pc = PETSc.PC().create(comm=COMM)
        pc.setFromOptions()
        pc.destroy()
    if 'ksp' in args:
        ksp = PETSc.KSP().create(comm=COMM)
        ksp.setFromOptions()
        ksp.destroy()
    if 'snes' in args:
        snes = PETSc.SNES().create(comm=COMM)
        snes.setFromOptions()
        snes.destroy()
    if 'ts' in args:
        ts = PETSc.TS().create(comm=COMM)
        ts.setFromOptions()
        ts.destroy()
    if 'tao' in args:
        tao = PETSc.TAO().create(comm=COMM)
        tao.setFromOptions()
        tao.destroy()
    if 'dmda' in args:
        dmda = PETSc.DMDA().create(comm=COMM)
        dmda.setFromOptions()
        dmda.destroy()
    if 'dmplex' in args:
        dmplex = PETSc.DMPlex().create(comm=COMM)
        dmplex.setFromOptions()
        dmplex.destroy()
Ejemplo n.º 6
0
 def setUp(self):
     self.ts = PETSc.TS()
     self.ts.createPython(MyTS(), comm=PETSc.COMM_SELF)
     eft = PETSc.TS.ExactFinalTime.STEPOVER
     self.ts.setExactFinalTime(eft)
     ctx = self.ts.getPythonContext()
     self.assertEqual(getrefcount(ctx), 3)
     self.assertEqual(ctx.log['create'], 1)
     self.nsolve = 0
Ejemplo n.º 7
0
        def __init__(self,
                     problem,
                     solution,
                     solution_dot,
                     solution_dot_dot=None):
            self.problem = problem
            self.solution = solution
            self.solution_dot = solution_dot
            self.solution_dot_dot = solution_dot_dot
            # Create PETSc's TS object
            self.ts = PETSc.TS().create(wrapping.get_mpi_comm(solution))
            # ... and associate residual and jacobian
            assert problem.time_order in (1, 2)
            if problem.time_order == 1:
                self.ts.setIFunction(
                    problem.residual_vector_eval,
                    wrapping.to_petsc4py(problem.residual_vector))
                self.ts.setIJacobian(
                    problem.jacobian_matrix_eval,
                    wrapping.to_petsc4py(problem.jacobian_matrix))
            elif problem.time_order == 2:
                self.ts.setI2Function(
                    problem.residual_vector_eval,
                    wrapping.to_petsc4py(problem.residual_vector))
                self.ts.setI2Jacobian(
                    problem.jacobian_matrix_eval,
                    wrapping.to_petsc4py(problem.jacobian_matrix))
            else:
                raise ValueError(
                    "Invalid time order in PETScTSIntegrator.__init__().")
            # ... and monitor
            self.ts.setMonitor(problem.monitor)
            # Set sensible default values to parameters
            default_parameters = {
                "exact_final_time": "stepover",
                "integrator_type": "beuler",
                "problem_type": "linear",
                "report": True
            }
            self.set_parameters(default_parameters)
            # TODO since PETSc 3.8 TSAlpha2 is not working properly in the linear case without attaching a fake monitor
            if self.problem.time_order == 2:

                def monitor(snes, it, fgnorm):
                    pass

                self.ts.getSNES().setMonitor(monitor)
Ejemplo n.º 8
0
def help(args=None):
    import sys, shlex
    # program name
    try:
        prog = sys.argv[0]
    except Exception:
        prog = getattr(sys, 'executable', 'python')
    if args is None:
        args = sys.argv[1:]
    elif isinstance(args, str):
        args = shlex.split(args)
    else:
        args = [str(a) for a in args]
    import petsc4py
    petsc4py.init([prog, '-help'] + args)
    from petsc4py import PETSc
    COMM = PETSc.COMM_SELF
    if 'vec' in args:
        vec = PETSc.Vec().create(comm=COMM)
        vec.setSizes(0)
        vec.setFromOptions()
        del vec
    if 'mat' in args:
        mat = PETSc.Mat().create(comm=COMM)
        mat.setSizes([0, 0])
        mat.setFromOptions()
        del mat
    if 'ksp' in args:
        ksp = PETSc.KSP().create(comm=COMM)
        ksp.setFromOptions()
        del ksp
    if 'pc' in args:
        pc = PETSc.PC().create(comm=COMM)
        pc.setFromOptions()
        del pc
    if 'snes' in args:
        snes = PETSc.SNES().create(comm=COMM)
        snes.setFromOptions()
        del snes
    if 'ts' in args:
        ts = PETSc.TS().create(comm=COMM)
        ts.setFromOptions()
        del ts
    if 'da' in args:
        da = PETSc.DA().create(comm=COMM)
        da.setFromOptions()
        del da
Ejemplo n.º 9
0
 def __init__(self, problem, solution, solution_dot):
     self.solution = solution
     self.solution_dot = solution_dot
     # Create PETSc's TS object
     self.ts = PETSc.TS().create(wrapping.get_mpi_comm(solution))
     # ... and associate residual and jacobian
     self.ts.setIFunction(problem.residual_vector_eval, wrapping.to_petsc4py(problem.residual_vector))
     self.ts.setIJacobian(problem.jacobian_matrix_eval, wrapping.to_petsc4py(problem.jacobian_matrix))
     self.monitor = _Monitor(self.ts)
     self.ts.setMonitor(self.monitor)
     # Set sensible default values to parameters
     default_parameters = {
         "exact_final_time": "stepover",
         "integrator_type": "beuler",
         "problem_type": "linear",
         "report": True
     }
     self.set_parameters(default_parameters)
 def __init__(self, problem, solution, solution_dot):
     self.solution = solution
     self.solution_dot = solution_dot
     # Create PETSc's TS object
     self.ts = PETSc.TS().create(
         solution.block_function_space().mesh().mpi_comm())
     # ... and associate residual and jacobian
     self.ts.setIFunction(problem.residual_vector_eval,
                          as_backend_type(problem.residual_vector).vec())
     self.ts.setIJacobian(problem.jacobian_matrix_eval,
                          as_backend_type(problem.jacobian_matrix).mat())
     self.monitor = _Monitor(self.ts)
     self.ts.setMonitor(self.monitor)
     # Set sensible default values to parameters
     default_parameters = {
         "exact_final_time": "stepover",
         "integrator_type": "beuler",
         "problem_type": "linear",
         "report": True
     }
     self.set_parameters(default_parameters)
Ejemplo n.º 11
0
def acoustics(kernel_language='Python',
              petscPlot=False,
              iplot=False,
              htmlplot=False,
              myplot=False,
              outdir='./_output',
              sclaw=False,
              **kwargs):
    import numpy as np
    """
    1D acoustics example.
    """

    from petclaw.patch import Patch
    from petclaw.patch import Dimension
    from pyclaw.solution import Solution
    from pyclaw.controller import Controller
    from petclaw import plot

    petscts = kwargs.get('petscts', False)

    # Initialize patch and solution
    xmin = 0.0
    xmax = 1.0
    ncells = kwargs.get('ncells', 100)
    x = Dimension('x', xmin, xmax, ncells, bc_lower=2, bc_upper=2)
    patch = Patch(x)
    rho = 1.0
    bulk = 1.0
    patch.problem_data['rho'] = rho
    patch.problem_data['bulk'] = bulk
    patch.problem_data['zz'] = np.sqrt(rho * bulk)
    patch.problem_data['cc'] = np.sqrt(rho / bulk)
    from classic1 import cparam
    for key, value in patch.problem_data.iteritems():
        setattr(cparam, key, value)
    patch.num_eqn = 2
    if sclaw:
        patch.num_ghost = 3
    patch.t = 0.0

    # init_q_petsc_structures must be called
    # before patch.x.centers and such can be accessed.
    patch.init_q_petsc_structures()
    xc = patch.x.centers
    q = np.zeros([patch.num_eqn, len(xc)], order='F')
    beta = 100
    gamma = 0
    x0 = 0.75
    q[0, :] = np.exp(-beta * (xc - x0)**2) * np.cos(gamma * (xc - x0))
    q[1, :] = 0.
    patch.q = q

    init_solution = Solution(patch)

    if sclaw:
        from petclaw.sharpclaw import SharpClawSolver1D
        solver = SharpClawSolver1D()
        solver.lim_type = kwargs.get('lim_type', 2)
        solver.time_integrator = 'SSP33'
        solver.num_waves = 2
        solver.char_decomp = 0
    else:
        from petclaw.clawpack import ClawSolver1D
        solver = ClawSolver1D()
        solver.num_waves = 2
        from pyclaw import limiters
        solver.mthlim = limiters.tvd.MC

    if kernel_language == 'Python': solver.set_riemann_solver('acoustics')
    solver.dt = patch.delta[0] / patch.problem_data['cc'] * 0.1
    solver.kernel_language = kernel_language

    claw = Controller()
    #claw.output_style = 3
    claw.keep_copy = True
    claw.num_output_times = 5
    # The output format MUST be set to petsc!
    claw.output_format = 'ascii'
    claw.outdir = outdir
    claw.tfinal = 1.0
    claw.solution = init_solution
    claw.solver = solver

    # Solve
    if petscts:
        # Uses PETSc time integrator. Needs sclaw=1 to get semidiscrete form. Examples:
        # ./acoustics.py sclaw=1 petscts=1 -ts_monitor_solution -ts_type theta -snes_mf_operator -ts_dt 0.02 -ts_max_steps 50 -ts_max_time 10 -draw_pause 0.05
        # ./acoustics.py sclaw=1 petscts=1 -ts_monitor_solution -ts_type ssp -ts_ssp_type rk104
        x = patch.q_da.createGlobalVector()
        f = x.duplicate()

        ts = PETSc.TS().create(PETSc.COMM_WORLD)
        ts.setDM(patch.q_da)
        ts.setProblemType(PETSc.TS.ProblemType.NONLINEAR)
        ts.setType(ts.Type.THETA)

        eqn = AcousticEquation(patch, solver)
        x[:] = patch.q
        ts.setRHSFunction(eqn.rhsfunction, f)
        ts.setIFunction(eqn.ifunction, f)
        ts.setIJacobian(eqn.ijacobian, patch.q_da.createMat())

        ts.setTimeStep(solver.dt)
        ts.setDuration(claw.tfinal, max_steps=1000)
        ts.setFromOptions()
        q0 = x[:].copy()
        ts.solve(x)
        qfinal = x[:].copy()
        dx = patch.delta[0]
    else:
        status = claw.run()
        #This test is set up so that the waves pass through the domain
        #exactly once, and the final solution should be equal to the
        #initial condition.  Here we output the 1-norm of their difference.
        q0 = claw.frames[0].patch.gqVec.getArray().reshape([-1])
        qfinal = claw.frames[
            claw.num_output_times].patch.gqVec.getArray().reshape([-1])
        dx = claw.frames[0].patch.delta[0]

    if htmlplot: plot.html_plot(outdir=outdir, format=output_format)
    if iplot: plot.interactive_plot(outdir=outdir, format=output_format)
    if petscPlot: plot.plotPetsc(output_object)

    print 'Max error:', np.max(qfinal - q0)

    return dx * np.sum(np.abs(qfinal - q0))
Ejemplo n.º 12
0
        x = numpy.arange(self.N) / self.N
        for i,t,u in self.history:
            pylab.plot(x, u, label='step=%d t=%8.2g'%(i,t))
        pylab.xlabel('$x$')
        pylab.ylabel('$u$')
        pylab.legend(loc='upper right')
        pylab.savefig('heat-history.png')
        #pylab.show()

OptDB = PETSc.Options()
ode = Heat(MPI.COMM_WORLD, OptDB.getInt('n',100))

x = ode.gvec.duplicate()
f = ode.gvec.duplicate()

ts = PETSc.TS().create(comm=ode.comm)
ts.setType(ts.Type.ROSW)        # Rosenbrock-W. ARKIMEX is a nonlinearly implicit alternative.

ts.setIFunction(ode.evalFunction, ode.gvec)
ts.setIJacobian(ode.evalJacobian, ode.mat)

ts.setMonitor(ode.monitor)

ts.setTime(0.0)
ts.setTimeStep(ode.h**2)
ts.setMaxTime(1)
ts.setMaxSteps(100)
ts.setExactFinalTime(PETSc.TS.ExactFinalTime.INTERPOLATE)
ts.setMaxSNESFailures(-1)       # allow an unlimited number of failures (step will be rejected and retried)

snes = ts.getSNES()             # Nonlinear solver
Ejemplo n.º 13
0
            P.setValues([mx - 1], [mx - 1], 1.0 / hx)
            lxe -= 1
        for i in range(lxs, lxe):
            P.setValues([i], [i - 1, i, i + 1], [
                -1.0 / hx, 2.0 / hx - hx * math.exp(xx[i - gxs]) + shift,
                -1.0 / hx
            ])
        P.assemble()
        return True  # same_nz


M = PETSc.Options().getInt('M', 9)
da = PETSc.DA().create([M], comm=PETSc.COMM_WORLD)
f = da.createGlobalVector()
x = f.duplicate()
J = da.getMatrix(PETSc.Mat.Type.AIJ)

ts = PETSc.TS().create(PETSc.COMM_WORLD)
ts.setProblemType(PETSc.TS.ProblemType.NONLINEAR)
ts.setType(ts.Type.GL)

ode = MyODE(da)
ts.setIFunction(ode.function, f)
ts.setIJacobian(ode.jacobian, J)

ts.setTimeStep(0.1)
ts.setDuration(10, 1.0)
ts.setFromOptions()
x.set(1.0)
ts.solve(x)
Ejemplo n.º 14
0
            xa[i] = (1 + (2**(self.nu / 2.0) - 1) *
                     np.exp(-self.nu / 2.0 * sig1 *
                            (-50 +
                             (i + 1) * self.dx + 2 * lam1 * t)))**(-2.0 /
                                                                   self.nu)


da = PETSc.DMDA().create([2049], dof=1, stencil_width=1)

OptDB = PETSc.Options()
ode = Fisher_split(da=da)

x = ode.gvec.duplicate()
f = ode.gvec.duplicate()

ts = PETSc.TS().create(comm=MPI.COMM_WORLD)
ts.setType(ts.Type.ARKIMEXARS443
           )  # Rosenbrock-W. ARKIMEX is a nonlinearly implicit alternative.
# ts.setRKType('3bs')

ts.setIFunction(ode.formFunction, ode.gvec)
ts.setIJacobian(ode.formJacobian, ode.mat)
ts.setRHSFunction(ode.formRHS, ode.rhs)

# ts.setMonitor(ode.monitor)

ts.setTime(0.0)
ts.setTimeStep(0.25)
ts.setMaxTime(1.0)
ts.setMaxSteps(100)
ts.setExactFinalTime(PETSc.TS.ExactFinalTime.INTERPOLATE)
Ejemplo n.º 15
0
        opt = {'M': MBlock, 'm': 4, 'd': 3}
        surface = Sphere()

        band = Band(surface, comm, opt)
        la, lv, gv, wv = band.createGLVectors()
        v = band.getCoordinates()
        vv = sp.array([[1, 0, 0], [-1, 0, 0], [0, 1, 0], [0, -1, 0], [0, 0, 1],
                       [0, 0, -1]])
        weights = sp.array([1, 1, 1, 1, 1, 1]) * (1 / band.dx**2)
        L = band.createAnyMat(vv, weights, (7, 3))
        PETSc.Sys.Print('Laplacian')

        M = band.createExtensionMat()
        PETSc.Sys.Print('ExtensionMat built')

        ts = PETSc.TS().create(comm=comm)
        ts.setProblemType(ts.ProblemType.LINEAR)
        ts.setType(ts.Type.BEULER)

        PETSc.Sys.Print('ML creating')

        LM = M.matMult(L)

        I = PETSc.Mat().create(comm=comm)
        I.setSizes((gv.sizes, gv.sizes))
        I.setFromOptions()
        I.setPreallocationNNZ(1)
        wv.set(1)
        I.setDiagonal(wv)
        I.assemble()
Ejemplo n.º 16
0
m = OptDB.getInt('m', PETSc.DECIDE)
n = OptDB.getInt('n', PETSc.DECIDE)
p = OptDB.getInt('p', PETSc.DECIDE)
dm = PETSc.DMDA().create(dim=3, sizes=(M, N, P), proc_sizes=(m, n, p),
                         boundary_type=(bx, by, bz), stencil_type=stype,
                         stencil_width=1, dof=1, comm=comm, setup=False)
dm.setFromOptions()
dm.setUp()
convdiff_problem = convection_diffusion(dm, {"dx": 0.1, "dy": 0.1, "dz": 0.1})

# prepare the initial conditions
rhs = dm.createGlobalVector()

# go do fun things with Poisson
# set up the SNES context
ts = PETSc.TS().create()
ts.setDM(dm)
ts.setRHSFunction(convdiff_problem.rhs, rhs)
ts.setDuration(100, 1.e10)

# --------------------------------------------------------------------------------
# finish the TS setup
# --------------------------------------------------------------------------------
# set any -ts commend-line options (including those we checked above)
ts.setFromOptions()

# create an initial guess
field = dm.createGlobalVector()
convdiff_problem.create_initial_guess(field)

# have fun (and measure how long fun takes)
Ejemplo n.º 17
0
def transient_pipe_flow_1D(
    npipes, nx, dof, nphases,
    pipe_length,
    initial_time,
    final_time,
    initial_time_step,
    dt_min,
    dt_max,
    initial_solution,    
    impl_python=False
    ):
    
    # Time Stepper (TS) for ODE and DAE
    # DAE - https://en.wikipedia.org/wiki/Differential_algebraic_equation
    # https://www.mcs.anl.gov/petsc/petsc-current/docs/manualpages/TS/
    ts = PETSc.TS().create()
    #ts.createPython(MyTS(), comm=PETSc.COMM_SELF)
    
    # http://www.mcs.anl.gov/petsc/petsc-current/docs/manualpages/DM/index.html
    pipes = []
    for i in range(npipes):
        boundary_type = PETSc.DMDA.BoundaryType.GHOSTED
        da = PETSc.DMDA().create([nx], dof=dof, stencil_width=1, stencil_type='star', boundary_type=boundary_type)
        da.setFromOptions()
        pipes.append(da)
    
    # Create a redundant DM, there is no petsc4py interface (yet)
    # so we created our own wrapper
    # http://www.mcs.anl.gov/petsc/petsc-current/docs/manualpages/DM/DMREDUNDANT.html
#     dmredundant = PETSc.DM().create()
#     dmredundant.setType(dmredundant.Type.REDUNDANT)
#     CompositeSimple1D.redundantSetSize(dmredundant, 0, dof)
#     dmredundant.setDimension(1)
#     dmredundant.setUp()

    # http://www.mcs.anl.gov/petsc/petsc-current/docs/manualpages/DM/DMCOMPOSITE.html
    dm = PETSc.DMComposite().create()
    
    for pipe in pipes:        
        dm.addDM(pipe)

#     dm.addDM(dmredundant)
#     CompositeSimple1D.compositeSetCoupling(dm)
    CompositeSimple1D.registerNewSNES()
    
    ts.setDM(dm)
        
    F = dm.createGlobalVec()

    if impl_python:     
        α0 = initial_solution.reshape((nx,dof))[:, nphases:-1]
        pde = Flow(dm, nx, dof, pipe_length, nphases, α0)
        ts.setIFunction(pde.evalFunction, F)
    else:
        # http://www.mcs.anl.gov/petsc/petsc-current/docs/manualpages/TS/TSSetIFunction.html
        assert False, 'C function not implemented yet!'
#         ts.setIFunction(CompositeSimple1D.formFunction, F,
#                          args=(conductivity, source_term, wall_length, temperature_presc))    
    
    snes = ts.getSNES()
    
    snes.setUpdate(pde.updateFunction)
    
    x = dm.createGlobalVec()    

    x[...] = initial_solution

    # http://www.mcs.anl.gov/petsc/petsc-current/docs/manualpages/TS/TSSetDuration.html
    ts.setDuration(max_time=final_time, max_steps=None)
    
    # http://www.mcs.anl.gov/petsc/petsc-current/docs/manualpages/TS/TSSetInitialTimeStep.html
    ts.setInitialTimeStep(initial_time=initial_time, initial_time_step=initial_time_step)
    
    # http://www.mcs.anl.gov/petsc/petsc-current/docs/manualpages/TS/TSSetProblemType.html
    ts.setProblemType(ts.ProblemType.NONLINEAR)
    ts.setEquationType(ts.EquationType.IMPLICIT)
    
    prev_sol = initial_solution.copy()
    
#     restart = PreStep(prev_sol)
#     ts.setPreStep(restart.prestep)
#     ts.setPostStep(restart.poststep)
    
    options = PETSc.Options()
    options.setValue('-ts_adapt_dt_min', dt_min)
    options.setValue('-ts_adapt_dt_max', dt_max)
    
    ts.setFromOptions()

    snes = ts.getSNES()
    if options.getString('snes_type') in [snes.Type.VINEWTONRSLS, snes.Type.VINEWTONSSLS]:
#     if True:
#         snesvi = snes.getCompositeSNES(1)
        snesvi = snes
        
        xl = np.zeros((nx, dof))
        xl[:,:nphases] = -100
        xl[:,-1] = 0
        xl[:, nphases:-1] = 0

        
        xu = np.zeros((nx, dof))    
        xu[:,:nphases] =  100
        xu[:,-1] = 1000
        xu[:, nphases:-1] = 1
             
        xlVec = dm.createGlobalVec()
        xuVec = dm.createGlobalVec()   
        xlVec.setArray(xl.flatten())
        xuVec.setArray(xu.flatten())    

        snesvi.setVariableBounds(xlVec, xuVec)
    
    ts.solve(x)
    
#     while ts.diverged:
#         x[...] = prev_sol.copy()
#         ts.setInitialTimeStep(initial_time=initial_time, initial_time_step=0.5*initial_time_step)
#         ts.solve(x)
    
    final_dt = ts.getTimeStep()
    
    return x, final_dt
Ejemplo n.º 18
0
def transient_heat_transfer_1D(
    npipes, nx, 
    initial_temperature,
    temperature_presc, 
    conductivity,
    source_term,
    wall_length,
    final_time,
    initial_time_step,
    impl_python=False
    ):
    
    # Time Stepper (TS) for ODE and DAE
    # DAE - https://en.wikipedia.org/wiki/Differential_algebraic_equation
    # https://www.mcs.anl.gov/petsc/petsc-current/docs/manualpages/TS/
    ts = PETSc.TS().create()

    # http://www.mcs.anl.gov/petsc/petsc-current/docs/manualpages/DM/index.html
    #
    pipes = []
    for i in range(npipes):
        pipes.append(PETSc.DMDA().create([nx],dof=1, stencil_width=1, stencil_type='star'))
    
    # Create a redundant DM, there is no petsc4py interface (yet)
    # so we created our own wrapper
    # http://www.mcs.anl.gov/petsc/petsc-current/docs/manualpages/DM/DMREDUNDANT.html
    dmredundant = PETSc.DM().create()
    dmredundant.setType(dmredundant.Type.REDUNDANT)
    HeatTransfer1D.redundantSetSize(dmredundant, 0, 1)
    dmredundant.setDimension(1)
    dmredundant.setUp()

    # http://www.mcs.anl.gov/petsc/petsc-current/docs/manualpages/DM/DMCOMPOSITE.html
    dm = PETSc.DMComposite().create()
    
    for pipe in pipes:        
        dm.addDM(pipe)

    dm.addDM(dmredundant)
    HeatTransfer1D.compositeSetCoupling(dm)
    
    ts.setDM(dm)

    F = dm.createGlobalVec()

    if impl_python:        
        ode = Heat(dm, temperature_presc, conductivity, source_term, wall_length)
        ts.setIFunction(ode.evalFunction, F)
    else:
        # http://www.mcs.anl.gov/petsc/petsc-current/docs/manualpages/TS/TSSetIFunction.html
        ts.setIFunction(HeatTransfer1D.formFunction, F,
                         args=(conductivity, source_term, wall_length, temperature_presc))    
    
    x = dm.createGlobalVec()
    
    x[...] = initial_temperature
    
    #HeatTransfer1D.formInitGuess(x, dm, initial_temperature)

    # http://www.mcs.anl.gov/petsc/petsc-current/docs/manualpages/TS/TSSetDuration.html
    ts.setDuration(max_time=final_time, max_steps=None)
    
    # http://www.mcs.anl.gov/petsc/petsc-current/docs/manualpages/TS/TSSetExactFinalTime.html
    ts.setExactFinalTime(ts.ExactFinalTimeOption.STEPOVER)
    
    # http://www.mcs.anl.gov/petsc/petsc-current/docs/manualpages/TS/TSSetInitialTimeStep.html
    ts.setInitialTimeStep(initial_time=0.0, initial_time_step=initial_time_step)
    
    # http://www.mcs.anl.gov/petsc/petsc-current/docs/manualpages/TS/TSSetProblemType.html
    ts.setProblemType(ts.ProblemType.NONLINEAR)
    
    # Another way to set the solve type is through PETSc.Options()
    #ts.setType(ts.Type.CRANK_NICOLSON)
    #ts.setType(ts.Type.THETA)
    #ts.setTheta(theta=0.9999)
    #ts.setType(ts.Type.EIMEX) # http://www.mcs.anl.gov/petsc/petsc-current/docs/manualpages/TS/TSEIMEX.html
    #ts.setType(ts.Type.BDF      )

    ts.setFromOptions()

    ts.solve(x)

    return x