Skip to content

Commit

Permalink
Model view restructure (#10)
Browse files Browse the repository at this point in the history
* Improve the structure of the main page

* Forgot one file

* Cleanup imports

* more cleanup

* cleaner naming

* cleaner naming

* cleaner naming

* added atmopsheric and immersion corrosion pages

* referecnes fixed

---------

Co-authored-by: Aravinth Ravikumar <aravinth.ravikumar@hereon.de>
  • Loading branch information
svchb and aravinth-ravikumar authored Aug 30, 2024
1 parent 36b0c86 commit b3c2b30
Show file tree
Hide file tree
Showing 37 changed files with 262 additions and 109 deletions.
1 change: 0 additions & 1 deletion data/animations/Animation - 1721376453953.json

This file was deleted.

1 change: 0 additions & 1 deletion data/animations/Animation - 1721376471730.json

This file was deleted.

Binary file removed data/images/iso_9224_eqn.png
Binary file not shown.
Binary file removed data/images/iso_9224_eqn_2.png
Binary file not shown.
Binary file removed data/images/load_calculations.png
Binary file not shown.
2 changes: 1 addition & 1 deletion web_app.dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -47,4 +47,4 @@ HEALTHCHECK CMD curl --fail http://localhost:8501/_stcore/health || exit 1
WORKDIR /app/web_app

# Run the application
ENTRYPOINT ["pipenv", "run", "streamlit", "run", "website.py", "--server.port=8501", "--server.address=0.0.0.0"]
ENTRYPOINT ["pipenv", "run", "streamlit", "run", "Home.py", "--server.port=8501", "--server.address=0.0.0.0"]
3 changes: 1 addition & 2 deletions web_app/website.py → web_app/Home.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,7 @@
from model_view import model_view
from helper import local_css


st.set_page_config(page_title="CorWiz", page_icon=":material/rainy:", layout="wide", initial_sidebar_state="collapsed")
st.set_page_config(page_title="CorWiz", page_icon=":material/rainy:", layout="wide", initial_sidebar_state="auto")

local_css('style/style.css')

Expand Down
193 changes: 90 additions & 103 deletions web_app/model_view.py
Original file line number Diff line number Diff line change
@@ -1,140 +1,119 @@
import matplotlib.pyplot as plt
import plotly.express as px
import os
import json
import numpy as np
import streamlit as st
from streamlit_extras.stylable_container import stylable_container
import plotly.express as px
import streamlit.components.v1 as components

from models import AC_model_fileu1993, AC_model_iso9223, AC_model_ma2010, AC_model_benarie1986, AC_model_soares1999, AC_model_klinesmith2007, IC_model_ali2020, IC_model_kovalenko2016, IC_model_garbatov2011, IC_model_hicks2012
import os
import json
from models import (
AC_model_fileu1993, AC_model_iso9223, AC_model_ma2010,
AC_model_benarie1986, AC_model_soares1999, AC_model_klinesmith2007,
IC_model_ali2020, IC_model_kovalenko2016, IC_model_garbatov2011,
IC_model_hicks2012
)


def extract_model_details_from_json(path):
model_infos = {
def extract_model_details_from_json(directory_path):
"""Extracts model details from JSON files in the specified directory."""
model_details = {
'names': [],
'kadi_identifiers': [],
'descriptions': [],
'special_notes': [],
'parameters': [],
'formulas': [],
'article_identifier' : []
}
'article_identifiers': []
}

# Iterate over each file in the specified path
for file_name in os.listdir(path):

# model_info = [model name, kadi identifier, description, special notes, parameteres, formula]
for file_name in os.listdir(directory_path):
if file_name.endswith('.json'):
json_file_path = os.path.join(path, file_name)

json_file_path = os.path.join(directory_path, file_name)
with open(json_file_path, 'r', encoding='utf-8') as file:
data = json.load(file)

# Access the 'extras' array in the JSON data
model_infos['descriptions'].append(data.get('description', []))
model_infos['names'].append(data.get('title', []))
model_infos['kadi_identifiers'].append(data.get('identifier', []))
model_infos['special_notes'].append(data.get('special notes', []))
model_infos['article_identifier'].append(data.get('links', [])[0]['record_to']['identifier'])
model_details['names'].append(data.get('title', ''))
model_details['kadi_identifiers'].append(data.get('identifier', ''))
model_details['descriptions'].append(data.get('description', ''))
model_details['special_notes'].append(data.get('special notes', ''))
model_details['article_identifiers'].append(data.get('links', [{}])[0].get('record_to', {}).get('identifier', ''))

extras = data.get('extras', [])
# Iterate through each model in the 'extras' array
parameters_found = False
formula_found = False
for item in extras:
if item['key'] == 'Parameters':
model_infos['parameters'].append(item['value'])
parameters_found = True
if item['key'] == 'Formula':
model_infos['formulas'].append(item['value'])
formula_found = True
if not parameters_found:
model_infos['parameters'].append('')
if not formula_found:
model_infos['formulas'].append('')


return model_infos


def display_model_info(model_info, model):
parameters = next((item['value'] for item in extras if item['key'] == 'Parameters'), '')
formula = next((item['value'] for item in extras if item['key'] == 'Formula'), '')

model_details['parameters'].append(parameters)
model_details['formulas'].append(formula)

return model_details


def display_model_info(model_info, model_name):
# st.markdown("#### Model developed by: \n" + model_info['model_developers'][model_info['model_names'].index(model)])
st.markdown("#### Model Description: \n" + str(model_info['descriptions'][model_info['names'].index(model)]))
st.markdown(str(model_info['descriptions'][model_info['names'].index(model_name)]))
try:
st.markdown("#### Model Notes: \n" + model_info['special_notes'][model_info['names'].index(model)])
st.markdown("#### Model Notes: \n" + model_info['special_notes'][model_info['names'].index(model_name)])
except:
pass


def run_model(model_identifier, model_functions, article_identifier):
with st.container():
model, time = model_functions[model_identifier](article_identifier)
return model, time
return model_functions[model_identifier](article_identifier)

def plot_mass_loss_over_time(model, time_range):
"""Generates and returns a Plotly figure for mass loss over time."""
t = np.linspace(0, time_range, 400)
D = model.eval_material_loss(t)
fig = px.line(x=t, y=D, labels={'x': 'Time [years]', 'y': 'Mass loss [um]'}, title="Mass Loss Over Time", height=700)
return fig


def model_view(model_view_container):
immersion_corrosion_models = extract_model_details_from_json('../data/kadi4mat_json/immersion_corrosion_models/')
atmospheric_corrosion_models = extract_model_details_from_json(
'../data/kadi4mat_json/atmospheric_corrosion_models/')

with model_view_container:
st.write("---")
st.header("Corrosion Mass Loss Models")

immersion_corrosion_models = extract_model_details_from_json('../data/kadi4mat_json/immersion_corrosion_models/')
atmospheric_corrosion_models = extract_model_details_from_json('../data/kadi4mat_json/atmospheric_corrosion_models/')

models = ['Atmospheric corrosion models', 'Immersed corrosion models']
ac_or_ic = st.selectbox(
'Is your problem atmospheric corrosion or immersed corrosion?',
models
)

if ac_or_ic == models[0]:
model_info = atmospheric_corrosion_models
model_functions = {'model_feliu1993': AC_model_fileu1993,
'din-corrosion-protection-model-iso-9223-compliant': AC_model_iso9223,
'model_ma2010': AC_model_ma2010,
'model_benarie1986': AC_model_benarie1986,
'model_soares1999': AC_model_soares1999,
'model_klinesmith2007': AC_model_klinesmith2007}
else:
model_info = immersion_corrosion_models
model_functions = {'model_ali2020': IC_model_ali2020,
'model_kovalenko2016': IC_model_kovalenko2016,
'model_garbatov2011': IC_model_garbatov2011,
'model_hicks2012': IC_model_hicks2012}

model = st.selectbox(
'Please select model',
model_info['names']
)

model_identifier = model_info['kadi_identifiers'][model_info['names'].index(model)]
article_identifier = model_info['article_identifier'][model_info['names'].index(model)]
formulas = model_info['formulas'][model_info['names'].index(model)]
st.subheader("Selected model: " + model)

image_column, data_column = st.columns((1, 1))
fig = plt.figure(figsize=(10, 6))

with data_column:
print('\n\n\n')
print(article_identifier)
display_model_info(model_info, model)
model, time = run_model(model_identifier, model_functions, article_identifier)


for formula in formulas:
st.write(r'' + formula['key'] + ': ' + formula['value'])

if model is not None:
t = np.linspace(0, time, 400)
D = model.eval_material_loss(t)

# Create the plot using Plotly Express
fig = px.line(x=t, y=D, labels={'x': 'Time [years]', 'y': 'Mass loss [um]'}, title="Mass Loss Over Time", height=700)
main_view = st.container()
description_box = st.container()
model_info = None
selected_model_name = None

with main_view:
image_column, data_column = st.columns((1, 1))
with data_column:
model_categories = ['Atmospheric corrosion', 'Immersion corrosion']

model_category_selection = st.selectbox('**Corrosion Type**', model_categories)

if model_category_selection == 'Atmospheric corrosion':
model_info = atmospheric_corrosion_models
model_functions = {'model_feliu1993': AC_model_fileu1993,
'din-corrosion-protection-model-iso-9223-compliant': AC_model_iso9223,
'model_ma2010': AC_model_ma2010,
'model_benarie1986': AC_model_benarie1986,
'model_soares1999': AC_model_soares1999,
'model_klinesmith2007': AC_model_klinesmith2007}
else:
model_info = immersion_corrosion_models
model_functions = {'model_ali2020': IC_model_ali2020,
'model_kovalenko2016': IC_model_kovalenko2016,
'model_garbatov2011': IC_model_garbatov2011,
'model_hicks2012': IC_model_hicks2012}

selected_model_name = st.selectbox('**Model**', model_info['names'])

model_identifier = model_info['kadi_identifiers'][model_info['names'].index(selected_model_name)]
article_identifier = model_info['article_identifiers'][model_info['names'].index(selected_model_name)]
formulas = model_info['formulas'][model_info['names'].index(selected_model_name)]

model, time = run_model(model_identifier, model_functions, article_identifier)

with image_column:
chart_container = st.container()
plot_html = fig.to_html(full_html=False, include_plotlyjs='cdn')
plot_html = plot_mass_loss_over_time(model, time).to_html(full_html=False, include_plotlyjs='cdn')

with chart_container:
components.html(
Expand All @@ -146,5 +125,13 @@ def model_view(model_view_container):
height=800,
scrolling=True
)
else:
st.write("No model selected.")

with description_box:
description = st.expander("**Model Description**", expanded=False)

with description:
display_model_info(model_info, selected_model_name)

st.write("### Model Formulas")
for formula in formulas:
st.write(r'' + formula['key'] + ': ' + formula['value'])
84 changes: 84 additions & 0 deletions web_app/pages/1_Atmospheric_Corrosion.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
import streamlit as st

st.title("Atmospheric Corrosion")

text_column, image_column = st.columns((0.7, 0.3))

with text_column:
st.write("""
## What is Atmospheric Corrosion?
Atmospheric corrosion is the deterioration of a material, typically a metal, due to its interaction with the surrounding atmosphere. It is an electrochemical process that requires the presence of an electrolyte, which is usually a thin film of moisture on the metal surface[1][2].
## Mechanism of Atmospheric Corrosion
The mechanism of atmospheric corrosion involves the following steps:
1. **Formation of an electrolyte layer**: When the relative humidity of the atmosphere exceeds a critical level (around 60% for iron in unpolluted atmospheres), a thin film of moisture forms on the metal surface[2].
2. **Anodic and cathodic reactions**: In the presence of the electrolyte, atmospheric corrosion proceeds through anodic and cathodic reactions. The anodic reaction involves the dissolution of the metal, while the cathodic reaction is often the reduction of oxygen from the atmosphere[2].
3. **Corrosion product formation**: The dissolved metal ions react with oxygen and water to form corrosion products, such as rust (iron oxide) on steel surfaces[1].
## Factors Affecting Atmospheric Corrosion
Several factors influence the rate and severity of atmospheric corrosion:
1. **Relative humidity**: Higher relative humidity increases the likelihood of moisture condensation on the metal surface, facilitating the formation of an electrolyte layer[1][2].
2. **Temperature**: Increased temperature can accelerate the corrosion reactions and affect the properties of the electrolyte layer[1].
3. **Atmospheric pollutants**: Pollutants like sulfur dioxide (SO2) and chlorides can increase the conductivity of the electrolyte layer, leading to higher corrosion rates[1][3].
4. **Surface characteristics**: The roughness and cleanliness of the metal surface can influence the formation and properties of the electrolyte layer[5].
## Mitigating Atmospheric Corrosion
Several methods are used to mitigate atmospheric corrosion, including:
1. **Coatings and paints**: Applying protective coatings or paints to the metal surface can create a barrier between the metal and the atmosphere[3].
2. **Cathodic protection**: This technique involves making the metal structure the cathode in an electrochemical cell, preventing the anodic dissolution of the metal[3].
3. **Alloying and surface treatments**: Modifying the metal composition or surface properties can enhance its resistance to atmospheric corrosion[5].
In conclusion, atmospheric corrosion is a complex electrochemical process that occurs when metals are exposed to the surrounding atmosphere. Understanding the mechanism and factors affecting atmospheric corrosion is crucial for developing effective prevention and mitigation strategies.
Citations:
[1] https://www.corrosionpedia.com/definition/116/atmospheric-corrosion
[2] https://corrosion-doctors.org/AtmCorros/mechani1.htm
[3] https://www.dreiym.com/2023/01/25/atmospheric-corrosion-what-it-is-and-how-to-mitigate-it/
[4] https://www.diva-portal.org/smash/get/diva2:12811/FULLTEXT01.pdf
[5] https://www.sciencedirect.com/science/article/pii/S2352492823010851
[6] https://www.db-thueringen.de/servlets/MCRFileNodeServlet/dbt_derivate_00051759/ilm1-2020000368.pdf
[7] https://www.ncbi.nlm.nih.gov/pmc/articles/PMC5506901/
[8] https://www.corrosionpedia.com/5-most-common-types-of-metal-coatings-that-everyone-should-know-about/2/6894
[9] https://www.corrosionpedia.com/2/1525/corrosion/system-dependent-corrosion-in-piping-systems
[10] https://link.springer.com/chapter/10.1007/978-3-319-97625-9_12
[11] https://www.azom.com/article.aspx?ArticleID=97
[12] https://www.corrosionpedia.com/2/1525/corrosion/system-dependent-corrosion-in-piping-systems
""")

with image_column:

st.image('static/images/Atmospheric-corrosion-14_W640.jpg', use_column_width=True)
st.image('static/images/Crevice-corrosion-17_W640.jpg', use_column_width=True)
st.image('static/images/Erosion-corrosion-21_W640.jpg', use_column_width=True)
st.image('static/images/Pitting-corrosion-18_W640.jpg', use_column_width=True)

st.markdown(
'<div style="text-align: center;">Image credits [9], [10], [11], [12]</div>',
unsafe_allow_html=True
)
Loading

0 comments on commit b3c2b30

Please sign in to comment.