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

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +57 -92
app.py CHANGED
@@ -96,47 +96,7 @@ def predict(x, request: gr.Request):
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)))
@@ -144,47 +104,56 @@ def fit_outputs_constraints(x, hardness_target, ys_target, request: gr.Request):
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
 
@@ -194,29 +163,30 @@ def predict_inverse(hardness_target, ys_target, formula, request: gr.Request):
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}
@@ -253,22 +223,20 @@ with gr.Blocks(css=css_styling, title=page_title, theme=osium_theme) as demo:
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():
@@ -284,11 +252,8 @@ with gr.Blocks(css=css_styling, title=page_title, theme=osium_theme) as demo:
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
  )
 
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
+ def fit_outputs_constraints(x, hardness_target, ys_target, metals_to_use, request: gr.Request):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
100
  predictions = predict(x, request)
101
  error_hardness = np.sqrt(np.square(predictions[0]-float(hardness_target)))
102
  error_ys = np.sqrt(np.square(predictions[2]-float(ys_target)))
 
104
  error_hardness, error_ys)
105
  return error_hardness + error_ys
106
 
107
+ def predict_inverse(hardness_original_target, ys_original_target, request: gr.Request):
108
+
109
+ #one_hot_columns = utils.return_feature_names()
110
 
111
+ hardness_target = (hardness_original_target-min_df_hardness)/(max_df_hardness-min_df_hardness)
112
+ ys_target = (ys_original_target-min_df_ys)/(max_df_ys-min_df_ys)
113
 
114
  continuous_variables = ['PROPERTY: Calculated Density (g/cm$^3$)',
115
+ 'PROPERTY: Calculated Young modulus (GPa)',
116
+ 'PROPERTY: Metal Al', 'PROPERTY: Metal Co',
117
+ 'PROPERTY: Metal Fe', 'PROPERTY: Metal Ni', 'PROPERTY: Metal Si',
118
+ 'PROPERTY: Metal Cr', 'PROPERTY: Metal Nb', 'PROPERTY: Metal Ti',
119
+ 'PROPERTY: Metal Mn', 'PROPERTY: Metal V', 'PROPERTY: Metal Mo',
120
+ 'PROPERTY: Metal Cu', 'PROPERTY: Metal Ta', 'PROPERTY: Metal Zr',
121
+ 'PROPERTY: Metal Hf', 'PROPERTY: Metal W', 'PROPERTY: Metal Zn',
122
+ 'PROPERTY: Metal Sn', 'PROPERTY: Metal Re', 'PROPERTY: Metal C',
123
+ 'PROPERTY: Metal Pd', 'PROPERTY: Metal Sc', 'PROPERTY: Metal Y']
124
+ categorical_variables = list(one_hot.columns)
125
  for c in continuous_variables:
126
  categorical_variables.remove(c)
127
 
128
+ # Metals constraints
129
+ metals_elements = [c for c in continuous_variables if c.startswith("PROPERTY: Metal")]
130
+ metals_to_use = ['Al', 'Co', 'Fe', 'Cr']
131
+ metals_to_use = ["PROPERTY: Metal " + metals_to_use[i] for i in range(len(metals_to_use))]
132
 
133
+ # Domain
 
 
134
  domain = []
135
+ for c in one_hot.columns:
136
  if c in continuous_variables:
137
+ if c.startswith("PROPERTY: Metal") and c not in metals_to_use:
138
+ domain.append({'name': str(c), 'type': 'continuous', 'domain': (0., 0.)})
 
 
139
  else:
140
+ domain.append({'name': str(c), 'type': 'continuous', 'domain': (0., 1.)})#(0.,1.)})
 
 
141
  else:
142
  domain.append({'name': str(c), 'type': 'discrete', 'domain': (0,1)})
143
 
144
+ # Constraints
145
  constraints = []
146
+ constrained_columns = ['Single/Multiphase', 'Preprocessing method', 'BCC/FCC/other'] #'PROPERTY: Metal']#, 'Microstructure']
 
147
  for constraint in constrained_columns:
148
  sum_string = ''
149
+ for i in range (len(one_hot.columns)):
150
+ column_one_hot = one_hot.columns[i]
151
  if column_one_hot.startswith(constraint):
152
  sum_string = sum_string+"+x[:," + str(i) + "]"
153
  constraints.append({'name': constraint + "+1", 'constraint': sum_string + '-1'})
154
  constraints.append({'name': constraint + "-1", 'constraint': '-1*(' + sum_string + ')+1'})
155
 
156
+
157
  def fit_outputs(x):
158
  return fit_outputs_constraints(x, hardness_target, ys_target, request)
159
 
 
163
  acquisition_type ='LCB', # LCB acquisition
164
  acquisition_weight = 0.1) # Exploration exploitation
165
  # it may take a few seconds
166
+ opt.run_optimization(max_iter=50)
167
+ # opt.plot_convergence()
168
  x_best = opt.X[np.argmin(opt.Y)]
169
  best_params = dict(zip(
170
  [el['name'] for el in domain],
171
  [[x] for x in x_best]))
172
  optimized_x = pd.DataFrame.from_dict(best_params)
173
+ for c in optimized_x.columns:
174
+ if c in continuous_variables:
175
+ if c in ['PROPERTY: Calculated Density (g/cm$^3$)', 'PROPERTY: Calculated Young modulus (GPa)']:
176
+ optimized_x[c]=optimized_x[c]*(scales_dictionary[c][1]-scales_dictionary[c][0])+scales_dictionary[c][0]
 
 
 
 
 
 
177
  result = optimized_x
 
 
178
 
179
+ # Normalize metals outputs
180
+ sum_metals = np.sum(result[c] for c in list(result. columns) if c.startswith("PROPERTY: Metal"))
181
+ for column in result.columns:
182
+ if column.startswith("PROPERTY: Metal"):
183
+ result[column]/= sum_metals
184
+ result = result.transpose()
185
 
186
+ return result
187
+
188
+
189
+ example_inputs = [820, 1800]
190
 
191
  css_styling = """#submit {background: #1eccd8}
192
  #submit:hover {background: #a2f1f6}
 
223
  prediction_button = gr.Button("Predict", elem_id="submit")
224
  with gr.Row():
225
  with gr.Column():
 
 
226
  gr.Markdown("### The target performance of your alloy")
227
  input_hardness = gr.Text(label="Enter your target hardness (in HV)")
228
  input_yield_strength = gr.Text(label="Enter your target yield strength (MPa)")
229
  with gr.Column():
230
  with gr.Row():
231
+ #with gr.Column():
232
+ # gr.Markdown("### Your optimal microstructure and processing conditions")
233
+ optimal_parameters = gr.DataFrame(label="Optimal parameters", wrap=True)
234
+ #with gr.Column():
235
+ # param1 = gr.Text(label="Processing method")
236
+ #with gr.Column():
237
+ # param2 = gr.Text(label="Microstructure")
238
+ #with gr.Column():
239
+ # param3 = gr.Text(label="Phase")
240
  #with gr.Row():
241
  #with gr.Column():
242
  #with gr.Row():
 
252
 
253
  prediction_button.click(
254
  fn=predict_inverse,
255
+ inputs=[input_hardness, input_yield_strength],
256
+ outputs=[optimal_parameters
 
 
 
257
  ],
258
  show_progress=True,
259
  )