Exemple #1
0
    def _setup_equation(self, biomass_height):
        height = biomass_height + self._layer_height
        size = height * self._layer
        mesh = self.space.construct_mesh(height)
        variables, terms = [], []
        phi = CellVariable(name=self.solute.name, mesh=mesh, hasOld=True)
        for r in self.reactions:
            variables.append(
                CellVariable(name=f"{r.bacteria.name}_rate",
                             mesh=mesh,
                             value=0.0))
            terms.append(
                ImplicitSourceTerm(coeff=(variables[-1] / (phi + self._sr))))
        equation = DiffusionTerm(coeff=self.diffusivity) - sum(terms)
        phi.constrain(1, where=mesh.facesTop)

        for var, coef in zip(
                variables,
            [r.rate_coefficient()[:size] for r in self.reactions]):
            try:
                var.setValue(coef / self.space.dV)
            except ValueError as err:
                print("Boundary layer height greater than system size")
                raise err
        phi.setValue(self.solute.value.reshape(-1)[:size])
        return equation, phi, size
Exemple #2
0
def GetAz(Bx, By, Jz, Nc, dl):

    mesh = Grid2D(dx=dl[0], dy=dl[1], nx=Nc[0], ny=Nc[1])

    _Az = CellVariable(mesh=mesh, value=0.0)

    _Bx = CellVariable(mesh=mesh)
    _Bx.value = np.reshape(Bx, Nc[0] * Nc[1], order='F')

    _By = CellVariable(mesh=mesh)
    _By.value = np.reshape(By, Nc[0] * Nc[1], order='F')

    _Jz = CellVariable(mesh=mesh)
    _Jz.value = np.reshape(Jz, Nc[0] * Nc[1], order='F')

    _Az.equation = (DiffusionTerm(coeff=1.0) + _Jz == 0)

    # beware of the sign of the flux : always consider outward direction
    BCs = [
        FixedFlux(value=_By.getFaceValue(), faces=mesh.getFacesLeft()),
        FixedFlux(value=-_By.getFaceValue(), faces=mesh.getFacesRight()),
        FixedFlux(value=-_Bx.getFaceValue(), faces=mesh.getFacesBottom()),
        FixedFlux(value=_Bx.getFaceValue(), faces=mesh.getFacesTop())
    ]

    _Az.equation.solve(var=_Az, boundaryConditions=BCs)

    Az = np.reshape(_Az.value, Nc, order='F')

    return Az
Exemple #3
0
    def __init__(self,
                 X=None,
                 T=None,
                 time_steps=5,
                 max_time=0.4,
                 num_cells=25,
                 L=1.):
        """Initialize the objet.

        Keyword Arguments:
            X           ---     The sensor locations.
            T           ---     The sensor measurment times.
            time_steps  ---     How many timesteps do you want to measure.
            max_time    ---     The maximum solution time.
            num_cells   ---     The number of cells per dimension.
            L           ---     The size of the computational domain.
        """
        assert isinstance(num_cells, int)
        self._num_cells = num_cells
        assert isinstance(L, float) and L > 0.
        self._dx = L / self.num_cells
        self._mesh = Grid2D(dx=self.dx,
                            dy=self.dx,
                            nx=self.num_cells,
                            ny=self.num_cells)
        self._phi = CellVariable(name='solution variable', mesh=self.mesh)
        self._source = CellVariable(name='source term',
                                    mesh=self.mesh,
                                    hasOld=True)
        self._eqX = TransientTerm() == ExplicitDiffusionTerm(
            coeff=1.) + self.source
        self._eqI = TransientTerm() == DiffusionTerm(coeff=1.) + self.source
        self._eq = self._eqX + self._eqI
        assert isinstance(max_time, float) and max_time > 0.
        self._max_time = max_time
        #self.max_time / time_steps #.
        if X is None:
            idx = range(self.num_cells**2)
        else:
            idx = []
            x1, x2 = self.mesh.cellCenters
            for x in X:
                dist = (x1 - x[0])**2 + (x2 - x[1])**2
                idx.append(np.argmin(dist))
        self._idx = idx
        if T is None:
            T = np.linspace(0, self.max_time, time_steps)[1:]
        self._max_time = T[-1]
        self._T = T
        self._dt = self.T[0] / time_steps
        super(Diffusion, self).__init__(5,
                                        len(self.T) * len(self.idx),
                                        name='Diffusion Solver')
Exemple #4
0
def GetAz(Bx, By, Jz, Nc, dl):

    mesh = Grid2D(dx=dl[0], dy=dl[1], nx=Nc[0], ny=Nc[1])

    _Az = CellVariable(mesh=mesh, value=0.0)

    _Bx = CellVariable(mesh=mesh)
    _Bx.value = np.reshape(Bx, Nc[0] * Nc[1], order='F')

    _By = CellVariable(mesh=mesh)
    _By.value = np.reshape(By, Nc[0] * Nc[1], order='F')

    _Jz = CellVariable(mesh=mesh)
    _Jz.value = np.reshape(Jz, Nc[0] * Nc[1], order='F')

    _Az.equation = (DiffusionTerm(coeff=1.0) + _Jz == 0)

    #diffcoeff = CellVariable(mesh=mesh, value = 1.0)
    #diffTerm = DiffusionTerm(coeff = diffcoeff)
    #diffTerm = DiffusionTerm(coeff = 1.0)
    #diffcoeff.constrain(0., mesh.exteriorFaces)

    # beware of the sign of the flux : always consider outward direction
    _Az.faceGrad.constrain(_By.arithmeticFaceValue, where=mesh.facesLeft)
    _Az.faceGrad.constrain(-_By.arithmeticFaceValue, where=mesh.facesRight)
    _Az.faceGrad.constrain(-_Bx.arithmeticFaceValue, where=mesh.facesBottom)
    _Az.faceGrad.constrain(_Bx.arithmeticFaceValue, where=mesh.facesTop)

    #_Az.faceGrad.constrain( _By.arithmeticFaceValue[mesh.facesLeft] , where=mesh.facesLeft)
    #_Az.faceGrad.constrain(-_By.arithmeticFaceValue[mesh.facesRight] , where=mesh.facesRight)
    #_Az.faceGrad.constrain(-_Bx.arithmeticFaceValue[mesh.facesBottom] , where=mesh.facesBottom)
    #_Az.faceGrad.constrain( _Bx.arithmeticFaceValue[mesh.facesTop] , where=mesh.facesTop)

    #_Az.equation = (diffTerm+_Jz == 0)
    #_Az.equation = (DiffusionTerm(diffcoeff)+ (mesh.exteriorFaces*exteriorFlux).divergence + _Jz== 0)
    #_Az.equation = (diffTerm + _Jz == 0)

    #BCs = [FixedFlux(value= _By.getFaceValue(), faces=mesh.getFacesLeft()),
    #       FixedFlux(value=-_By.getFaceValue(), faces=mesh.getFacesRight()),
    #       FixedFlux(value=-_Bx.getFaceValue(), faces=mesh.getFacesBottom()),
    #       FixedFlux(value= _Bx.getFaceValue(), faces=mesh.getFacesTop())]

    #_Az.equation.solve(var=_Az, boundaryConditions=BCs)
    _Az.equation.solve(var=_Az)

    Az = np.reshape(_Az.value, Nc, order='F')

    return Az
    def __solve_diffusion(self, model):
        oxygen_grid = model.environments[self.oxygen_env_name]
        nx = oxygen_grid.xsize
        ny = oxygen_grid.ysize
        nz = oxygen_grid.zsize

        dx = dy = dz = 1.0

        D = self.oxygen_diffusion_coeff

        mesh = Grid3D(dx=dx, dy=dy, nx=nx, ny=ny, dz=dz, nz=nz)

        phi = CellVariable(name="solutionvariable", mesh=mesh)
        phi.setValue(0.)

        start = time.time()
        for _ in range(self.diffusion_solve_iterations):
            source_grid, sink_grid = self.__get_source_sink_grids(phi, model)
            eq = TransientTerm() == DiffusionTerm(
                coeff=D) + source_grid - sink_grid

            eq.solve(var=phi, dt=1)
            eq = TransientTerm() == DiffusionTerm(coeff=D)

            eq.solve(var=phi, dt=self.dt)
        end = time.time()
        print("Solving oxygen diffusion took %s seconds" % str(end - start))

        return phi, nx, ny, nz
Exemple #6
0
 def initializeTright(self):
     extrapol_dist = (
         self.mesh.mesh.faceCenters[0, self.mesh.mesh.facesRight()][0] -
         self.mesh.cell_mid_points)
     self.dxf = CellVariable(mesh=self.mesh.mesh, value=extrapol_dist)
     self.variables['T_right'] = (self.variables['T'] +
                                  self.variables['T'].grad[0] * self.dxf)
 def define_convection_variable(self, current_time):
     x_convection, y_convection = self.get_convection_x_and_y(current_time)
     if self.baseline_convection is None:
         convection_variable = CellVariable(mesh=self.mesh, rank=1) #  Only define the variable from scratch once
     else:
         convection_variable = self.baseline_convection
     convection_variable.setValue((x_convection, y_convection))
     return convection_variable
Exemple #8
0
    def icir_rect(self):
        # step 1: Mesh
        mesh = Grid2D(dx=self.gsize, dy=self.gsize, nx=self.xy_n[0], ny=self.xy_n[1])

        # step 2: Equation
        phi = CellVariable(mesh=mesh, name='potential phi', value=0.)
        eqn = (DiffusionTerm(coeff = 1.) == 0.)

        # step 3: Boundary conditions
        # compute flow of 4 vertexes
        # one vertex has 2 components of wind vector, (x, y)
        vertexWindVec = np.array([ [0.0 for i in range(2)] for i in range(4)])
        for i in range(4): # 4 vertexes
            for j in range(2): # 2 components
                vertexWindVec[i, j] = self.mean_flow[j] \
                        + self.colored_noise(self.vertexWindVecRanInc[i][j])
        # interpolate flow vector on sim area edges, and set neumann boundary
        #   conditions, because /grad /phi = V(x,y)
        # get all points which lie on the center of edges of cells
        X, Y = mesh.faceCenters
        # /grad /phi array, of points of mesh face centers
        #   grad_phi_bc[0, :]  /grad/phi_x
        #   grad_phi_bc[1, :]  /grad/phi_y
        grad_phi_bc = np.zeros_like(mesh.faceCenters())
        # p: points on one edge to interpolate, 1 dimension
        # vx, vy: x&y components of interpolated wind vectors of points list p
        # vertex index, for interpolate bc on 4 edges
        # vertexIndex[0] = [1,2], down  boundary, 0<x<nx*dx, y=0
        # vertexIndex[1] = [1,0], left  boundary, x=0, 0<y<ny*dy
        # vertexIndex[2] = [0,3], up    boundary, 0<x<nx*dx, y=ny*dy
        # vertexIndex[3] = [2,3], right boundary, x=nx*dx, 0<y<ny*dy
        vertexIndex = np.array([ [1,2], [1,0], [0,3], [2,3] ])
        for i in range(4): # 4 edges for 2D rect area
            p = np.arange(self.gsize/2, self.gsize*self.xy_n[i%2], self.gsize)
            vx = np.interp(p, [0.0, self.gsize*self.xy_n[i%2]], \
                    [vertexWindVec[vertexIndex[0,0], 0], \
                    vertexWindVec[vertexIndex[0,1], 0]]).T.reshape(1,-1)[0]
            vy = np.interp(p, [0.0, self.gsize*self.xy_n[i%2]], \
                    [vertexWindVec[vertexIndex[0,0], 1], \
                    vertexWindVec[vertexIndex[0,1], 1]]).T.reshape(1,-1)[0]
            print 'vx = ' + str(vx)
            if i == 0: # down boundary
                grad_phi_bc[:, mesh.facesDown()] = np.array([vx, vy])
            elif i == 1: # left boundary
                grad_phi_bc[:, mesh.facesLeft()] = np.array([vx, vy])
            elif i == 2: # up boundary
                grad_phi_bc[:, mesh.facesUp()] = np.array([vx, vy])
            elif i == 3: # right boundary
                grad_phi_bc[:, mesh.facesRight()] = np.array([vx, vy])
        # set neumann boundary condition
        phi.faceGrad.constrain(((grad_phi_bc[0]),(grad_phi_bc[1])), where=mesh.exteriorFaces)

        # step 4: Solve
        eqn.solve(var=phi)
        #print str(phi)
        #print str(type(np.array(phi)))
        self.wind_phi_field = np.array(phi)
        self.wind_mesh_centers = mesh.cellCenters()
Exemple #9
0
 def define_cellvariables(self, phi_s_initial, cs_surface_initial,
                          phi_e_initial, theta_initial, ce_initial,
                          sim_cell):
     self.phi_s = CellVariable(mesh=self.axial_mesh, value=phi_s_initial)
     # self.deltaPhiS = CellVariable(mesh=self.axial_mesh, value = 0.)                                               # For Newton iteration
     self.phi_e_copy_from_supermesh = CellVariable(mesh=self.axial_mesh,
                                                   value=phi_e_initial)
     self.Cs_surface = CellVariable(mesh=self.axial_mesh,
                                    value=cs_surface_initial)
     self.overpotential = CellVariable(
         mesh=self.axial_mesh,
         value=(phi_s_initial - phi_e_initial -
                self.calc_ocp_interp(theta_initial)))
     self.Cs_p2d = CellVariable(mesh=self.p2d_mesh,
                                value=cs_surface_initial[0],
                                hasOld=True)
     self.j0 = CellVariable(
         mesh=self.axial_mesh,
         value=self.k_norm * numerix.absolute(
             ((self.cs_max - cs_surface_initial) / self.cs_max)
             **(1 - sim_cell.alpha)) * numerix.absolute(
                 (cs_surface_initial / self.cs_max)**sim_cell.alpha) *
         numerix.absolute(
             (ce_initial / ce_initial)**(1.0 - sim_cell.alpha)))
     self.uocp = CellVariable(mesh=self.axial_mesh,
                              value=self.calc_ocp_interp(self.Cs_surface /
                                                         self.cs_max))
Exemple #10
0
    def __get_source_sink_grids(self, phi, model):
        xsize = model.environments[self.vegf_env_name].xsize
        ysize = model.environments[self.vegf_env_name].ysize
        zsize = model.environments[self.vegf_env_name].zsize

        agent_grid = model.environments["agentEnv"].grid
        phi_tmp = np.reshape(phi._array, (xsize, ysize, zsize))

        source_grid = CellVariable(name="source",
                                   mesh=Grid3D(dx=1,
                                               dy=1,
                                               dz=1,
                                               nx=xsize,
                                               ny=ysize,
                                               nz=zsize))

        for coordinate, agents in agent_grid.items():
            if len(agents) == 0:
                continue

            concentration_at_pos = phi_tmp[coordinate[0]][coordinate[1]][
                coordinate[2]]

            source_rate = sum([
                a.current_vegf_secretion_rate for a in agents
                if (a.__class__.__name__ == "CancerCell"
                    and not (a.quiescent or a.dead))
            ])
            # A pre-estimate of what the concentration at this position will
            # be. This of course neglects diffusion,
            # but can give an estimate of how we should regulate our sources
            # and sinks
            estimated_concentration = concentration_at_pos + source_rate

            # If our estimated concentration is greater than our maximum
            # source rate, this means we really are outputting
            # too much. At most, we want to achieve equilibrium between
            # sources and environment, so we reduce our
            # output rate. Of course, we can't reduce our output rate by
            # more than the output rate itself
            if estimated_concentration >= self.max_vegf:
                source_rate -= min(source_rate,
                                   estimated_concentration - self.max_vegf)

            i = np.ravel_multi_index(
                [coordinate[0], coordinate[1], coordinate[2]],
                (xsize, ysize, zsize))

            source_grid.value[i] = source_rate

        return source_grid
Exemple #11
0
    def Battery_cellvariables(self, neg_epsilon_e, sep_epsilon_e,
                              pos_epsilon_e, neg_a_s, pos_a_s, nx_neg, nx_sep,
                              nx_pos, j_battery_value, ce_initial,
                              phi_e_initial, neg_L, sep_L, pos_L, neg_De_eff,
                              sep_De_eff, pos_De_eff):
        self.Ce = CellVariable(mesh=self.axial_mesh,
                               value=ce_initial,
                               hasOld=True)
        self.phi_e = CellVariable(mesh=self.axial_mesh, value=phi_e_initial)

        self.epsilon_e_value = numerix.zeros(nx_neg + nx_sep + nx_pos)
        self.epsilon_e_value[0:nx_neg], self.epsilon_e_value[
            nx_neg:nx_neg + nx_sep] = neg_epsilon_e, sep_epsilon_e
        self.epsilon_e_value[nx_neg + nx_sep:] = pos_epsilon_e
        self.epsilon_e = CellVariable(mesh=self.axial_mesh,
                                      value=self.epsilon_e_value)

        self.epsilon_e_eff_value = numerix.zeros(nx_neg + nx_sep + nx_pos)
        self.epsilon_e_eff_value[0:nx_neg] = neg_epsilon_e**self.brug
        self.epsilon_e_eff_value[nx_neg:nx_neg +
                                 nx_sep] = sep_epsilon_e**self.brug
        self.epsilon_e_eff_value[nx_neg + nx_sep:] = pos_epsilon_e**self.brug
        self.epsilon_e_eff = CellVariable(mesh=self.axial_mesh,
                                          value=self.epsilon_e_eff_value)

        self.a_s_value = numerix.zeros(nx_neg + nx_pos + nx_sep)
        self.a_s_value[0:nx_neg] = neg_a_s
        self.a_s_value[nx_neg:nx_neg + nx_sep] = 0.0
        self.a_s_value[nx_neg + nx_sep:] = pos_a_s
        self.a_s = CellVariable(mesh=self.axial_mesh, value=self.a_s_value)

        self.L_value = numerix.zeros(nx_neg + nx_pos + nx_sep)
        self.L_value[0:nx_neg], self.L_value[nx_neg:nx_neg +
                                             nx_sep] = neg_L, sep_L
        self.L_value[nx_neg + nx_sep:] = pos_L
        self.L = CellVariable(mesh=self.axial_mesh, value=self.L_value)

        self.De_eff_value = numerix.zeros(nx_neg + nx_pos + nx_sep)
        self.De_eff_value[0:nx_neg], self.De_eff_value[
            nx_neg:nx_neg + nx_sep], self.De_eff_value[
                nx_neg + nx_sep:] = neg_De_eff, sep_De_eff, pos_De_eff
        self.De_eff = CellVariable(mesh=self.axial_mesh,
                                   value=self.De_eff_value)

        self.j_battery = CellVariable(mesh=self.axial_mesh,
                                      value=j_battery_value)
Exemple #12
0
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
Exemple #13
0
 def initializeDiagnostic(self,
                          variable,
                          funpointer,
                          default=0.0,
                          face_variable=False,
                          output_variable=True):
     if not face_variable:
         self.variables[variable] = CellVariable(name=variable,
                                                 mesh=self.mesh.mesh,
                                                 value=default)
     else:
         self.variables[variable] = FaceVariable(name=variable,
                                                 mesh=self.mesh.mesh,
                                                 value=default)
     self.diagnostic_modules[variable] = DiagnosticModule(funpointer, self)
     if output_variable:
         self.variables_store.append(variable)
     self.diagnostic_update_order.append(variable)
    def define_solution_variable(self, existing_solution=None, boundary_source = None):
        if existing_solution is None:
            initial_condition_value = self.parameter.IC_value
            ic_region = self.parameter.IC_region
            ic_array = copy.deepcopy(self.mesh.cellCenters[0])

            xmesh = self.mesh.cellCenters[0]
            ymesh = self.mesh.cellCenters[1]

            ic_array[xmesh < ic_region['xmin']] = 0
            ic_array[xmesh >= ic_region['xmin']] = initial_condition_value
            ic_array[xmesh > ic_region['xmax']] = 0
            ic_array[ymesh < ic_region['ymin']] = 0
            ic_array[ymesh > ic_region['ymax']] = 0

            ic_array.mesh = self.mesh

        else:
            ic_array = existing_solution

        # Create solution variable
        phi = CellVariable(name="solution variable",
                           mesh=self.mesh,
                           value=ic_array)

        # Edit to add boundary condition if requried.
        if boundary_source is not 'no flux' or boundary_source is not None:
            x, y = self.mesh.faceCenters

            boundary_source_value = self.parameter.boundary_source_value
            boundary_source_region = self.parameter.boundary_source_region

            boundary_source_mask = (
                (x > boundary_source_region.xmin) &
                (x < boundary_source_region.xmax) &
                (y > boundary_source_region.ymin) &
                (y < boundary_source_region.ymax)
            )

            # phi.faceGrad.constrain(0*self.mesh.faceNormals, self.mesh.exteriorFaces)
            phi.faceGrad.constrain(boundary_source_value*self.mesh.faceNormals,
                                   self.mesh.exteriorFaces & boundary_source_mask)

        return phi
Exemple #15
0
    def __init__(self,
                 tsmesh,
                 time_step_module=None,
                 output_step_module=None,
                 h_initial=0.0,
                 T_initial=None,
                 time_initial=None,
                 proportion_frozen_initial=None,
                 forcing_module=None,
                 thermal_properties=None,
                 bc_inside=None,
                 bc_headwall=None):
        # T_initial only works if thermal_properties are provided
        ThawSlump.__init__(self,
                           tsmesh,
                           time_step_module=time_step_module,
                           output_step_module=output_step_module,
                           time_initial=time_initial,
                           forcing_module=forcing_module,
                           thermal_properties=thermal_properties)
        self._initializeSourcesZero(source_name='S')
        self._initializeSourcesZero(source_name='S_inside')
        self._initializeSourcesZero(source_name='S_headwall')
        # specific volumetric enthalpy
        self.variables['h'] = CellVariable(name='h',
                                           mesh=self.mesh.mesh,
                                           value=h_initial,
                                           hasOld=True)
        self.addStoredVariable('h')
        if T_initial is not None:  # essentially overrides h_initial
            self.initializeEnthalpyTemperature(
                T_initial, proportion_frozen=proportion_frozen_initial)
        if (bc_inside is not None and bc_headwall is not None
                and self.thermal_properties is not None
                and self.forcing_module is not None):
            bcc = BoundaryConditionCollection1D(bc_headwall=bc_headwall,
                                                bc_inside=bc_inside)
            self.specifyBoundaryConditions(bcc)

        self._output_module.storeInitial(self)
Exemple #16
0
    def run(self, initialConditions, step_n):
        pinit = np.zeros(
            self.nx * self.ny *
            self.nz)  #TODO: how to map from the ABM domain to this form
        if initialConditions == None:
            for i in range(self.nx * self.ny * self.nz):
                pinit[i] = float(
                    decimal.Decimal(random.randrange(8, 50)) /
                    1000000)  #ng/mm3
        else:
            pass

        print("Initial values:")
        print(pinit)
        phi = CellVariable(name="Concentration (ng/ml)",
                           mesh=self.mesh,
                           value=pinit)
        t = Variable(0.)
        for step in range(step_n):
            print("Time = {}".format(t.value))
            self.eq.solve(var=phi, dt=self.timeStepDuration)
            t.setValue(t.value + self.timeStepDuration)
        return phi.value
Exemple #17
0
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)

Pion = CellVariable(mesh=mesh,
                    name='Positive ion Charge Density',
                    value=y01(mesh.x))
Nion = CellVariable(mesh=mesh,
                    name='Negative ion Charge Density',
                    value=y02(mesh.x))
potential = CellVariable(mesh=mesh, name='Potential', value=y03(mesh.x))
Jp = CellVariable(mesh=mesh, name='Positive ion Current Density', value=0.)
Jn = CellVariable(mesh=mesh, name='Negative ion Current Density', value=0.)

Jp.value = -mu_p * Pion * potential.arithmeticFaceValue.divergence + Dn * Pion.arithmeticFaceValue.divergence
Jn.value = -mu_n * Nion * potential.arithmeticFaceValue.divergence + Dn * Pion.arithmeticFaceValue.divergence

Pion.equation = TransientTerm(
    coeff=1,
    var=Pion) == -k_rec * Pion * Nion + (Jp.arithmeticFaceValue).divergence
Nion.equation = TransientTerm(
Exemple #18
0
    >>> print var.allclose(analyticalArray)
    1

"""

__docformat__ = 'restructuredtext'

from fipy import Tri2D, CellVariable, DiffusionTerm, Viewer

nx = 50
dx = 1.

mesh = Tri2D(dx = dx, nx = nx)

valueLeft = 0.
valueRight = 1.
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)
    viewer.plot()
    x = mesh.cellCenters[0]
    Lx = nx * dx
    analyticalArray = valueLeft + (valueRight - valueLeft) * x / Lx
    print var.allclose(analyticalArray)
    raw_input("finished")
Exemple #19
0
import time
from fipy import PeriodicGrid2D

from params_fipy import (A_RAW, NOISE_MAGNITUDE, TIME_MAX, DT, N_CELLS,
                         DOMAIN_LENGTH, TIME_STRIDE, chi_AB, N_A, N_B, GIBBS,
                         DESIRED_RESIDUAL)

print("Yay")

# # Define mesh
# mesh = Grid2D(dx=dx, dy=dx, nx=N_CELLS, ny=N_CELLS)
mesh = PeriodicGrid2D(nx=50.0, ny=50.0, dx=0.1, dy=0.1)
print("mesh loaded")

# We need to define the relevant variables:
x_a = CellVariable(name=r"x_a", mesh=mesh, hasOld=1)
mu_AB = CellVariable(name=r"mu_AB", mesh=mesh, hasOld=1)

# We need to introduce the noise
noise = GaussianNoiseVariable(mesh=mesh, mean=A_RAW,
                              variance=NOISE_MAGNITUDE).value

x_a[:] = noise

# x_a.setValue(GaussianNoiseVariable(mesh=mesh,
#                                    mean=A_RAW,
#                                    variance=NOISE_MAGNITUDE)
# )

# def g(x_a):
#     if GIBBS == "FH":
Exemple #20
0
from builtins import range
from fipy import input
from fipy import CellVariable, Tri2D, TransientTerm, ExplicitDiffusionTerm, DefaultSolver, Viewer
from fipy.tools import numerix

dx = 1.
dy = 1.
nx = 10
ny = 1
valueLeft = 0.
valueRight = 1.
timeStepDuration = 0.02

mesh = Tri2D(dx, dy, nx, ny)

var = CellVariable(name="concentration", mesh=mesh, value=valueLeft)

eq = TransientTerm() == ExplicitDiffusionTerm()

solver = DefaultSolver(tolerance=1e-6, iterations=1000)

var.constrain(valueLeft, mesh.facesLeft)
var.constrain(valueRight, mesh.facesRight)

answer = numerix.array([
    0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00,
    0.00000000e+00, 0.00000000e+00, 1.58508452e-07, 6.84325019e-04,
    7.05111362e-02, 7.81376523e-01, 0.00000000e+00, 0.00000000e+00,
    0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00,
    0.00000000e+00, 4.99169535e-05, 1.49682805e-02, 3.82262622e-01,
    0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00,
Extrude {{ {{1, 0, 0}}, {{0, 0, 0}}, Pi/2}} {{
  Surface{{16}}; 
}}

Physical Surface("inner") = {{30, 26}};
Physical Surface("outer") = {{37}};
Physical Volume("volume") = {{1}};

'''.format(cellSize, l1, l2,
           math.tan(beta) * (l2 - l1), l3,
           math.tan(alpha) * l3)

mesh = Gmsh3D(geometryTemplate)

# Enthaelt die Temperatur
phi = CellVariable(name="Temperature", mesh=mesh, value=T0)

# boundry conditions ----------------------------------------------------------

phi.constrain(Ti, where=mesh.physicalFaces["inner"])
phi.constrain(Te, where=mesh.physicalFaces["outer"])

# calculation -----------------------------------------------------------------

viewer = Viewer(vars=phi, datamin=200., datamax=Te * 1.01)

print "Calculation started"
started = time.clock()

# Loest die Stationaere Waermegleichung
DiffusionTerm(coeff=D).solve(var=phi)
Exemple #22
0
valueRight = 0.
L = 10.
nx = 400
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()
    raw_input("press key to continue")
    for step in range(steps):
        eq.solve(var,
                 dt = timeStepDuration,
Exemple #23
0
    temp_yR = (2 * temp_i[:-2, 1:-1] - 2 * temp_i[1:-1, 1:-1]) / (dx**2)
    temp_yy = (temp_i[1:-1, 2:] - 2 * temp_i[1:-1, 1:-1] +
               temp_i[:2, 1:-1]) / (dy**2)
    temp_xL = (2 * temp_i[1:-1, 2:] - 2 * temp_i[1:-1, 1:-1]) / (dy**2)
    temp_xR = (2 * temp_i[1:-1, :-2] - 2 * temp_i[1:-1, 1:-1]) / (dy**2)
    temp_f[1:-1, 1:-1] = temp_xx + temp_yy
    temp_f[-1, 1:-1] = temp_xR
    temp_f[0, 1:-1] = temp_xL
    temp_f[1:-1, 0] = temp_yL
    return temp_f


#%% Phase Field Derivative

#%% Phase Field Variable
phase = CellVariable(name=r'$\phi$', mesh=mesh, hasOld=True)
D_temp = CellVariable(name=r'$\Delta T$', mesh=mesh, hasOld=True)
CHANGE_TEMP = 2.25
#%% Heat Equation
heatEQ = (TransientTerm() == DiffusionTerm(CHANGE_TEMP) +
          (phase - phase.old) / D_time)

#%% Parameter Setup
# ALPHA = 0.015 # Alpha CONSTANT
C_ani = 0.02  # Component of (D) the anisotropic diffusion tensor in 2D
N = 6.  # Symmetry
THETA = np.pi / 8  # Orientation

psi = THETA + np.arctan2(phase.faceGrad[1], phase.faceGrad[0])

PHI = np.tan(N * psi / 2)
del logLevel, logFilename

R_outer = 2e-6  #SETTING  must match what is in .geo file
R_inner = 1e-6  #SETTING  must match what is in .geo file
cellSize = .05 * (R_outer - R_inner)  #SETTING  must match what is in .geo file

#run gmsh gui to produce this mesh (.msh file)
#gmsh infiniteCylinder01.geo
filename = 'infiniteCylinder01.msh'
mesh = Gmsh2D(filename, communicator=serialComm)
del filename

T_initial = 425.08  #deg K
T_infinity = 293.15  #deg K  #SETTING

var = CellVariable(mesh=mesh,
                   value=T_initial - T_infinity)  #let var be T-T_infinity

rho = 6980.  #kg/m^3
cp = 227.  #J/kg/K
k = 59.6  #W/m/K
D_thermal = k / rho / cp

X_faces, Y_faces = mesh.faceCenters

surfaceFaces = (Y_faces > 0) & (
    (X_faces**2 + Y_faces**2)**.5 > R_outer - cellSize / 10.)

#convectionCoeff=200.  #W/m^2/K
Bi_desired = 10.  #SETTING
convectionCoeff = Bi_desired * k / R_inner
logging.info('convection coefficient is %.2E' % convectionCoeff)
Exemple #25
0
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
D_Zohm = (D_max + D_min) / 2.0 + ((D_max - D_min) * numerix.tanh(Z)) / 2.0
# Stap's Model
alpha_sup = 0.5
Exemple #26
0
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'])
KMEq = TransientTerm() - KMscCoeff + ImplicitSourceTerm(KMspCoeff)

TMscCoeff = params['chiT'] * (1 - TCVar - TMVar.cellVolumeAverage)
TMspCoeff = params['lambdaT'] * (KMVar + params['zetaT'])
Exemple #27
0
steps = 100
timeStepDuration = 0.02
L = 1.5
nx = 100
temperature = 1.
phaseTransientCoeff = 0.1
epsilon = 0.008
s = 0.01
alpha = 0.015
temperature = 1.

dx = L / nx

mesh = Grid1D(dx=dx, nx=nx)

phase = CellVariable(name='PhaseField', mesh=mesh, value=1.)

theta = ModularVariable(name='Theta', mesh=mesh, value=1.)
theta.setValue(0., where=mesh.cellCenters[0] > L / 2.)

mPhiVar = phase - 0.5 + temperature * phase * (1 - phase)
thetaMag = theta.old.grad.mag
implicitSource = mPhiVar * (phase - (mPhiVar < 0))
implicitSource += (2 * s + epsilon**2 * thetaMag) * thetaMag

phaseEq = TransientTerm(phaseTransientCoeff) == \
          ExplicitDiffusionTerm(alpha**2) \
          - ImplicitSourceTerm(implicitSource) \
          + (mPhiVar > 0) * mPhiVar * phase

if __name__ == '__main__':
    """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',
                    value=y02(x))

potential = CellVariable(mesh=mesh, name='Potential', value=y03(x))

#EQUATION SETUP BASIC DESCRIPTION
'''Equations to solve for each varible must be defined:
  -TransientTerm = dvar/dt
  -ConvectionTerm = dvar/dx
  -DiffusionTerm = d^2var/dx^2
  -Source terms can be described as they would appear mathematically
Notes:  coeff = terms that are multiplied by the Term.. must be rank-1 FaceVariable for ConvectionTerm
Exemple #29
0
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, ))

if __name__ == '__main__':

    viewer1 = Viewer(vars=var1)
    viewer2 = Viewer(vars=var2)
    viewer1.plot()
    viewer2.plot()
Exemple #30
0
Line Loop(1) = {1, 2, 3, 4, 5, 6};
Line Loop(2) = {7, 8, 9, 10};
Line Loop(3) = {11, 12, 13, 14};
Plane Surface(1) = {1, 2, 3};
Plane Surface(2) = {2};
Plane Surface(3) = {3};

Physical Line("Ground") = {4, 5, 6};
Physical Surface("Field") = {1};
Physical Surface("Anode") = {2};
Physical Surface("Cathode") = {3};
"""
for refinement in range(10):
    mesh = Gmsh2D(geo, background=monitor)

    charge = CellVariable(mesh=mesh, name=r"$\rho$", value=0.)
    charge.setValue(+1, where=mesh.physicalCells["Anode"])
    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))