def define_uniform_comp_domain_ax( self, no_of_nodes, normalised_domain_thickness): # Uniform axial domain, electrodes self.nx = int(no_of_nodes) self.L_normalised = normalised_domain_thickness self.dx = numerix.full((self.nx, ), (self.L_normalised / self.nx)) self.axial_mesh = Grid1D(nx=self.nx, Lx=self.L_normalised) self.axial_mesh = Grid1D(nx=self.nx, Lx=self.L_normalised) self.axialfaces = self.axial_mesh.faceCenters # Create a shorthand name for accessing axial faces
def create_mesh(self): """ Create the :mod:`fipy` mesh for the domain using :attr:`cell_size` and :attr:`total_cells`. The arrays :attr:`depths` and :attr:`distances` are created, which provide the coordinates and distances of the mesh cells. """ self.logger.info( 'Creating UniformGrid1D with {} sediment and {} DBL cells of {}'. format(self.sediment_cells, self.DBL_cells, self.cell_size)) self.mesh = Grid1D( dx=self.cell_size.numericValue, nx=self.total_cells, ) self.logger.debug('Created domain mesh: {}'.format(self.mesh)) #: An array of the scaled cell distances of the mesh self.distances = Variable(value=self.mesh.scaledCellDistances[:-1], unit='m', name='distances') Z = self.mesh.x() Z = Z - Z[self.idx_surface] #: An array of the cell center coordinates, with the 0 set at the sediment surface self.depths = Variable(Z, unit='m', name='depths')
def define_non_uniform_comp_domain_ax( self, no_of_nodes, normalised_domain_thickness ): # Non-uniform axial domain, electrodes self.nx = int(no_of_nodes) self.L_normalised = normalised_domain_thickness self.dx = compute_cheb_pts(self.L_normalised, self.nx) self.axial_mesh = Grid1D(dx=self.dx, Lx=self.L_normalised) self.axialfaces = self.axial_mesh.faceCenters # Create a shorthand name for accessing axial faces
def solve_pde( xmin, # domain min xmax, # domain max Tmax, # time max theta=1, # dynamics drift mu=0, # dynamics stable level sigma=1, # dynamics noise dx=0.01, # space discretization dt=0.01, # time discretization gbm=False): # state-dependent drift mesh = Grid1D(dx=dx, nx=(xmax - xmin) / dx) + xmin Tsteps = int(Tmax / dt) + 1 x_face = mesh.faceCenters x_cell = mesh.cellCenters[0] V = CellVariable(name="V", mesh=mesh, value=0.) # PDE if gbm: eq = TransientTerm( var=V) == (DiffusionTerm(coeff=float(sigma) * sigma / 2, var=V) - UpwindConvectionTerm( coeff=float(theta) * (x_face - float(mu)), var=V) + V * (float(theta) - x_cell)) else: eq = TransientTerm( var=V) == (DiffusionTerm(coeff=float(sigma) * sigma / 2, var=V) - UpwindConvectionTerm(coeff=float(theta) * (x_face - float(mu)), var=V) + V * float(theta)) # Boundary conditions V.constrain(1., mesh.facesRight) V.faceGrad.constrain([0.], mesh.facesLeft) # Solve by stepping in time sol = np.zeros((Tsteps, mesh.nx)) for step in range(Tsteps): eq.solve(var=V, dt=dt) sol[step] = V.value X = mesh.cellCenters.value[0] T = dt * np.arange(Tsteps) return T, X, sol
((x / l)**(k1 - 1)) * (1 - (x / l))**(p1 - 1)) / 7.3572 def y02(x): """"Initial negative ion charge density""" return nini * ((special.gamma(k2 + p2)) / (special.gamma(k2) * special.gamma(p2)) * ((x / l)**(k2 - 1)) * (1 - (x / l))**(p2 - 1)) / 7.3572 def y03(x): """Initial potential""" return a1 * np.sin(b1 * x + c1) + a2 * np.sin(b2 * x + c2) mesh = Grid1D(dx=dx, nx=nx) #Establish mesh in how many dimensions necessary ############################################################################## #################''' SETUP CELLVARIABLES AND EQUATIONS '''#################### ############################################################################## #CellVariable - defines the variables that you want to solve for: '''Initial value can be established when defining the variable, or later using 'var.value =' Value defaults to zero if not defined''' Pion = CellVariable(mesh=mesh, name='Positive ion Charge Density', value=y01(x)) Nion = CellVariable(mesh=mesh, name='Negative ion Charge Density',
from fipy import CellVariable, Grid1D, DiffusionTerm, Viewer, ImplicitSourceTerm from fipy.tools import numerix from fipy.solvers import * from parameters import * # ----------------- Solver -------------------------------- mySolver = LinearGMRESSolver(iterations=1000, tolerance=1.0e-6) # ----------------- Mesh Generation ----------------------- nx = 100 L = 5.0 mesh = Grid1D(nx=nx, Lx=L) x = mesh.cellCenters[0] # Cell position # ----------------- Variable Declarations ----------------- density = CellVariable(name=r"$n$", mesh=mesh, hasOld=True) temperature = CellVariable(name=r"$T$", mesh=mesh, hasOld=True) Z = CellVariable(name=r"$Z$", mesh=mesh, hasOld=True) Diffusivity = CellVariable(name=r"$D$", mesh=mesh, hasOld=True) # ----------- Initial Conditions of Z --------------------- Z0L = 1.0 # L--mode Z0H = Z_S * (1.0 - numerix.tanh((L * x - L) / 2.0)) # H--mode Z.setValue(Z0H) # ----------------- Diffusivities ------------------------- # Itohs'/Zohm's model
from builtins import range __docformat__ = 'restructuredtext' from fipy import input from fipy import CellVariable, FaceVariable, Grid1D, TransientTerm, CentralDifferenceConvectionTerm from fipy.tools import numerix L = 2. X0 = -1. nx = 800 cfl = 0.1 K = 4. rho = 1. dx = L / nx m = Grid1D(nx=nx, dx=dx) + X0 x, = m.cellCenters q = CellVariable(mesh=m, rank=1, elementshape=(2, )) q[0, :] = numerix.exp(-50 * (x - 0.3)**2) * numerix.cos(20 * (x - 0.3)) q[0, x > 0.3] = 0. Ax = FaceVariable(mesh=m, rank=3, value=[((0, K), (1 / rho, 0))], elementshape=(1, 2, 2)) eqn = TransientTerm() + CentralDifferenceConvectionTerm(Ax) == 0 if __name__ == '__main__':
# parameter values diffusion = 101. rateConstant = .5 L = 1. siteDensity = 1. cinf = 1. nx = 100 totalTimeSteps = 100 dt = 0.001 ## build the mesh dx = L / (nx - 1.5) mesh = Grid1D(nx=nx, dx=dx, communicator=serialComm) ## build the distance variable value = mesh.cellCenters[0] - 1.499 * dx ##distanceVar = DistanceVariable(mesh = mesh, value = dx * (arange(nx) - 0.999)) distanceVar = DistanceVariable(mesh=mesh, value=value, hasOld=1) ## Build the bulk diffusion equation bulkVar = CellVariable(mesh=mesh, value=cinf) surfactantVar = SurfactantVariable(distanceVar=distanceVar) from .surfactantBulkDiffusionEquation import buildSurfactantBulkDiffusionEquation bulkEqn = buildSurfactantBulkDiffusionEquation(bulkVar,
from mpi4py import MPI m4comm = MPI.COMM_WORLD mpi4py_info = "mpi4py: processor %d of %d" % (m4comm.Get_rank(), m4comm.Get_size()) from PyTrilinos import Epetra epcomm = Epetra.PyComm() trilinos_info = "PyTrilinos: processor %d of %d" % (epcomm.MyPID(), epcomm.NumProc()) from fipy import parallelComm, Grid1D mesh = Grid1D(nx=10) fipy_info = "FiPy: %d cells on processor %d of %d" % ( mesh.numberOfCells, parallelComm.procID, parallelComm.Nproc) print " :: ".join((mpi4py_info, trilinos_info, fipy_info))
def define_global_mesh(self, node_spacing, normalised_domain_thickness ): # Only Ce & phi_e are solved on this mesh self.dx = node_spacing # node_spacing vector passed can be either uniformly or non-uniformly spaced points self.L_normalised = normalised_domain_thickness self.axial_mesh = Grid1D(Lx=self.L_normalised, dx=self.dx)
def createPhreeqcInstance(filename, kinetics): nx = 100 ny = 1 nz = 1 dx = 1.5 mesh = Grid1D(nx=nx, dx=dx) v_cell = mesh.cellVolumes nxyz = nx * ny * nz # number of cells nthreads = 1 # number of threads phreeqc_rm = PhreeqcRM(nxyz, nthreads) # create a phreeqc instance # Set properties status = phreeqc_rm.RM_SetErrorHandlerMode(1) status = phreeqc_rm.RM_SetComponentH2O(0) status = phreeqc_rm.RM_SetRebalanceFraction(0.5) status = phreeqc_rm.RM_SetRebalanceByCell(1) status = phreeqc_rm.RM_UseSolutionDensityVolume(0) status = phreeqc_rm.RM_SetPartitionUZSolids(0) status = phreeqc_rm.RM_SetFilePrefix("Advect_cpp") status = phreeqc_rm.RM_OpenFiles() status = phreeqc_rm.RM_SetUnitsSolution(2) # 1, mg/L 2, mol/L 3, kg/kgs status = phreeqc_rm.RM_SetUnitsPPassemblage( 1) # 0, mol/L cell 1, mol/L water 2 mol/L rock status = phreeqc_rm.RM_SetUnitsExchange( 1) # 0, mol/L cell 1, mol/L water 2 mol/L rock status = phreeqc_rm.RM_SetUnitsSurface( 1) # 0, mol/L cell 1, mol/L water 2 mol/L rock status = phreeqc_rm.RM_SetUnitsGasPhase( 1) # 0, mol/L cell 1, mol/L water 2 mol/L rock status = phreeqc_rm.RM_SetUnitsSSassemblage( 1) # 0, mol/L cell 1, mol/L water 2 mol/L rock status = phreeqc_rm.RM_SetUnitsKinetics( 1) # 0, mol/L cell 1, mol/L water 2 mol/L rock # Set conversion from seconds to days # I prefer to work with seconds, so I keep it to 1.0 status = phreeqc_rm.RM_SetTimeConversion(1.0 / 86400) # Set representative volume rv = np.ones_like(v_cell, dtype='float64') # volume is in liter status = phreeqc_rm.RM_SetRepresentativeVolume(rv) # Set initial porosity por = np.ones(nxyz, dtype='float64') * 1 status = phreeqc_rm.RM_SetPorosity(por) # Set initial saturation sat = np.ones(nxyz, dtype='float64') status = phreeqc_rm.RM_SetSaturation(sat) # Set cells to print chemistry when print chemistry is turned on print_chemistry_mask = np.zeros(nxyz, dtype='int') print_chemistry_mask[:np.int(nxyz / 2)] = 1 status = phreeqc_rm.RM_SetPrintChemistryMask(print_chemistry_mask) # Partitioning of uz solids #status = phreeqc_rm.RM_SetPartitionUZSolids(0) # Demonstation of mapping, no symmetry, only one row of cells grid2chem = np.arange(nxyz, dtype='int32') status = phreeqc_rm.RM_CreateMapping(grid2chem) if (status < 0): status = phreeqc_rm.RM_DecodeError(status) nchem = phreeqc_rm.RM_GetChemistryCellCount() status = phreeqc_rm.RM_SetPrintChemistryOn( 0, 1, 0) # workers, initial_phreeqc, utility # Set printing of chemistry file status = phreeqc_rm.RM_LoadDatabase("minteq.v4.dat") # Demonstration of error handling if ErrorHandlerMode is 0 # commented out for now (AAE) # if (status != Iphreeqc_rm.RM_OK) # { # l = phreeqc_rm.RM_GetErrorStringLength() # errstr = (char *) malloc((size_t) (l * sizeof(char) + 1)) # phreeqc_rm.RM_GetErrorString(errstr, l+1) # fprintf(stderr,"Beginning of error string:\n") # fprintf(stderr,"%s", errstr) # fprintf(stderr,"End of error string.\n") # free(errstr) # errstr = NULL # phreeqc_rm.RM_Destroy() # exit(1) # } # Run file to define solutions and reactants for initial conditions, selected output # There are three types of IPhreeqc instances in Phreeqcphreeqc_rm.RM # Argument 1 refers to the workers for doing reaction calculations for transport # Argument 2 refers to the InitialPhreeqc instance for accumulating initial and boundary conditions # Argument 3 refers to the Utility instance status = phreeqc_rm.RM_RunFile(1, 1, 1, filename) # Clear contents of workers and utility Str = "DELETE -all" status = phreeqc_rm.RM_RunString(1, 0, 1, Str) # workers, initial_phreeqc, utility # Determine number of components to transport ncomps = phreeqc_rm.RM_FindComponents() gfw = np.zeros(ncomps, dtype='float64') status = phreeqc_rm.RM_GetGfw(gfw) #for i in range(ncomps): # I consider the maximum number of characters for components' name to be 10 components = np.zeros(ncomps, dtype='U10') for i in range(ncomps): status = phreeqc_rm.RM_GetComponent(i, components, 10) # print(components[i].encode(), "\t", gfw[i], "\n") ic1 = -1 * np.ones(nxyz * 7, dtype=np.int32) ic2 = -1 * np.ones(nxyz * 7, dtype=np.int32) f1 = np.ones(nxyz * 7, dtype=np.float64) for i in np.arange(nxyz): ic1[i] = 1 # Solution 1 ic1[i + nxyz] = -1 # Equilibrium phases none ic1[i + 2 * nxyz] = -1 # Exchpdange 1 ic1[i + 3 * nxyz] = -1 # Surface none ic1[i + 4 * nxyz] = -1 # Gas phase none ic1[i + 5 * nxyz] = -1 # Solid solutions none ic1[i + 6 * nxyz] = kinetics # Kinetics none status = phreeqc_rm.RM_InitialPhreeqc2Module(ic1, ic2, f1) t = 0.0 # changed time to time1 to avoid conflicts with julia time function time_step = 0.0 c = np.zeros(ncomps * nxyz, dtype=np.float64) status = phreeqc_rm.RM_SetTime(t) status = phreeqc_rm.RM_SetTimeStep(time_step) status = phreeqc_rm.RM_SetSpeciesSaveOn(1) status = phreeqc_rm.RM_RunCells() status = phreeqc_rm.RM_GetConcentrations(c) nbound = 1 bc1 = np.zeros(nbound, dtype='int32') bc2 = -1 * np.ones(nbound, dtype='int32') bc_f1 = np.ones(nbound, dtype='float64') bc_conc = np.zeros(ncomps * nbound, dtype='float64') status = phreeqc_rm.RM_InitialPhreeqc2Concentrations( bc_conc, nbound, bc1, bc2, bc_f1) density = np.ones(nxyz, dtype=np.float64) volume = np.zeros(nxyz, dtype=np.float64) pressure = 2 * np.ones(nxyz, dtype=np.float64) temperature = 20 * np.ones(nxyz, dtype=np.float64) sat_calc = np.zeros(nxyz, dtype=np.float64) status = phreeqc_rm.RM_SetDensity(density) status = phreeqc_rm.RM_SetPressure(pressure) status = phreeqc_rm.RM_SetTemperature(temperature) return bc_conc, mesh, ncomps, components, c, nxyz, phreeqc_rm
""" This file generates the 1D mesh and the 4 cell state variables needed for the model (including Diffusivity). """ from fipy import Grid1D, CellVariable from fipy.tools import numerix, dump from parameters import * # ----------------- Mesh Generation ----------------------- mesh = Grid1D(nx=config.nx, Lx=L) x = mesh.cellCenters[0] # Cell position X = mesh.faceCenters[0] # Face position, if needed # -------------- State Variable Declarations -------------- density = CellVariable(name=r"$n$", mesh=mesh, hasOld=True) temperature = CellVariable(name=r"$T$", mesh=mesh, hasOld=True) U = CellVariable(name=r"$U$", mesh=mesh, hasOld=True) Z = CellVariable(name=r"$Z$", mesh=mesh, hasOld=True) Diffusivity = CellVariable(name=r"$D$", mesh=mesh, hasOld=True) U.setValue(density * temperature / (gamma - 1.0)) # -------------- Other Variable Declarations -------------- # Thermal velocities (most probable)
from fipy import Grid1D, CellVariable, TransientTerm, DiffusionTerm, Viewer m = Grid1D(nx=100, Lx=1.) v0 = CellVariable(mesh=m, hasOld=True, value=0.5) v1 = CellVariable(mesh=m, hasOld=True, value=0.5) v0.constrain(0, m.facesLeft) v0.constrain(1, m.facesRight) v1.constrain(1, m.facesLeft) v1.constrain(0, m.facesRight) eq0 = TransientTerm() == DiffusionTerm(coeff=0.01) - v1.faceGrad.divergence eq1 = TransientTerm() == v0.faceGrad.divergence + DiffusionTerm(coeff=0.01) vi = Viewer((v0, v1)) for t in range(100): v0.updateOld() v1.updateOld() res0 = res1 = 1e100 while max(res0, res1) > 0.1: res0 = eq0.sweep(var=v0, dt=1e-5) res1 = eq1.sweep(var=v1, dt=1e-5) if t % 10 == 0: vi.plot() # eqn0 = TransientTerm(var=v0) == DiffusionTerm(0.01, var=v0) - DiffusionTerm(1, var=v1) # eqn1 = TransientTerm(var=v1) == DiffusionTerm(1, var=v0) + DiffusionTerm(0.01, var=v1)
def __init__(self, dx): self.mesh = Grid1D(dx=dx)
def __init__(self, nx, dx): assert np.array(dx).shape == () self.mesh = Grid1D(nx=nx, dx=dx)
>>> print KCVar.allclose(params['KC'], atol = accuracy) 1 """ from examples.chemotaxis.parameters import parameters from fipy import CellVariable, Grid1D, TransientTerm, DiffusionTerm, ImplicitSourceTerm, Viewer params = parameters['case 2'] nx = 50 dx = 1. L = nx * dx mesh = Grid1D(nx=nx, dx=dx) shift = 1. KMVar = CellVariable(mesh=mesh, value=params['KM'] * shift, hasOld=1) KCVar = CellVariable(mesh=mesh, value=params['KC'] * shift, hasOld=1) TMVar = CellVariable(mesh=mesh, value=params['TM'] * shift, hasOld=1) TCVar = CellVariable(mesh=mesh, value=params['TC'] * shift, hasOld=1) P3Var = CellVariable(mesh=mesh, value=params['P3'] * shift, hasOld=1) P2Var = CellVariable(mesh=mesh, value=params['P2'] * shift, hasOld=1) RVar = CellVariable(mesh=mesh, value=params['R'], hasOld=1) PN = P3Var + P2Var KMscCoeff = params['chiK'] * (RVar + 1) * (1 - KCVar - KMVar.cellVolumeAverage) KMspCoeff = params['lambdaK'] / (1 + PN / params['kappaK'])
__docformat__ = 'restructuredtext' from fipy import CellVariable, Grid1D, PeriodicGrid1D, TransientTerm, VanLeerConvectionTerm, DefaultAsymmetricSolver, Viewer from fipy.tools import numerix L = 20. nx = 40 dx = L / nx cfl = 0.5 velocity = 1.0 dt = cfl * dx / velocity steps = int(L / 4. / dt / velocity) mesh = Grid1D(dx=dx, nx=nx) periodicMesh = PeriodicGrid1D(dx=dx, nx=nx // 2) startingArray = numerix.zeros(nx, 'd') startingArray[2 * nx // 10:3 * nx // 10] = 1. var1 = CellVariable(name="non-periodic", mesh=mesh, value=startingArray) var2 = CellVariable(name="periodic", mesh=periodicMesh, value=startingArray[:nx // 2]) eq1 = TransientTerm() - VanLeerConvectionTerm(coeff=(-velocity, )) eq2 = TransientTerm() - VanLeerConvectionTerm(coeff=(-velocity, ))
nx = 100 dx = L/nx timeStep = dx/10.0 steps = 150 phim = 0.10 # mobile zone porosity phiim = 0.05 # immobile zone porosity beta = 0.05 # mobile/immobile domain transfer rate D = 1.0E-1 # mobile domain diffusion coeff Rm = 1.0 # mobile domain retardation coefficient Rim = 1.0 # immobile domain retardation coefficient betaT = phiim*Rim/(phim*Rm) DR = D/Rm m = Grid1D(dx=dx, nx=nx) c0 = np.zeros(nx, 'd') c0[20:50] = 1.0 # mobile domain concentration cm = CellVariable(name="$c_m$", mesh=m, value=c0) # immobile domain concentration cim = CellVariable(name="$c_{im}$", mesh=m, value=0.0) cm.constrain(0, m.facesLeft) cm.constrain(0, m.facesRight) cim.constrain(0, m.facesLeft) cim.constrain(0, m.facesRight)