File size: 6,484 Bytes
99c4896
e594240
99c4896
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
67b1eed
f128da1
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
import cadquery as cq
import numpy as np
import matplotlib.pyplot as plt
import pyvista as pv
from reportlab.lib.pagesizes import letter
from reportlab.pdfgen import canvas
import gradio as gr
import os
from ansys.mapdl.core import launch_mapdl  # For ANSYS integration


# Function for Progressive Die Design
def generate_die(length, width, thickness):
    try:
        plate = cq.Workplane("XY").box(length, width, thickness)
        punch = cq.Workplane("XY").rect(10, 10).extrude(5).translate((length / 4, width / 4, thickness / 2))
        die = plate.cut(punch)
        filename = "progressive_die.step"
        cq.exporters.export(die, filename)
        return filename
    except Exception as e:
        return f"Error generating die: {str(e)}"


# Function to visualize die in 3D
def visualize_die(length, width, thickness):
    try:
        plate = cq.Workplane("XY").box(length, width, thickness)
        punch = cq.Workplane("XY").rect(10, 10).extrude(5).translate((length / 4, width / 4, thickness / 2))
        die = plate.cut(punch)

        # Export to STL for visualization
        cq.exporters.exportShape(die.val(), "STL", "progressive_die.stl")

        # Visualize with PyVista
        mesh = pv.read("progressive_die.stl")
        plotter = pv.Plotter(off_screen=True)
        plotter.add_mesh(mesh, color="blue")
        screenshot = "progressive_die_visualization.png"
        plotter.screenshot(screenshot)
        return screenshot
    except Exception as e:
        return f"Error visualizing die: {str(e)}"


# Function for Python-based Stress Analysis
def stress_analysis(force, die_width, die_height, material_strength):
    try:
        stress = force / (die_width * die_height)
        safety_factor = material_strength / stress

        fig, ax = plt.subplots()
        ax.bar(["Stress", "Material Strength"], [stress, material_strength])
        ax.set_ylabel("Stress (MPa)")
        ax.set_title("Stress Analysis")
        plt.close(fig)

        return f"Safety Factor: {round(safety_factor, 2)}", fig
    except Exception as e:
        return f"Error in stress analysis: {str(e)}", None


# ANSYS Integration for Stress Analysis
def run_ansys_simulation(force, die_width, die_height, material_strength):
    try:
        # Launch ANSYS MAPDL instance
        mapdl = launch_mapdl()
        mapdl.prep7()  # Enter pre-processing module

        # Define geometry and material properties
        mapdl.rectng(0, die_width, 0, die_height)
        mapdl.mp('EX', 1, material_strength)
        mapdl.et(1, 'PLANE183')

        # Apply loads
        mapdl.nsel('S', 'LOC', 'X', 0)
        mapdl.d('ALL', 'UX', 0)
        mapdl.f('ALL', 'FY', -force)

        # Solve
        mapdl.run('/SOLU')
        mapdl.solve()
        mapdl.finish()

        # Post-processing
        mapdl.post1()
        stress = mapdl.get_value('NODE', 1, 'S', 'EQV')  # Retrieve max equivalent stress
        mapdl.exit()

        return f"Max Stress: {stress:.2f} MPa"
    except Exception as e:
        return f"Error running ANSYS simulation: {str(e)}"


# SolidWorks Placeholder for Stress Analysis
def solidworks_stress_analysis(force, die_width, die_height, material_strength):
    # Replace this function with SolidWorks API or external script
    try:
        output_file = "/path/to/solidworks/output.txt"  # Replace with actual path
        if os.path.exists(output_file):
            with open(output_file, "r") as file:
                result = file.read()
            return result.strip()
        else:
            return "SolidWorks simulation output not found."
    except Exception as e:
        return f"Error running SolidWorks simulation: {str(e)}"


# Function to generate PDF report
def generate_pdf_report(data, filename="report.pdf"):
    try:
        c = canvas.Canvas(filename, pagesize=letter)
        c.drawString(100, 750, "Simulation Report")
        c.drawString(100, 730, f"Max Stress: {data.get('stress', 'N/A')} MPa")
        c.drawString(100, 710, f"Safety Factor: {data.get('safety_factor', 'N/A')}")
        c.save()
        return filename
    except Exception as e:
        return f"Error generating report: {str(e)}"


# Tool Optimization Function
def optimize_tool(speed, feed_rate, depth_of_cut, material):
    try:
        # Example formula for tool optimization
        tool_life = 1000 / (speed * feed_rate * depth_of_cut)
        recommended_speed = 0.8 * speed
        recommended_feed_rate = 0.9 * feed_rate

        # Return optimization results in dictionary
        results = {
            "Estimated Tool Life (hrs)": round(tool_life, 2),
            "Recommended Speed (m/min)": round(recommended_speed, 2),
            "Recommended Feed Rate (mm/rev)": round(recommended_feed_rate, 2)
        }
        return results
    except Exception as e:
        return {"Error": str(e)}


# Gradio interface functions
def stress_analysis_interface(force, die_width, die_height, material_strength, simulation_tool):
    if simulation_tool == "Python":
        # Python-based stress analysis
        safety_factor, fig = stress_analysis(force, die_width, die_height, material_strength)
        data = {"stress": force / (die_width * die_height), "safety_factor": safety_factor}
        pdf_filename = generate_pdf_report(data)
        return safety_factor, fig, pdf_filename

    elif simulation_tool == "ANSYS":
        # Run ANSYS-based simulation
        result = run_ansys_simulation(force, die_width, die_height, material_strength)
        return result, None, None

    elif simulation_tool == "SolidWorks":
        # Run SolidWorks-based simulation
        result = solidworks_stress_analysis(force, die_width, die_height, material_strength)
        return result, None, None

    else:
        return "Invalid simulation tool selected", None, None


# Create Gradio App
   # with gr.Tab("Progressive Die Design"):
    gr.Markdown("### Enter Dimensions for Progressive Die")
    length = gr.Number(label="Length (mm)", value=100)
    width = gr.Number(label="Width (mm)", value=50)  # Fixed the parenthesis here
    thickness = gr.Number(label="Thickness (mm)", value=10)
    die_output = gr.Textbox(label="Die Output File")
    visualization_output = gr.Image(label="3D Visualization")
    die_button = gr.Button("Generate Die")
    die_button.click(
        lambda l, w, t: (generate_die(l, w, t), visualize_die(l, w, t)),
        inputs=[length, width, thickness],
        outputs=[die_output, visualization_output],
    )