Alex Liberzon Qwen-Coder commited on
Commit
dbdf005
·
0 Parent(s):

Initial commit: OpenPIV MCP server

Browse files

- FastMCP server with compute_piv tool for PIV analysis
- create_quiver_plot tool for velocity field visualization
- Dependencies: mcp, openpiv, numpy, pandas, matplotlib
- Python 3.14+ compatible

Co-authored-by: Qwen-Coder <qwen-coder@alibabacloud.com>

Files changed (8) hide show
  1. .gitattributes +6 -0
  2. .gitignore +10 -0
  3. .python-version +1 -0
  4. README.md +0 -0
  5. main.py +6 -0
  6. pyproject.toml +15 -0
  7. src/openpiv_mcp.py +187 -0
  8. uv.lock +0 -0
.gitattributes ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ demo/*.tiff filter=lfs diff=lfs merge=lfs -text
2
+ demo/*.bmp filter=lfs diff=lfs merge=lfs -text
3
+ demo/*.tif filter=lfs diff=lfs merge=lfs -text
4
+ *.tiff filter=lfs diff=lfs merge=lfs -text
5
+ *.bmp filter=lfs diff=lfs merge=lfs -text
6
+ *.tif filter=lfs diff=lfs merge=lfs -text
.gitignore ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ # Python-generated files
2
+ __pycache__/
3
+ *.py[oc]
4
+ build/
5
+ dist/
6
+ wheels/
7
+ *.egg-info
8
+
9
+ # Virtual environments
10
+ .venv
.python-version ADDED
@@ -0,0 +1 @@
 
 
1
+ 3.14
README.md ADDED
File without changes
main.py ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ def main():
2
+ print("Hello from openpiv-mcp!")
3
+
4
+
5
+ if __name__ == "__main__":
6
+ main()
pyproject.toml ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [project]
2
+ name = "openpiv-mcp"
3
+ version = "0.1.0"
4
+ description = "Add your description here"
5
+ readme = "README.md"
6
+ requires-python = ">=3.14"
7
+ dependencies = [
8
+ "matplotlib>=3.10.8",
9
+ "mcp>=1.26.0",
10
+ "numpy>=2.4.3",
11
+ "openpiv>=0.25.1",
12
+ "pandas>=3.0.1",
13
+ "setuptools>=82.0.1",
14
+ "setuptools-scm>=9.2.2",
15
+ ]
src/openpiv_mcp.py ADDED
@@ -0,0 +1,187 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from mcp.server.fastmcp import FastMCP
2
+ from openpiv import tools, pyprocess
3
+ import numpy as np
4
+ import pandas as pd
5
+ import os
6
+ import tempfile
7
+ import matplotlib
8
+ matplotlib.use('Agg') # Non-interactive backend for PNG generation
9
+ import matplotlib.pyplot as plt
10
+
11
+ # Initialize the FastMCP server
12
+ mcp = FastMCP("OpenPIV-Server")
13
+
14
+ @mcp.tool()
15
+ def compute_piv(
16
+ image_a_path: str,
17
+ image_b_path: str,
18
+ window_size: int = 32,
19
+ overlap: int = 16,
20
+ dt: float = 1.0,
21
+ output_dir: str = ""
22
+ ) -> str:
23
+ """
24
+ Computes Particle Image Velocimetry (PIV) on two images.
25
+ Use this tool when the user asks to analyze flow, movement, or PIV on two frames.
26
+
27
+ Args:
28
+ image_a_path: Absolute path to the first image frame.
29
+ image_b_path: Absolute path to the second image frame.
30
+ window_size: Interrogation window size (default 32).
31
+ overlap: Overlap between windows (default 16).
32
+ dt: Time delay between frames (default 1.0).
33
+ output_dir: Where to save the CSV. Defaults to a temp directory.
34
+ """
35
+ if not os.path.exists(image_a_path) or not os.path.exists(image_b_path):
36
+ return "Error: Image paths provided do not exist."
37
+
38
+ try:
39
+ # 1. Read Images
40
+ frame_a = tools.imread(image_a_path)
41
+ frame_b = tools.imread(image_b_path)
42
+
43
+ frame_a = frame_a.astype(np.int32)
44
+ frame_b = frame_b.astype(np.int32)
45
+
46
+ # 2. Process PIV
47
+ u, v, s2n = pyprocess.extended_search_area_piv(
48
+ frame_a, frame_b,
49
+ window_size=window_size,
50
+ overlap=overlap,
51
+ dt=dt,
52
+ search_area_size=window_size
53
+ )
54
+ x, y = pyprocess.get_coordinates(
55
+ image_size=frame_a.shape,
56
+ search_area_size=window_size,
57
+ overlap=overlap
58
+ )
59
+
60
+ # 3. Structure Output Data
61
+ # Flatten arrays to create a table of x, y, u, v, s2n
62
+ df = pd.DataFrame({
63
+ 'x': x.flatten(),
64
+ 'y': y.flatten(),
65
+ 'u': u.flatten(),
66
+ 'v': v.flatten(),
67
+ 's2n': s2n.flatten()
68
+ })
69
+
70
+ # 4. Save to CSV
71
+ if not output_dir:
72
+ output_dir = tempfile.gettempdir()
73
+
74
+ output_path = os.path.join(output_dir, "piv_results.csv")
75
+ df.to_csv(output_path, index=False)
76
+
77
+ # 5. Calculate summary statistics for the LLM
78
+ valid_vectors = df[df['s2n'] > 1.0] # Simple threshold example
79
+ max_u = df['u'].max()
80
+ max_v = df['v'].max()
81
+ mean_u = df['u'].mean()
82
+
83
+ # 6. Return response to the LLM
84
+ return (
85
+ f"PIV computation successful!\n"
86
+ f"Full data saved to: {output_path}\n"
87
+ f"Summary Statistics:\n"
88
+ f"- Total vectors computed: {len(df)}\n"
89
+ f"- Mean U velocity: {mean_u:.4f}\n"
90
+ f"- Max U velocity: {max_u:.4f}\n"
91
+ f"- Max V velocity: {max_v:.4f}\n"
92
+ f"The LLM can now use pandas or python tools to plot the data from {output_path} if requested."
93
+ )
94
+
95
+ except Exception as e:
96
+ return f"An error occurred during OpenPIV computation: {str(e)}"
97
+
98
+
99
+ @mcp.tool()
100
+ def create_quiver_plot(
101
+ csv_path: str,
102
+ output_path: str = "",
103
+ title: str = "PIV Velocity Field",
104
+ scale: int = 50,
105
+ width: float = 0.003,
106
+ cmap: str = "viridis"
107
+ ) -> str:
108
+ """
109
+ Creates a quiver (vector field) plot from PIV results CSV.
110
+ Use this tool when the user wants to visualize the flow field.
111
+
112
+ Args:
113
+ csv_path: Path to the PIV results CSV file.
114
+ output_path: Where to save the PNG. Defaults to CSV directory.
115
+ title: Plot title (default "PIV Velocity Field").
116
+ scale: Quiver scale factor (default 50, higher = shorter arrows).
117
+ width: Arrow width (default 0.003).
118
+ cmap: Colormap for velocity magnitude (default "viridis").
119
+ """
120
+ if not os.path.exists(csv_path):
121
+ return "Error: CSV file does not exist."
122
+
123
+ try:
124
+ # Read CSV data
125
+ df = pd.read_csv(csv_path)
126
+
127
+ # Reshape to 2D grids
128
+ x = df['x'].values
129
+ y = df['y'].values
130
+ u = df['u'].values
131
+ v = df['v'].values
132
+
133
+ # Get unique coordinates to determine grid shape
134
+ x_unique = np.unique(x)
135
+ y_unique = np.unique(y)
136
+ nx, ny = len(x_unique), len(y_unique)
137
+
138
+ # Reshape to 2D
139
+ X = x.reshape(ny, nx)
140
+ Y = y.reshape(ny, nx)
141
+ U = u.reshape(ny, nx)
142
+ V = v.reshape(ny, nx)
143
+
144
+ # Calculate velocity magnitude for coloring
145
+ magnitude = np.sqrt(U**2 + V**2)
146
+
147
+ # Create figure
148
+ fig, ax = plt.subplots(figsize=(10, 8))
149
+
150
+ # Create quiver plot with colored arrows
151
+ q = ax.quiver(X, Y, U, V, magnitude, cmap=cmap,
152
+ scale=scale, width=width, alpha=0.8)
153
+
154
+ # Add colorbar
155
+ cbar = plt.colorbar(q, ax=ax, label='Velocity Magnitude (pixels/dt)')
156
+
157
+ # Set labels and title
158
+ ax.set_xlabel('X (pixels)')
159
+ ax.set_ylabel('Y (pixels)')
160
+ ax.set_title(title)
161
+ ax.set_aspect('equal')
162
+
163
+ # Determine output path
164
+ if not output_path:
165
+ output_path = os.path.join(os.path.dirname(csv_path), "piv_quiver.png")
166
+
167
+ # Save figure
168
+ plt.tight_layout()
169
+ plt.savefig(output_path, dpi=150, bbox_inches='tight')
170
+ plt.close()
171
+
172
+ return (
173
+ f"Quiver plot created successfully!\n"
174
+ f"Saved to: {output_path}\n"
175
+ f"Plot details:\n"
176
+ f"- Grid size: {nx} x {ny} vectors\n"
177
+ f"- Velocity range: {magnitude.min():.4f} to {magnitude.max():.4f}\n"
178
+ f"- Colormap: {cmap}"
179
+ )
180
+
181
+ except Exception as e:
182
+ return f"An error occurred while creating the quiver plot: {str(e)}"
183
+
184
+
185
+ if __name__ == "__main__":
186
+ # Runs the server over stdio (standard for local MCP clients like Claude Desktop)
187
+ mcp.run()
uv.lock ADDED
The diff for this file is too large to render. See raw diff