def _implicitBuildMatrix_(self, SparseMatrix, L, id1, id2, b, weight, var, boundaryConditions, interiorFaces, dt): mesh = var.mesh coeffMatrix = self._getCoeffMatrix_(var, weight) id1 = self._reshapeIDs(var, id1) id2 = self._reshapeIDs(var, id2) L.addAt(numerix.take(coeffMatrix['cell 1 diag'], interiorFaces, axis=-1).ravel(), id1.ravel(), id1.swapaxes(0, 1).ravel()) L.addAt(numerix.take(coeffMatrix['cell 1 offdiag'], interiorFaces, axis=-1).ravel(), id1.ravel(), id2.swapaxes(0, 1).ravel()) L.addAt(numerix.take(coeffMatrix['cell 2 offdiag'], interiorFaces, axis=-1).ravel(), id2.ravel(), id1.swapaxes(0, 1).ravel()) L.addAt(numerix.take(coeffMatrix['cell 2 diag'], interiorFaces, axis=-1).ravel(), id2.ravel(), id2.swapaxes(0, 1).ravel()) N = mesh.numberOfCells M = mesh._maxFacesPerCell for boundaryCondition in boundaryConditions: LL, bb = boundaryCondition._buildMatrix(SparseMatrix, N, M, coeffMatrix) if 'FIPY_DISPLAY_MATRIX' in os.environ: self._viewer.title = r"%s %s" % (boundaryCondition.__class__.__name__, self.__class__.__name__) self._viewer.plot(matrix=LL, RHSvector=bb) from fipy import raw_input input() L += LL b += bb
def _buildAndAddMatrices(self, var, SparseMatrix, boundaryConditions=(), dt=None, transientGeomCoeff=None, diffusionGeomCoeff=None, buildExplicitIfOther=False): """Build matrices of constituent Terms and collect them Only called at top-level by `_prepareLinearSystem()` Test for ticket:343. >>> from fipy import * >>> m = Grid1D(nx=2) >>> v0 = CellVariable(mesh=m) >>> v1 = CellVariable(mesh=m) >>> (TransientTerm(var=v0) - DiffusionTerm(var=v0)).solve(var=v1, dt=1., solver=DummySolver()) >>> DiffusionTerm(var=v0).solve(var=v1, dt=1.0, solver=DummySolver()) """ if var is self.var or self.var is None: var, matrix, RHSvector = self._buildMatrix( var, SparseMatrix, boundaryConditions=boundaryConditions, dt=dt, transientGeomCoeff=transientGeomCoeff, diffusionGeomCoeff=diffusionGeomCoeff) elif buildExplicitIfOther: _, matrix, RHSvector = self._buildMatrix( self.var, SparseMatrix, boundaryConditions=boundaryConditions, dt=dt, transientGeomCoeff=transientGeomCoeff, diffusionGeomCoeff=diffusionGeomCoeff) RHSvector = RHSvector - matrix * self.var.value matrix = SparseMatrix(mesh=var.mesh) else: RHSvector = numerix.zeros(len(var.ravel()), 'd') matrix = SparseMatrix(mesh=var.mesh) if ('FIPY_DISPLAY_MATRIX' in os.environ and "terms" in os.environ['FIPY_DISPLAY_MATRIX'].lower().split()): self._viewer.title = "%s %s" % (var.name, repr(self)) self._viewer.plot(matrix=matrix, RHSvector=RHSvector) input() return (var, matrix, RHSvector)
def _applyTrilinosSolver(self, A, LHS, RHS): Prec = ML.MultiLevelPreconditioner(A, False) Prec.SetParameterList(self.MLOptions) Prec.ComputePreconditioner() Prec.TestSmoothers() input( "Results of preconditioner tests shown above. Currently, the first tests in the 'Gauss-Seidel (sym)','Aztec preconditioner', and 'Aztec as solver' sections indicate the expected performance of the MultilevelSGSPreconditioner, MultilevelDDPreconditioner, and MultilevelSolverSmootherPreconditioner classes, respectively.\n\nPress enter to quit." ) import sys sys.exit(0)
def __doBCs(self, SparseMatrix, higherOrderBCs, N, M, coeffs, coefficientMatrix, boundaryB): for boundaryCondition in higherOrderBCs: LL, bb = boundaryCondition._buildMatrix(SparseMatrix, N, M, coeffs) if 'FIPY_DISPLAY_MATRIX' in os.environ: self._viewer.title = r"%s %s" % ( boundaryCondition.__class__.__name__, self.__class__.__name__) self._viewer.plot(matrix=LL, RHSvector=bb) from fipy import input input() self.__bcAdd(coefficientMatrix, boundaryB, LL, bb) return coefficientMatrix, boundaryB
def _prepareLinearSystem(self, var, solver, boundaryConditions, dt): solver = self.getDefaultSolver(var, solver) var = self._verifyVar(var) self._checkVar(var) if type(boundaryConditions) not in (type(()), type([])): boundaryConditions = (boundaryConditions, ) for bc in boundaryConditions: bc._resetBoundaryConditionApplied() if 'FIPY_DISPLAY_MATRIX' in os.environ: if not hasattr(self, "_viewer"): from fipy.viewers.matplotlibViewer.matplotlibSparseMatrixViewer import MatplotlibSparseMatrixViewer Term._viewer = MatplotlibSparseMatrixViewer() var, matrix, RHSvector = self._buildAndAddMatrices( var, self._getMatrixClass(solver, var), boundaryConditions=boundaryConditions, dt=dt, transientGeomCoeff=self._getTransientGeomCoeff(var), diffusionGeomCoeff=self._getDiffusionGeomCoeff(var), buildExplicitIfOther=self._buildExplcitIfOther) self._buildCache(matrix, RHSvector) solver._storeMatrix(var=var, matrix=matrix, RHSvector=RHSvector) if 'FIPY_DISPLAY_MATRIX' in os.environ: if var is None: name = "" else: if not hasattr(var, "name"): name = "" else: name = var.name self._viewer.title = r"%s %s" % (name, repr(self)) from fipy.variables.coupledCellVariable import _CoupledCellVariable if isinstance(solver.RHSvector, _CoupledCellVariable): RHSvector = solver.RHSvector.globalValue else: RHSvector = solver.RHSvector self._viewer.plot(matrix=solver.matrix, RHSvector=RHSvector) from fipy import raw_input input() return solver
>>> elapsed = 0. >>> if __name__ == "__main__": ... duration = 1000. ... else: ... duration = 1e-2 >>> while elapsed < duration: ... dt = min(100, numerix.exp(dexp)) ... elapsed += dt ... dexp += 0.01 ... eq.solve(phi, dt=dt, solver=DefaultSolver(precon=None)) # doctest: +GMSH ... if __name__ == "__main__": ... viewer.plot() .. image:: sphere.* :width: 90% :align: center :alt: Cahn-Hilliard phase separation on the surface of a sphere with a rendering of the mesh """ from __future__ import unicode_literals __docformat__ = 'restructuredtext' from fipy import input if __name__ == '__main__': import fipy.tests.doctestPlus exec(fipy.tests.doctestPlus._getScript()) input('finished')
""" from __future__ import unicode_literals __docformat__ = 'restructuredtext' from fipy import input from fipy import CellVariable, Grid2D, DiffusionTerm, Viewer nx = 50 ny = 50 dx = 1. valueLeft = 0. valueRight = 1. mesh = Grid2D(dx=dx, nx=nx, ny=ny) var = CellVariable(name="solution variable", mesh=mesh, value=valueLeft) var.constrain(valueLeft, mesh.facesLeft) var.constrain(valueRight, mesh.facesRight) if __name__ == '__main__': DiffusionTerm().solve(var) viewer = Viewer(vars=var, datamin=0., datamax=1.) viewer.plot() input("finished")
(4.0 / (9.0 * pi * numerix.sinh(9.0 * pi))) * (numerix.sin(9.0 * pi * x)) * (numerix.sinh(9.0 * pi * y)) + (4.0 / (11.0 * pi * numerix.sinh(11.0 * pi))) * (numerix.sin(11.0 * pi * x)) * (numerix.sinh(11.0 * pi * y)) + (4.0 / (13.0 * pi * numerix.sinh(13.0 * pi))) * (numerix.sin(13.0 * pi * x)) * (numerix.sinh(13.0 * pi * y))) analytical = CellVariable(mesh=mesh, name=r"$\phi_{Analytical}$", value=analytical_solution) phi.equation.solve(var=phi) from fipy import input if __name__ == '__main__': vi = Viewer(phi, title=None, colorbar=None) vi.colorbar = _ColorBar(viewer=vi, vmin=0.0, vmax=1.0) # vi.axes.set_ylabel("y") # vi.axes.set_xlabel("x") # plt.savefig("ex1numerical.png", dpi=1200) vi.plot() input("Press <return> to proceed") # plt.clf() # Setting up the second viewer for the analytical solution if __name__ == '__main__': vi2 = Viewer(analytical, colorbar=None) vi2.colorbar = _ColorBar(viewer=vi2, vmin=0.0, vmax=1.0) # plt.savefig("ex1analytical.png", dpi=1200) input("Press <return> to proceed")
dx = L / nx cfl = 0.01 velocity = 1. timeStepDuration = cfl * dx / abs(velocity) steps = 1000 mesh = Grid1D(dx=dx, nx=nx) startingArray = numerix.zeros(nx, 'd') startingArray[50:90] = 1. var = CellVariable(name="advection variable", mesh=mesh, value=startingArray) var.constrain(valueLeft, mesh.facesLeft) var.constrain(valueRight, mesh.facesRight) eq = TransientTerm() - PowerLawConvectionTerm(coeff=(velocity, )) if __name__ == '__main__': viewer = Viewer(vars=(var, )) viewer.plot() input("press key to continue") for step in range(steps): eq.solve(var, dt=timeStepDuration, solver=LinearLUSolver(tolerance=1.e-15)) viewer.plot() viewer.plot() input('finished')
charge.setValue(-1, where=mesh.physicalCells["Cathode"]) potential = CellVariable(mesh=mesh, name=r"$\psi$") potential.constrain(0., where=mesh.physicalFaces["Ground"]) eq = DiffusionTerm(coeff=1.) == -charge res0 = eq.sweep(var=potential) res = eq.justResidualVector(var=potential) res1 = numerix.L2norm(res) res1a = CellVariable(mesh=mesh, value=abs(res)) res = CellVariable(mesh=mesh, name="residual", value=abs(res) / mesh.cellVolumes**(1./mesh.dim) / 1e-3) # want cells no bigger than 1 and no smaller than 0.001 maxSize = 1. minSize = 0.001 monitor = CellVariable(mesh=mesh, name="monitor", value= 1. / (res + maxSize) + minSize) viewer = Viewer(vars=potential, xmin=3.5, xmax=4.5, ymin=3.5, ymax=4.5) # viewer = Viewer(vars=(potential, charge)) viewer.plot() # resviewer = Viewer(vars=res1a, log=True, datamin=1e-6, datamax=1e-2, cmap=cm.gray) # monviewer = Viewer(vars=monitor, log=True, datamin=1e-3, datamax=1) input("refinement %d, res0: %g, res: %g:%g, N: %d, min: %g, max: %g, avg: %g. Press <return> to proceed..." \ % (refinement, res0, res1, res1a.cellVolumeAverage, mesh.numberOfCells, numerix.sqrt(min(mesh.cellVolumes)), numerix.sqrt(max(mesh.cellVolumes)), numerix.mean(numerix.sqrt(mesh.cellVolumes))))