jithenderchoudary commited on
Commit
5293b90
·
verified ·
1 Parent(s): 609c6e8

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +121 -129
app.py CHANGED
@@ -1,148 +1,140 @@
1
  import gradio as gr
2
- import sys
3
  import os
4
 
5
- # Add FreeCAD library paths
6
- sys.path.append(r"C:\Program Files\FreeCAD 1.0\bin") # Update with your FreeCAD bin path
7
- sys.path.append(r"C:\Program Files\FreeCAD 1.0\lib") # Update with your FreeCAD lib path
8
-
9
- try:
10
- import FreeCAD, Fem, FemGui
11
- from FreeCAD import Gui
12
- print("FreeCAD modules imported successfully.")
13
- except ImportError as e:
14
- print(f"Error importing FreeCAD modules: {e}")
15
- sys.exit(1)
16
-
17
- # Default APDL Script
18
- apdl_script = """
19
- /CLEAR
20
- /PREP7
21
- MP, EX, 1, 210E3
22
- MP, PRXY, 1, 0.3
23
- RECTNG, 0, 100, 0, 50
24
- ET, 1, PLANE183
25
- ESIZE, 5
26
- AMESH, ALL
27
- D, NODE(0, 0), ALL, 0
28
- D, NODE(100, 0), UY, 0
29
- F, NODE(50, 50), FX, 1000
30
- FINISH
31
- /SOLU
32
- ANTYPE, 0
33
- SOLVE
34
- FINISH
35
- /POST1
36
- PLNSOL, U, SUM
37
- /IMAGE, SAVE, '2D_View', JPG
38
- /VIEW, 1, 1, 1, 1
39
- PLNSOL, S, EQV
40
- /IMAGE, SAVE, '3D_View', JPG
41
  FINISH
42
  """
43
 
44
- def run_fea_with_apdl(step_file, apdl_script, output_dir):
45
- """Run FEA using FreeCAD and APDL script."""
46
- doc = FreeCAD.newDocument("FEM_Analysis")
47
-
48
- # Import STEP file
49
- obj = doc.addObject("Part::Feature", "ImportedPart")
50
- obj.Shape = FreeCAD.importShape(step_file.name)
51
- doc.recompute()
52
-
53
- # Assign material properties
54
- mat = doc.addObject("App::MaterialObjectPython", "Material")
55
- mat.Material = {
56
- "Name": "Steel",
57
- "YoungsModulus": 210e9, # Pa
58
- "PoissonRatio": 0.3,
59
- }
60
- doc.addObject("Fem::ConstraintMaterial", "MaterialConstraint").References = [(obj, "Face1")]
61
- doc.recompute()
62
-
63
- # Create a mesh
64
- mesh = doc.addObject("Fem::FemMeshShapeNetgenObject", "FEMMesh")
65
- mesh.Shape = obj.Shape
66
- mesh.MaxSize = 5
67
- doc.recompute()
68
-
69
- # Apply boundary conditions
70
- fixed_constraint = doc.addObject("Fem::ConstraintFixed", "FixedConstraint")
71
- fixed_constraint.References = [(obj, "Face1")]
72
- doc.recompute()
73
-
74
- # Apply a force
75
- force_constraint = doc.addObject("Fem::ConstraintForce", "ForceConstraint")
76
- force_constraint.References = [(obj, "Face2")]
77
- force_constraint.Force = 1000 # N
78
- doc.recompute()
79
-
80
- # Add solver
81
- solver = doc.addObject("Fem::SolverCalculixCcxTools", "Solver")
82
- solver.InputFile = os.path.join(output_dir, "input.inp")
83
- solver.WorkingDir = output_dir
84
- doc.recompute()
85
-
86
- # Solve
87
- solver.write_input_file()
88
- solver.run()
89
-
90
- # Save results
91
- results = solver.load_results()
92
- results_obj = doc.addObject("Fem::FemResultObject", "Results")
93
- results_obj.Mesh = results.Mesh
94
- results_obj.NodeCount = len(results.Mesh.Nodes)
95
- doc.recompute()
96
-
97
- # Save 2D/3D views as images
98
- two_d_image = os.path.join(output_dir, "2D_View.png")
99
- three_d_image = os.path.join(output_dir, "3D_View.png")
100
-
101
- Gui.ActiveDocument.ActiveView.saveImage(two_d_image, 1024, 768, "White")
102
- Gui.ActiveDocument.ActiveView.viewIsometric()
103
- Gui.ActiveDocument.ActiveView.saveImage(three_d_image, 1024, 768, "White")
104
-
105
- # Save APDL Script to File
106
- apdl_file = os.path.join(output_dir, "script.dat")
107
- with open(apdl_file, "w") as f:
108
- f.write(apdl_script)
109
-
110
- return two_d_image, three_d_image, apdl_file
111
-
112
- # Gradio Workflow
113
- def fea_workflow(file, apdl_script):
114
- """Gradio workflow for FEA with APDL integration."""
115
- output_dir = "output"
116
- os.makedirs(output_dir, exist_ok=True)
117
 
118
  try:
119
- two_d_image, three_d_image, apdl_file = run_fea_with_apdl(file, apdl_script, output_dir)
120
- return (
121
- "Analysis completed successfully!",
122
- two_d_image,
123
- three_d_image,
124
- f"APDL script saved to: {apdl_file}"
125
- )
126
- except Exception as e:
127
- return f"Error during FEA: {e}", None, None, None
128
-
129
- # Gradio Interface
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
130
  with gr.Blocks() as app:
131
- gr.Markdown("# FreeCAD and APDL-Based FEA Workflow")
132
-
133
  with gr.Row():
134
  step_file = gr.File(label="Upload STEP File")
135
- apdl_editor = gr.Textbox(value=apdl_script, label="APDL Script", lines=20)
 
136
 
137
  with gr.Row():
138
- execute_button = gr.Button("Submit")
 
 
139
 
140
  with gr.Row():
141
- status = gr.Text(label="Execution Status")
 
 
 
 
 
 
 
142
  view_2d = gr.Image(label="2D View", interactive=False)
143
  view_3d = gr.Image(label="3D View", interactive=False)
144
- apdl_path = gr.Text(label="APDL Script Path")
145
-
146
- execute_button.click(fea_workflow, inputs=[step_file, apdl_editor], outputs=[status, view_2d, view_3d, apdl_path])
147
 
148
  app.launch()
 
1
  import gradio as gr
2
+ import subprocess
3
  import os
4
 
5
+ # APDL Script for ANSYS
6
+ apdl_script = """/CLEAR ! Clear any existing database
7
+ /PREP7 ! Enter preprocessor
8
+ /CWD, '{cwd}' ! Set the working directory
9
+ ! Define material properties
10
+ MP, EX, 1, 210E3 ! Young's Modulus (e.g., Steel)
11
+ MP, PRXY, 1, 0.3 ! Poisson's Ratio
12
+ ! Define geometry (e.g., a rectangular plate)
13
+ RECTNG, 0, 100, 0, 50 ! Rectangle from (0,0) to (100,50)
14
+ ! Define element type and mesh
15
+ ET, 1, PLANE183 ! 2D structural element
16
+ ESIZE, 5 ! Set element size
17
+ AMESH, ALL ! Mesh the area
18
+ ! Apply boundary conditions
19
+ D, NODE(0, 0), ALL, 0 ! Fix the bottom-left corner
20
+ D, NODE(100, 0), UY, 0 ! Restrict vertical movement at bottom-right
21
+ ! Apply loads
22
+ F, NODE(50, 50), FX, 1000 ! Apply a horizontal load at the top-middle node
23
+ ! Solve
24
+ FINISH ! Exit preprocessor
25
+ /SOLU ! Enter solution processor
26
+ ANTYPE, 0 ! Static analysis
27
+ SOLVE ! Solve the system
28
+ FINISH ! Exit solution processor
29
+ /POST1 ! Enter post-processor
30
+ /SHOW, JPEG ! Set output format to JPEG
31
+ /DEVICE, HARD, JPEG ! Configure device for image output
32
+ PLNSOL, U, SUM ! Plot nodal displacement (2D view)
33
+ FILE, '2D_View', 'JPEG' ! Save 2D view as an image
34
+ /SHOW, CLOSE ! Close the graphical window
35
+ /VIEW, 1, 1, 1, 1 ! Set 3D view (isometric)
36
+ /SHOW, JPEG ! Set output format to JPEG
37
+ /DEVICE, HARD, JPEG ! Configure device for image output
38
+ PLNSOL, S, EQV ! Plot equivalent stress (3D view)
39
+ FILE, '3D_View', 'JPEG' ! Save 3D view as an image
40
+ /SHOW, CLOSE ! Close the graphical window
41
  FINISH
42
  """
43
 
44
+ def upload_step_file(file):
45
+ """Handle STEP file upload."""
46
+ return f"STEP file '{file.name}' uploaded successfully."
47
+
48
+ def modify_apdl_script(modified_script):
49
+ """Modify and save the APDL script."""
50
+ global apdl_script
51
+ apdl_script = modified_script
52
+ return "APDL script updated successfully."
53
+
54
+ def execute_script():
55
+ """Execute the APDL script using ANSYS."""
56
+ global apdl_script
57
+
58
+ # Set the working directory
59
+ cwd = os.getcwd()
60
+ apdl_script_with_cwd = apdl_script.format(cwd=cwd)
61
+
62
+ # Save the APDL script to a file
63
+ script_file = "script.dat"
64
+ with open(script_file, "w") as f:
65
+ f.write(apdl_script_with_cwd)
66
+
67
+ # Define ANSYS execution command
68
+ ansys_command = [
69
+ "C:\\Program Files\\ANSYS Inc\\v211\\ansys\\bin\\winx64\\ansys.exe", # Replace with your actual path
70
+ "-b",
71
+ "-i", script_file,
72
+ "-o", "output.log"
73
+ ]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
74
 
75
  try:
76
+ # Run the ANSYS command
77
+ subprocess.run(ansys_command, check=True)
78
+
79
+ # Check for image outputs
80
+ two_d_image = os.path.join(cwd, "2D_View.jpg")
81
+ three_d_image = os.path.join(cwd, "3D_View.jpg")
82
+
83
+ if os.path.exists(two_d_image) and os.path.exists(three_d_image):
84
+ return "APDL script executed successfully. 2D and 3D views generated."
85
+ else:
86
+ with open("output.log", "r") as log_file:
87
+ log_contents = log_file.read()
88
+ return f"APDL script executed, but images not found. Check log:\n{log_contents}"
89
+
90
+ except subprocess.CalledProcessError as e:
91
+ return f"Error executing APDL script: {str(e)}. Check output.log for details."
92
+ except FileNotFoundError:
93
+ return "ANSYS executable not found. Verify the path in ansys_command."
94
+
95
+ def get_generated_images():
96
+ """Return the generated 2D and 3D view images if they exist."""
97
+ two_d_image = os.path.join(os.getcwd(), "2D_View.jpg")
98
+ three_d_image = os.path.join(os.getcwd(), "3D_View.jpg")
99
+ if os.path.exists(two_d_image) and os.path.exists(three_d_image):
100
+ return two_d_image, three_d_image
101
+ else:
102
+ return None, None
103
+
104
+ def read_output_log():
105
+ """Read and return the contents of output.log."""
106
+ if os.path.exists("output.log"):
107
+ with open("output.log", "r") as f:
108
+ return f.read()
109
+ else:
110
+ return "No output log found."
111
+
112
+ # Gradio interface
113
  with gr.Blocks() as app:
114
+ gr.Markdown("# ANSYS APDL Script for 2D and 3D Views")
115
+
116
  with gr.Row():
117
  step_file = gr.File(label="Upload STEP File")
118
+ step_output = gr.Text(label="Upload Status")
119
+ step_file.upload(upload_step_file, inputs=step_file, outputs=step_output)
120
 
121
  with gr.Row():
122
+ apdl_view = gr.Textbox(apdl_script, lines=20, label="APDL Script")
123
+ modify_button = gr.Button("Save Changes")
124
+ modify_button.click(modify_apdl_script, inputs=apdl_view, outputs=step_output)
125
 
126
  with gr.Row():
127
+ execute_button = gr.Button("Run Script")
128
+ execution_output = gr.Text(label="Execution Status")
129
+ log_output = gr.Textbox(label="Output Log", lines=10, interactive=False)
130
+ execute_button.click(execute_script, outputs=[execution_output])
131
+ execute_button.click(read_output_log, outputs=log_output)
132
+
133
+ with gr.Row():
134
+ gr.Markdown("## Generated Images")
135
  view_2d = gr.Image(label="2D View", interactive=False)
136
  view_3d = gr.Image(label="3D View", interactive=False)
137
+ refresh_button = gr.Button("Refresh Images")
138
+ refresh_button.click(get_generated_images, outputs=[view_2d, view_3d])
 
139
 
140
  app.launch()