Rui Wan commited on
Commit
b96110f
·
1 Parent(s): 6306eda

Gradio demo

Browse files
.~lock.DataForThermoforming.xlsx# ADDED
@@ -0,0 +1 @@
 
 
1
+ ,wan6,precision,21.01.2026 10:05,file:///home/wan6/snap/libreoffice/365/.config/libreoffice/4;
.~lock.DataForThermoforming_Modified_Pritom.xlsx# ADDED
@@ -0,0 +1 @@
 
 
1
+ ,wan6,precision,12.01.2026 14:02,file:///home/wan6/snap/libreoffice/365/.config/libreoffice/4;
.~lock.Hat_Section_AM.pptx# ADDED
@@ -0,0 +1 @@
 
 
1
+ ,wan6,precision,12.01.2026 16:00,/home/wan6/snap/onlyoffice-desktopeditors/890/.local/share/onlyoffice;
Data/DataForThermoforming.xlsx ADDED
Binary file (28.5 kB). View file
 
Data/FDM_192_Simulation_Matrix_Shared.xlsx ADDED
Binary file (40.3 kB). View file
 
app.py ADDED
@@ -0,0 +1,65 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ import gradio as gr
3
+
4
+ from model_inverse import inverse_design
5
+
6
+
7
+ def run_inverse_design(ply_number, a1, b1, c1, stress, n_restarts, epochs, loss_scale, use_lbfgs):
8
+ y_target = np.array([a1, b1, c1, stress], dtype=np.float32)
9
+ best = inverse_design(
10
+ pile_number=int(ply_number),
11
+ y_target=y_target,
12
+ n_restarts=int(n_restarts),
13
+ epochs=int(epochs),
14
+ loss_scale=float(loss_scale),
15
+ use_lbfgs=bool(use_lbfgs),
16
+ )
17
+ if best["input"] is None or best["output"] is None:
18
+ return {"Initial Temp": None, "Punch Velocity": None, "Cooling Time": None}, {"A1": None, "B1": None, "C1": None, "Stress": None}
19
+
20
+ input_vals = {
21
+ "Initial Temp": float(best["input"][0]),
22
+ "Punch Velocity": float(best["input"][1]),
23
+ "Cooling Time": float(best["input"][2]),
24
+ }
25
+ output_vals = {
26
+ "A1": float(best["output"][0][0]),
27
+ "B1": float(best["output"][0][1]),
28
+ "C1": float(best["output"][0][2]),
29
+ "Stress": float(best["output"][0][3]),
30
+ }
31
+ return input_vals, output_vals
32
+
33
+
34
+ with gr.Blocks(title="Inverse Design Demo") as demo:
35
+ gr.Markdown("# Inverse Design Demo")
36
+ gr.Markdown("Enter a target output; the model finds processing parameters.")
37
+
38
+ with gr.Row():
39
+ with gr.Column():
40
+ pile_number = gr.Number(label="Pile number", value=2, precision=0)
41
+ a1 = gr.Number(label="A1", value=0.89, precision=4)
42
+ b1 = gr.Number(label="B1", value=0.83, precision=4)
43
+ c1 = gr.Number(label="C1", value=0.12, precision=4)
44
+ stress = gr.Number(label="Stress", value=180.2, precision=4)
45
+ with gr.Column():
46
+ n_restarts = gr.Number(label="Restarts", value=5, precision=0)
47
+ epochs = gr.Number(label="Epochs", value=1000, precision=0)
48
+ loss_scale = gr.Number(label="Loss scale", value=1.0, precision=3)
49
+ use_lbfgs = gr.Checkbox(label="Use LBFGS", value=False)
50
+
51
+ run_btn = gr.Button("Run Inverse Design")
52
+
53
+ with gr.Row():
54
+ best_input = gr.JSON(label="Best Input")
55
+ best_output = gr.JSON(label="Predicted Output")
56
+
57
+ run_btn.click(
58
+ run_inverse_design,
59
+ inputs=[pile_number, a1, b1, c1, stress, n_restarts, epochs, loss_scale, use_lbfgs],
60
+ outputs=[best_input, best_output],
61
+ )
62
+
63
+
64
+ if __name__ == "__main__":
65
+ demo.launch()
model.py ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+
3
+
4
+ class NeuralNetwork(torch.nn.Module):
5
+ def __init__(self, layer_sizes, dropout_rate=0.0, activation=torch.nn.ReLU):
6
+ super(NeuralNetwork, self).__init__()
7
+
8
+ if dropout_rate > 0:
9
+ self.dropout_layer = torch.nn.Dropout(dropout_rate)
10
+
11
+ self.layer_sizes = layer_sizes
12
+ self.layers = torch.nn.ModuleList()
13
+ for i in range(len(layer_sizes) - 2):
14
+ self.layers.append(torch.nn.Linear(layer_sizes[i], layer_sizes[i + 1]))
15
+ self.layers.append(activation())
16
+ self.layers.append(torch.nn.Linear(layer_sizes[-2], layer_sizes[-1]))
17
+
18
+ # self.sequential = torch.nn.Sequential(*self.layers)
19
+
20
+ self.init_weights()
21
+
22
+ def init_weights(self):
23
+ for layer in self.layers:
24
+ if isinstance(layer, torch.nn.Linear):
25
+ torch.nn.init.xavier_normal_(layer.weight)
26
+ layer.bias.data.fill_(0.0)
27
+
28
+ def forward(self, x, train=True):
29
+ for layer in self.layers:
30
+ x = layer(x)
31
+ if train and hasattr(self, 'dropout_layer'):
32
+ x = self.dropout_layer(x)
33
+
34
+ return x
35
+
36
+ def predict(self, x, train=False):
37
+ self.eval()
38
+ with torch.no_grad():
39
+ return self.forward(x, train)
model_inverse.py ADDED
@@ -0,0 +1,262 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import numpy as np
3
+ import matplotlib.pyplot as plt
4
+ from Dataset import Dataset
5
+
6
+ DEVICE = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
7
+ # Set global plotting parameters
8
+ plt.rcParams.update({'font.size': 14,
9
+ 'figure.figsize': (10, 8),
10
+ 'lines.linewidth': 2,
11
+ 'lines.markersize': 6,
12
+ 'axes.grid': True,
13
+ 'axes.labelsize': 16,
14
+ 'legend.fontsize': 14,
15
+ 'xtick.labelsize': 14,
16
+ 'ytick.labelsize': 14,
17
+ 'figure.autolayout': True
18
+ })
19
+
20
+ def set_seed(seed=42):
21
+ np.random.seed(seed)
22
+ torch.manual_seed(seed)
23
+ if torch.cuda.is_available():
24
+ torch.cuda.manual_seed_all(seed)
25
+
26
+ class NeuralNetwork(torch.nn.Module):
27
+ def __init__(self, layer_sizes, dropout_rate=0.0, activation=torch.nn.ReLU):
28
+ super(NeuralNetwork, self).__init__()
29
+
30
+ if dropout_rate > 0:
31
+ self.dropout_layer = torch.nn.Dropout(dropout_rate)
32
+
33
+ self.layer_sizes = layer_sizes
34
+ self.layers = torch.nn.ModuleList()
35
+ for i in range(len(layer_sizes) - 2):
36
+ self.layers.append(torch.nn.Linear(layer_sizes[i], layer_sizes[i + 1]))
37
+ self.layers.append(activation())
38
+ self.layers.append(torch.nn.Linear(layer_sizes[-2], layer_sizes[-1]))
39
+
40
+ # self.sequential = torch.nn.Sequential(*self.layers)
41
+
42
+ self.init_weights()
43
+
44
+ def init_weights(self):
45
+ for layer in self.layers:
46
+ if isinstance(layer, torch.nn.Linear):
47
+ torch.nn.init.xavier_normal_(layer.weight)
48
+ layer.bias.data.fill_(0.0)
49
+
50
+ def forward(self, x, train=True):
51
+ for layer in self.layers:
52
+ x = layer(x)
53
+ if train and hasattr(self, 'dropout_layer'):
54
+ x = self.dropout_layer(x)
55
+
56
+ return x
57
+
58
+ def predict(self, x, train=False):
59
+ self.eval()
60
+ with torch.no_grad():
61
+ return self.forward(x, train)
62
+
63
+ def train_neural_network(model, inputs, outputs, optimizer, epochs=1000, lr_scheduler=None):
64
+ model.train()
65
+ for epoch in range(epochs):
66
+ optimizer.zero_grad()
67
+ predictions = model(inputs)
68
+ loss = torch.mean(torch.square(predictions - outputs))
69
+ loss.backward()
70
+ optimizer.step()
71
+
72
+ if lr_scheduler:
73
+ lr_scheduler.step()
74
+
75
+ if epoch % 100 == 0:
76
+ print(f'Epoch {epoch}, Loss: {loss.item()}, Learning Rate: {optimizer.param_groups[0]["lr"]}')
77
+
78
+
79
+ def load_model(model_path):
80
+ checkpoint = torch.load(model_path)
81
+ model_config = checkpoint['model_config']
82
+ model = NeuralNetwork(model_config['layer_sizes'], dropout_rate=model_config['dropout_rate'])
83
+ model.load_state_dict(checkpoint['model_state_dict'])
84
+ print(f"Model loaded from {model_path}")
85
+ return model
86
+
87
+ def inverse_design(ply_number, y_target, n_restarts=20, epochs=1000, use_lbfgs=False):
88
+ model = load_model('./model_inverse_ckpt.pth')
89
+
90
+ data = Dataset()
91
+ y_target_norm = data.normalize_output(y_target) # (A1, B1, C1, Stress)
92
+ y_target_tensor = torch.tensor(y_target, dtype=torch.float32)
93
+ input_mean = torch.tensor(data.input_mean)
94
+ input_std = torch.tensor(data.input_std)
95
+ output_mean = torch.tensor(data.output_mean)
96
+ output_std = torch.tensor(data.output_std)
97
+
98
+
99
+ model.eval()
100
+ weights = torch.tensor([1.0, 1.0, 1.0, 0.0], dtype=torch.float32)
101
+ bounds = torch.tensor([[350., 450.], [100., 500.], [450., 550.]], dtype=torch.float32) # Initial_Temp, Punch_Velocity, Cooling_Time
102
+ best = {"loss": float('inf'), "input": None, "output": None}
103
+
104
+ for restart in range(n_restarts):
105
+ z = torch.randn(3, requires_grad=True)
106
+
107
+ if use_lbfgs:
108
+ optimizer = torch.optim.LBFGS([z], lr=0.5, max_iter=500, line_search_fn="strong_wolfe")
109
+ else:
110
+ optimizer = torch.optim.Adam([z], lr=0.001)
111
+
112
+ for step in range(epochs):
113
+ def closure():
114
+ var = bounds[:, 0] + (bounds[:, 1] - bounds[:, 0]) * torch.sigmoid(z)
115
+ optimizer.zero_grad()
116
+ input_raw = torch.cat([torch.tensor([ply_number]), var]).unsqueeze(0)
117
+ input_norm = (input_raw - input_mean) / input_std
118
+ output_pred = model(input_norm)
119
+ output_pred = (output_pred * output_std) + output_mean
120
+ loss = torch.sum(weights * (output_pred - y_target_tensor) ** 2)
121
+ loss.backward()
122
+ return loss
123
+
124
+ if use_lbfgs:
125
+ loss = optimizer.step(closure)
126
+ else:
127
+ loss = closure()
128
+ optimizer.step()
129
+
130
+ if (step + 1) % 200 == 0:
131
+ print(f'Restart {restart + 1}, Step {step + 1}, Loss: {loss.item():.6f}, grad: {z.grad.norm().item():.6f}')
132
+
133
+ with torch.no_grad():
134
+ var = bounds[:, 0] + (bounds[:, 1] - bounds[:, 0]) * torch.sigmoid(z)
135
+ input_raw = torch.cat([torch.tensor([ply_number]), var]).unsqueeze(0)
136
+ input_norm = (input_raw - input_mean) / input_std
137
+ output_pred = model(input_norm)
138
+ output_pred = data.denormalize_output(output_pred.numpy())
139
+ final_loss = np.sum(weights.numpy() * (output_pred - y_target) ** 2).item()
140
+ if final_loss < best["loss"]:
141
+ best["loss"] = final_loss
142
+ best["input"] = var.detach().cpu().numpy()
143
+ best["output"] = output_pred
144
+
145
+ return best
146
+
147
+
148
+ def inverse_model():
149
+ set_seed(5324)
150
+ dataset = Dataset(inverse=True)
151
+ inputs, outputs = dataset.get_input(normalize=True), dataset.get_output(normalize=True)
152
+
153
+ idx_train = np.random.choice(len(inputs), size=int(0.85 * len(inputs)), replace=False)
154
+ idx_test = np.setdiff1d(np.arange(len(inputs)), idx_train)
155
+ # idx_test = np.array([1, 14+1, 18+1, 20+1, 23+1])
156
+ # idx_train = np.setdiff1d(np.arange(len(inputs)), idx_test)
157
+
158
+ inputs_train = torch.tensor(inputs[idx_train], dtype=torch.float32).to(DEVICE)
159
+ outputs_train = torch.tensor(outputs[idx_train], dtype=torch.float32).to(DEVICE)
160
+
161
+ inputs_test = torch.tensor(inputs[idx_test], dtype=torch.float32).to(DEVICE)
162
+ outputs_test = torch.tensor(outputs[idx_test], dtype=torch.float32).to(DEVICE)
163
+
164
+ layer_sizes = [inputs.shape[1]] + [64] * 3 + [outputs.shape[1]]
165
+ model = NeuralNetwork(layer_sizes, dropout_rate=0.05, activation=torch.nn.ReLU).to(DEVICE)
166
+ optimizer = torch.optim.Adam(model.parameters(), lr=0.001)
167
+ lr_scheduler = torch.optim.lr_scheduler.StepLR(optimizer, step_size=5000, gamma=0.9)
168
+
169
+ # Create a proper dataset that keeps input-output pairs together
170
+ train_dataset = torch.utils.data.TensorDataset(inputs_train, outputs_train)
171
+ train_loader = torch.utils.data.DataLoader(train_dataset, batch_size=16, shuffle=True)
172
+
173
+ # Train the model
174
+ epochs = 20000
175
+ for epoch in range(epochs):
176
+ model.train()
177
+ for inputs_batch, outputs_batch in train_loader:
178
+ inputs_batch = inputs_batch.to(DEVICE)
179
+ outputs_batch = outputs_batch.to(DEVICE)
180
+ optimizer.zero_grad()
181
+ predictions = model(inputs_batch)
182
+ loss = torch.mean(torch.square(predictions - outputs_batch))
183
+ loss.backward()
184
+ optimizer.step()
185
+
186
+ if lr_scheduler:
187
+ lr_scheduler.step()
188
+
189
+ if epoch % 500 == 0:
190
+ train_pred = model(inputs_train)
191
+ train_loss = torch.mean(torch.square(train_pred - outputs_train))
192
+ test_pred = model(inputs_test)
193
+ test_loss = torch.mean(torch.square(test_pred - outputs_test))
194
+ print(f'Epoch {epoch}, Train Loss: {train_loss.item():.6f}, Test Loss: {test_loss.item():.6f}')
195
+ # print(f'Learning Rate: {optimizer.param_groups[0]["lr"]}')
196
+
197
+
198
+ predictions = model.predict(inputs_test)
199
+ test_loss = torch.mean(torch.square(predictions - outputs_test))
200
+ print(f'Test Loss: {test_loss.item()}. Samples: {idx_test}')
201
+
202
+ x = np.arange(0, len(idx_test))
203
+
204
+ outputs_test = dataset.denormalize_output(outputs_test.cpu().numpy())
205
+ predictions = dataset.denormalize_output(predictions.cpu().numpy())
206
+ # for sample in outputs_test:
207
+ # print(f'Test samples: {sample}')
208
+ plt.figure(figsize=(10, 6))
209
+ plt.plot(x, outputs_test[:, 0], color='b', linestyle='--', label='True Initial Temp')
210
+ plt.plot(x, predictions[:, 0], color='b', linestyle='-', label='Predicted Initial Temp')
211
+ plt.plot(x, outputs_test[:, 1], color='r', linestyle='--', label='True Punch Velocity')
212
+ plt.plot(x, predictions[:, 1], color='r', linestyle='-', label='Predicted Punch Velocity')
213
+ plt.plot(x, outputs_test[:, 2], color='g', linestyle='--', label='True Cooling Time')
214
+ plt.plot(x, predictions[:, 2], color='g', linestyle='-', label='Predicted Cooling Time')
215
+ plt.gca().xaxis.set_major_locator(plt.MaxNLocator(integer=True))
216
+ plt.xlabel('Sample Index')
217
+ plt.xticks(ticks=range(len(idx_test)),labels=idx_test + 1)
218
+ plt.ylabel('Processing Parameters')
219
+ plt.legend(loc='upper right')
220
+ plt.savefig('inverse_design.png')
221
+
222
+ # MSE
223
+ mse = np.mean((predictions - outputs_test) ** 2, axis=0)
224
+ print(f'Mean Squared Error for Initial Temp: {mse[0]:.6f}, Punch Velocity: {mse[1]:.6f}, Cooling Time: {mse[2]:.6f}')
225
+
226
+ # R 2 score
227
+ ss_ress = np.sum((outputs_test - predictions) ** 2, axis=0)
228
+ ss_tots = np.sum((outputs_test - np.mean(outputs_test, axis=0)) ** 2, axis=0)
229
+ r2_scores = 1 - ss_ress / ss_tots
230
+ print(f'R² Score for Initial Temp: {r2_scores[0]:.6f}, Punch Velocity: {r2_scores[1]:.6f}, Cooling Time: {r2_scores[2]:.6f}')
231
+
232
+ # Error
233
+
234
+ # Save the model
235
+ model_save_path = './model_inverse_ckpt.pth'
236
+ model_config = {'layer_sizes': layer_sizes,
237
+ 'dropout_rate': 0.05
238
+ }
239
+ checkpoint = {
240
+ 'model_state_dict': model.state_dict(),
241
+ 'model_config': model_config
242
+ }
243
+ torch.save(checkpoint, model_save_path)
244
+ # Load the model
245
+ # model = NeuralNetwork(layer_sizes)
246
+ # model.load_state_dict(torch.load(model_save_path))
247
+
248
+
249
+ if __name__ == "__main__":
250
+ # train the inverse model over springback data
251
+ # inverse_model()
252
+
253
+ # perform inverse design
254
+ import time
255
+ start_time = time.time()
256
+ best = inverse_design(ply_number=2, y_target=np.array([0.89, 0.83, 0.12, 180.2]), n_restarts=5, epochs=100, use_lbfgs=True)
257
+ end_time = time.time()
258
+ time_elapsed = (end_time - start_time) # in milliseconds
259
+ print(f"Inverse design completed in {time_elapsed:.2f} seconds.")
260
+ print("Best Input (Initial Temp, Punch Velocity, Cooling Time):", best["input"])
261
+ print("Best Output (A1, B1, C1, Stress):", best["output"])
262
+
model_inverse_ckpt.pth ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:1d8a6c28d5674b85ab110058a65eab6bed5cc61c1180b22a4105dac959f0c493
3
+ size 39655
requirements.txt ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ numpy>=1.20.0
2
+ matplotlib>=3.5.0
3
+ pandas>=1.3.0
4
+ torch>=1.10.0
5
+ tensorflow>=2.8.0
6
+ gradio>=3.50.0