karthikmn commited on
Commit
e594240
·
verified ·
1 Parent(s): f1f47ae

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +101 -192
app.py CHANGED
@@ -1,193 +1,102 @@
1
- # Import necessary libraries
2
- import cadquery as cq
3
- import numpy as np
4
- import matplotlib.pyplot as plt
5
- import pyvista as pv
6
- from reportlab.lib.pagesizes import letter
7
- from reportlab.pdfgen import canvas
8
  import gradio as gr
9
- import os
10
- from ansys.mapdl.core import launch_mapdl # For ANSYS integration
11
-
12
- # Function for Progressive Die Design
13
- def generate_die(length, width, thickness):
14
- try:
15
- plate = cq.Workplane("XY").box(length, width, thickness)
16
- punch = cq.Workplane("XY").rect(10, 10).extrude(5).translate((length / 4, width / 4, thickness / 2))
17
- die = plate.cut(punch)
18
- filename = "progressive_die.step"
19
- cq.exporters.export(die, filename)
20
- return filename
21
- except Exception as e:
22
- return f"Error generating die: {str(e)}"
23
-
24
- # Function to visualize die in 3D
25
- def visualize_die(length, width, thickness):
26
- try:
27
- plate = cq.Workplane("XY").box(length, width, thickness)
28
- punch = cq.Workplane("XY").rect(10, 10).extrude(5).translate((length / 4, width / 4, thickness / 2))
29
- die = plate.cut(punch)
30
-
31
- # Export to STL for visualization
32
- cq.exporters.exportShape(die.val(), "STL", "progressive_die.stl")
33
-
34
- # Visualize with PyVista
35
- mesh = pv.read("progressive_die.stl")
36
- plotter = pv.Plotter(off_screen=True)
37
- plotter.add_mesh(mesh, color="blue")
38
- screenshot = "progressive_die_visualization.png"
39
- plotter.screenshot(screenshot)
40
- return screenshot
41
- except Exception as e:
42
- return f"Error visualizing die: {str(e)}"
43
-
44
- # Function for Python-based Stress Analysis
45
- def stress_analysis(force, die_width, die_height, material_strength):
46
- try:
47
- stress = force / (die_width * die_height)
48
- safety_factor = material_strength / stress
49
-
50
- fig, ax = plt.subplots()
51
- ax.bar(["Stress", "Material Strength"], [stress, material_strength])
52
- ax.set_ylabel("Stress (MPa)")
53
- ax.set_title("Stress Analysis")
54
- plt.close(fig)
55
-
56
- return f"Safety Factor: {round(safety_factor, 2)}", fig
57
- except Exception as e:
58
- return f"Error in stress analysis: {str(e)}", None
59
-
60
- # ANSYS Integration for Stress Analysis
61
- def run_ansys_simulation(force, die_width, die_height, material_strength):
62
- try:
63
- # Launch ANSYS MAPDL instance
64
- mapdl = launch_mapdl()
65
- mapdl.prep7() # Enter pre-processing module
66
-
67
- # Define geometry and material properties
68
- mapdl.rectng(0, die_width, 0, die_height)
69
- mapdl.mp('EX', 1, material_strength)
70
- mapdl.et(1, 'PLANE183')
71
-
72
- # Apply loads
73
- mapdl.nsel('S', 'LOC', 'X', 0)
74
- mapdl.d('ALL', 'UX', 0)
75
- mapdl.f('ALL', 'FY', -force)
76
-
77
- # Solve
78
- mapdl.run('/SOLU')
79
- mapdl.solve()
80
- mapdl.finish()
81
-
82
- # Post-processing
83
- mapdl.post1()
84
- stress = mapdl.get_value('NODE', 1, 'S', 'EQV') # Retrieve max equivalent stress
85
- mapdl.exit()
86
-
87
- return f"Max Stress: {stress:.2f} MPa"
88
- except Exception as e:
89
- return f"Error running ANSYS simulation: {str(e)}"
90
-
91
- # SolidWorks Placeholder for Stress Analysis
92
- def solidworks_stress_analysis(force, die_width, die_height, material_strength):
93
- try:
94
- output_file = "/path/to/solidworks/output.txt" # Replace with actual path
95
- if os.path.exists(output_file):
96
- with open(output_file, "r") as file:
97
- result = file.read()
98
- return result.strip()
99
- else:
100
- return "SolidWorks simulation output not found."
101
- except Exception as e:
102
- return f"Error running SolidWorks simulation: {str(e)}"
103
-
104
- # Function to generate PDF report
105
- def generate_pdf_report(data, filename="report.pdf"):
106
- try:
107
- c = canvas.Canvas(filename, pagesize=letter)
108
- c.drawString(100, 750, "Simulation Report")
109
- c.drawString(100, 730, f"Max Stress: {data.get('stress', 'N/A')} MPa")
110
- c.drawString(100, 710, f"Safety Factor: {data.get('safety_factor', 'N/A')}")
111
- c.save()
112
- return filename
113
- except Exception as e:
114
- return f"Error generating report: {str(e)}"
115
-
116
- # Tool Optimization Function
117
- def optimize_tool(speed, feed_rate, depth_of_cut, material):
118
- try:
119
- tool_life = 1000 / (speed * feed_rate * depth_of_cut)
120
- recommended_speed = 0.8 * speed
121
- recommended_feed_rate = 0.9 * feed_rate
122
-
123
- return {
124
- "Estimated Tool Life (hrs)": round(tool_life, 2),
125
- "Recommended Speed (m/min)": round(recommended_speed, 2),
126
- "Recommended Feed Rate (mm/rev)": round(recommended_feed_rate, 2)
127
- }
128
- except Exception as e:
129
- return {"Error": str(e)}
130
-
131
- # Gradio interface functions
132
- def stress_analysis_interface(force, die_width, die_height, material_strength, simulation_tool):
133
- if simulation_tool == "Python":
134
- safety_factor, fig = stress_analysis(force, die_width, die_height, material_strength)
135
- data = {"stress": force / (die_width * die_height), "safety_factor": safety_factor}
136
- pdf_filename = generate_pdf_report(data)
137
- return safety_factor, fig, pdf_filename
138
- elif simulation_tool == "ANSYS":
139
- result = run_ansys_simulation(force, die_width, die_height, material_strength)
140
- return result, None, None
141
- elif simulation_tool == "SolidWorks":
142
- result = solidworks_stress_analysis(force, die_width, die_height, material_strength)
143
- return result, None, None
144
- else:
145
- return "Invalid simulation tool selected", None, None
146
-
147
- # Create Gradio App
148
- with gr.Blocks() as app:
149
- gr.Markdown("## Press Tool AI Suite")
150
- gr.Markdown("Select a tool below to get started:")
151
- with gr.Tabs():
152
- with gr.Tab("Progressive Die Design"):
153
- length = gr.Number(label="Length (mm)", value=100)
154
- width = gr.Number(label="Width (mm)", value=50)
155
- thickness = gr.Number(label="Thickness (mm)", value=10)
156
- die_output = gr.Textbox(label="Die Output File")
157
- visualization_output = gr.Image(label="3D Visualization")
158
- die_button = gr.Button("Generate Die")
159
- die_button.click(
160
- lambda l, w, t: (generate_die(l, w, t), visualize_die(l, w, t)),
161
- inputs=[length, width, thickness],
162
- outputs=[die_output, visualization_output],
163
- )
164
- with gr.Tab("Stress Analysis"):
165
- simulation_tool = gr.Dropdown(
166
- choices=["Python", "ANSYS", "SolidWorks"], label="Simulation Tool", value="Python"
167
- )
168
- force = gr.Number(label="Force (N)", value=10000)
169
- die_width = gr.Number(label="Width (m)", value=0.05)
170
- die_height = gr.Number(label="Height (m)", value=0.01)
171
- material_strength = gr.Number(label="Material Strength (MPa)", value=250)
172
- safety_factor_output = gr.Textbox(label="Safety Factor or Simulation Result")
173
- stress_chart = gr.Plot()
174
- pdf_file = gr.File(label="Download Report (Python Only)")
175
- stress_button = gr.Button("Analyze Stress")
176
- stress_button.click(
177
- stress_analysis_interface,
178
- inputs=[force, die_width, die_height, material_strength, simulation_tool],
179
- outputs=[safety_factor_output, stress_chart, pdf_file],
180
- )
181
- with gr.Tab("Tool Optimization"):
182
- speed = gr.Number(label="Cutting Speed (m/min)", value=100)
183
- feed_rate = gr.Number(label="Feed Rate (mm/rev)", value=0.2)
184
- depth_of_cut = gr.Number(label="Depth of Cut (mm)", value=1.0)
185
- material = gr.Dropdown(choices=["Steel", "Aluminum", "Titanium"], label="Material", value="Steel")
186
- optimization_results = gr.JSON(label="Optimization Results")
187
- optimize_button = gr.Button("Optimize Tool")
188
- optimize_button.click(
189
- optimize_tool,
190
- inputs=[speed, feed_rate, depth_of_cut, material],
191
- outputs=optimization_results,
192
- )
193
- app.launch()
 
 
 
 
 
 
 
 
1
  import gradio as gr
2
+ import pandas as pd
3
+ import numpy as np
4
+ from sklearn.ensemble import RandomForestClassifier, RandomForestRegressor
5
+ from ansys.mapdl.core import launch_mapdl
6
+
7
+ # Load AI models
8
+ def load_models():
9
+ # Validation model
10
+ validation_model = RandomForestClassifier()
11
+ validation_model.fit([[150, 0.1], [200, 0.2], [250, 0.3], [300, 0.4], [350, 0.5]], [1, 1, 0, 0, 0])
12
+
13
+ # Optimization models
14
+ stress_model = RandomForestRegressor()
15
+ deformation_model = RandomForestRegressor()
16
+ X = np.column_stack((np.linspace(10, 25, 4), np.linspace(5000, 12000, 4)))
17
+ stress_model.fit(X, [300, 250, 200, 150])
18
+ deformation_model.fit(X, [0.5, 0.4, 0.3, 0.2])
19
+
20
+ return validation_model, stress_model, deformation_model
21
+
22
+ validation_model, stress_model, deformation_model = load_models()
23
+
24
+ # ANSYS MAPDL simulation function
25
+ def run_simulation(thickness, force):
26
+ mapdl = launch_mapdl() # Start MAPDL instance
27
+ mapdl.clear()
28
+ mapdl.prep7()
29
+
30
+ # Set up material and geometry
31
+ mapdl.mp("EX", 1, 2e11)
32
+ mapdl.mp("PRXY", 1, 0.3)
33
+ mapdl.block(0, 100, 0, 50, 0, thickness)
34
+ mapdl.cylind(0, 5, 20, 25, 0, thickness)
35
+ mapdl.vsubtract("ALL")
36
+ mapdl.et(1, "SOLID185")
37
+ mapdl.esize(5)
38
+ mapdl.vmesh("ALL")
39
+ mapdl.nsel("S", "LOC", "X", 0)
40
+ mapdl.d("ALL", "ALL")
41
+ mapdl.nsel("S", "LOC", "X", 100)
42
+ mapdl.f("ALL", "FY", -force)
43
+
44
+ # Solve
45
+ mapdl.run("/SOLU")
46
+ mapdl.antype("STATIC")
47
+ mapdl.solve()
48
+ mapdl.finish()
49
+
50
+ # Extract results
51
+ mapdl.post1()
52
+ max_stress = mapdl.get_value("NODE", 0, "S", "EQV")
53
+ max_deformation = mapdl.get_value("NODE", 0, "U", "SUM")
54
+ mapdl.exit()
55
+
56
+ return max_stress, max_deformation
57
+
58
+ # Gradio function
59
+ def simulate_and_optimize(thickness, force):
60
+ # Run ANSYS simulation
61
+ max_stress, max_deformation = run_simulation(thickness, force)
62
+
63
+ # AI validation
64
+ validation_result = validation_model.predict([[max_stress, max_deformation]])[0]
65
+
66
+ # AI optimization
67
+ thickness_values = np.linspace(10, 30, 5)
68
+ force_values = np.linspace(5000, 15000, 5)
69
+ results = []
70
+ for t in thickness_values:
71
+ for f in force_values:
72
+ stress = stress_model.predict([[t, f]])[0]
73
+ deformation = deformation_model.predict([[t, f]])[0]
74
+ results.append({"Thickness": t, "Force": f, "Stress": stress, "Deformation": deformation})
75
+ optimization_df = pd.DataFrame(results)
76
+
77
+ return {
78
+ "Simulation Results": {
79
+ "Max Stress": max_stress,
80
+ "Max Deformation": max_deformation,
81
+ "Validation Status": "Pass" if validation_result else "Fail"
82
+ },
83
+ "Optimization Suggestions": optimization_df.to_dict(orient="records")
84
+ }
85
+
86
+ # Gradio Interface
87
+ interface = gr.Interface(
88
+ fn=simulate_and_optimize,
89
+ inputs=[
90
+ gr.Number(label="Thickness (mm)", value=20),
91
+ gr.Number(label="Force (N)", value=5000),
92
+ ],
93
+ outputs=[
94
+ gr.JSON(label="Simulation Results"),
95
+ gr.JSON(label="Optimization Suggestions"),
96
+ ],
97
+ title="AI-Driven Press Tool Simulation & Optimization",
98
+ description="Automates the design, simulation, and optimization of press tools using AI and ANSYS."
99
+ )
100
+
101
+ if __name__ == "__main__":
102
+ interface.launch()