karthikmn commited on
Commit
e952dbf
·
verified ·
1 Parent(s): dcbde3d

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +88 -149
app.py CHANGED
@@ -1,177 +1,116 @@
1
  import gradio as gr
2
- import subprocess
3
- import numpy as np
4
- import pyvista as pv
5
- import matplotlib.pyplot as plt
6
- from ansys.mapdl.core import launch_mapdl
7
- from pycalculix import *
8
 
9
- # Simulation Workflow
10
- def simulation_workflow(use_case, simulator, thickness, length, width, hole_diameter, force, load):
11
- print(f"Running simulation for use_case={use_case}, simulator={simulator}")
12
-
13
- # Handle optional parameters with default values
14
- hole_diameter = hole_diameter if hole_diameter is not None else 0
15
- force = force if force is not None else 0
16
- load = load if load is not None else 0
17
 
18
- # Generate APDL script based on user inputs
 
 
 
 
19
  if use_case == "plate":
20
- print("Generating APDL script for plate simulation...")
21
- apdl_script = f"""
22
- /PREP7
23
- MP,EX,1,2E11 ! Elastic modulus
24
- MP,PRXY,1,0.3 ! Poisson's ratio
25
- BLOCK,0,{length},0,{width},0,{thickness} ! Main block geometry
26
- CYLIND,0,{hole_diameter / 2},0,0,{thickness} ! Circular hole geometry
27
- VSUB,ALL ! Subtract the hole from the block
28
- ET,1,SOLID185 ! Define element type as SOLID185
29
- ESIZE,5 ! Mesh element size
30
- VMESH,ALL ! Mesh the entire volume
31
- NSEL,S,LOC,Z,0 ! Select bottom face nodes
32
- D,ALL,ALL ! Apply constraints on selected nodes
33
- NSEL,S,LOC,Z,{thickness} ! Select top face nodes
34
- F,ALL,FY,-{force} ! Apply vertical force
35
- /SOLU
36
- ANTYPE,STATIC ! Static structural analysis
37
- SOLVE
38
- /POST1
39
- PRNSOL,S,EQV ! Print equivalent stress results
40
- PRNSOL,U,SUM ! Print total deformation results
41
- /EXIT
42
- """
43
  elif use_case == "beam":
44
- print("Generating APDL script for beam simulation...")
45
- apdl_script = f"""
46
- /PREP7
47
- MP,EX,1,2E11 ! Elastic modulus
48
- MP,PRXY,1,0.3 ! Poisson's ratio
49
- BLOCK,0,{length},0,{width},0,{thickness} ! Beam geometry
50
- ET,1,SOLID185 ! Define element type as SOLID185
51
- ESIZE,5 ! Mesh element size
52
- VMESH,ALL ! Mesh the entire volume
53
- NSEL,S,LOC,X,0 ! Select nodes at one end of the beam
54
- D,ALL,ALL ! Apply fixed constraints on one end
55
- NSEL,S,LOC,X,{length} ! Select nodes at the other end
56
- F,ALL,FY,-{load} ! Apply uniform load
57
- /SOLU
58
- ANTYPE,STATIC ! Static structural analysis
59
- SOLVE
60
- /POST1
61
- PRNSOL,S,EQV ! Print equivalent stress results
62
- PRNSOL,U,SUM ! Print total deformation results
63
- /EXIT
64
- """
65
  else:
66
- print("Invalid use case selected.")
67
- return "Invalid use case selected.", None, None
68
-
69
- # Save APDL script
70
- with open("simulation_input.inp", "w") as file:
71
- file.write(apdl_script)
72
-
73
- print(f"APDL script saved at: simulation_input.inp")
74
- from time import sleep # Add this at the top to handle sleep
75
 
76
- print("Running ANSYS simulation...")
77
- mapdl = launch_mapdl()
78
- mapdl.input("simulation_input.inp")
79
- sleep(5) # Wait for 5 seconds to ensure results are calculated
80
 
81
- # Check if the values are being fetched correctly
82
- try:
83
- max_stress = mapdl.get_value("NODE", 0, "S", "EQV")
84
- deformation = mapdl.get_value("NODE", 0, "U", "SUM")
85
- print("Running ANSYS simulation...")
86
- mapdl = launch_mapdl()
87
- mapdl.input("simulation_input.inp")
88
- sleep(5) # Wait for 5 seconds to ensure results are calculated
89
 
90
- # Check if the values are being fetched correctly
91
- try:
92
- max_stress = mapdl.get_value("NODE", 0, "S", "EQV")
93
- deformation = mapdl.get_value("NODE", 0, "U", "SUM")
94
- except Exception as e: # <-- This line should have the same indentation as the try block
95
- print(f"Error reading ANSYS results: {e}")
96
- max_stress = deformation = 0 # Default values in case of error
97
 
98
- mapdl.exit()
99
- stress, deformation = max_stress, deformation
100
- print(f"Stress: {stress}, Deformation: {deformation}")
 
 
101
 
102
- # Run the selected simulator
103
- if simulator == "PyCalculix":
104
- print("Running PyCalculix simulation...")
105
- model = Model("pycalculix_simulation")
106
- model.set_units("mm")
107
- part = Part("block", model)
108
- part.make_box(0, length, 0, width, 0, thickness)
109
- if use_case == "plate":
110
- part.cut_cylinder(0, hole_diameter / 2, 0, hole_diameter / 2, thickness)
111
- model.make_step_static(force if force else load)
112
 
113
- # Check if simulation is finished
114
- try:
115
- model.run()
116
- stress = model.results().max_stress()
117
- deformation = model.results().max_displacement()
118
- except Exception as e:
119
- print(f"Error reading PyCalculix results: {e}")
120
- stress = deformation = 0 # Default values in case of error
121
 
122
- print(f"PyCalculix Stress: {stress}, Deformation: {deformation}")()
123
- elif simulator == "ANSYS":
124
- print("Running ANSYS simulation...")
125
- mapdl = launch_mapdl()
126
- mapdl.input("simulation_input.inp")
127
- max_stress = mapdl.get_value("NODE", 0, "S", "EQV")
128
- deformation = mapdl.get_value("NODE", 0, "U", "SUM")
129
- mapdl.exit()
130
- stress, deformation = max_stress, deformation
131
- else:
132
- print("Invalid simulator selected.")
133
- return "Invalid simulator selected.", None, None
134
 
135
- print(f"Simulation results - Stress: {stress}, Deformation: {deformation}")
136
-
137
- # Visualize results (both 2D and 3D)
138
- print("Visualizing results...")
139
- fig, ax = plt.subplots()
140
- ax.bar(["Stress", "Deformation"], [stress, deformation], color=["red", "blue"])
141
- ax.set_title(f"Results ({simulator})")
142
- plt.savefig("results_2d.png")
143
- plt.close(fig)
144
 
145
- # 3D Visualization
146
- mesh = pv.Box(bounds=(0, length, 0, width, 0, thickness))
147
- plotter = pv.Plotter(off_screen=True)
148
- plotter.add_mesh(mesh, color="white", show_edges=True)
149
- plotter.screenshot("results_3d.png")
 
 
150
 
151
- return f"Stress: {stress:.2f} MPa, Deformation: {deformation:.2f} mm", "results_2d.png", "results_3d.png"
 
 
 
 
 
 
 
152
 
153
- # Define Gradio interface
154
  interface = gr.Interface(
155
  fn=simulation_workflow,
156
  inputs=[
157
- gr.Radio(["plate", "beam"], label="Select Use Case"), # Choose plate or beam simulation
158
- gr.Dropdown(["PyCalculix", "ANSYS"], label="Select Simulator"), # Choose simulator
159
- gr.Slider(10, 50, step=1, label="Thickness (mm)"), # Input: Thickness
160
- gr.Slider(100, 500, step=10, label="Length (mm)"), # Input: Length
161
- gr.Slider(50, 200, step=10, label="Width (mm)"), # Input: Width
162
- gr.Slider(5, 25, step=1, label="Hole Diameter (mm)", value=None), # Input: Hole Diameter (for plate)
163
- gr.Slider(1000, 10000, step=500, label="Force (N)", value=None), # Input: Force (for plate)
164
- gr.Slider(1000, 20000, step=1000, label="Load (N)", value=None) # Input: Load (for beam)
 
 
 
 
165
  ],
166
  outputs=[
167
- gr.Textbox(label="Simulation Results"), # Output: Simulation text results
168
- gr.Image(label="2D Results Visualization"), # Output: 2D plot (stress and deformation)
169
- gr.Image(label="3D Results Visualization") # Output: 3D plot (stress distribution)
 
 
 
170
  ],
171
- title="Unified Simulation Tool (PyCalculix and ANSYS)",
172
  live=True
173
  )
174
 
175
  # Launch Gradio interface
176
- print("Launching Gradio interface...")
177
  interface.launch()
 
1
  import gradio as gr
2
+ from apdl_generator.apdl_plate import generate_plate_apdl
3
+ from apdl_generator.apdl_beam import generate_beam_apdl
4
+ from simulators.python_simulation import run_python_simulation
5
+ from visualization import visualize_results, visualize_end_product
6
+ import os
 
7
 
8
+ def simulation_workflow(tool_type, use_case, include_hole, include_force, include_load, thickness, length, width, hole_diameter, force, load, elastic_modulus):
9
+ """
10
+ Main simulation workflow that generates multiple formats for APDL, Python code, and simulation results.
11
+ """
 
 
 
 
12
 
13
+ # Handle optional parameters
14
+ force = force if include_force else 0
15
+ load = load if include_load else 0
16
+
17
+ # Generate APDL script dynamically
18
  if use_case == "plate":
19
+ hole_diameter = hole_diameter if include_hole else 0
20
+ apdl_path = generate_plate_apdl(thickness, length, width, hole_diameter, force)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
21
  elif use_case == "beam":
22
+ apdl_path = generate_beam_apdl(length, width, thickness, load)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
23
  else:
24
+ return "Invalid use case selected.", None, None, None
 
 
 
 
 
 
 
 
25
 
26
+ # Read the generated APDL program
27
+ with open(apdl_path, "r") as file:
28
+ apdl_program = file.read()
 
29
 
30
+ # Run simulation using Python-based solver
31
+ stress, deformation = run_python_simulation(apdl_path, use_case, thickness, length, width, force, load, elastic_modulus)
 
 
 
 
 
 
32
 
33
+ # Explanation for negligible deformation
34
+ if deformation < 1e-6:
35
+ deformation_note = "\nNote: Deformation is negligible due to the high rigidity of the material."
36
+ else:
37
+ deformation_note = ""
 
 
38
 
39
+ # Generate 2D simulation visualization
40
+ graph_path, _ = visualize_results("Python-Based Solver", length, width, thickness, stress, deformation)
41
+
42
+ # Generate end-product visualization
43
+ product_path = visualize_end_product(use_case, length, width, thickness, deformation)
44
 
45
+ # Save Python code for simulation
46
+ python_code = f"""
47
+ import numpy as np
 
 
 
 
 
 
 
48
 
49
+ # Define material properties
50
+ elastic_modulus = {elastic_modulus}
51
+ thickness = {thickness}
52
+ length = {length}
53
+ width = {width}
 
 
 
54
 
55
+ # Simulate stress and deformation (simplified example)
56
+ def simulate():
57
+ stress = elastic_modulus * thickness * width / length # Example formula
58
+ deformation = stress / elastic_modulus # Simplified deformation
59
+ return stress, deformation
 
 
 
 
 
 
 
60
 
61
+ # Run the simulation
62
+ stress, deformation = simulate()
63
+ print(f"Stress: {stress:.2f} MPa")
64
+ print(f"Deformation: {deformation:.6f} mm")
65
+ """
66
+ python_file_path = "simulation_code.py"
67
+ with open(python_file_path, "w") as f:
68
+ f.write(python_code)
 
69
 
70
+ # Generate results in different formats
71
+ results_text = f"{tool_type} Simulation\nStress: {stress:.2f} MPa\nDeformation: {deformation:.6f} mm{deformation_note}"
72
+
73
+ # Save results to a .txt file
74
+ results_file_path = "simulation_results.txt"
75
+ with open(results_file_path, "w") as f:
76
+ f.write(results_text)
77
 
78
+ return (
79
+ results_text,
80
+ graph_path,
81
+ product_path,
82
+ apdl_program,
83
+ python_file_path, # Provide the path for Python code download
84
+ results_file_path # Provide the path for results file download
85
+ )
86
 
 
87
  interface = gr.Interface(
88
  fn=simulation_workflow,
89
  inputs=[
90
+ gr.Radio(["Punch", "Die"], label="Select Tool Type"),
91
+ gr.Radio(["plate", "beam"], label="Select Use Case"),
92
+ gr.Checkbox(label="Include Hole for Plate Simulation"), # Checkbox for optional hole
93
+ gr.Checkbox(label="Include Force"), # Checkbox for optional force
94
+ gr.Checkbox(label="Include Load"), # Checkbox for optional load
95
+ gr.Slider(10, 50, step=1, label="Thickness (mm)"),
96
+ gr.Slider(100, 500, step=10, label="Length (mm)"),
97
+ gr.Slider(50, 200, step=10, label="Width (mm)"),
98
+ gr.Slider(5, 25, step=1, label="Hole Diameter (mm)"), # Controlled by "Include Hole"
99
+ gr.Slider(1000, 10000, step=500, label="Force (N)"), # Controlled by "Include Force"
100
+ gr.Slider(1000, 20000, step=1000, label="Load (N)"), # Controlled by "Include Load"
101
+ gr.Slider(5e10, 3e11, step=1e10, label="Elastic Modulus (Pa)") # Slider for Elastic Modulus
102
  ],
103
  outputs=[
104
+ gr.Textbox(label="Simulation Results"),
105
+ gr.Image(label="2D Simulation Visualization"),
106
+ gr.Image(label="End Product Visualization"),
107
+ gr.Code(language="python", label="Generated APDL Program"), # Python Code Output
108
+ gr.File(label="Download Python Simulation Code"), # Allow file download of Python code
109
+ gr.File(label="Download Simulation Results") # Allow file download of results
110
  ],
111
+ title="Punch and Die Simulation Tool with End Product Visualization and APDL",
112
  live=True
113
  )
114
 
115
  # Launch Gradio interface
 
116
  interface.launch()