Commit 9b2ace20 by Markus Holzer

### Update documentation

parent 58e206b4
RELEASE-VERSION 0 → 100644
 0.2.12.dev4+729b9d0110 \ No newline at end of file
This diff is collapsed.
 ... ... @@ -361,7 +361,7 @@ "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.6.8" "version": "3.7.4" } }, "nbformat": 4, ... ...
 %% Cell type:code id: tags:  python from lbmpy.session import *  %% Cell type:markdown id: tags: # Tutorial 03: Defining LB methods in *lbmpy* ## A) General Form %% Cell type:markdown id: tags: The lattice Boltzmann equation in its most general form is: $$f_q(\mathbf{x} + \mathbf{c}_q \delta t, t+\delta t) = K\left( f_q(\mathbf{x}, t) \right)$$ with a discrete velocity set $\mathbf{c}_q$ (stencil) and a generic collision operator $K$. So a lattice Boltzmann method can be fully defined by picking a stencil and a collision operator. The collision operator $K$ has the following structure: - Transformation of particle distribution function $f$ into collision space. This transformation has to be invertible and may be nonlinear. - The collision operation is an convex combination of the pdf representation in collision space $c$ and some equilibrium vector $c^{(eq)}$. This equilibrium can also be defined in physical space, then $c^{(eq)} = C( f^{(eq)} )$. The convex combination is done elementwise using a diagonal matrix $S$ where the diagonal entries are the relaxation rates. - After collision, the collided state $c'$ is transformed back into physical space ![](../img/collision.svg) The full collision operator is: $$K(f) = C^{-1}\left( (I-S)C(f) + SC(f^{(eq}) \right)$$ or $$K(f) = C^{-1}\left( C(f) - S (C(f) - C(f^{(eq})) \right)$$ %% Cell type:markdown id: tags: ## B) Moment-based relaxation The most commonly used LBM collision operator is the multi relaxation time (MRT) collision. In MRT methods the collision space is spanned by moments of the distribution function. This is a very natural approach, since the pdf moments are the quantities that go into the Chapman Enskog analysis that is used to show that LB methods can solve the Navier Stokes equations. Also the lower order moments correspond to the macroscopic quantities of interest (density/pressure, velocity, shear rates, heat flux). Furthermore the transformation to collision space is linear in this case, simplifying the collision equations: $$K(f) = C^{-1}\left( C(f) - S (C(f) - C(f^{(eq})) \right)$$ $$K(f) = f - \underbrace{ C^{-1}SC}_{A}(f - f^{(eq)})$$ in *lbmpy* the following formulation is used, since it is more natural to define the equilibrium in moment-space instead of physical space: $$K(f) = f - C^{-1}S(Cf - c^{(eq)})$$ %% Cell type:markdown id: tags: ### Use a pre-defined method Lets create a moment-based method in *lbmpy* and see how the moment transformation $C$ and the relaxation rates that comprise the diagonal matrix $S$ can be defined. We start with a function that creates a basic MRT model. Don't use this for real simulations, there orthogonalized MRT methods should be used, as discussed in the next section. %% Cell type:code id: tags:  python from lbmpy.creationfunctions import create_lb_method method = create_lb_method(stencil='D2Q9', method='mrt_raw') # check also method='srt', 'trt', 'mrt' or 'mrt3' # check also method='srt', 'trt', 'mrt' method  %% Output %% Cell type:markdown id: tags: The first column labeled "Moment" defines the collision space and thus the transformation matrix $C$. The remaining columns specify the equilibrium vector in moment space $c^{(eq)}$ and the corresponding relaxation rate. Each row of the "Moment" column defines one row of $C$. In the next cells this matrix and the discrete velocity set (stencil) of our method are shown. Check for example the second last row of the table $x^2 y$: In the corresponding second last row of the moment matrix $C$ where each column stands for a lattice velocity (for ordering visualized stencil below) and each entry is the expression $x^2 y$ where $x$ and $y$ are the components of the lattice velocity. In general the transformation matrix $C_{iq}$ is defined as; $$c_i = C_{iq} f_q = \sum_q m_i(c_q)$$ where $m_i(c_q)$ is the $i$'th moment polynomial where $x$ and $y$ are substituted with the components of the $q$'th lattice velocity %% Cell type:code id: tags:  python # Transformation matrix C method.moment_matrix  %% Output $\displaystyle \left[\begin{matrix}1 & 1 & 1 & 1 & 1 & 1 & 1 & 1 & 1\\0 & 0 & 0 & -1 & 1 & -1 & 1 & -1 & 1\\0 & 1 & -1 & 0 & 0 & 1 & 1 & -1 & -1\\0 & 0 & 0 & 1 & 1 & 1 & 1 & 1 & 1\\0 & 1 & 1 & 0 & 0 & 1 & 1 & 1 & 1\\0 & 0 & 0 & 0 & 0 & -1 & 1 & 1 & -1\\0 & 0 & 0 & 0 & 0 & 1 & 1 & -1 & -1\\0 & 0 & 0 & 0 & 0 & -1 & 1 & -1 & 1\\0 & 0 & 0 & 0 & 0 & 1 & 1 & 1 & 1\end{matrix}\right]$ ⎡1 1 1 1 1 1 1 1 1 ⎤ ⎢ ⎥ ⎢0 0 0 -1 1 -1 1 -1 1 ⎥ ⎢ ⎥ ⎢0 1 -1 0 0 1 1 -1 -1⎥ ⎢ ⎥ ⎢0 0 0 1 1 1 1 1 1 ⎥ ⎢ ⎥ ⎢0 1 1 0 0 1 1 1 1 ⎥ ⎢ ⎥ ⎢0 0 0 0 0 -1 1 1 -1⎥ ⎢ ⎥ ⎢0 0 0 0 0 1 1 -1 -1⎥ ⎢ ⎥ ⎢0 0 0 0 0 -1 1 -1 1 ⎥ ⎢ ⎥ ⎣0 0 0 0 0 1 1 1 1 ⎦ %% Cell type:code id: tags:  python ps.stencil.plot(method.stencil) method.stencil  %% Output $\displaystyle \left( \left( 0, \ 0\right), \ \left( 0, \ 1\right), \ \left( 0, \ -1\right), \ \left( -1, \ 0\right), \ \left( 1, \ 0\right), \ \left( -1, \ 1\right), \ \left( 1, \ 1\right), \ \left( -1, \ -1\right), \ \left( 1, \ -1\right)\right)$ ((0, 0), (0, 1), (0, -1), (-1, 0), (1, 0), (-1, 1), (1, 1), (-1, -1), (1, -1)) %% Cell type:markdown id: tags: ### Orthogonal MRTs For a real MRT method, the moments should be orthogonalized. One can either orthogonalize using the standard scalar product or a scalar product that is weighted with the lattice weights. If unsure, use the weighted version. The next cell shows how to get both orthogonalized MRT versions in lbmpy. %% Cell type:code id: tags:  python weighted_ortho_mrt = create_lb_method(stencil="D2Q9", method="mrt", weighted=True) weighted_ortho_mrt  %% Output %% Cell type:code id: tags:  python ortho_mrt = create_lb_method(stencil="D2Q9", method="mrt", weighted=False) ortho_mrt  %% Output %% Cell type:markdown id: tags: One can check if a method is orthogonalized: %% Cell type:code id: tags:  python ortho_mrt.is_orthogonal, weighted_ortho_mrt.is_weighted_orthogonal  %% Output (True, True) %% Cell type:markdown id: tags: ### Define custom MRT method To choose custom values for the left moment column one can pass a nested list of moments. Moments that should be relaxed with the same paramter are grouped together. *lbmpy* also comes with a few templates for this list taken from literature: %% Cell type:code id: tags:  python from lbmpy.methods import mrt_orthogonal_modes_literature from lbmpy.stencils import get_stencil from lbmpy.moments import MOMENT_SYMBOLS x, y, z = MOMENT_SYMBOLS moments = mrt_orthogonal_modes_literature(get_stencil("D2Q9"), is_weighted=True, is_cumulant=False) moments  %% Output $\displaystyle \left[ \left[ 1\right], \ \left[ x, \ y\right], \ \left[ 3 x^{2} + 3 y^{2} - 2, \ x^{2} - y^{2}, \ x y\right], \ \left[ x \left(3 x^{2} + 3 y^{2} - 4\right), \ y \left(3 x^{2} + 3 y^{2} - 4\right)\right], \ \left[ - 15 x^{2} - 15 y^{2} + 9 \left(x^{2} + y^{2}\right)^{2} + 2\right]\right]$ ⎡ ⎢ ⎡ 2 2 2 2 ⎤ ⎡ ⎛ 2 2 ⎞ ⎛ 2 ⎣[1], [x, y], ⎣3⋅x + 3⋅y - 2, x - y , x⋅y⎦, ⎣x⋅⎝3⋅x + 3⋅y - 4⎠, y⋅⎝3⋅x + ⎡ 2 ⎤⎤ 2 ⎞⎤ ⎢ 2 2 ⎛ 2 2⎞ ⎥⎥ 3⋅y - 4⎠⎦, ⎣- 15⋅x - 15⋅y + 9⋅⎝x + y ⎠ + 2⎦⎦ %% Cell type:markdown id: tags: This nested moment list can be passed to create_lb_method: %% Cell type:code id: tags:  python create_lb_method(stencil="D2Q9", method="mrt", nested_moments=moments)  %% Output %% Cell type:markdown id: tags: If one needs to also specify custom equilibrium moments the following approach can be used %% Cell type:code id: tags:  python rho = sp.symbols("rho") u = sp.symbols("u_:3") omega = sp.symbols("omega_:4") method_table = [ # Conserved moments (1, rho, 0 ), (x, u[0], 0 ), (y, u[1], 0 ), # Shear moments (x*y, u[0]*u[1], omega[0]), (x**2-y**2, u[0]**2 - u[1]**2, omega[0]), (x**2+y**2, 2*rho/3 + u[0]**2 + u[1]**2, omega[1]), # Higher order (x * y**2, u[0]/3, omega[2]), (x**2 * y, u[1]/3, omega[2]), (x**2 * y**2, rho/9 + u[0]**2/3 + u[1]**2/3, omega[3]), ] method = create_generic_mrt(get_stencil("D2Q9"), method_table) method  %% Output %% Cell type:markdown id: tags: Instead of manually defining all entries in the method table, *lbmpy* has functions to fill the table according to a specific pattern. For example: - for a full stencil (D2Q9, D3Q27) there exist exactly 9 or 27 linearly independent moments. These can either be taken as they are, or orthogonalized using Gram-Schmidt, weighted Gram-Schmidt or a Hermite approach - equilibrium values can be computed from the standard discrete equilibrium of order 1,2 or 3. Alternatively they can also be computed as continuous moments of a Maxwellian distribution One option is to start with one of *lbmpy*'s built-in methods and modify it with create_lb_method_from_existing. In the next cell we fix the fourth order relaxation rate to a constant, by writing a function that defines how to alter each row of the collision table. This is for demonstration only, of course we could have done it right away when passing in the collision table. %% Cell type:code id: tags:  python def modification_func(moment, eq, rate): if rate == omega[3]: return moment, eq, 1.0 return moment, eq, rate method = create_lb_method_from_existing(method, modification_func) method  %% Output %% Cell type:markdown id: tags: Our customized method can be directly passed into one of the scenarios. We can for example set up a channel flow with it. Since we used symbols as relaxation rates, we have to pass them in as kernel_params. %% Cell type:code id: tags:  python ch = create_channel(domain_size=(100, 30), lb_method=method, u_max=0.05, kernel_params={'omega_0': 1.8, 'omega_1': 1.4, 'omega_2': 1.5}) ch.run(500) plt.vector_field(ch.velocity[:, :]);  %% Output %% Cell type:markdown id: tags: #### Bonus: Automatic analysis Above we have created a non-orthogonal MRT, where the shear viscosity and bulk viscosity can be independently controlled. For moment-based methods, *lbmpy* also offers an automatic Chapman Enskog analysis that can find the relation between viscosity and relaxation rate(s): %% Cell type:code id: tags:  python from lbmpy.chapman_enskog import ChapmanEnskogAnalysis analysis = ChapmanEnskogAnalysis(method) analysis.get_dynamic_viscosity()  %% Output $\displaystyle - \frac{\omega_{0} - 2}{6 \omega_{0}}$ -(ω₀ - 2) ────────── 6⋅ω₀ %% Cell type:code id: tags:  python analysis.get_bulk_viscosity()  %% Output $\displaystyle - \frac{1}{9} - \frac{1}{3 \omega_{1}} + \frac{5}{9 \omega_{0}}$ 1 1 5 - ─ - ──── + ──── 9 3⋅ω₁ 9⋅ω₀ ... ...
 ... ... @@ -58,8 +58,8 @@ General: - velocity_input: symbolic field where the velocities are read from (for advection diffusion LBM) - density_input: symbolic field or field access where to read density from. When passing this parameter, velocity_input has to be passed as well - kernel_type: supported values: 'stream_pull_collide' (default), 'collide_only' - kernel_type: supported values: 'stream_pull_collide' (default), 'collide_only', stream_pull_only, collide_stream_push, esotwist_even, esotwist_odd, aa_even, aa_odd Entropic methods: ... ... @@ -419,7 +419,10 @@ def create_lb_method(**params): def relaxation_rate_getter(moments): try: if all(get_order(m) < 2 for m in moments): return 0 if params['entropic']: return relaxation_rates[0] else: return 0 res = relaxation_rates[next_relaxation_rate[0]] next_relaxation_rate[0] += 1 except IndexError: ... ...
 ... ... @@ -109,6 +109,13 @@ class MomentBasedLbMethod(AbstractLbMethod): new_entry = RelaxationInfo(prev_entry[0], relaxation_rate) self._momentToRelaxationInfoDict[e] = new_entry def set_conserved_moments_relaxation_rate(self, relaxation_rate): self.set_zeroth_moment_relaxation_rate(relaxation_rate) self.set_first_moment_relaxation_rate(relaxation_rate) def set_force_model(self, force_model): self._forceModel = force_model @property def collision_matrix(self): pdfs_to_moments = self.moment_matrix ... ... @@ -220,7 +227,7 @@ class MomentBasedLbMethod(AbstractLbMethod): """ For SRT and TRT the equations can be easier simplified if the relaxation times are symbols, not numbers. This function replaces the numbers in the relaxation matrix with symbols in this case, and returns also the subexpressions, that assign the number to the newly introduced symbol the subexpressions, that assign the number to the newly introduced symbol """ rr = [relaxation_matrix[i, i] for i in range(relaxation_matrix.rows)] if keep_rr_symbolic <= 2: ... ...
 from pystencils.field import Field from lbmpy.creationfunctions import update_with_default_parameters from lbmpy.fieldaccess import StreamPushTwoFieldsAccessor, CollideOnlyInplaceAccessor from pystencils.fd.derivation import FiniteDifferenceStencilDerivation ... ... @@ -271,7 +270,7 @@ def interface_tracking_force(phi_field, stencil, interface_thickness, fd_stencil return result def get_update_rules_velocity(src_field, u_in, lb_method, force, density): def get_update_rules_velocity(src_field, u_in, lb_method, force, density, sub_iterations=2): r""" Get assignments to update the velocity with a force shift Args: ... ... @@ -280,6 +279,7 @@ def get_update_rules_velocity(src_field, u_in, lb_method, force, density): lb_method: mrt lattice boltzmann method used for hydrodynamics force: force acting on the hydrodynamic lb step density: the interpolated density of the simulation sub_iterations: number of updates of the velocity field """ stencil = lb_method.stencil dimensions = len(stencil[0]) ... ... @@ -298,25 +298,36 @@ def get_update_rules_velocity(src_field, u_in, lb_method, force, density): update_u = list() update_u.append(Assignment(sp.symbols("rho"), m0[0])) index = 0 u_symp = sp.symbols("u_:{}".format(dimensions)) zw = sp.symbols("zw_:{}".format(dimensions)) aleph = sp.symbols("aleph_:{}".format(dimensions * sub_iterations)) for i in range(dimensions): update_u.append(Assignment(zw[i], u_in.center_vector[i])) update_u.append(Assignment(aleph[i], u_in.center_vector[i])) index += 1 for k in range(sub_iterations - 1): subs_dict = dict(zip(u_symp, aleph[k * dimensions:index])) for i in range(dimensions): update_u.append(Assignment(aleph[index], m0[indices[i]] + force[i].subs(subs_dict) / density / 2)) index += 1 subs_dict = dict(zip(u_symp, zw)) subs_dict = dict(zip(u_symp, aleph[index - dimensions:index])) for i in range(dimensions): update_u.append(Assignment(u_in.center_vector[i], m0[indices[i]] + force[i].subs(subs_dict) / density / 2)) update_u.append(Assignment(u_symp[i], m0[indices[i]] + force[i].subs(subs_dict) / density / 2)) # update_u.append(Assignment(u_in.center_vector[i], m0[indices[i]] + force[i].subs(subs_dict) / density / 2)) return update_u def get_collision_assignments_hydro(density=1, optimization=None, **kwargs): def get_collision_assignments_hydro(density=1, optimization=None, sub_iterations=2, **kwargs): r""" Get collision assignments for the hydrodynamic lattice Boltzmann step. Here the force gets applied in the moment space. Afterwards the transformation back to the pdf space happens. Args: density: the interpolated density of the simulation optimization: for details see createfunctions.py sub_iterations: number of updates of the velocity field """ if optimization is None: optimization = {} ... ... @@ -327,22 +338,11 @@ def get_collision_assignments_hydro(density=1, optimization=None, **kwargs): stencil = lb_method.stencil dimensions = len(stencil[0]) field_data_type = 'float64' if opt_params['double_precision'] else 'float32' q = len(stencil) u_in = params['velocity_input'] force = params['force'] if opt_params['symbolic_field'] is not None: src_field = opt_params['symbolic_field'] else: src_field = Field.create_generic(params['field_name'], spatial_dimensions=lb_method.dim, index_shape=(q,), layout=opt_params['field_layout'], dtype=field_data_type) if opt_params['symbolic_temporary_field'] is not None: dst_field = opt_params['symbolic_temporary_field'] else: dst_field = src_field.new_field_with_different_name(params['temporary_field_name']) src_field = opt_params['symbolic_field'] dst_field = opt_params['symbolic_temporary_field'] moment_matrix = lb_method.moment_matrix rel = lb_method.relaxation_rates ... ... @@ -364,12 +364,9 @@ def get_collision_assignments_hydro(density=1, optimization=None, **kwargs): m = sp.symbols("m_:{}".format(len(stencil))) update_m = get_update_rules_velocity(src_field, u_in, lb_method, force, density) update_m = get_update_rules_velocity(src_field, u_in, lb_method, force, density, sub_iterations=sub_iterations) u_symp = sp.symbols("u_:{}".format(dimensions)) for i in range(dimensions): update_m.append(Assignment(u_symp[i], u_in.center_vector[i])) for i in range(0, len(stencil)): update_m.append(Assignment(m[i], m0[i] - (m0[i] - eq[i] + mf[i] / 2) * rel[i] + mf[i])) ... ... @@ -385,6 +382,9 @@ def get_collision_assignments_hydro(density=1, optimization=None, **kwargs): for i in range(0, len(stencil)): update_g.append(Assignment(post_collision_accesses[i], var[i])) for i in range(dimensions): update_g.append(Assignment(u_in.center_vector[i], u_symp[i])) hydro_lb_update_rule = AssignmentCollection(main_assignments=update_g, subexpressions=update_m) ... ...
 from collections import OrderedDict import numpy as np from lbmpy.creationfunctions import create_lb_method, create_lb_update_rule from lbmpy.methods.creationfunctions import create_with_discrete_maxwellian_eq_moments from lbmpy.phasefield_allen_cahn.analytical import analytic_rising_speed from lbmpy.phasefield_allen_cahn.force_model import MultiphaseForceModel from lbmpy.phasefield_allen_cahn.kernel_equations import ( ... ... @@ -85,11 +82,9 @@ def test_codegen_3d(): method_phase = create_lb_method(stencil=stencil_phase, method='srt', relaxation_rate=w_c, compressible=True) mrt = create_lb_method(method="mrt", weighted=False, stencil=stencil_hydro, relaxation_rates=[1, 1, relaxation_rate, 1, 1, 1, 1]) rr_dict = OrderedDict(zip(mrt.moments, mrt.relaxation_rates)) method_hydro = create_with_discrete_maxwellian_eq_moments(stencil_hydro, rr_dict, compressible=False) method_hydro = create_lb_method(stencil=stencil_hydro, method="mrt", weighted=True, relaxation_rates=[relaxation_rate, 1, 1, 1, 1, 1], maxwellian_moments=True, entropic=False) # create the kernels for the initialization of the g and h field h_updates = initializer_kernel_phase_field_lb(h, C, u, method_phase, W) ... ... @@ -105,12 +100,8 @@ def test_codegen_3d(): h_tmp_symbol_list = [h_tmp.center(i) for i, _ in enumerate(stencil_phase)] sum_h = np.sum(h_tmp_symbol_list[:]) method_phase = create_lb_method(stencil=stencil_phase, method='srt', relaxation_rate=w_c, compressible=True, force_model=force_model_h) method_phase.set_force_model(force_model_h) allen_cahn_lb = create_lb_update_rule(lb_method=method_phase, velocity_input=u, compressible=True, ... ... @@ -123,8 +114,6 @@ def test_codegen_3d(): subexpressions=allen_cahn_lb.subexpressions) # --------------------------------------------------------------------------------------------------------- method_hydro = create_with_discrete_maxwellian_eq_moments(stencil_hydro, rr_dict, force_model=force_model_g) hydro_lb_update_rule_normal = get_collision_assignments_hydro(lb_method=method_hydro, density=density, velocity_input=u, ... ... @@ -140,9 +129,3 @@ def test_codegen_3d(): optimization={"symbolic_field": g, "symbolic_temporary_field": g_tmp}, kernel_type='collide_stream_push') hydro_lb_update_rule_generic_fields = get_collision_assignments_hydro(lb_method=method_hydro, density=density, velocity_input=u, force=force_g, kernel_type='collide_only')