jithenderchoudary commited on
Commit
b01da0d
·
verified ·
1 Parent(s): 74e9731

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +82 -82
app.py CHANGED
@@ -1,92 +1,92 @@
1
- import pyvista as pv
2
- import streamlit as st
3
 
4
- # Material properties (dummy data)
5
- materials = {
6
- "Steel": {"Density": 7850, "Yield Strength": 250},
7
- "Aluminum": {"Density": 2700, "Yield Strength": 50},
8
- "Brass": {"Density": 8500, "Yield Strength": 200},
9
- }
 
 
 
10
 
11
- # Function to create punch and die geometry
12
- def create_geometry(length, width, height, inner_width, inner_height, thickness):
13
- punch = pv.Box(bounds=(0, length, 0, width, 0, height))
14
- die = pv.Box(bounds=(-inner_width / 2, inner_width / 2,
15
- -inner_height / 2, inner_height / 2,
16
- -thickness, 0))
17
- return punch, die
 
18
 
19
- # Streamlit App
20
- st.title("Interactive Punch and Die Design Tool")
21
- st.sidebar.header("Input Parameters")
 
22
 
23
- # User inputs for Punch Dimensions
24
- st.sidebar.subheader("Punch Dimensions")
25
- length = st.sidebar.slider("Length (mm)", 10, 200, 50)
26
- width = st.sidebar.slider("Width (mm)", 10, 200, 30)
27
- height = st.sidebar.slider("Height (mm)", 5, 100, 10)
28
 
29
- # User inputs for Die Dimensions
30
- st.sidebar.subheader("Die Dimensions")
31
- inner_width = st.sidebar.slider("Inner Width (mm)", 10, 150, 40)
32
- inner_height = st.sidebar.slider("Inner Height (mm)", 10, 150, 20)
33
- die_thickness = st.sidebar.slider("Die Thickness (mm)", 5, 50, 15)
34
 
35
- # Material Selection
36
- st.sidebar.subheader("Material Selection")
37
- material = st.sidebar.selectbox("Material", list(materials.keys()))
38
- mesh_size = st.sidebar.slider("Mesh Size (mm)", 1, 10, 5)
39
- force = st.sidebar.slider("Force Applied (kN)", 1, 1000, 200)
40
 
41
- # Display selected material properties
42
- st.sidebar.subheader("Material Properties")
43
- st.sidebar.write(f"Density: {materials[material]['Density']} kg/m³")
44
- st.sidebar.write(f"Yield Strength: {materials[material]['Yield Strength']} MPa")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
45
 
46
- # Generate Punch and Die Models
47
- punch, die = create_geometry(length, width, height, inner_width, inner_height, die_thickness)
 
 
 
 
 
 
 
 
 
 
 
 
48
 
49
- # 3D Visualization
50
- st.subheader("3D Visualization of Punch and Die")
51
- plotter = pv.Plotter(off_screen=True) # Use off_screen for static visualization
52
- plotter.add_mesh(punch, color="blue", opacity=0.5, label="Punch")
53
- plotter.add_mesh(die, color="red", opacity=0.5, label="Die")
54
- plotter.add_axes()
55
- plotter.show_bounds()
56
- plotter.view_xy()
57
-
58
- # Save the visualization as an image
59
- image_path = "visualization.png"
60
- plotter.screenshot(image_path)
61
-
62
- # Display the image in Streamlit
63
- st.image(image_path, caption="3D Visualization of Punch and Die", use_column_width=True)
64
-
65
- # Generate APDL Script
66
- st.subheader("Generated APDL Script")
67
- apdl_script = f"""
68
- /PREP7
69
- ! Define material properties
70
- MP,DENS,1,{materials[material]['Density']}
71
- MP,YIELD,1,{materials[material]['Yield Strength']}
72
- ! Define punch geometry
73
- BLOCK,0,{length},0,{width},0,{height}
74
- ! Define die geometry
75
- BLOCK,-{inner_width/2},{inner_width/2},-{inner_height/2},{inner_height/2},-{die_thickness},0
76
- ! Mesh settings
77
- ESIZE,{mesh_size}
78
- ! Apply force
79
- F,1,FZ,{force}
80
- /SOLU
81
- SOLVE
82
- /POST1
83
- """
84
-
85
- # Display and Download APDL Script
86
- st.code(apdl_script)
87
- st.download_button("Download APDL Script", apdl_script, "generated_apdl_script.txt")
88
-
89
- # Placeholder for Validation Results
90
- st.subheader("Validation Feedback")
91
- st.write("Validation results and stress maps will be shown here.")
92
 
 
 
 
 
1
+ # app.py
 
2
 
3
+ # Import libraries
4
+ import numpy as np
5
+ import pandas as pd
6
+ import matplotlib.pyplot as plt
7
+ from sklearn.ensemble import RandomForestClassifier
8
+ from sklearn.model_selection import train_test_split
9
+ from sklearn.metrics import accuracy_score
10
+ import gradio as gr
11
+ import joblib
12
 
13
+ # Step 1: Generate or Load Sample Data
14
+ np.random.seed(42)
15
+ data = pd.DataFrame({
16
+ "Pressure": np.random.randint(50, 200, 200),
17
+ "Temperature": np.random.randint(300, 700, 200),
18
+ "Material_Type": np.random.randint(1, 5, 200),
19
+ "Defect_Type": np.random.choice([0, 1, 2], 200, p=[0.6, 0.3, 0.1])
20
+ })
21
 
22
+ # Splitting data
23
+ X = data[["Pressure", "Temperature", "Material_Type"]]
24
+ y = data["Defect_Type"]
25
+ X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
26
 
27
+ # Step 2: Train the Model
28
+ model = RandomForestClassifier(n_estimators=100, random_state=42)
29
+ model.fit(X_train, y_train)
 
 
30
 
31
+ # Save the model
32
+ joblib.dump(model, "defect_model.pkl")
 
 
 
33
 
34
+ # Test the Model
35
+ y_pred = model.predict(X_test)
36
+ print(f"Model Accuracy: {accuracy_score(y_test, y_pred):.2f}")
 
 
37
 
38
+ # Step 3: Define Helper Functions for Visualizations
39
+ def plot_simulation(pressure, temperature, material_type):
40
+ # Simulate some stress/strain values for visualization
41
+ stress = np.linspace(pressure * 0.5, pressure * 1.5, 100)
42
+ strain = stress / (temperature * 0.01 * material_type)
43
+
44
+ # Create the plot
45
+ plt.figure(figsize=(8, 5))
46
+ plt.plot(stress, strain, label="Stress-Strain Curve")
47
+ plt.xlabel("Stress (MPa)")
48
+ plt.ylabel("Strain (%)")
49
+ plt.title("Stress-Strain Simulation")
50
+ plt.legend()
51
+ plt.grid(True)
52
+
53
+ # Save the plot to an image
54
+ plot_path = "simulation_plot.png"
55
+ plt.savefig(plot_path)
56
+ plt.close()
57
+ return plot_path
58
 
59
+ # Step 4: Prediction and Visualization Function
60
+ def predict_and_visualize(pressure, temperature, material_type):
61
+ # Load the model
62
+ loaded_model = joblib.load("defect_model.pkl")
63
+ # Predict
64
+ input_data = np.array([[pressure, temperature, material_type]])
65
+ prediction = loaded_model.predict(input_data)[0]
66
+ defect_map = {0: "No Defect", 1: "Crack", 2: "Wrinkle"}
67
+ defect_prediction = defect_map[prediction]
68
+
69
+ # Generate visualization
70
+ plot_path = plot_simulation(pressure, temperature, material_type)
71
+
72
+ return f"Predicted Defect: {defect_prediction}", plot_path
73
 
74
+ # Step 5: Create Gradio Interface with Visualization
75
+ interface = gr.Interface(
76
+ fn=predict_and_visualize,
77
+ inputs=[
78
+ gr.Slider(50, 200, step=1, label="Pressure"),
79
+ gr.Slider(300, 700, step=1, label="Temperature"),
80
+ gr.Dropdown(choices=["1", "2", "3", "4"], label="Material Type")
81
+ ],
82
+ outputs=[
83
+ gr.Textbox(label="Prediction"),
84
+ gr.Image(label="Stress-Strain Visualization")
85
+ ],
86
+ title="Defect Prediction & Simulation",
87
+ description="Predict defect type and visualize stress-strain simulation for input features: Pressure, Temperature, and Material Type."
88
+ )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
89
 
90
+ # Step 6: Launch the Interface
91
+ if __name__ == "__main__":
92
+ interface.launch()