bhajay commited on
Commit
1357ed1
·
1 Parent(s): e9053e0

Add application file

Browse files
Files changed (5) hide show
  1. app.py +48 -0
  2. requirements.txt +4 -0
  3. stream_functions.py +101 -0
  4. ui_components.py +143 -0
  5. visualization.py +181 -0
app.py ADDED
@@ -0,0 +1,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ from stream_functions import calculate_stream_function, calculate_velocity_field
3
+ from visualization import create_flow_visualization, display_equations
4
+ from ui_components import create_sidebar_controls
5
+ import numpy as np
6
+ import matplotlib.pyplot as plt
7
+
8
+ def main():
9
+ st.set_page_config(page_title="Flow Visualizer", layout="wide")
10
+
11
+ st.title("Flow Visualizer")
12
+ st.write("""
13
+ This app helps you understand and visualize stream functions in fluid dynamics.
14
+ Stream functions (ψ) describe fluid flow patterns where streamlines are lines of constant ψ.
15
+ The velocity components can be derived from the stream function as:
16
+ u = ∂ψ/∂y and v = -∂ψ/∂x
17
+
18
+ Developed by Vijay N
19
+ """)
20
+
21
+ col1, col2 = st.columns([1, 2])
22
+
23
+ with col1:
24
+ st.header("Flow Parameters")
25
+
26
+ # Get all user inputs and parameters from the controls in the left column
27
+ pattern_type, params, domain_settings, viz_settings = create_sidebar_controls(col1)
28
+
29
+ with col2:
30
+ # Extract domain settings
31
+ domain_size = domain_settings["domain_size"]
32
+ grid_points = domain_settings["grid_points"]
33
+
34
+ # Create visualization based on user parameters
35
+ create_flow_visualization(
36
+ pattern_type,
37
+ params,
38
+ domain_size,
39
+ grid_points,
40
+ viz_settings
41
+ )
42
+
43
+ # Display relevant equations for the selected flow pattern
44
+ # Pass params to display_equations for custom functions
45
+ display_equations(pattern_type, params)
46
+
47
+ if __name__ == "__main__":
48
+ main()
requirements.txt ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ matplotlib==3.10.1
2
+ numpy==2.2.4
3
+ streamlit==1.43.2
4
+ sympy==1.13.3
stream_functions.py ADDED
@@ -0,0 +1,101 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ from sympy import symbols, lambdify, sympify, parsing
3
+
4
+
5
+ def parse_custom_function(expr_string):
6
+ """
7
+ Parse a user-provided string into a callable function
8
+
9
+ Parameters:
10
+ expr_string (str): String representation of a mathematical expression
11
+
12
+ Returns:
13
+ callable: Function that takes x, y arrays and returns evaluated expression
14
+ """
15
+ try:
16
+ # Define symbols
17
+ x, y = symbols('x y')
18
+
19
+ # Parse the expression string
20
+ expr = sympify(expr_string, evaluate=True)
21
+
22
+ # Convert to a numpy-compatible function
23
+ func = lambdify((x, y), expr, modules=['numpy'])
24
+
25
+ return func
26
+ except (parsing.sympy_parser.ParserError, SyntaxError, TypeError, ValueError) as e:
27
+ # Return None if parsing fails
28
+ return None
29
+
30
+ def calculate_stream_function(x, y, pattern_type, params):
31
+ """Calculate stream function values based on selected flow pattern"""
32
+ if pattern_type == "Uniform Flow":
33
+ # ψ = U * y (uniform flow in x-direction)
34
+ return params["U"] * y
35
+
36
+ elif pattern_type == "Source/Sink":
37
+ # ψ = (Q/2π) * θ (source or sink at origin)
38
+ r = np.sqrt(x**2 + y**2) + 1e-10 # avoid division by zero
39
+ theta = np.arctan2(y, x)
40
+ return (params["Q"]/(2*np.pi)) * theta
41
+
42
+ elif pattern_type == "Vortex":
43
+ # ψ = (Γ/2π) * ln(r) (vortex at origin)
44
+ r = np.sqrt(x**2 + y**2) + 1e-10 # avoid division by zero
45
+ return (params["Gamma"]/(2*np.pi)) * np.log(r)
46
+
47
+ elif pattern_type == "Doublet":
48
+ # ψ = -κ * sin(θ)/r (doublet at origin)
49
+ r = np.sqrt(x**2 + y**2) + 1e-10 # avoid division by zero
50
+ theta = np.arctan2(y, x)
51
+ return -params["kappa"] * np.sin(theta)/r
52
+
53
+ elif pattern_type == "Cylinder in Flow":
54
+ # Combination of uniform flow and doublet
55
+ U = params["U"]
56
+ a = params["radius"]
57
+ r = np.sqrt(x**2 + y**2) + 1e-10
58
+ theta = np.arctan2(y, x)
59
+ return U * (r - a**2/r) * np.sin(theta)
60
+
61
+ elif pattern_type == "Custom Combination":
62
+ # Combined flow patterns
63
+ psi = np.zeros_like(x)
64
+
65
+ if params["include_uniform"]:
66
+ psi += params["U"] * y
67
+
68
+ if params["include_source"]:
69
+ r = np.sqrt(x**2 + y**2) + 1e-10
70
+ theta = np.arctan2(y, x)
71
+ psi += (params["Q"]/(2*np.pi)) * theta
72
+
73
+ if params["include_vortex"]:
74
+ r = np.sqrt(x**2 + y**2) + 1e-10
75
+ psi += (params["Gamma"]/(2*np.pi)) * np.log(r)
76
+
77
+ return psi
78
+
79
+ elif pattern_type == "Custom Function":
80
+ # User-defined function
81
+ if params.get("func") is not None:
82
+ try:
83
+ return params["func"](x, y)
84
+ except Exception as e:
85
+ # Return zeros if evaluation fails
86
+ return np.zeros_like(x)
87
+ return np.zeros_like(x)
88
+
89
+ return np.zeros_like(x)
90
+
91
+ def calculate_velocity_field(x, y, psi, h=0.1):
92
+ """Calculate velocity field from stream function using finite difference"""
93
+ u = np.zeros_like(psi)
94
+ v = np.zeros_like(psi)
95
+
96
+ # Interior points (central difference)
97
+ # Calculate derivatives correctly: u = ∂ψ/∂y, v = -∂ψ/∂x
98
+ u[1:-1, 1:-1] = (psi[2:, 1:-1] - psi[:-2, 1:-1]) / (2 * h) # ∂ψ/∂y (vertical derivative)
99
+ v[1:-1, 1:-1] = -(psi[1:-1, 2:] - psi[1:-1, :-2]) / (2 * h) # -∂ψ/∂x (negative horizontal derivative)
100
+
101
+ return u, v
ui_components.py ADDED
@@ -0,0 +1,143 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Update the ui_components.py file
2
+
3
+ import streamlit as st
4
+ from stream_functions import parse_custom_function
5
+
6
+ def create_sidebar_controls(container):
7
+ """Create and handle all user interface controls"""
8
+
9
+ pattern_type = container.selectbox(
10
+ "Select Flow Pattern",
11
+ ["Uniform Flow", "Source/Sink", "Vortex", "Doublet", "Cylinder in Flow",
12
+ "Custom Combination", "Custom Function"] # Added Custom Function option
13
+ )
14
+
15
+ # Parameters for different flow patterns
16
+ params = {}
17
+
18
+ if pattern_type == "Uniform Flow":
19
+ params["U"] = container.slider("Flow Speed (U)", -10.0, 10.0, 1.0, 0.1)
20
+
21
+ elif pattern_type == "Source/Sink":
22
+ params["Q"] = container.slider("Strength (Q)", -10.0, 10.0, 5.0, 0.1,
23
+ help="Positive for source, negative for sink")
24
+
25
+ elif pattern_type == "Vortex":
26
+ params["Gamma"] = container.slider("Circulation (Γ)", -10.0, 10.0, 5.0, 0.1,
27
+ help="Positive for counterclockwise, negative for clockwise")
28
+
29
+ elif pattern_type == "Doublet":
30
+ params["kappa"] = container.slider("Doublet Strength (κ)", 0.0, 10.0, 5.0, 0.1)
31
+
32
+ elif pattern_type == "Cylinder in Flow":
33
+ params["U"] = container.slider("Free Stream Velocity (U)", 0.1, 10.0, 1.0, 0.1)
34
+ params["radius"] = container.slider("Cylinder Radius (a)", 0.5, 5.0, 1.0, 0.1)
35
+
36
+ elif pattern_type == "Custom Combination":
37
+ container.subheader("Select Flow Components")
38
+ params["include_uniform"] = container.checkbox("Uniform Flow", True)
39
+ if params["include_uniform"]:
40
+ params["U"] = container.slider("Flow Speed (U)", -5.0, 5.0, 1.0, 0.1)
41
+
42
+ params["include_source"] = container.checkbox("Source/Sink", False)
43
+ if params["include_source"]:
44
+ params["Q"] = container.slider("Source Strength (Q)", -5.0, 5.0, 1.0, 0.1)
45
+
46
+ params["include_vortex"] = container.checkbox("Vortex", False)
47
+ if params["include_vortex"]:
48
+ params["Gamma"] = container.slider("Circulation (Γ)", -5.0, 5.0, 1.0, 0.1)
49
+
50
+ elif pattern_type == "Custom Function":
51
+ container.subheader("Enter Custom Stream Function")
52
+
53
+ container.markdown("""
54
+ Enter a mathematical expression for the stream function ψ(x,y).
55
+
56
+ **Available variables:**
57
+ - `x`, `y`: Coordinates
58
+ - `r` and `theta` will be calculated automatically
59
+
60
+ **Examples:**
61
+ - `x*y`: Simple shear flow
62
+ - `sin(x)*cos(y)`: Cellular flow pattern
63
+ - `x**2 - y**2`: Hyperbolic flow
64
+ """)
65
+
66
+ # Text area for custom function
67
+ default_func = "x*y"
68
+ func_string = container.text_area("Stream Function ψ(x,y)", default_func,
69
+ height=100, help="Enter a mathematical expression in terms of x and y")
70
+
71
+ # Add common mathematical functions buttons
72
+ container.markdown("**Common Functions**")
73
+ col1, col2, col3, col4 = container.columns(4)
74
+
75
+ if col1.button("sin(x)"):
76
+ func_string = "sin(x)"
77
+ if col2.button("cos(y)"):
78
+ func_string = "cos(y)"
79
+ if col3.button("x²-y²"):
80
+ func_string = "x**2 - y**2"
81
+ if col4.button("x*y"):
82
+ func_string = "x*y"
83
+
84
+ # Second row of buttons
85
+ col1, col2, col3, col4 = container.columns(4)
86
+
87
+ if col1.button("log(r)"):
88
+ func_string = "log(sqrt(x**2 + y**2))"
89
+ if col2.button("sin(x)*cos(y)"):
90
+ func_string = "sin(x)*cos(y)"
91
+ if col3.button("r*sin(theta)"):
92
+ func_string = "sqrt(x**2 + y**2)*y/sqrt(x**2 + y**2)"
93
+ if col4.button("r²*sin(2*theta)"):
94
+ func_string = "(x**2 + y**2)*2*x*y/(x**2 + y**2)"
95
+
96
+ # Parse the function
97
+ func = parse_custom_function(func_string)
98
+
99
+ if func is None:
100
+ container.error("Invalid function expression. Please check syntax.")
101
+ else:
102
+ container.success("Function parsed successfully!")
103
+
104
+ params["func"] = func
105
+ params["func_string"] = func_string
106
+
107
+ # Domain settings
108
+ container.subheader("Domain Settings")
109
+ domain_size = container.slider("Domain Size", 2.0, 20.0, 10.0, 0.5)
110
+ grid_points = container.slider("Grid Resolution", 20, 100, 50, 5)
111
+
112
+ domain_settings = {
113
+ "domain_size": domain_size,
114
+ "grid_points": grid_points
115
+ }
116
+
117
+ # Visualization settings
118
+ container.subheader("Visualization Settings")
119
+ show_streamlines = container.checkbox("Show Streamlines", True)
120
+ streamline_density = container.slider("Streamline Density", 5, 40, 20, 1) if show_streamlines else 20
121
+
122
+ show_velocity = container.checkbox("Show Velocity Field", True)
123
+ vector_density = container.slider("Vector Density", 5, 40, 15, 1) if show_velocity else 15
124
+
125
+ show_contour = container.checkbox("Show Stream Function Contour", True)
126
+ contour_levels = container.slider("Number of Contour Levels", 5, 50, 20, 1) if show_contour else 20
127
+
128
+ colormap = container.selectbox(
129
+ "Colormap",
130
+ ["viridis", "plasma", "inferno", "magma", "cividis", "turbo", "jet", "coolwarm", "RdBu", "RdYlBu"]
131
+ )
132
+
133
+ viz_settings = {
134
+ "show_streamlines": show_streamlines,
135
+ "streamline_density": streamline_density,
136
+ "show_velocity": show_velocity,
137
+ "vector_density": vector_density,
138
+ "show_contour": show_contour,
139
+ "contour_levels": contour_levels,
140
+ "colormap": colormap
141
+ }
142
+
143
+ return pattern_type, params, domain_settings, viz_settings
visualization.py ADDED
@@ -0,0 +1,181 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ import numpy as np
3
+ import matplotlib.pyplot as plt
4
+ from matplotlib.colors import LinearSegmentedColormap
5
+ import matplotlib.cm as cm
6
+ from mpl_toolkits.axes_grid1 import make_axes_locatable
7
+
8
+ from stream_functions import calculate_stream_function, calculate_velocity_field
9
+
10
+ def create_flow_visualization(pattern_type, params, domain_size, grid_points, viz_settings):
11
+ """Create and display the flow visualization based on user parameters"""
12
+
13
+ # Create grid
14
+ x = np.linspace(-domain_size/2, domain_size/2, grid_points)
15
+ y = np.linspace(-domain_size/2, domain_size/2, grid_points)
16
+ X, Y = np.meshgrid(x, y)
17
+
18
+ # Calculate stream function
19
+ psi = calculate_stream_function(X, Y, pattern_type, params)
20
+
21
+ # Calculate velocity field
22
+ h = domain_size / (grid_points - 1)
23
+ u, v = calculate_velocity_field(X, Y, psi, h)
24
+ speed = np.sqrt(u**2 + v**2)
25
+
26
+ # Extract visualization settings
27
+ show_streamlines = viz_settings["show_streamlines"]
28
+ streamline_density = viz_settings["streamline_density"]
29
+ show_velocity = viz_settings["show_velocity"]
30
+ vector_density = viz_settings["vector_density"]
31
+ show_contour = viz_settings["show_contour"]
32
+ contour_levels = viz_settings["contour_levels"]
33
+ colormap = viz_settings["colormap"]
34
+
35
+ # Create plot
36
+ fig, ax = plt.subplots(figsize=(10, 8))
37
+
38
+ # Plot stream function contour
39
+ if show_contour:
40
+ contour = ax.contourf(X, Y, psi, levels=contour_levels, cmap=colormap, alpha=0.7)
41
+ divider = make_axes_locatable(ax)
42
+ cax = divider.append_axes("right", size="5%", pad=0.1)
43
+ fig.colorbar(contour, cax=cax, label="Stream Function (ψ)")
44
+
45
+ # Plot streamlines
46
+ if show_streamlines:
47
+ ax.streamplot(X, Y, u, v, density=streamline_density/10,
48
+ color='white' if show_contour else 'black',
49
+ linewidth=1, arrowsize=1)
50
+
51
+ # Plot velocity vectors
52
+ if show_velocity:
53
+ # Subsample for clearer visualization
54
+ skip = grid_points // vector_density
55
+ ax.quiver(X[::skip, ::skip], Y[::skip, ::skip],
56
+ u[::skip, ::skip], v[::skip, ::skip],
57
+ scale=25, color='black', alpha=0.7)
58
+
59
+ # Plot special features for certain flow patterns
60
+ if pattern_type == "Cylinder in Flow":
61
+ circle = plt.Circle((0, 0), params["radius"], color='black', fill=False, linewidth=2)
62
+ ax.add_patch(circle)
63
+
64
+ ax.set_aspect('equal')
65
+ ax.set_title(f"Stream Function Visualization: {pattern_type}")
66
+ ax.set_xlabel("x")
67
+ ax.set_ylabel("y")
68
+ ax.grid(True, linestyle='--', alpha=0.6)
69
+
70
+ # Display the plot in Streamlit
71
+ st.pyplot(fig)
72
+
73
+ def display_equations(pattern_type, params=None):
74
+ """Display relevant equations for the selected flow pattern"""
75
+
76
+ st.subheader("Governing Equations")
77
+
78
+ if pattern_type == "Uniform Flow":
79
+ st.latex(r"\psi(x, y) = U \cdot y")
80
+ st.latex(r"u = U, \quad v = 0")
81
+
82
+ elif pattern_type == "Source/Sink":
83
+ st.latex(r"\psi(x, y) = \frac{Q}{2\pi} \cdot \theta")
84
+ st.latex(r"u = \frac{Q}{2\pi} \cdot \frac{x}{x^2 + y^2}, \quad v = \frac{Q}{2\pi} \cdot \frac{y}{x^2 + y^2}")
85
+
86
+ elif pattern_type == "Vortex":
87
+ st.latex(r"\psi(x, y) = \frac{\Gamma}{2\pi} \cdot \ln(r)")
88
+ st.latex(r"u = -\frac{\Gamma}{2\pi} \cdot \frac{y}{x^2 + y^2}, \quad v = \frac{\Gamma}{2\pi} \cdot \frac{x}{x^2 + y^2}")
89
+
90
+ elif pattern_type == "Doublet":
91
+ st.latex(r"\psi(x, y) = -\frac{\kappa \sin\theta}{r} = -\frac{\kappa y}{x^2 + y^2}")
92
+
93
+ elif pattern_type == "Cylinder in Flow":
94
+ st.latex(r"\psi(x, y) = U \cdot \left(r - \frac{a^2}{r}\right) \cdot \sin\theta")
95
+ st.write("Where r is the distance from origin and a is the cylinder radius")
96
+
97
+ elif pattern_type == "Custom Function" and params and "func_string" in params:
98
+ # Display the user's custom function
99
+ st.latex(r"\psi(x, y) = " + params["func_string"])
100
+ st.write("Velocity components are calculated using numerical differentiation")
101
+ st.latex(r"u = \frac{\partial \psi}{\partial y}, \quad v = -\frac{\partial \psi}{\partial x}")
102
+
103
+
104
+ def create_flow_visualization(pattern_type, params, domain_size, grid_points, viz_settings):
105
+ """Create and display the flow visualization based on user parameters"""
106
+
107
+ # Create grid
108
+ x = np.linspace(-domain_size/2, domain_size/2, grid_points)
109
+ y = np.linspace(-domain_size/2, domain_size/2, grid_points)
110
+ X, Y = np.meshgrid(x, y)
111
+
112
+ # Calculate stream function
113
+ try:
114
+ psi = calculate_stream_function(X, Y, pattern_type, params)
115
+
116
+ # Check if the result contains any invalid values
117
+ if np.isnan(psi).any() or np.isinf(psi).any():
118
+ if pattern_type == "Custom Function":
119
+ st.error("Your function produced invalid values (NaN or Inf). Please check your expression.")
120
+ return
121
+
122
+ # Calculate velocity field
123
+ h = domain_size / (grid_points - 1)
124
+ u, v = calculate_velocity_field(X, Y, psi, h)
125
+ speed = np.sqrt(u**2 + v**2)
126
+
127
+ # print(f"Average u: {np.mean(u):.4f}, Average v: {np.mean(v):.4f}")
128
+ # print(f"Max u: {np.max(u):.4f}, Min u: {np.min(u):.4f}")
129
+ # print(f"Max v: {np.max(v):.4f}, Min v: {np.min(v):.4f}")
130
+
131
+ # Extract visualization settings
132
+ show_streamlines = viz_settings["show_streamlines"]
133
+ streamline_density = viz_settings["streamline_density"]
134
+ show_velocity = viz_settings["show_velocity"]
135
+ vector_density = viz_settings["vector_density"]
136
+ show_contour = viz_settings["show_contour"]
137
+ contour_levels = viz_settings["contour_levels"]
138
+ colormap = viz_settings["colormap"]
139
+
140
+ # Create plot
141
+ fig, ax = plt.subplots(figsize=(10, 8))
142
+
143
+ # Plot stream function contour
144
+ if show_contour:
145
+ contour = ax.contourf(X, Y, psi, levels=contour_levels, cmap=colormap, alpha=0.7)
146
+ divider = make_axes_locatable(ax)
147
+ cax = divider.append_axes("right", size="5%", pad=0.1)
148
+ fig.colorbar(contour, cax=cax, label="Stream Function (ψ)")
149
+
150
+ # Plot streamlines
151
+ if show_streamlines:
152
+ ax.streamplot(X, Y, u, v, density=streamline_density/10,
153
+ color='white' if show_contour else 'black',
154
+ linewidth=1, arrowsize=1)
155
+
156
+ # Plot velocity vectors
157
+ if show_velocity:
158
+ # Subsample for clearer visualization
159
+ skip = grid_points // vector_density
160
+ ax.quiver(X[::skip, ::skip], Y[::skip, ::skip],
161
+ u[::skip, ::skip], v[::skip, ::skip], # Original, correct order
162
+ scale=25, color='black', alpha=0.7)
163
+
164
+ # Plot special features for certain flow patterns
165
+ if pattern_type == "Cylinder in Flow":
166
+ circle = plt.Circle((0, 0), params["radius"], color='black', fill=False, linewidth=2)
167
+ ax.add_patch(circle)
168
+
169
+ ax.set_aspect('equal')
170
+ ax.set_title(f"Flow Visualization: {pattern_type}")
171
+ ax.set_xlabel("x")
172
+ ax.set_ylabel("y")
173
+ ax.grid(True, linestyle='--', alpha=0.6)
174
+
175
+ # Display the plot in Streamlit
176
+ st.pyplot(fig)
177
+
178
+ except Exception as e:
179
+ st.error(f"Error generating visualization: {str(e)}")
180
+ if pattern_type == "Custom Function":
181
+ st.error("There was a problem with your custom function. Please check the syntax and try again.")