-
Notifications
You must be signed in to change notification settings - Fork 14
Expand file tree
/
Copy pathweb_paraview.py
More file actions
executable file
·259 lines (214 loc) · 10.3 KB
/
web_paraview.py
File metadata and controls
executable file
·259 lines (214 loc) · 10.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
#!/usr/bin/env python3
"""
Simple Web Server for OpenFOAM ParaView Visualization
Serves visualization images on port 8080
"""
import os
import sys
import http.server
import socketserver
import threading
import time
import subprocess
from pathlib import Path
# Set environment for ParaView
os.environ['PYTHONPATH'] = '/usr/lib/python3/dist-packages'
def generate_visualizations():
"""Generate ParaView visualizations of the cavity case"""
script_content = '''
import sys
sys.path.insert(0, "/usr/lib/python3/dist-packages")
import paraview.simple as pvs
import os
# Disable all output and warnings
pvs._DisableFirstRenderCameraReset()
# Change to cavity directory
os.chdir("/workspaces/openfoam-mcp-server/results/cavity")
try:
# Load OpenFOAM case
reader = pvs.OpenFOAMReader(FileName="cavity.foam")
reader.MeshRegions = ["internalMesh"]
reader.CellArrays = ["U", "p"]
# Set the time step to the last one
pvs.GetAnimationScene().GoToLast()
# Create view
view = pvs.CreateView("RenderView")
view.ViewSize = [800, 600]
view.Background = [1, 1, 1] # White background
# Show the data
rep = pvs.Show(reader, view)
# Color by velocity magnitude
pvs.ColorBy(rep, ("POINTS", "U", "Magnitude"))
# Get color transfer function and configure
lut = pvs.GetColorTransferFunction("U")
lut.RescaleTransferFunction(0.0, 1.0)
# Add color bar
colorbar = pvs.GetScalarBar(lut, view)
colorbar.Title = "Velocity Magnitude (m/s)"
colorbar.ComponentTitle = ""
# Reset camera and render
pvs.ResetCamera(view)
pvs.Render(view)
# Save velocity visualization
pvs.SaveScreenshot("/workspaces/openfoam-mcp-server/results/velocity_magnitude.png")
print("Velocity magnitude visualization saved")
# Color by pressure
pvs.ColorBy(rep, ("CELLS", "p"))
lut_p = pvs.GetColorTransferFunction("p")
lut_p.RescaleTransferFunction(-1.0, 0.5)
colorbar.Title = "Pressure (Pa)"
pvs.Render(view)
pvs.SaveScreenshot("/workspaces/openfoam-mcp-server/results/pressure.png")
print("Pressure visualization saved")
# Create streamlines
pvs.ColorBy(rep, ("POINTS", "U", "Magnitude"))
# Create stream tracer
stream = pvs.StreamTracer(Input=reader, SeedType="High Resolution Line Source")
stream.SeedType.Point1 = [0.01, 0.01, 0.005]
stream.SeedType.Point2 = [0.01, 0.09, 0.005]
stream.SeedType.Resolution = 10
# Show streamlines
stream_rep = pvs.Show(stream, view)
stream_rep.ColorArrayName = ("POINTS", "U", "Magnitude")
stream_rep.LineWidth = 2.0
pvs.Hide(reader, view) # Hide the mesh
pvs.ResetCamera(view)
pvs.Render(view)
pvs.SaveScreenshot("/workspaces/openfoam-mcp-server/results/streamlines.png")
print("Streamlines visualization saved")
print("All visualizations generated successfully!")
except Exception as e:
print(f"Error generating visualization: {e}")
import traceback
traceback.print_exc()
'''
# Write and execute the script
with open("/tmp/paraview_viz.py", "w") as f:
f.write(script_content)
# Run the visualization script
result = subprocess.run([
"python3", "/tmp/paraview_viz.py"
], capture_output=True, text=True, cwd="/workspaces/openfoam-mcp-server/results/cavity")
print("Visualization generation output:")
print("STDOUT:", result.stdout)
if result.stderr:
print("STDERR:", result.stderr)
print("Return code:", result.returncode)
class OpenFOAMWebHandler(http.server.SimpleHTTPRequestHandler):
"""Custom HTTP handler for OpenFOAM visualization"""
def do_GET(self):
if self.path == '/':
self.serve_index()
elif self.path == '/generate':
self.generate_viz()
else:
# Serve static files
super().do_GET()
def serve_index(self):
"""Serve the main visualization page"""
html_content = '''<!DOCTYPE html>
<html>
<head>
<title>OpenFOAM ParaView Visualization</title>
<style>
body { font-family: Arial, sans-serif; margin: 40px; background: #f5f5f5; }
.container { max-width: 1200px; margin: 0 auto; background: white; padding: 30px; border-radius: 10px; box-shadow: 0 2px 10px rgba(0,0,0,0.1); }
h1 { color: #2c3e50; text-align: center; }
.viz-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(400px, 1fr)); gap: 20px; margin-top: 30px; }
.viz-item { text-align: center; padding: 20px; border: 1px solid #ddd; border-radius: 8px; background: #fafafa; }
.viz-item img { max-width: 100%; height: auto; border-radius: 5px; box-shadow: 0 2px 8px rgba(0,0,0,0.2); }
.viz-item h3 { color: #34495e; margin-top: 15px; }
.generate-btn { background: #3498db; color: white; padding: 12px 24px; border: none; border-radius: 5px; cursor: pointer; font-size: 16px; margin: 20px 0; }
.generate-btn:hover { background: #2980b9; }
.info { background: #e8f4fd; padding: 15px; border-radius: 5px; margin: 20px 0; }
</style>
</head>
<body>
<div class="container">
<h1>🌊 OpenFOAM Cavity Flow Visualization</h1>
<div class="info">
<strong>Case:</strong> 2D Driven Cavity Flow<br>
<strong>Solver:</strong> incompressibleFluid<br>
<strong>Reynolds Number:</strong> ~1000<br>
<strong>Time:</strong> 10 seconds (steady state)
</div>
<button class="generate-btn" onclick="generateVisualization()">🔄 Generate New Visualizations</button>
<div class="viz-grid">
<div class="viz-item">
<h3>Velocity Magnitude</h3>
<img src="velocity_magnitude.png" alt="Velocity Magnitude" onerror="this.src='data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iNDAwIiBoZWlnaHQ9IjMwMCIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj48cmVjdCB3aWR0aD0iMTAwJSIgaGVpZ2h0PSIxMDAlIiBmaWxsPSIjZjBmMGYwIi8+PHRleHQgeD0iNTAlIiB5PSI1MCUiIGZvbnQtZmFtaWx5PSJBcmlhbCIgZm9udC1zaXplPSIxOCIgZmlsbD0iIzk5OSIgdGV4dC1hbmNob3I9Im1pZGRsZSIgZHk9Ii4zZW0iPkNsaWNrIEdlbmVyYXRlPC90ZXh0Pjwvc3ZnPg=='"/>
<p>Shows the magnitude of velocity vectors throughout the cavity</p>
</div>
<div class="viz-item">
<h3>Pressure Field</h3>
<img src="pressure.png" alt="Pressure Field" onerror="this.src='data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iNDAwIiBoZWlnaHQ9IjMwMCIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj48cmVjdCB3aWR0aD0iMTAwJSIgaGVpZ2h0PSIxMDAlIiBmaWxsPSIjZjBmMGYwIi8+PHRleHQgeD0iNTAlIiB5PSI1MCUiIGZvbnQtZmFtaWx5PSJBcmlhbCIgZm9udC1zaXplPSIxOCIgZmlsbD0iIzk5OSIgdGV4dC1hbmNob3I9Im1pZGRsZSIgZHk9Ii4zZW0iPkNsaWNrIEdlbmVyYXRlPC90ZXh0Pjwvc3ZnPg=='"/>
<p>Pressure distribution showing the flow-induced pressure gradients</p>
</div>
<div class="viz-item">
<h3>Streamlines</h3>
<img src="streamlines.png" alt="Streamlines" onerror="this.src='data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iNDAwIiBoZWlnaHQ9IjMwMCIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj48cmVjdCB3aWR0aD0iMTAwJSIgaGVpZ2h0PSIxMDAlIiBmaWxsPSIjZjBmMGYwIi8+PHRleHQgeD0iNTAlIiB5PSI1MCUiIGZvbnQtZmFtaWx5PSJBcmlhbCIgZm9udC1zaXplPSIxOCIgZmlsbD0iIzk5OSIgdGV4dC1hbmNob3I9Im1pZGRsZSIgZHk9Ii4zZW0iPkNsaWNrIEdlbmVyYXRlPC90ZXh0Pjwvc3ZnPg=='"/>
<p>Streamlines showing the characteristic vortex pattern</p>
</div>
</div>
<div class="info" style="margin-top: 40px;">
<h3>🔬 About This Visualization</h3>
<p>This is a classic 2D driven cavity flow - a benchmark CFD case where the top wall moves with constant velocity creating a recirculating flow pattern. The OpenFOAM simulation shows the steady-state solution with the characteristic primary vortex and smaller corner vortices.</p>
</div>
</div>
<script>
function generateVisualization() {
document.querySelector('.generate-btn').innerHTML = '⏳ Generating...';
fetch('/generate')
.then(response => response.text())
.then(data => {
document.querySelector('.generate-btn').innerHTML = '🔄 Generate New Visualizations';
// Reload images by adding timestamp
const timestamp = new Date().getTime();
document.querySelectorAll('.viz-item img').forEach(img => {
const originalSrc = img.src.split('?')[0];
img.src = originalSrc + '?' + timestamp;
});
alert('Visualizations updated!');
})
.catch(error => {
document.querySelector('.generate-btn').innerHTML = '🔄 Generate New Visualizations';
alert('Error generating visualizations: ' + error);
});
}
</script>
</body>
</html>'''
self.send_response(200)
self.send_header('Content-type', 'text/html')
self.end_headers()
self.wfile.write(html_content.encode())
def generate_viz(self):
"""Generate new visualizations"""
self.send_response(200)
self.send_header('Content-type', 'text/plain')
self.end_headers()
try:
generate_visualizations()
self.wfile.write(b"Visualizations generated successfully!")
except Exception as e:
self.wfile.write(f"Error: {str(e)}".encode())
def start_web_server():
"""Start the web server"""
port = 8080
# Change to the results directory to serve images
os.chdir("/workspaces/openfoam-mcp-server/results")
# Generate initial visualizations
print("Generating initial visualizations...")
generate_visualizations()
# Start web server
with socketserver.TCPServer(("0.0.0.0", port), OpenFOAMWebHandler) as httpd:
print(f"🌐 OpenFOAM ParaView Server running on port {port}")
print(f"🔗 Access at: http://localhost:{port}")
print("📊 Serving OpenFOAM cavity flow visualizations")
print("Press Ctrl+C to stop...")
try:
httpd.serve_forever()
except KeyboardInterrupt:
print("\n🛑 Server stopped")
if __name__ == "__main__":
start_web_server()