snajmark commited on
Commit
edeec9a
·
1 Parent(s): ff02646

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +311 -0
app.py ADDED
@@ -0,0 +1,311 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import csv
3
+ import gradio as gr
4
+ import tensorflow as tf
5
+ import numpy as np
6
+ import pandas as pd
7
+ from datetime import datetime
8
+ import utils
9
+ from huggingface_hub import Repository
10
+ import itertools
11
+ import GPyOpt
12
+
13
+ # Unique phase elements
14
+
15
+ # Load access tokens
16
+ WRITE_TOKEN = os.environ.get("WRITE_PER") # write
17
+
18
+ # Logs repo path
19
+ dataset_url = "https://huggingface.co/datasets/sandl/upload_alloy_hardness"
20
+ dataset_path = "logs_alloy_hardness.csv"
21
+
22
+ scaling_factors = {'PROPERTY: Calculated Density (g/cm$^3$)': (5.5, 13.7),
23
+ 'PROPERTY: Calculated Young modulus (GPa)': (77.0, 336.0),
24
+ 'PROPERTY: HV': (107.0, 1183.0),
25
+ 'PROPERTY: YS (MPa)': (62.0, 3416.0)}
26
+
27
+ input_mapping = {'PROPERTY: BCC/FCC/other': {'BCC': 0, 'FCC': 1, 'OTHER': 2},#, 'nan': 2},
28
+ 'PROPERTY: Processing method': {'ANNEAL': 0, 'CAST': 1, 'OTHER': 2, 'POWDER': 3, 'WROUGHT': 4},#, 'nan': 2},
29
+ 'PROPERTY: Microstructure': {'B2': 0, 'B2+BCC': 1, 'B2+L12': 2, 'B2+Laves+Sec.': 3, 'B2+Sec.': 4, 'BCC': 5,
30
+ 'BCC+B2': 6, 'BCC+B2+FCC': 7, 'BCC+B2+FCC+Sec.': 8, 'BCC+B2+L12': 9, 'BCC+B2+Laves': 10,
31
+ 'BCC+B2+Sec.': 11, 'BCC+BCC': 12, 'BCC+BCC+HCP': 13, 'BCC+BCC+Laves': 14,
32
+ 'BCC+BCC+Laves(C14)': 15, 'BCC+BCC+Laves(C15)': 16, 'BCC+FCC': 17, 'BCC+HCP': 18,
33
+ 'BCC+Laves': 19, 'BCC+Laves(C14)': 20, 'BCC+Laves(C15)': 21, 'BCC+Laves+Sec.': 22,
34
+ 'BCC+Sec.': 23, 'FCC': 24, 'FCC+B2': 25, 'FCC+B2+Sec.': 26, 'FCC+BCC': 27,
35
+ 'FCC+BCC+B2': 28, 'FCC+BCC+B2+Sec.': 29, 'FCC+BCC+BCC': 30, 'FCC+BCC+Sec.': 31,
36
+ 'FCC+FCC': 32, 'FCC+HCP': 33, 'FCC+HCP+Sec.': 34, 'FCC+L12': 35, 'FCC+L12+B2': 36,
37
+ 'FCC+L12+Sec.': 37, 'FCC+Laves': 38, 'FCC+Laves(C14)': 39, 'FCC+Laves+Sec.': 40,
38
+ 'FCC+Sec.': 41, 'L12+B2': 42, 'Laves(C14)+Sec.': 43, 'OTHER': 44},#, 'nan': 44},
39
+ 'PROPERTY: Single/Multiphase': {'': 0, 'M': 1, 'S': 2, 'OTHER': 3}}#, 'nan': 3}}
40
+
41
+ unique_phase_elements = ['B2', 'BCC', 'FCC', 'HCP', 'L12', 'Laves', 'Laves(C14)', 'Laves(C15)', 'Sec.', 'OTHER']
42
+
43
+ input_cols = {
44
+ "PROPERTY: Alloy formula": "(PROPERTY: Alloy formula) "
45
+ "Enter alloy formula using proportions representation (i.e. Al0.25 Co1 Fe1 Ni1)",
46
+ "PROPERTY: Single/Multiphase": "(PROPERTY: Single/Multiphase) "
47
+ "Choose between Single (S), Multiphase (M) and other (OTHER)",
48
+ "PROPERTY: BCC/FCC/other": "(PROPERTY: BCC/FCC/other) "
49
+ "Choose between BCC, FCC and other ",
50
+ "PROPERTY: Processing method": "(PROPERTY: Processing method) "
51
+ "Choose your processing method (ANNEAL, CAST, POWDER, WROUGHT or OTHER)",
52
+ "PROPERTY: Microstructure": "(PROPERTY: Microstructure) "
53
+ "Choose the microstructure (SEC means the secondary/tertiary microstructure is not one of FCC, BCC, HCP, L12, B2, Laves, Laves (C14), Laves (C15))",
54
+ }
55
+
56
+ def process_microstructure(list_phases):
57
+ permutations = list(itertools.permutations(list_phases))
58
+ permutations_strings = [str('+'.join(list(e))) for e in permutations]
59
+ for e in permutations_strings:
60
+ if e in list(input_mapping['PROPERTY: Microstructure'].keys()):
61
+ return e
62
+ return 'OTHER'
63
+
64
+ def write_logs(message, message_type="Prediction"):
65
+ """
66
+ Write logs
67
+ """
68
+ #with Repository(local_dir="data", clone_from=dataset_url, use_auth_token=WRITE_TOKEN).commit(commit_message="from private", blocking=False):
69
+ # with open(dataset_path, "a") as csvfile:
70
+ # writer = csv.DictWriter(csvfile, fieldnames=["name", "message", "time"])
71
+ # writer.writerow(
72
+ # {"name": message_type, "message": message, "time": str(datetime.now())}
73
+ # )
74
+ return
75
+
76
+ def predict(x, request: gr.Request):
77
+ """
78
+ Predict the hardness and yield strength using the ML model. Input data is a dataframe
79
+ """
80
+ loaded_model = tf.keras.models.load_model("hardness.h5")
81
+ print("summary is", loaded_model.summary())
82
+ #x = x.replace("", 0)
83
+ x = np.asarray(x).astype("float32")
84
+ y = loaded_model.predict(x)
85
+ y_hardness = y[0][0]
86
+ y_ys = y[0][1]
87
+ minimum_hardness, maximum_hardness = scaling_factors['PROPERTY: HV']
88
+ minimum_ys, maximum_ys = scaling_factors['PROPERTY: YS (MPa)']
89
+ print("Prediction is ", y)
90
+ if request is not None: # Verify if request is not None (when building the app the first request is None)
91
+ message = f"{request.username}_{request.client.host}"
92
+ print("MESSAGE")
93
+ print(message)
94
+ res = write_logs(message)
95
+ #interpret_fig = utils.interpret(x)
96
+ return (round(y_hardness*(maximum_hardness-minimum_hardness)+minimum_hardness, 2), 12,
97
+ round(y_ys*(maximum_ys-minimum_ys)+minimum_ys, 2), 12)
98
+
99
+
100
+ def predict_from_tuple(in1, in2, in3, in4, in5, request: gr.Request):
101
+ """
102
+ Predict the hardness using the ML model. Input data is a tuple. Input order should be the same as the cols list
103
+ """
104
+ input_tuple = (in1, in2, in3, in4, in5)
105
+ formula = utils.normalize_and_alphabetize_formula(in1)
106
+ density = utils.calculate_density(formula)
107
+ young_modulus = utils.calculate_youngs_modulus(formula)
108
+ input_dict = {}
109
+
110
+ in2 = input_mapping['PROPERTY: Single/Multiphase'][str(in2)]
111
+ input_dict['PROPERTY: Single/Multiphase'] = [int(in2)]
112
+
113
+ in3 = input_mapping['PROPERTY: BCC/FCC/other'][str(in3)]
114
+ input_dict['PROPERTY: BCC/FCC/other'] = [int(in3)]
115
+
116
+ in4 = input_mapping['PROPERTY: Processing method'][str(in4)]
117
+ input_dict['PROPERTY: Processing method'] = [int(in4)]
118
+
119
+ in5 = process_microstructure(in5)
120
+ in5 = input_mapping['PROPERTY: Microstructure'][in5]
121
+ input_dict['PROPERTY: Microstructure'] = [int(in5)]
122
+
123
+ density_scaling_factors = scaling_factors['PROPERTY: Calculated Density (g/cm$^3$)']
124
+ density = (density-density_scaling_factors[0])/(
125
+ density_scaling_factors[1]-density_scaling_factors[0])
126
+ input_dict['PROPERTY: Calculated Density (g/cm$^3$)'] = [float(density)]
127
+
128
+
129
+ ym_scaling_factors = scaling_factors['PROPERTY: Calculated Young modulus (GPa)']
130
+ young_modulus = (young_modulus-ym_scaling_factors[0])/(
131
+ ym_scaling_factors[1]-ym_scaling_factors[0])
132
+ input_dict['PROPERTY: Calculated Young modulus (GPa)'] = [float(young_modulus)]
133
+
134
+ input_df = pd.DataFrame.from_dict(input_dict)
135
+ one_hot = utils.turn_into_one_hot(input_df, input_mapping)
136
+ print("One hot columns are ", one_hot.columns)
137
+ return predict(one_hot, request)
138
+
139
+ def fit_outputs_constraints(x, hardness_target, ys_target, request: gr.Request):
140
+ predictions = predict(x, request)
141
+ error_hardness = np.sqrt(np.square(predictions[0]-float(hardness_target)))
142
+ error_ys = np.sqrt(np.square(predictions[2]-float(ys_target)))
143
+ print("Optimization step is ", predictions, float(hardness_target), float(ys_target),
144
+ error_hardness, error_ys)
145
+ return error_hardness + error_ys
146
+
147
+ def predict_inverse(hardness_target, ys_target, formula, request: gr.Request):
148
+
149
+ one_hot_columns = utils.return_feature_names()
150
+
151
+ continuous_variables = ['PROPERTY: Calculated Density (g/cm$^3$)',
152
+ 'PROPERTY: Calculated Young modulus (GPa)']
153
+ categorical_variables = list(one_hot_columns)
154
+ for c in continuous_variables:
155
+ categorical_variables.remove(c)
156
+
157
+
158
+ fixed_density = utils.calculate_density(str(formula))
159
+ fixed_ym = utils.calculate_youngs_modulus(str(formula))
160
+
161
+ domain = []
162
+ for c in one_hot_columns:
163
+ if c in continuous_variables:
164
+ if c == continuous_variables[0]:
165
+ domain_density = (fixed_density-scaling_factors[c][0])/(
166
+ scaling_factors[c][1]-scaling_factors[c][0])
167
+ domain.append({'name': str(c), 'type': 'continuous', 'domain': (domain_density, domain_density)})#(0.,1.)})
168
+ else:
169
+ domain_ym = (fixed_ym-scaling_factors[c][0])/(
170
+ scaling_factors[c][1]-scaling_factors[c][0])
171
+ domain.append({'name': str(c), 'type': 'continuous', 'domain': (domain_ym, domain_ym)})#(0.,1.)})
172
+ else:
173
+ domain.append({'name': str(c), 'type': 'discrete', 'domain': (0,1)})
174
+
175
+ print("Domain is ", domain)
176
+ constraints = []
177
+ constrained_columns = ['Single/Multiphase', 'Preprocessing method', 'BCC/FCC/other']#, 'Microstructure']
178
+
179
+ for constraint in constrained_columns:
180
+ sum_string = ''
181
+ for i in range (len(one_hot_columns)):
182
+ column_one_hot = one_hot_columns[i]
183
+ if column_one_hot.startswith(constraint):
184
+ sum_string = sum_string+"+x[:," + str(i) + "]"
185
+ constraints.append({'name': constraint + "+1", 'constraint': sum_string + '-1'})
186
+ constraints.append({'name': constraint + "-1", 'constraint': '-1*(' + sum_string + ')+1'})
187
+
188
+ def fit_outputs(x):
189
+ return fit_outputs_constraints(x, hardness_target, ys_target, request)
190
+
191
+ opt = GPyOpt.methods.BayesianOptimization(f = fit_outputs, # function to optimize
192
+ domain = domain, # box-constraints of the problem
193
+ constraints = constraints,
194
+ acquisition_type ='LCB', # LCB acquisition
195
+ acquisition_weight = 0.1) # Exploration exploitation
196
+ # it may take a few seconds
197
+ opt.run_optimization(max_iter=20)
198
+ opt.plot_convergence()
199
+ x_best = opt.X[np.argmin(opt.Y)]
200
+ best_params = dict(zip(
201
+ [el['name'] for el in domain],
202
+ [[x] for x in x_best]))
203
+ optimized_x = pd.DataFrame.from_dict(best_params)
204
+ #for c in optimized_x.columns:
205
+ # if c in continuous_variables:
206
+ # optimized_x[c]=optimized_x[c]*(scaling_factors[c][1]-scaling_factors[c][0])+scaling_factors[c][0]
207
+ optimized_x = optimized_x[['PROPERTY: Calculated Density (g/cm$^3$)',
208
+ 'PROPERTY: Calculated Young modulus (GPa)',
209
+ 'Preprocessing method ANNEAL',
210
+ 'Preprocessing method CAST', 'Preprocessing method OTHER',
211
+ 'Preprocessing method POWDER', 'Preprocessing method WROUGHT',
212
+ 'BCC/FCC/other BCC', 'BCC/FCC/other FCC', 'BCC/FCC/other OTHER',
213
+ 'Single/Multiphase ', 'Single/Multiphase M', 'Single/Multiphase S']]
214
+ result = optimized_x
215
+ result = result[result>0.0].dropna(axis=1)
216
+ return list(result.keys())[2:]
217
+
218
+
219
+ example_inputs = ["Al0.25 Co1 Fe1 Ni1", 820, 1800]
220
+
221
+ css_styling = """#submit {background: #1eccd8}
222
+ #submit:hover {background: #a2f1f6}
223
+ .output-image, .input-image, .image-preview {height: 250px !important}
224
+ .output-plot {height: 250px !important}"""
225
+
226
+ light_theme_colors = gr.themes.Color(c50="#e4f3fa", # Dataframe background cell content - light mode only
227
+ c100="#e4f3fa", # Top corner of clear button in light mode + markdown text in dark mode
228
+ c200="#a1c6db", # Component borders
229
+ c300="#FFFFFF", #
230
+ c400="#e4f3fa", # Footer text
231
+ c500="#0c1538", # Text of component headers in light mode only
232
+ c600="#a1c6db", # Top corner of button in dark mode
233
+ c700="#475383", # Button text in light mode + component borders in dark mode
234
+ c800="#0c1538", # Markdown text in light mode
235
+ c900="#a1c6db", # Background of dataframe - dark mode
236
+ c950="#0c1538") # Background in dark mode only
237
+ # secondary color used for highlight box content when typing in light mode, and download option in dark mode
238
+ # primary color used for login button in dark mode
239
+ osium_theme = gr.themes.Default(primary_hue="cyan", secondary_hue="cyan", neutral_hue=light_theme_colors)
240
+ page_title = "Alloys' hardness and yield strength prediction"
241
+ favicon_path = "osiumai_favicon.ico"
242
+ logo_path = "osiumai_logo.jpg"
243
+ html = f"""<html> <link rel="icon" type="image/x-icon" href="file={favicon_path}">
244
+ <img src='file={logo_path}' alt='Osium AI logo' width='200' height='100'> </html>"""
245
+
246
+
247
+ with gr.Blocks(css=css_styling, title=page_title, theme=osium_theme) as demo:
248
+ #gr.HTML(html)
249
+ gr.Markdown("# <p style='text-align: center;'>Get optimal alloy recommendations based on your target performance</p>")
250
+ gr.Markdown("This AI model provides a recommended alloy formula, microstructure and processing conditions based on your target hardness and yield strength")
251
+ with gr.Row():
252
+ clear_button = gr.Button("Clear")
253
+ prediction_button = gr.Button("Predict", elem_id="submit")
254
+ with gr.Row():
255
+ with gr.Column():
256
+ gr.Markdown("### Your alloy formula")
257
+ formula = gr.Text(label = "Alloy formula")
258
+ gr.Markdown("### The target performance of your alloy")
259
+ input_hardness = gr.Text(label="Enter your target hardness (in HV)")
260
+ input_yield_strength = gr.Text(label="Enter your target yield strength (MPa)")
261
+ with gr.Column():
262
+ with gr.Row():
263
+ with gr.Column():
264
+ gr.Markdown("### Your optimal microstructure and processing conditions")
265
+ #optimal_parameters = gr.DataFrame(label="Optimal parameters", wrap=True)
266
+ with gr.Column():
267
+ param1 = gr.Text(label="Processing method")
268
+ with gr.Column():
269
+ param2 = gr.Text(label="Microstructure")
270
+ with gr.Column():
271
+ param3 = gr.Text(label="Phase")
272
+ #with gr.Row():
273
+ #with gr.Column():
274
+ #with gr.Row():
275
+ # gr.Markdown("### Interpretation of hardness prediction")
276
+ # gr.Markdown("### Interpretation of yield strength prediction")
277
+ #with gr.Row():
278
+ # output_interpretation = gr.Plot(label="Interpretation")
279
+
280
+ with gr.Row():
281
+ gr.Examples([example_inputs], [formula, input_hardness, input_yield_strength])
282
+
283
+
284
+
285
+ prediction_button.click(
286
+ fn=predict_inverse,
287
+ inputs=[input_hardness, input_yield_strength, formula],
288
+ outputs=[
289
+ param1,
290
+ param2,
291
+ param3,
292
+ ],
293
+ show_progress=True,
294
+ )
295
+ clear_button.click(
296
+ lambda x: [gr.update(value=None)] * 6,
297
+ [],
298
+ [
299
+ param1,
300
+ param2,
301
+ param3,
302
+ input_hardness,
303
+ input_yield_strength,
304
+ formula
305
+ ],
306
+ )
307
+
308
+
309
+ if __name__ == "__main__":
310
+ demo.queue(concurrency_count=2)
311
+ demo.launch()