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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
|
| 12 |
+
# Unique phase elements
|
| 13 |
+
|
| 14 |
+
# Load access tokens
|
| 15 |
+
WRITE_TOKEN = os.environ.get("WRITE_PER") # write
|
| 16 |
+
|
| 17 |
+
# Logs repo path
|
| 18 |
+
dataset_url = "https://huggingface.co/datasets/sandl/upload_alloy_hardness"
|
| 19 |
+
dataset_path = "logs_alloy_hardness.csv"
|
| 20 |
+
|
| 21 |
+
scaling_factors = {'PROPERTY: Calculated Density (g/cm$^3$)': (5.5, 13.7),
|
| 22 |
+
'PROPERTY: Calculated Young modulus (GPa)': (77.0, 336.0),
|
| 23 |
+
'PROPERTY: HV': (107.0, 1183.0),
|
| 24 |
+
'PROPERTY: YS (MPa)': (62.0, 3416.0)}
|
| 25 |
+
|
| 26 |
+
input_mapping = {'PROPERTY: BCC/FCC/other': {'BCC': 0, 'FCC': 1, 'OTHER': 2, 'nan': 2},
|
| 27 |
+
'PROPERTY: Processing method': {'ANNEAL': 0, 'CAST': 1, 'OTHER': 2, 'POWDER': 3, 'WROUGHT': 4, 'nan': 2},
|
| 28 |
+
'PROPERTY: Microstructure': {'B2': 0, 'B2+BCC': 1, 'B2+L12': 2, 'B2+Laves+Sec.': 3, 'B2+Sec.': 4, 'BCC': 5,
|
| 29 |
+
'BCC+B2': 6, 'BCC+B2+FCC': 7, 'BCC+B2+FCC+Sec.': 8, 'BCC+B2+L12': 9, 'BCC+B2+Laves': 10,
|
| 30 |
+
'BCC+B2+Sec.': 11, 'BCC+BCC': 12, 'BCC+BCC+HCP': 13, 'BCC+BCC+Laves': 14,
|
| 31 |
+
'BCC+BCC+Laves(C14)': 15, 'BCC+BCC+Laves(C15)': 16, 'BCC+FCC': 17, 'BCC+HCP': 18,
|
| 32 |
+
'BCC+Laves': 19, 'BCC+Laves(C14)': 20, 'BCC+Laves(C15)': 21, 'BCC+Laves+Sec.': 22,
|
| 33 |
+
'BCC+Sec.': 23, 'FCC': 24, 'FCC+B2': 25, 'FCC+B2+Sec.': 26, 'FCC+BCC': 27,
|
| 34 |
+
'FCC+BCC+B2': 28, 'FCC+BCC+B2+Sec.': 29, 'FCC+BCC+BCC': 30, 'FCC+BCC+Sec.': 31,
|
| 35 |
+
'FCC+FCC': 32, 'FCC+HCP': 33, 'FCC+HCP+Sec.': 34, 'FCC+L12': 35, 'FCC+L12+B2': 36,
|
| 36 |
+
'FCC+L12+Sec.': 37, 'FCC+Laves': 38, 'FCC+Laves(C14)': 39, 'FCC+Laves+Sec.': 40,
|
| 37 |
+
'FCC+Sec.': 41, 'L12+B2': 42, 'Laves(C14)+Sec.': 43, 'OTHER': 44, 'nan': 44},
|
| 38 |
+
'PROPERTY: Single/Multiphase': {'': 0, 'M': 1, 'S': 2, 'OTHER': 3, 'nan': 3}}
|
| 39 |
+
|
| 40 |
+
unique_phase_elements = ['B2', 'BCC', 'FCC', 'HCP', 'L12', 'Laves', 'Laves(C14)', 'Laves(C15)', 'Sec.', 'OTHER']
|
| 41 |
+
|
| 42 |
+
input_cols = {
|
| 43 |
+
"PROPERTY: Alloy formula": "(PROPERTY: Alloy formula) "
|
| 44 |
+
"Recommended alloy formula using proportions representation (i.e. Al0.25 Co1 Fe1 Ni1)",
|
| 45 |
+
"PROPERTY: Single/Multiphase": "(PROPERTY: Single/Multiphase) "
|
| 46 |
+
"Recommended between Single (S), Multiphase (M) and other (OTHER)",
|
| 47 |
+
"PROPERTY: BCC/FCC/other": "(PROPERTY: BCC/FCC/other) "
|
| 48 |
+
"Recommended microstructure between BCC, FCC and other ",
|
| 49 |
+
"PROPERTY: Processing method": "(PROPERTY: Processing method) "
|
| 50 |
+
"Recommended processing method (ANNEAL, CAST, POWDER, WROUGHT or OTHER)",
|
| 51 |
+
"PROPERTY: Microstructure": "(PROPERTY: Microstructure) "
|
| 52 |
+
"Recommended microstructure (SEC means the secondary/tertiary microstructure is not one of FCC, BCC, HCP, L12, B2, Laves, Laves (C14), Laves (C15))",
|
| 53 |
+
}
|
| 54 |
+
|
| 55 |
+
def process_microstructure(list_phases):
|
| 56 |
+
permutations = list(itertools.permutations(list_phases))
|
| 57 |
+
permutations_strings = [str('+'.join(list(e))) for e in permutations]
|
| 58 |
+
for e in permutations_strings:
|
| 59 |
+
if e in list(input_mapping['PROPERTY: Microstructure'].keys()):
|
| 60 |
+
return e
|
| 61 |
+
return 'OTHER'
|
| 62 |
+
|
| 63 |
+
def write_logs(message, message_type="Prediction"):
|
| 64 |
+
"""
|
| 65 |
+
Write logs
|
| 66 |
+
"""
|
| 67 |
+
# with Repository(local_dir="data", clone_from=dataset_url, use_auth_token=WRITE_TOKEN).commit(commit_message="from private", blocking=False):
|
| 68 |
+
# with open(dataset_path, "a") as csvfile:
|
| 69 |
+
# writer = csv.DictWriter(csvfile, fieldnames=["name", "message", "time"])
|
| 70 |
+
# writer.writerow(
|
| 71 |
+
# {"name": message_type, "message": message, "time": str(datetime.now())}
|
| 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
|
| 79 |
+
"""
|
| 80 |
+
loaded_model = tf.keras.models.load_model("models/hardness_old.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_hardness, fig2 = utils.interpret(x)
|
| 96 |
+
#interpret_fig_ys = utils.interpret(x, 1)
|
| 97 |
+
return (np.round(y_hardness*(maximum_hardness-minimum_hardness)+minimum_hardness, 2), 12, interpret_fig_hardness)
|
| 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(input_df, request)
|
| 138 |
+
return predict(one_hot, 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]
|
| 146 |
+
|
| 147 |
+
css_styling = """#submit {background: #1eccd8}
|
| 148 |
+
submit {color: white}
|
| 149 |
+
.output-image, .input-image, .image-preview {height: 250px !important}
|
| 150 |
+
.output-plot {height: 250px !important}"""
|
| 151 |
+
|
| 152 |
+
new_blue_color = gr.themes.Color(c50="#FFFFFF", # Dataframe background cell content - light mode only
|
| 153 |
+
c100="#0c1538", # Text of markdown (headers) and componnet contencts
|
| 154 |
+
c200="#000000", # Text of component headers
|
| 155 |
+
c300="#a1c6db", # Login button when used in primary color
|
| 156 |
+
c400="#000000", # Text of "or" objects and footer
|
| 157 |
+
c500="#000000", # Text of component headers in light mode only
|
| 158 |
+
c600="#e4f3fa", # Clear button (gradient between c600 and c700 + mouse over)
|
| 159 |
+
c700="#a1c6db", # Componennt borders
|
| 160 |
+
c800="#e4f3fa", # Background of components
|
| 161 |
+
c900="#a1c6db", # Etiquette of components
|
| 162 |
+
c950="#FFFFFF") # Background
|
| 163 |
+
# secondary color used for highlight box content when typing in light mode, and download option in dark mode
|
| 164 |
+
# primary color used for login button in dark mode
|
| 165 |
+
osium_theme = gr.themes.Default(primary_hue="cyan", secondary_hue="cyan", neutral_hue=new_blue_color)
|
| 166 |
+
page_title = "Alloys' hardness and yield strength prediction"
|
| 167 |
+
favicon_path = "osiumai_favicon.ico"
|
| 168 |
+
logo_path = "osiumai_logo.jpg"
|
| 169 |
+
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, theme=osium_theme) 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")
|
| 177 |
+
with gr.Row():
|
| 178 |
+
clear_button = gr.Button("Clear")
|
| 179 |
+
prediction_button = gr.Button("Predict", elem_id="submit")
|
| 180 |
+
with gr.Row():
|
| 181 |
+
with gr.Column():
|
| 182 |
+
gr.Markdown("### The target performance of your alloy")
|
| 183 |
+
input_hardness = gr.Text(label="Enter your target hardness (in HV)")
|
| 184 |
+
input_yield_strength = gr.Text(label="Enter your target yield strength (MPa)")
|
| 185 |
+
with gr.Column():
|
| 186 |
+
gr.Markdown("### Your optimal formulation and processing conditions")
|
| 187 |
+
output_formula = gr.Textbox(
|
| 188 |
+
lines=1, label=input_cols["PROPERTY: Alloy formula"]
|
| 189 |
+
)
|
| 190 |
+
output_phase = gr.Dropdown(
|
| 191 |
+
choices=list(input_mapping["PROPERTY: Single/Multiphase"].keys()),
|
| 192 |
+
label=input_cols["PROPERTY: Single/Multiphase"],
|
| 193 |
+
)
|
| 194 |
+
output_bccfcc = gr.Dropdown(
|
| 195 |
+
choices=list(input_mapping["PROPERTY: BCC/FCC/other"].keys()),
|
| 196 |
+
label=input_cols["PROPERTY: BCC/FCC/other"],
|
| 197 |
+
)
|
| 198 |
+
output_processing = gr.Dropdown(
|
| 199 |
+
choices=list(input_mapping["PROPERTY: Processing method"].keys()),
|
| 200 |
+
label=input_cols["PROPERTY: Processing method"],
|
| 201 |
+
)
|
| 202 |
+
output_microstructure = gr.CheckboxGroup(
|
| 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)")
|
| 209 |
+
# output_ys = gr.Text(label="Yield Strength (MPa)")
|
| 210 |
+
# output_ys_uncertainty = gr.Text(label="Yield strength uncertainty (%)")
|
| 211 |
+
# output_ys_interpretation = gr.Plot(label="Yield strength interpretation")
|
| 212 |
+
with gr.Row():
|
| 213 |
+
gr.Examples([example_inputs], [input_hardness, input_yield_strength])
|
| 214 |
+
|
| 215 |
+
|
| 216 |
+
|
| 217 |
+
prediction_button.click(
|
| 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 |
+
)
|
| 229 |
+
clear_button.click(
|
| 230 |
+
lambda x: [gr.update(value=None)] * 8,
|
| 231 |
+
[],
|
| 232 |
+
[
|
| 233 |
+
output_formula,
|
| 234 |
+
output_phase,
|
| 235 |
+
output_bccfcc,
|
| 236 |
+
output_processing,
|
| 237 |
+
output_microstructure,
|
| 238 |
+
input_hardness,
|
| 239 |
+
input_yield_strength,
|
| 240 |
+
],
|
| 241 |
+
)
|
| 242 |
+
|
| 243 |
+
|
| 244 |
+
if __name__ == "__main__":
|
| 245 |
+
demo.queue(concurrency_count=2)
|
| 246 |
+
demo.launch()
|