snajmark commited on
Commit
a3639a3
·
1 Parent(s): 6fd74af

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +66 -8
app.py CHANGED
@@ -72,7 +72,15 @@ def write_logs(message, message_type="Prediction"):
72
  # )
73
  print(message)
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
@@ -139,7 +147,60 @@ def predict_from_tuple(in1, in2, in3, in4, in5, request: gr.Request):
139
 
140
 
141
  def predict_inverse(target_hardness, target_yield_strength, request: gr.Request):
142
- return "Al1", "S", "BCC", "CAST", "HCP"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
143
 
144
 
145
  example_inputs = [420, 10]
@@ -170,7 +231,7 @@ html = f"""<html> <link rel="icon" type="image/x-icon" href="file={favicon_path}
170
  <img src='file={logo_path}' alt='Osium AI logo' width='200' height='100'> </html>"""
171
 
172
 
173
- with gr.Blocks(css=css_styling, title=page_title) as demo:
174
  gr.HTML(html)
175
  gr.Markdown("# <p style='text-align: center;'>Get optimal alloy recommendations based on your target performance</p>")
176
  gr.Markdown("This AI model provides a recommended alloy formula, microstructure and processing conditions based on your target hardness and yield strength")
@@ -203,6 +264,7 @@ with gr.Blocks(css=css_styling, title=page_title) as demo:
203
  choices=unique_phase_elements, #list(input_mapping["PROPERTY: Microstructure"].keys()),
204
  label=input_cols["PROPERTY: Microstructure"],
205
  )
 
206
 
207
  # with gr.Column():
208
  # gr.Markdown("### Your alloy's yield strength (MPa)")
@@ -218,11 +280,7 @@ with gr.Blocks(css=css_styling, title=page_title) as demo:
218
  fn=predict_inverse,
219
  inputs=[input_hardness, input_yield_strength],
220
  outputs=[
221
- output_formula,
222
- output_phase,
223
- output_bccfcc,
224
- output_processing,
225
- output_microstructure
226
  ],
227
  show_progress=True,
228
  )
 
72
  # )
73
  print(message)
74
  return
75
+
76
+ def fit_outputs(x, hardness_target, ys_target):
77
+ predictions = predict(x)[0]
78
+ error_hardness = np.sqrt(np.square(predictions[0]-hardness_target))
79
+ error_ys = np.sqrt(np.square(predictions[1]-ys_target))
80
+ print(predictions, hardness_target, ys_target, error_hardness, error_ys)
81
+ return error_hardness + error_ys
82
+
83
+
84
  def predict(x, request: gr.Request):
85
  """
86
  Predict the hardness and yield strength using the ML model. Input data is a dataframe
 
147
 
148
 
149
  def predict_inverse(target_hardness, target_yield_strength, request: gr.Request):
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
+ domain = []
158
+ for c in one_hot.columns:
159
+ if c in continuous_variables:
160
+ if c == continuous_variables[0]:
161
+ domain.append({'name': str(c), 'type': 'continuous', 'domain': (0.528, 0.528)})#(0.,1.)})
162
+ else:
163
+ domain.append({'name': str(c), 'type': 'continuous', 'domain': (0.539, 0.539)})#(0.,1.)})
164
+ else:
165
+ domain.append({'name': str(c), 'type': 'discrete', 'domain': (0,1)})
166
+
167
+ constraints = []
168
+ constrained_columns = ['Single/Multiphase', 'Preprocessing method', 'BCC/FCC/other']#, 'Microstructure']
169
+ for constraint in constrained_columns:
170
+ sum_string = ''
171
+ for i in range (len(one_hot.columns)):
172
+ column_one_hot = one_hot.columns[i]
173
+ if column_one_hot.startswith(constraint):
174
+ sum_string = sum_string+"+x[:," + str(i) + "]"
175
+ constraints.append({'name': constraint + "+1", 'constraint': sum_string + '-1'})
176
+ constraints.append({'name': constraint + "-1", 'constraint': '-1*(' + sum_string + ')+1'})
177
+
178
+ opt = GPyOpt.methods.BayesianOptimization(f = fit_outputs, # function to optimize
179
+ domain = domain, # box-constraints of the problem
180
+ constraints = constraints,
181
+ acquisition_type ='LCB', # LCB acquisition
182
+ acquisition_weight = 0.1) # Exploration exploitation
183
+ # it may take a few seconds
184
+ opt.run_optimization(max_iter=50)
185
+ opt.plot_convergence()
186
+ x_best = opt.X[np.argmin(opt.Y)]
187
+ best_params = dict(zip(
188
+ [el['name'] for el in domain],
189
+ [[x] for x in x_best]))
190
+ optimized_x = pd.DataFrame.from_dict(best_params)
191
+ for c in optimized_x.columns:
192
+ if c in continuous_variables:
193
+ optimized_x[c]=optimized_x[c]*(dictionary[c][1]-dictionary[c][0])+dictionary[c][0]
194
+ optimized_x = optimized_x[['PROPERTY: Calculated Density (g/cm$^3$)',
195
+ 'PROPERTY: Calculated Young modulus (GPa)',
196
+ 'Preprocessing method ANNEAL',
197
+ 'Preprocessing method CAST', 'Preprocessing method OTHER',
198
+ 'Preprocessing method POWDER', 'Preprocessing method WROUGHT',
199
+ 'BCC/FCC/other BCC', 'BCC/FCC/other FCC', 'BCC/FCC/other OTHER',
200
+ 'Single/Multiphase ', 'Single/Multiphase M', 'Single/Multiphase S']]
201
+ result = optimized_x
202
+ result = result[result>0.0].dropna(axis=1)
203
+ return result
204
 
205
 
206
  example_inputs = [420, 10]
 
231
  <img src='file={logo_path}' alt='Osium AI logo' width='200' height='100'> </html>"""
232
 
233
 
234
+ with gr.Blocks(css=css_styling, title=page_title, theme=osium_theme) as demo:
235
  gr.HTML(html)
236
  gr.Markdown("# <p style='text-align: center;'>Get optimal alloy recommendations based on your target performance</p>")
237
  gr.Markdown("This AI model provides a recommended alloy formula, microstructure and processing conditions based on your target hardness and yield strength")
 
264
  choices=unique_phase_elements, #list(input_mapping["PROPERTY: Microstructure"].keys()),
265
  label=input_cols["PROPERTY: Microstructure"],
266
  )
267
+ optimal_parameters = gr.DataFrame(label="Optimal parameters")
268
 
269
  # with gr.Column():
270
  # gr.Markdown("### Your alloy's yield strength (MPa)")
 
280
  fn=predict_inverse,
281
  inputs=[input_hardness, input_yield_strength],
282
  outputs=[
283
+ optimal_parameters
 
 
 
 
284
  ],
285
  show_progress=True,
286
  )