Showing posts with label GPU. Show all posts
Showing posts with label GPU. Show all posts

Monday, 7 July 2025

A Simplified Immersed Boundary Method using Ray Casting

     Yours truly is an avid gamer, @fadoobaba (YouTube). The ray casting algorithm๐Ÿ›ธ; a fundamental ๐Ÿงฑ technique used in video game ๐ŸŽฎ development and computer graphics, has been implemented within the finite difference method ๐Ÿ code yours truly has been developing. In abundant spare time, of course๐Ÿ˜ผ. In this post, this method is explained. For details about ray casting using matplotlib.path, refer to here. For validation of the code, refer to here, backwards-facing step, curved boundaries, here (moving cylinder) and here.

NOTE: This method requires a GPU, if dear readers don't have a GPU then please stop being peasants... ๐Ÿ™‰

     If you plan to use these codes in your scholarly work, do cite this blog as:

     Fahad Butt (2025). S-IBM (https://fluiddynamicscomputer.blogspot.com/2025/07/a-simplified-immersed-boundary-method.html), Blogger. Retrieved Month Date, Year

     The first step is to setup the polygon ๐Ÿ . The polygon = cp.column_stack((x1, y1)) statement is used to combine x1 and y1 into a single array representing the polygon vertices. The following statements are used to store the x and y coordinates of the polygon vertices and nvert is the total number of vertices.

px = polygon[:, 0]

py = polygon[:, 1]

nvert = len(polygon)

     The boolean masks ๐Ÿ‘บ are then initialized. The following arrays track whether a grid point is inside the polygon based on horizontal and vertical ray intersections. False = outside ❌, True = inside ✅. Then a loop is implemented to for each edge ๐Ÿ“ of the polygon, defined by vertices i (current) and j (previous), with % nvert ensuring the polygon is closed (last vertex connects back to the first). (xi, yi) and (xj, yj) define the current edge and previous edge.

horizontal_inside = cp.zeros_like(test_x, dtype=bool) 

vertical_inside = cp.zeros_like(test_x, dtype=bool) 

for i in range(nvert):

    j = (i - 1) % nvert

xi, yi = px[i], py[i]

xj, yj = px[j], py[j]

     A check ⁉️ is performed to ensure a ray crosses the polygon edge once. cond1 statement checks if the test point lies between the y-values of the edge's endpoints i.e., a ray could cross it. intersect_x finds where the edge crosses a horizontal line at test_y. cond2 checks if the intersection lies to the right of the test point. ^= is XOR toggles the "inside" state each time the ray crosses an edge. The addition of small term ~1e-16 prevents division by zero for horizontal edges. Similar method is applied to verify the points using vertical ray. cond3 checks if the edge crosses a vertical ray (top to bottom) from (test_x, test_y). slope1 and intersect_y computes where the vertical ray at x=test_x intersects the edge. A point is inside only if both horizontal and vertical rays classify it as inside. A point is considered inside the foil only if both ray checks are true. curve is the 2D boolean mask of grid points inside the foil body.

cond1 = ((yi > test_y) != (yj > test_y))

slope = (xj - xi) / (yj - yi + 1e-16)

intersect_x = slope * (test_y - yi) + xi

cond2 = test_x < intersect_x 

horizontal_inside ^= cond1 & cond2

cond3 = ((xi > test_x) != (xj > test_x))

slope1 = (yj - yi) / (xj - xi + 1e-16)

intersect_y = slope1 * (test_x - xi) + yi

cond4 = test_y < intersect_y

vertical_inside ^= cond3 & cond4

inside = horizontal_inside & vertical_inside

curve = inside.reshape(X.T.shape)

     Using both horizontal and vertical rays reduces false positives (e.g., near sharp corners). The & ensures only points unambiguously inside are marked. Within Fig. 1, the points on the shape boundary, points inside ๐Ÿชฐ and outside ๐ŸŒ the shape boundary are shown. A point is a boundary if it is inside the body, but any of its neighbors is outside. Following statements are used to mark the boundary of the object. Boundary detects the "skin" of the body for applying no-slip, force, or stress conditions.

interior = curve[1:-1, 1:-1]

right = curve[2:, 1:-1]

left = curve[:-2, 1:-1]

top = curve[1:-1, 2:]

bottom = curve[1:-1, :-2]

boundary = interior & ~(right & left & top & bottom)

     The statements boundary_indices = cp.where(boundary_mask) ... valid_right = (boundary_indices[0] + 1 < X.shape[0]) & (~curve[right_neighbors]) ... etc. extract boundary indices and their valid neighbors i.e. these lines extract the (i, j) grid indices of the surface and locate which neighbor cells are valid fluid neighbors (outside the body and within domain bounds). These are needed to compute normals or apply boundary conditions via interpolation or extrapolation from the fluid.
Fig. 1, Mesh cells


     For validation of the results from present simulations, the case of flow around a circular cylinder is selected. Fig. 1 shows the results from the code at Re 200. The drag coefficient obtained from this code is 1.396 while from the literature, the value is at 1.4 [1]. The lift coefficient from the code is at 0.000134. Within Fig. 2, top row shows u and v velocity components and bottom row shows pressure and vorticity.


Fig. 2, The flow-field

     For the second an more complex validation case, a swimming fish is simulated. The lift and drag coefficients obtained from the simulation are compared with experimental results. The drag coefficient from the current code is at 0.328 while from the published literature, the value is at 0.348. Maximum lift coefficient is at 7.5 and 8 from the present code as compared to the published literature [2]. Within Fig. 3 the u and v velocities, pressure and velocity streamlines are shown for St = 0.8 and Reynolds number of 500. The computational mesh near the fish is shown in Fig. 4. Within Fig.4, a zoomed in view towards the right shows the mesh at the trailing edge of the fish.


Fig.3, Post-processing of results

Fig. 4, The mesh

     This method allows handling arbitrary deforming / non-deforming shapes on a fixed Cartesian grid. In summary, the method has the following steps.

1. Generate polygon shape (e.g., airfoil, cylinder)

2. Flatten mesh for vectorized testing

3. Use ray casting to check if points are inside shape

4. Build a boolean mask of body region

5. Identify surface (boundary) points

6. Extract boundary indices for physics coupling


References

     [1] Braza M, Chassaing P, Minh HH. Numerical study and physical analysis of the pressure and velocity fields in the near wake of a circular cylinder. Journal of Fluid Mechanics. 1986;165:79-130. doi:10.1017/S0022112086003014

     [2] Fulong ShiJianjian XinChuanzhong OuZhiwei LiXing ChangLing Wan; Effects of the Reynolds number and attack angle on wake dynamics of fish swimming in oblique flows. Physics of Fluids 1 February 2025; 37 (2): 025205 doi.org/10.1063/5.0252506

     Thank you for reading! If you want to hire me as a post-doc researcher in the fields of thermo-fluids and / or fracture mechanics, do reach out!