playground / app.py
fractben's picture
Fracture-Bench playground
cc3506e verified
Raw History Blame Contribute Delete
59 kB
"""Fracture-Bench Playground — interactive surrogate predictions for phase-field fracture. Run locally: streamlit run app.py """ from __future__ import annotations import os import time import numpy as np import streamlit as st from models import registry from utils import geometry as geo from utils import plotting as viz st.set_page_config(page_title="Fracture-Bench Playground", page_icon="⚡", layout="wide") # Pages, chosen by ?view=: # home hero + project cards (only when run locally) # playground datasets overview + interactive tabs # embed the two dataset tabs only, for embedding in the github.io site # When FRACTURE_BENCH_SITE is set (the hosted Hugging Face Space), that site is # the home page, so the app opens on the playground and links home to the site. SITE_URL = os.environ.get("FRACTURE_BENCH_SITE", "") VIEW = st.query_params.get("view", "playground" if SITE_URL else "home") if SITE_URL and VIEW not in ("playground", "embed"): VIEW = "playground" EMBED = VIEW == "embed" ON_PLAYGROUND = VIEW in ("playground", "embed") # ---------------------------------------------------------------- theme --- NAVY, NAVY2, BLUE, MIST, WHITE = ("#0D1F45", "#16315E", "#245E94", "#BCCBDC", "#FFFFFF") INK, PALE, LINE = "#13294B", "#F4F8FC", "#D1DCF0" with st.container(key="fb_toggle"): dark_mode = st.toggle("🌙 Dark", value=False, key="theme_dark") if dark_mode: _css = f""" .stApp {{ background: {NAVY}; color: {WHITE}; --fb-pg-bg:{NAVY}; --fb-pg-copy:#B9C9DE; --fb-pg-strong:#FFFFFF; }} header[data-testid="stHeader"] {{ background: rgba(13,31,69,0.85); }} .stApp h1, .stApp h2, .stApp h3, .stMarkdown p, label p, [data-testid="stWidgetLabel"] p, .stRadio label p, .stSelectbox label p {{ color: #E9F0F9 !important; }} button[data-baseweb="tab"] p {{ color: {MIST} !important; font-weight: 600; }} button[data-baseweb="tab"][aria-selected="true"] p {{ color: {WHITE} !important; }} [data-testid="stAlertContainer"] {{ background: {NAVY2}; color: #E9F0F9; border-left: 4px solid {BLUE}; }} [data-testid="stAlertContainer"] p {{ color: #E9F0F9 !important; }} div[data-baseweb="select"] > div, [data-testid="stNumberInputContainer"] {{ background: {NAVY2}; border-color: #2C4A7C; }} div[data-baseweb="select"] div, div[data-baseweb="select"] span {{ color: #E9F0F9 !important; }} div[data-baseweb="select"] svg {{ fill: #E9F0F9; }} [data-testid="stNumberInputContainer"] input {{ color: #E9F0F9; }} div[data-baseweb="input"], div[data-baseweb="base-input"] {{ background: {NAVY2} !important; }} div[data-baseweb="input"] input, [data-testid="stNumberInputContainer"] input {{ color: #E9F0F9 !important; -webkit-text-fill-color: #E9F0F9 !important; background: {NAVY2} !important; }} [data-testid="stNumberInputContainer"] button {{ background: {NAVY2}; }} [data-testid="stNumberInputContainer"] button svg {{ fill: #E9F0F9; }} hr {{ border-color: {NAVY2}; }} .fb-eyebrow {{ color: #9AB4D4 !important; }} .fb-sub {{ color: #B9C9DE !important; }} .fb-chip {{ background: {NAVY2} !important; color: #D7E3F2 !important; border-color: #2C4A7C !important; }} div[data-baseweb="tab-list"] {{ gap: .35rem; }} button[data-baseweb="tab"] {{ background: {NAVY2}; border: 1px solid #2C4A7C; border-radius: 2px; padding: .6rem 1.05rem; }} button[data-baseweb="tab"][aria-selected="true"] {{ background: {BLUE}; border-color: {BLUE}; }} div[data-baseweb="tab-highlight"], div[data-baseweb="tab-border"] {{ display: none; }} """ else: _css = f""" .stApp {{ background: {WHITE}; color: {NAVY}; --fb-pg-bg:#F4F8FC; --fb-pg-copy:#446083; --fb-pg-strong:#16315E; }} header[data-testid="stHeader"] {{ background: rgba(255,255,255,0.9); }} button[data-baseweb="tab"] p {{ color: #5B7693; font-weight: 600; }} button[data-baseweb="tab"][aria-selected="true"] p {{ color: {BLUE}; }} [data-testid="stAlertContainer"] {{ background: #F4F8FC; color: #13294B; border-left: 4px solid {BLUE}; }} .fb-eyebrow {{ color: #6E89A8; }} .fb-sub {{ color: #446083; }} .fb-chip {{ background: #F0F5FB; color: #2A4A74; border-color: #D6E2F0; }} div[data-baseweb="tab-list"] {{ gap: .35rem; }} button[data-baseweb="tab"] {{ background: #F0F5FB; border: 1px solid #C9D6E8; border-radius: 2px; padding: .6rem 1.05rem; }} button[data-baseweb="tab"][aria-selected="true"] {{ background: {BLUE}; border-color: {BLUE}; }} button[data-baseweb="tab"][aria-selected="true"] p {{ color: #FFFFFF !important; }} div[data-baseweb="tab-highlight"], div[data-baseweb="tab-border"] {{ display: none; }} """ _css += f""" [data-testid="stMainBlockContainer"] {{ padding: 0 2.5rem 3rem; max-width: 1280px; }} [data-testid="stMainBlockContainer"] > [data-testid="stVerticalBlock"] {{ gap: 0; }} .st-key-fb_toggle {{ position: fixed; top: .53rem; right: 2.1rem; z-index: 9999999; width: auto; }} .st-key-fb_toggle label p {{ font-size: .85rem; color: #FFFFFF !important; }} header[data-testid="stHeader"] {{ display: none; }} """ _css += """ @import url('https://fonts.googleapis.com/css2?family=Poppins:wght@400;500;600;700;800&display=swap'); html, body, .stApp, .stApp p, .stApp span, .stApp label, .stApp li, .stApp h1, .stApp h2, .stApp h3, .stApp h4, .stApp button, .stApp input, .stMarkdown, [data-testid="stWidgetLabel"] p { font-family: 'Poppins', 'Lato', sans-serif; } [data-testid="stIconMaterial"] { font-family: 'Material Symbols Rounded' !important; } /* Project-page shell, inspired by the TopoDiff hierarchy. */ .fb-fullbleed { width: 100vw; margin-left: calc(50% - 50vw); } .fb-site-nav { background: #0D1F45; min-height: 58px; color: #FFFFFF; display: flex; align-items: center; } .fb-nav-inner { width: min(1180px, calc(100% - 3rem)); margin: 0 auto; padding-right: 7.25rem; display: flex; align-items: center; justify-content: space-between; gap: 1.5rem; } .fb-brand { display: inline-flex; align-items: center; gap: .72rem; color: #FFFFFF !important; text-decoration: none !important; font-size: .92rem; font-weight: 700; letter-spacing: .08em; text-transform: uppercase; white-space: nowrap; } .fb-mark { width: 26px; height: 26px; display: grid; place-items: center; border: 1px solid rgba(255,255,255,.55); color: #FFFFFF; font-size: .82rem; transform: rotate(45deg); } .fb-mark span { transform: rotate(-45deg); } .fb-nav-links { display: flex; align-items: center; gap: 1.45rem; } .fb-nav-links a { color: #E9F0F9 !important; text-decoration: none !important; text-transform: uppercase; font-size: .7rem; font-weight: 600; letter-spacing: .09em; } .fb-nav-links a:hover { color: #FFFFFF !important; } .fb-nav-links a.fb-nav-current { color: #FFFFFF !important; padding-bottom: .2rem; border-bottom: 2px solid #BCCBDC; } .fb-hero { position: relative; overflow: hidden; background: radial-gradient(circle at 82% 18%, rgba(188,203,220,.25), transparent 28%), radial-gradient(circle at 65% 86%, rgba(36,94,148,.6), transparent 38%), linear-gradient(118deg, #0D1F45 3%, #16315E 50%, #245E94 100%); color: #FFFFFF; min-height: 430px; display: flex; align-items: center; } .fb-hero::before, .fb-hero::after { content: ''; position: absolute; pointer-events: none; } .fb-hero::before { width: 560px; height: 560px; right: -105px; top: -235px; border: 1px solid rgba(255,255,255,.16); border-radius: 50%; box-shadow: 0 0 0 78px rgba(255,255,255,.035), 0 0 0 156px rgba(255,255,255,.025); } .fb-hero::after { right: 8%; bottom: -12%; width: 340px; height: 330px; opacity: .34; background: linear-gradient(142deg, transparent 0 43%, #FFFFFF 43% 44%, transparent 44% 100%), linear-gradient(34deg, transparent 0 61%, #FFFFFF 61% 62%, transparent 62% 100%), linear-gradient(84deg, transparent 0 74%, #FFFFFF 74% 75%, transparent 75% 100%); transform: rotate(-7deg); } .fb-hero-inner { position: relative; z-index: 1; width: min(1180px, calc(100% - 3rem)); margin: 0 auto; padding: 4.6rem 0 4.2rem; } .fb-kicker { margin: 0 0 .9rem; color: #BCCBDC; text-transform: uppercase; letter-spacing: .14em; font-weight: 600; font-size: .74rem; } .fb-hero h1 { color: #FFFFFF !important; font-size: clamp(2.65rem, 6vw, 5.6rem) !important; line-height: .95 !important; letter-spacing: -.045em !important; margin: 0 0 1rem !important; max-width: 880px; } .fb-hero-deck { color: #FFFFFF !important; margin: 0 0 .85rem !important; font-size: clamp(1.05rem, 2vw, 1.45rem) !important; font-weight: 500; max-width: 760px; } .fb-hero-copy { color: #D8E3F1 !important; margin: 0 !important; font-size: .9rem !important; line-height: 1.7 !important; max-width: 700px; } .fb-hero-metrics { margin-top: 2rem; display: flex; flex-wrap: wrap; gap: .6rem; } .fb-metric { border-left: 2px solid #BCCBDC; background: rgba(13,31,69,.28); padding: .6rem 1.15rem .62rem; min-width: 150px; backdrop-filter: blur(6px); } .fb-metric strong { display: block; color: #FFFFFF; font-size: 1.05rem; } .fb-metric span { color: #BCCBDC; font-size: .68rem; text-transform: uppercase; letter-spacing: .09em; } .fb-section { padding: 4.4rem 0 3.7rem; } .fb-section-inner { width: min(1180px, calc(100% - 3rem)); margin: 0 auto; } .fb-section-label { color: #245E94; font-size: .72rem; font-weight: 700; letter-spacing: .12em; text-transform: uppercase; margin-bottom: .55rem; } .fb-section-title { position: relative; display: inline-block; color: #0D1F45; font-size: clamp(1.45rem, 2.5vw, 2.15rem); line-height: 1.15; text-transform: uppercase; letter-spacing: -.015em; margin: 0 0 1.55rem; padding-bottom: .52rem; } .fb-section-title::after { content: ''; position: absolute; left: 0; bottom: 0; width: 72%; height: 2px; background: #245E94; } .fb-lead { color: #13294B; font-size: .98rem; line-height: 1.85; max-width: 920px; margin: 0; } .fb-lead + .fb-lead { margin-top: 1rem; } .fb-basics { background: #FFFFFF; color: #13294B; padding: 4rem 0 1.75rem; } .fb-basics-inner { width: min(1180px, calc(100% - 3rem)); margin: 0 auto; } .stApp .fb-basics-title { position: relative; display: inline-block; color: #16315E !important; font-size: clamp(2rem, 4vw, 3rem) !important; line-height: 1.05 !important; font-weight: 800 !important; letter-spacing: -.025em !important; margin: 0 0 1.55rem !important; padding-bottom: .65rem; text-transform: uppercase; } .stApp .fb-basics-title::after { content: ''; position: absolute; left: 0; bottom: 0; width: 74%; height: 4px; background: #245E94; } .stApp .fb-basics-copy { color: #172238 !important; font-size: clamp(1.02rem, 1.65vw, 1.28rem) !important; line-height: 1.85 !important; max-width: 1120px; margin: 0 !important; } .fb-project-grid { width: min(1080px, 100%); margin: 0 auto; display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 6px; } .fb-project-card { position: relative; overflow: hidden; min-height: 305px; display: flex; align-items: flex-end; justify-content: center; padding: 1.25rem; border: 1px solid #D1DCF0; border-radius: 3px; color: #FFFFFF !important; text-decoration: none !important; isolation: isolate; background: #16315E; } .fb-project-card::after { content: ''; position: absolute; inset: 0; z-index: -1; background: linear-gradient(to top, rgba(6,16,36,.92), transparent 58%); transition: background .2s ease; } .fb-project-card:hover::after { background: linear-gradient(to top, rgba(6,16,36,.96), rgba(36,94,148,.05) 72%); } .fb-project-card:hover .fb-project-card-title { transform: translateY(-3px); } .fb-project-card-title { position: relative; z-index: 2; color: #FFFFFF; font-size: 1.24rem; font-weight: 700; line-height: 1.2; text-align: center; text-shadow: 0 2px 12px rgba(0,0,0,.45); transition: transform .2s ease; } .fb-placeholder-tag { position: absolute; z-index: 3; top: .72rem; left: .72rem; padding: .28rem .48rem; border: 1px solid rgba(255,255,255,.62); background: rgba(13,31,69,.76); color: #FFFFFF; font-size: .55rem; font-weight: 700; letter-spacing: .1em; text-transform: uppercase; } .fb-paper-card { background: #E8E9E7; } .fb-paper-sheet { position: absolute; inset: 26px 34px 22px; padding: 1.25rem 1.05rem; background: #FEFEFC; color: #101828; box-shadow: 0 8px 22px rgba(13,31,69,.18); text-align: center; } .fb-paper-sheet b { display: block; font-family: Georgia, serif; font-size: .8rem; line-height: 1.25; margin-bottom: .35rem; } .fb-paper-sheet i { display: block; font-family: Georgia, serif; font-size: .47rem; margin-bottom: .75rem; } .fb-paper-lines { height: 155px; background: linear-gradient(90deg, transparent 49.4%, #CDD2D8 49.4% 50.6%, transparent 50.6%), repeating-linear-gradient(0deg, #4F5968 0 1px, transparent 1px 5px); opacity: .72; } .fb-code-card { background: #121720; } .fb-code-snippet { position: absolute; inset: 24px 22px 18px; margin: 0; color: #9DC3E9; font-family: ui-monospace, SFMono-Regular, Menlo, monospace; font-size: .6rem; line-height: 1.65; white-space: pre-wrap; opacity: .96; } .fb-code-snippet .kw { color: #D5A4F5; } .fb-code-snippet .fn { color: #EBCB8B; } .fb-code-snippet .cm { color: #6F8199; } .fb-dataset-card { background-image: url('https://raw.githubusercontent.com/Centrum-IntelliPhysics/Benchmark-Data--Phase-field-fracture-in-hyperelastic-material/main/animations/phase_and_disp_evolution_sample1.gif'); background-size: cover; background-position: center; } .fb-files-card { background: #E8EDF3; } .fb-file-grid { position: absolute; inset: 30px 24px 34px; display: grid; grid-template-columns: repeat(3, 1fr); gap: .65rem; } .fb-file-grid i { display: grid; place-items: center; min-height: 62px; border: 1px solid #C3CEDD; border-radius: 4px; background: linear-gradient(#FFFFFF, #E6EBF2); color: #5B7693; box-shadow: 0 4px 10px rgba(13,31,69,.08); font-style: normal; font-size: .58rem; font-weight: 700; } .fb-model-card { background: #B9C7D8; } .fb-model-card svg { position: absolute; inset: 12px; width: calc(100% - 24px); height: calc(100% - 24px); } .fb-model-card line { stroke: #0D1F45; stroke-width: 5; } .fb-model-card circle { fill: #BCCBDC; stroke: #0D1F45; stroke-width: 6; } .fb-video-card { background: radial-gradient(circle at 20% 30%, rgba(188,203,220,.36), transparent 24%), linear-gradient(138deg, #245E94, #0D1F45); } .fb-video-frame { position: absolute; inset: 32px 28px 42px; display: grid; place-items: center; border: 1px solid rgba(255,255,255,.34); background: linear-gradient(115deg, transparent 0 41%, rgba(255,255,255,.13) 41% 42%, transparent 42%), linear-gradient(35deg, transparent 0 61%, rgba(255,255,255,.13) 61% 62%, transparent 62%); } .fb-play-icon { width: 72px; height: 72px; display: grid; place-items: center; border: 2px solid #FFFFFF; border-radius: 50%; color: #FFFFFF; font-size: 1.8rem; padding-left: .2rem; } .fb-poster-card { background: #DCE5EF; } .fb-poster-thumb { position: absolute; top: 22px; left: 22px; width: calc(100% - 44px); height: calc(100% - 22px - 68px); object-fit: contain; object-position: center top; filter: drop-shadow(0 6px 12px rgba(13,31,69,.28)); } .fb-band { background: #0D1F45; color: #FFFFFF; } .fb-band .fb-section-label { color: #9AB4D4; } .fb-band .fb-section-title { color: #FFFFFF; } .fb-band .fb-section-title::after { background: #BCCBDC; } .fb-band .fb-lead { color: #D8E3F1; } .fb-resource-grid { display: grid; grid-template-columns: repeat(4, minmax(0, 1fr)); gap: 2px; margin-top: 1.75rem; background: rgba(188,203,220,.34); } .fb-resource { min-height: 225px; position: relative; overflow: hidden; display: flex; align-items: flex-end; padding: 1.15rem; color: #FFFFFF !important; text-decoration: none !important; isolation: isolate; background-color: #16315E; background-size: cover; background-position: center; } .fb-resource::before { content: ''; position: absolute; inset: 0; z-index: -1; background: linear-gradient(to top, rgba(7,18,41,.98), rgba(13,31,69,.08) 70%); transition: background .2s ease; } .fb-resource:hover::before { background: linear-gradient(to top, rgba(7,18,41,.98), rgba(36,94,148,.18) 75%); } .fb-resource:hover .fb-resource-arrow { transform: translateX(4px); } .fb-resource small { display: block; color: #BCCBDC; text-transform: uppercase; letter-spacing: .1em; font-size: .62rem; margin-bottom: .25rem; } .fb-resource strong { color: #FFFFFF; font-size: .95rem; line-height: 1.35; } .fb-resource-arrow { display: inline-block; margin-left: .35rem; transition: transform .2s ease; } .fb-resource-d1 { background-image: url('https://raw.githubusercontent.com/Centrum-IntelliPhysics/Benchmark-Data--Phase-field-fracture-in-hyperelastic-material/main/animations/phase_and_disp_evolution_sample1.gif'); } .fb-resource-d2 { background-image: url('https://raw.githubusercontent.com/Centrum-IntelliPhysics/Benchmark_Data_Phase_field_fracture_in_fgm/main/figure/1_animation.gif'); } .fb-resource-code { background-image: linear-gradient(130deg, rgba(36,94,148,.2), transparent), repeating-linear-gradient(0deg, transparent 0 20px, rgba(188,203,220,.09) 20px 21px), repeating-linear-gradient(90deg, transparent 0 20px, rgba(188,203,220,.09) 20px 21px); } .fb-resource-play { background-image: radial-gradient(circle at 28% 36%, rgba(188,203,220,.38) 0 3px, transparent 4px), radial-gradient(circle at 72% 64%, rgba(188,203,220,.38) 0 3px, transparent 4px), linear-gradient(145deg, #245E94, #0D1F45); } .fb-card-foot { position: relative; z-index: 2; display: flex; flex-direction: column; align-items: center; gap: .6rem; } .fb-card-links { display: flex; flex-wrap: wrap; justify-content: center; gap: .4rem; } .fb-card-links a { padding: .3rem .62rem; border: 1px solid rgba(255,255,255,.72); border-radius: 2px; background: rgba(13,31,69,.6); color: #FFFFFF !important; font-size: .68rem; font-weight: 600; letter-spacing: .02em; text-decoration: none !important; transition: background .2s ease, color .2s ease; } .fb-card-links a:hover { background: #FFFFFF; color: #0D1F45 !important; } .fb-project-card:has(.fb-card-foot)::after { background: linear-gradient(to top, rgba(6,16,36,.95) 34%, transparent 82%); } .fb-page-head { background: linear-gradient(to top, rgba(6,16,36,.95), rgba(13,31,69,.62)), url('https://raw.githubusercontent.com/Centrum-IntelliPhysics/Benchmark-Data--Phase-field-fracture-in-hyperelastic-material/main/animations/phase_and_disp_evolution_sample1.gif') center / cover; color: #FFFFFF; } .fb-page-head-inner { width: min(1080px, calc(100% - 3rem)); margin: 0 auto; padding: 2.6rem 0 2.1rem; } .fb-page-head h1 { color: #FFFFFF !important; font-size: clamp(1.7rem, 3.4vw, 2.6rem) !important; line-height: 1.1 !important; margin: 0 0 .7rem !important; } .fb-page-head .fb-page-sub { color: #D8E3F1 !important; margin: 0 !important; font-size: .72rem !important; font-weight: 600; letter-spacing: .08em; text-transform: uppercase; } .st-key-fb_playground_page { width: min(1080px, 100%); margin: 1.6rem auto 0 !important; } .stApp .fb-playground-copy { color: var(--fb-pg-copy) !important; font-size: .94rem !important; line-height: 1.7 !important; margin: 0 0 1rem !important; } .stApp .fb-playground-copy strong { color: var(--fb-pg-strong) !important; } .st-key-fb_playground_page button[data-baseweb="tab"] { margin-bottom: .4rem; } .fb-footer { margin-top: 4.5rem; background: #08152F; color: #BCCBDC; padding: 2.5rem 0; } .fb-footer-inner { width: min(1180px, calc(100% - 3rem)); margin: 0 auto; display: flex; justify-content: space-between; align-items: flex-end; gap: 2rem; } .fb-footer strong { color: #FFFFFF; } .fb-footer p { color: #BCCBDC !important; font-size: .76rem; margin: .25rem 0 0 !important; } .fb-footer a { color: #FFFFFF !important; } @media (max-width: 900px) { [data-testid="stMainBlockContainer"] { padding-left: 1.25rem; padding-right: 1.25rem; } .fb-nav-links { display: none; } .fb-resource-grid { grid-template-columns: repeat(2, minmax(0, 1fr)); } .fb-project-grid { grid-template-columns: repeat(2, minmax(0, 1fr)); } .fb-hero { min-height: 390px; } } @media (max-width: 600px) { .st-key-fb_toggle { right: .8rem; } .fb-nav-inner { width: calc(100% - 2rem); padding-right: 5.8rem; } .fb-hero-inner, .fb-section-inner, .fb-footer-inner { width: calc(100% - 2rem); } .fb-resource-grid { grid-template-columns: 1fr; } .fb-project-grid { grid-template-columns: 1fr; } .fb-project-card { min-height: 275px; } .fb-resource { min-height: 190px; } .fb-hero-metrics { display: grid; grid-template-columns: 1fr 1fr; } .fb-metric { min-width: 0; } .fb-footer-inner { display: block; } .fb-page-head-inner { width: calc(100% - 2rem); } } """ st.markdown(f"<style>{_css}</style>", unsafe_allow_html=True) # ---------------------------------------------------------------- links --- # Public links. While one is empty, its card shows a "Coming soon" tag. PAPER_URL = "" # preprint or journal page CODE_URL = "https://github.com/Centrum-IntelliPhysics/fracture_bench" # training code MODELS_URL = "" # page where the trained weights can be downloaded POSTER_URL = "app/static/Fracture-Bench_poster.pdf" # served from ./static POSTER_THUMB = "app/static/Fracture-Bench_poster.png" PLAYGROUND_URL = "?view=playground" D1_DOI = "https://doi.org/10.7281/T1XFF19O" D2_DOI = "https://doi.org/10.7281/T1RZFI3I" D1_GITHUB = ("https://github.com/Centrum-IntelliPhysics/" "Benchmark-Data--Phase-field-fracture-in-hyperelastic-material") D2_GITHUB = ("https://github.com/Centrum-IntelliPhysics/" "Benchmark_Data_Phase_field_fracture_in_fgm") def _card_open(card_id: str, cls: str, url: str, label: str) -> str: """Opening tag of a home-page card: a link, or a 'Coming soon' tile.""" if url: return (f'<a id="{card_id}" class="fb-project-card {cls}" href="{url}" ' f'target="_blank" rel="noopener" aria-label="{label}">') return (f'<div id="{card_id}" class="fb-project-card {cls}" aria-label="{label}, coming soon">' '<span class="fb-placeholder-tag">Coming soon</span>') def _card_close(url: str) -> str: return "</a>" if url else "</div>" _CODE_LINK = (f'<a href="{CODE_URL}" target="_blank" rel="noopener">Training code · GitHub ↗</a>' if CODE_URL else "") def _footer(): st.markdown( """ <span id="contact"></span> <footer class="fb-fullbleed fb-footer"> <div class="fb-footer-inner"> <div> <strong>Fracture-Bench</strong> <p>Open benchmarks for phase-field fracture surrogates.</p> </div> <div> <p> Questions or contributions? Write to <a href="mailto:ukrishn4@jh.edu">ukrishn4@jh.edu</a> </p> <p>Johns Hopkins University · IntelliPhysics Lab</p> </div> </div> </footer> """, unsafe_allow_html=True, ) # ---------------------------------------------------------------- header -- _home = SITE_URL or ("./" if ON_PLAYGROUND else "") _home_target = "_top" if SITE_URL else "_self" # leave the Hugging Face frame _nav_playground = ( '<a class="fb-nav-current" href="#top" target="_self">Playground</a>' if ON_PLAYGROUND else f'<a href="{PLAYGROUND_URL}" target="_blank" rel="noopener">Playground</a>') if EMBED: # embedded in the github.io playground: no site chrome, no theme toggle st.markdown( "<style>.st-key-fb_toggle, .st-key-fb_hidden_overview { display: none !important; }" " .block-container { padding-top: 1rem !important; }</style>", unsafe_allow_html=True, ) else: st.markdown( f""" <div class="fb-fullbleed fb-site-nav"> <div class="fb-nav-inner"> <a class="fb-brand" href="{_home}#top" target="{_home_target}"> <span class="fb-mark"><span>ϕ</span></span> <span>Fracture-Bench</span> </a> <nav class="fb-nav-links" aria-label="Project navigation"> <a href="{_home}#about" target="{_home_target}">About</a> <a href="{_home}#resources" target="{_home_target}">Datasets &amp; code</a> {_nav_playground} <a href="#contact" target="_self">Contact</a> </nav> </div> </div> <span id="top"></span> """, unsafe_allow_html=True, ) _HERO_AND_INTRO = """\ <section class="fb-fullbleed fb-hero"> <div class="fb-hero-inner"> <p class="fb-kicker">A benchmark for scientific machine learning</p> <h1>FRACTURE-BENCH</h1> <p class="fb-hero-deck">Fast neural surrogates for phase-field fracture</p> <p class="fb-hero-copy"> Compare operator-learning architectures on two high-fidelity fracture datasets, then predict crack initiation and propagation in a single forward pass. </p> <div class="fb-hero-metrics"> <div class="fb-metric"><strong>2</strong><span>physics datasets</span></div> <div class="fb-metric"><strong>5</strong><span>model families</span></div> <div class="fb-metric"><strong>5,000</strong><span>FEM simulations</span></div> <div class="fb-metric"><strong>ms</strong><span>surrogate inference</span></div> </div> </div> </section> <span id="about"></span> <section class="fb-fullbleed fb-basics"> <div class="fb-basics-inner"> <h2 class="fb-basics-title">The basics</h2> <p class="fb-basics-copy"> Fracture-Bench introduces neural surrogate models to phase-field fracture simulation. It compares operator-learning and generative architectures on shared data splits and evaluation metrics across two high-fidelity datasets. The playground makes these models interactive, so hours of finite-element fracture physics can be explored in a single forward pass. You can find the most up-to-date project resources below: </p> <span id="resources"></span> """ _MODELS_AND_POSTER = """\ __MODELS_OPEN__ <svg viewBox="0 0 360 260" aria-hidden="true"> <line x1="42" y1="48" x2="142" y2="30"/><line x1="42" y1="48" x2="150" y2="130"/> <line x1="42" y1="210" x2="150" y2="130"/><line x1="42" y1="210" x2="142" y2="230"/> <line x1="142" y1="30" x2="260" y2="70"/><line x1="142" y1="30" x2="150" y2="130"/> <line x1="150" y1="130" x2="260" y2="70"/><line x1="150" y1="130" x2="270" y2="190"/> <line x1="142" y1="230" x2="270" y2="190"/><line x1="260" y1="70" x2="326" y2="130"/> <line x1="270" y1="190" x2="326" y2="130"/> <circle cx="42" cy="48" r="22"/><circle cx="42" cy="210" r="22"/> <circle cx="142" cy="30" r="22"/><circle cx="150" cy="130" r="22"/><circle cx="142" cy="230" r="22"/> <circle cx="260" cy="70" r="22"/><circle cx="270" cy="190" r="22"/><circle cx="326" cy="130" r="22"/> </svg> <span class="fb-project-card-title">Download trained models</span> __MODELS_CLOSE__ <a id="poster" class="fb-project-card fb-poster-card" href="__POSTER__" target="_blank" rel="noopener" aria-label="Benchmark poster, PDF"> <img class="fb-poster-thumb" src="__POSTER_THUMB__" alt=""> <span class="fb-project-card-title">Benchmark poster</span> </a> """ # ====================================================================== # Home page: hero + project cards. Every card opens in a new browser tab. # ====================================================================== if not ON_PLAYGROUND: _landing = """ __HERO__ <div class="fb-project-grid"> __PAPER_OPEN__ <div class="fb-paper-sheet"> <b>Fracture-Bench: A Controlled Benchmark Suite for Machine Learning Surrogates in Phase-Field Fracture Mechanics</b> <i>U. Meenu Krishnan · Somdatta Goswami · Lori Graham-Brady</i> <div class="fb-paper-lines"></div> </div> <span class="fb-project-card-title">Paper</span> __PAPER_CLOSE__ <div id="code" class="fb-project-card fb-code-card"> <div class="fb-code-snippet"><span class="kw">import</span> numpy <span class="kw">as</span> np <span></span> <span class="cm"># Dataset 2, inclusion case 1</span> data = np.<span class="fn">load</span>("train_case1.npz") <span></span> d = data["phase_field"] u = data["displacement_field"] E = data["e_field"]</div> <div class="fb-card-foot"> <span class="fb-project-card-title">Code</span> <div class="fb-card-links"> __CODE_LINK__<a href="__D1_GITHUB__" target="_blank" rel="noopener">Dataset 1 · GitHub ↗</a> <a href="__D2_GITHUB__" target="_blank" rel="noopener">Dataset 2 · GitHub ↗</a> </div> </div> </div> <a id="playground" class="fb-project-card fb-dataset-card" href="__PLAYGROUND__" target="_blank" rel="noopener" aria-label="About the datasets and playground"> <span class="fb-project-card-title">About the datasets &amp; playground</span> </a> <div id="datasets" class="fb-project-card fb-files-card"> <div class="fb-file-grid"> <i>NPZ</i><i>H5</i><i>CSV</i><i>NPZ</i><i>XDMF</i><i>H5</i> </div> <div class="fb-card-foot"> <span class="fb-project-card-title">Download the datasets</span> <div class="fb-card-links"> <a href="__D1_DOI__" target="_blank" rel="noopener">Dataset 1 · JHU archive ↗</a> <a href="__D2_DOI__" target="_blank" rel="noopener">Dataset 2 · JHU archive ↗</a> </div> </div> </div> __MODELS_AND_POSTER__ </div> </div> </section> """ st.markdown( (_landing.replace("__HERO__", _HERO_AND_INTRO) .replace("__MODELS_AND_POSTER__", _MODELS_AND_POSTER) .replace("__PAPER_OPEN__", _card_open("paper", "fb-paper-card", PAPER_URL, "Paper")) .replace("__PAPER_CLOSE__", _card_close(PAPER_URL)) .replace("__MODELS_OPEN__", _card_open("models", "fb-model-card", MODELS_URL, "Download trained models")) .replace("__MODELS_CLOSE__", _card_close(MODELS_URL)) .replace("__CODE_LINK__", _CODE_LINK) .replace("__POSTER__", POSTER_URL).replace("__POSTER_THUMB__", POSTER_THUMB) .replace("__PLAYGROUND__", PLAYGROUND_URL) .replace("__D1_GITHUB__", D1_GITHUB).replace("__D2_GITHUB__", D2_GITHUB) .replace("__D1_DOI__", D1_DOI).replace("__D2_DOI__", D2_DOI)), unsafe_allow_html=True, ) _footer() st.stop() # ====================================================================== # Playground page: datasets overview + interactive tabs # ====================================================================== if not EMBED: st.markdown( """ <section class="fb-fullbleed fb-page-head"> <div class="fb-page-head-inner"> <p class="fb-kicker">Fracture-Bench</p> <h1>About the datasets &amp; playground</h1> <p class="fb-page-sub">Configure inputs · Compare surrogates · Inspect FEM error</p> </div> </section> """, unsafe_allow_html=True, ) playground_block = st.container(key="fb_playground_page") if not EMBED: playground_block.markdown( """ <p class="fb-playground-copy"> Choose a dataset, configure its physical inputs, and run the available neural surrogates side by side. Held-out cases include FEM ground truth for direct <strong>pixel-wise error comparison</strong>. </p> """, unsafe_allow_html=True, ) _DATASET_TABS = ["Dataset 1 : Perforated plate of hyperelastic material", "Dataset 2 : Heterogeneous plate with two inclusions"] if EMBED: # the github.io page has its own overview; this container is hidden by CSS tab_d1, tab_d2 = playground_block.tabs(_DATASET_TABS) tab_ov = st.container(key="fb_hidden_overview") else: tab_ov, tab_d1, tab_d2 = playground_block.tabs(["Overview"] + _DATASET_TABS) # ====================================================================== # Overview tab # ====================================================================== _txt = "#E9F0F9" if dark_mode else "#13294B" _card_bg = "#16315E" if dark_mode else "#F4F8FC" _border = "#2C4A7C" if dark_mode else "#D1DCF0" def _dataset_card(inner_html: str, cta_intro: str, tab_prefix: str, link_text: str, height: int = 680): """Render a dataset card (content + a working tab-switch CTA) in one themed iframe, so the link runs JS yet sits inside the same box. Use the token __CTA_LI__ inside inner_html to place the CTA tick item.""" if EMBED: # overview is hidden there return lc = "#8FB7EC" if dark_mode else "#235AAA" cta_li = """<li>__CTA__ <a class='cta-link' href='javascript:void(0)' onclick="var t=Array.from(window.parent.document.querySelectorAll('[role=tab]')).find(function(x){return x.innerText.trim().indexOf('__PREF__')===0;});if(t){t.click();window.parent.scrollTo({top:0,behavior:'smooth'});}">__LINK__ &rarr;</a></li>""" cta_li = (cta_li.replace("__CTA__", cta_intro) .replace("__PREF__", tab_prefix) .replace("__LINK__", link_text)) inner_html = inner_html.replace("__CTA_LI__", cta_li) doc = """ <!doctype html><html><head><meta charset='utf-8'> <style> @import url('https://fonts.googleapis.com/css2?family=Poppins:wght@400;500;600;700&display=swap'); *{box-sizing:border-box;} html,body{margin:0;padding:0;background:transparent;height:100%;} body{font-family:'Poppins',system-ui,sans-serif;} .card{background:__BG__;border:1px solid __BORDER__;border-radius:2px; padding:1.2rem 1.4rem;color:__TXT__;font-size:.9rem;line-height:1.6; min-height:100%;} .card h3{margin:0 0 .6rem 0;font-size:1.05rem;} .card img{width:100%;max-height:240px;object-fit:contain;border-radius:0; margin-bottom:.7rem;} .card ul{padding-left:1.1rem;margin:.2rem 0;} .card a{color:__BLUE__;} ul.ticks{list-style:none;padding-left:0 !important;margin:.7rem 0 0 0;} ul.ticks li{position:relative;padding-left:1.6rem;margin-bottom:.55rem;} ul.ticks li::before{content:'\\2713';position:absolute;left:0;top:0; color:#2E8B57;font-weight:700;} .cta-link{color:__LC__;font-weight:600;text-decoration:underline;cursor:pointer;} </style></head><body> <div class='card'> __INNER__ </div></body></html> """ doc = (doc.replace("__BG__", _card_bg).replace("__BORDER__", _border) .replace("__TXT__", _txt).replace("__BLUE__", BLUE) .replace("__LC__", lc).replace("__INNER__", inner_html)) st.iframe(doc, height=height, width="stretch", tab_index=0) with tab_ov: st.markdown( f""" <style> .ov-card {{ background:{_card_bg}; border:1px solid {_border}; border-left:3px solid {BLUE}; border-radius:2px; padding:1.2rem 1.4rem; margin-bottom:1rem; }} .ov-card h3 {{ color:{_txt}; margin-top:0; font-size:1.05rem; }} .ov-card p, .ov-card li {{ color:{_txt}; font-size:.9rem; line-height:1.65; }} .ov-ds {{ display:flex; flex-direction:column; height:100%; }} .ov-foot {{ margin-top:auto; padding-top:.5rem; }} .ov-tag {{ display:inline-block; background:{BLUE}; color:#fff; border-radius:999px; padding:.15rem .65rem; font-size:.78rem; font-weight:600; margin-right:.35rem; margin-bottom:.2rem; }} </style> """, unsafe_allow_html=True) st.markdown(f""" <div class="ov-card"> <p> Phase-field models are the method of choice for simulating fracture — crack nucleation, propagation, branching, and coalescence — within a single variational framework, but each quasi-static simulation is expensive, making ensemble workflows such as uncertainty quantification, Bayesian inference, and design optimization intractable. </p> <p> <b>Fracture-Bench</b> is a benchmark suite that evaluates machine-learning surrogates which replace the finite-element solve with a single network forward pass. Five architectures (UNet, FNO, DeepONet, Latent DeepONet, and a conditional denoising diffusion model) are trained on identical data splits and scored with common test metrics across <b>two high-fidelity datasets</b> that differ in phase-field formulation, material heterogeneity, and prediction task. </p> <p> Evaluation spans accuracy, computational efficiency, and generalization to load steps withheld during training. The headline result: <b>no single architecture dominates</b>, and prediction difficulty scales with material heterogeneity and crack-path sensitivity. All datasets, evaluation protocols, and model code are released openly. </p> </div> """, unsafe_allow_html=True) ov_d1, ov_d2 = st.columns(2, gap="large") with ov_d1: _dataset_card(f""" <h3>Dataset 1 : Perforated plate of hyperelastic material</h3> <img src="https://raw.githubusercontent.com/Centrum-IntelliPhysics/Benchmark-Data--Phase-field-fracture-in-hyperelastic-material/main/animations/phase_and_disp_evolution_sample1.gif"> <ul> <li><b>Formulation:</b> Phase-field fracture : AT2 model</li> <li><b>Domain:</b> Ω = [−1.1, 1.1]² square plate, central hole r = 0.5 · grid 128 × 128</li> <li><b>Loading:</b> affine GRF boundary displacement, u = α(s)·x on ∂Ω, 44 load steps</li> <li><b>Operator:</b> 𝒢 : u(x,0) ↦ d(x,t), t ∈ {{t₁,…,t₄₄}}</li> <li><b>Phase field:</b> <i>vector</i> d(x,t) ∈ ℝ² (crack magnitude + orientation, after Hakimzadeh et&nbsp;al.); scalar damage measure ‖d‖ ∈ [0,1] used for visualization</li> <li><b>Size:</b> 1,000 simulations · train / test = 900 / 100</li> </ul> <ul class="ticks"> <li>Download the full dataset from the <a href="https://doi.org/10.7281/T1XFF19O" target="_blank">JHU Data Archive</a>.</li> <li>Get the simulation and data-generation code from the <a href="https://github.com/Centrum-IntelliPhysics/Benchmark-Data--Phase-field-fracture-in-hyperelastic-material" target="_blank">GitHub repository</a>.</li> __CTA_LI__ </ul> """, "Want to play with the dataset and see how the crack path varies " "with the boundary load?", "Dataset 1", "Go to the Dataset 1 tab") with ov_d2: _dataset_card(f""" <h3>Dataset 2 : Heterogeneous plate with two inclusions</h3> <img src="https://raw.githubusercontent.com/Centrum-IntelliPhysics/Benchmark_Data_Phase_field_fracture_in_fgm/main/figure/1_animation.gif"> <ul> <li><b>Formulation:</b> Phase-field fracture : PF-CZM model</li> <li><b>Domain:</b> 4 mm × 8 mm heterogeneous plate · two circular inclusions · grid 128 × 256</li> <li><b>Material:</b> modulus field E(x); each inclusion stiffer (E = 10 E<sub>m</sub>) or softer (E = 0.1 E<sub>m</sub>)</li> <li><b>Loading:</b> Mode-I tension, 31 load steps</li> <li><b>Operator:</b> 𝒢 : (d(x,0), E(x)) ↦ d(x,t<sub>f</sub>)</li> <li><b>Phase field:</b> <i>scalar</i> d ∈ [0,1] (0 = intact, 1 = fully cracked); only the final step t<sub>f</sub> predicted</li> <li><b>Size:</b> 4,000 simulations (4 inclusion cases) · train / test = 3,600 / 400</li> </ul> <ul class="ticks"> <li>Download the full dataset from the <a href="https://doi.org/10.7281/T1RZFI3I" target="_blank">JHU Data Archive</a>.</li> <li>Get the adaptive-mesh simulation and data-generation code from the <a href="https://github.com/Centrum-IntelliPhysics/Benchmark_Data_Phase_field_fracture_in_fgm" target="_blank">GitHub repository</a>.</li> __CTA_LI__ </ul> """, "Want to play with the dataset and see how the crack path bends " "around the inclusions?", "Dataset 2", "Go to the Dataset 2 tab") st.markdown(f""" <div class="ov-card"> <h3>Contributing &amp; contact</h3> <p> Fracture-Bench is meant to grow as a community resource. If you would like to <b>contribute a new surrogate architecture</b> (or a new dataset or fracture problem) to the benchmark, we would be glad to include it — please reach out to any of us: </p> <ul style="padding-left:1.1rem"> <li>Dr. U. Meenu Krishnan — <a href="mailto:ukrishn4@jh.edu" style="color:{BLUE}">ukrishn4@jh.edu</a></li> <li>Prof. Somdatta Goswami — <a href="mailto:somdatta@jhu.edu" style="color:{BLUE}">somdatta@jhu.edu</a></li> <li>Prof. Lori Graham-Brady — <a href="mailto:lori@jhu.edu" style="color:{BLUE}">lori@jhu.edu</a></li> </ul> </div> """, unsafe_allow_html=True) # ====================================================================== # Dataset 1 # ====================================================================== with tab_d1: st.markdown(f""" <div style="background:{_card_bg};border:1px solid {_border}; border-radius:2px;padding:.9rem 1.2rem;margin-bottom:1rem; color:{_txt};font-size:.9rem;line-height:1.6"> Predict crack growth in a <b>perforated hyperelastic plate</b> (AT2), where the load is a Gaussian-random-field (GRF) boundary displacement. Controls in this tab: <ul style="padding-left:1.2rem;margin:.4rem 0 0 0"> <li><b>Input source</b> — pick a <b>held-out test sample</b> (a real FEM simulation the models never saw in training; its ground truth is stored so the error can be measured), or a <b>new GRF case</b> you design by setting the field parameters γ, τ, σ, μ.</li> <li><b>Architecture(s)</b> — run one or several surrogates (FNO, DeepONet, Latent DeepONet) side by side, and set the <b>temporal resolution</b> (11 / 22 / 44 load steps).</li> <li><b>Output</b> — press <b>Predict crack evolution</b> to get the vector phase-field ‖d(x,t)‖ across the load steps; for held-out samples a <b>pixel-wise error</b> map |prediction − FEM| is shown beneath each model.</li> </ul> </div> """, unsafe_allow_html=True) col_in, col_out = st.columns([1.4, 2.6], gap="large") with col_in: ctrl_col1, img_col1 = st.columns([2.1, 1], gap="medium") with ctrl_col1: st.subheader("Input: GRF boundary loading") S = geo.d1_samples() d1_mode = st.radio( "Input source", ["Held-out test sample", "New GRF case (unseen)"], horizontal=True, key="d1_mode", help="Test samples come with FEM ground truth for error comparison.") sample_idx = 0 if d1_mode == "Held-out test sample": n_avail = S["u0"].shape[0] sample_idx = st.selectbox( "Held-out test simulation", list(range(n_avail)), format_func=lambda i: f"Sample #{int(S['sample_ids'][i])} (test split)", ) u0_sel = S["u0"][sample_idx] # (128,128,2), raw else: from utils import elasticity as ela st.caption("Boundary load drawn from the same Gaussian random " "field (GRF) the FEA solver uses:") st.latex(r"f(s)=\mu+\sum_{n=1}^{N}\lambda_n\big[\xi_n\cos(n\phi)" r"+\eta_n\sin(n\phi)\big],\;\;" r"\lambda_n=\sqrt{2}\,\sigma\big((2\pi n)^2+\tau^2\big)" r"^{-\gamma/2}") grf_seed = st.number_input("Random seed (ξₙ, ηₙ)", 0, 99999, 42, step=1) gp1, gp2 = st.columns(2) with gp1: gamma = st.number_input("γ — smoothness", 1.0, 8.0, 4.0, 0.5) tau = st.number_input("τ — inverse length scale", 0.5, 20.0, 5.0, 0.5) with gp2: sigma = st.number_input("σ — amplitude", 1.0, 2000.0, 625.0, 25.0) mean = st.number_input("μ — mean load level", 0.3, 3.0, 1.0, 0.05) st.caption("Training distribution: γ=4, τ=5, σ=625, μ=1. " "Move away from these for unseen (out-of-distribution) " "loads.") alpha = ela.spectral_boundary_profile( int(grf_seed), gamma=float(gamma), tau=float(tau), sigma=float(sigma), mean=float(mean)) st.pyplot(viz.plot_grf_profile(alpha / max(abs(alpha.mean()), 1e-12)), width="stretch") with st.spinner("Elasticity solve for u(x,0)…"): u0_sel = ela.solve_first_step(alpha) with img_col1: u0_mag = np.linalg.norm(u0_sel, axis=-1) st.pyplot(viz.plot_field( u0_mag, title="‖u(x, 0)‖ — initial displacement", vmax=float(u0_mag.max()), mask=geo.hole_mask()), width="stretch") st.subheader("Surrogate") d1_models = registry.playground_models(1) sel_models = st.multiselect("Architecture(s)", d1_models, default=["DeepONet", "Latent DeepONet"], key="d1_models") st.caption("UNet and cDDPM will be added once their trained weights are released.") n_steps = st.select_slider( "Temporal resolution (load steps)", options=[11, 22, 44], value=11, help="All three architectures have checkpoints at 11/22/44 steps.") run_d1 = st.button("Predict crack evolution", type="primary", width="stretch") with col_out: if run_d1 and sel_models: u0 = u0_sel st.session_state["d1_preds"] = {} for name in sel_models: m = registry.get_model(name) note = m.info.inference_note with st.spinner(f"{name} predicting… ({note})"): t0 = time.perf_counter() try: d = m.predict_d1(u0, n_steps) except NotImplementedError as e: st.error(f"{name}: {e}") continue dt = time.perf_counter() - t0 st.session_state["d1_preds"][name] = d st.session_state["d1_time_" + name] = dt st.session_state["d1_nsteps"] = n_steps st.session_state["d1_sample"] = sample_idx st.session_state["d1_has_truth"] = (d1_mode == "Held-out test sample") preds = st.session_state.get("d1_preds", {}) if preds: ns = st.session_state["d1_nsteps"] step = st.slider("Load step", 1, ns, ns, key="d1_step") mask = geo.hole_mask() # Build per-model fields at current step model_fields = { name: np.linalg.norm(d[step - 1], axis=-1) for name, d in preds.items() } # Prediction + truth row row = { f"{name} · {st.session_state['d1_time_'+name]*1e3:.0f} ms": f for name, f in model_fields.items() } has_truth = st.session_state.get("d1_has_truth", False) true_field = None if has_truth: s_idx = st.session_state.get("d1_sample", 0) sub = 44 // ns d_true_raw = S["phase"][s_idx][::sub][step - 1] true_field = np.linalg.norm(d_true_raw, axis=-1) row["Ground truth (FEM)"] = true_field st.pyplot( viz.plot_comparison_row( row, vmax=1.0, mask=mask, suptitle=f"‖d(x, t)‖ at load step {step}/{ns}", n_slots=len(d1_models) + 1), width="stretch", ) # Error row if has_truth and true_field is not None and model_fields: err_row = { f"{name} · {st.session_state['d1_time_'+name]*1e3:.0f} ms": np.abs(f - true_field) for name, f in model_fields.items() } ev = [v[~mask] for v in err_row.values()] err_vmax = float(np.percentile(np.concatenate(ev), 95)) if ev else 0.1 st.pyplot( viz.plot_comparison_row( err_row, vmax=err_vmax, mask=mask, cmap="Oranges", suptitle=f"|pred − FEM| at step {step}/{ns}", n_slots=len(d1_models) + 1, cbar_label="|pred − FEM|"), width="stretch", ) else: st.info("Pick a held-out test simulation and press " "**Predict crack evolution**.") # ====================================================================== # Dataset 2 # ====================================================================== with tab_d2: st.markdown(f""" <div style="background:{_card_bg};border:1px solid {_border}; border-radius:2px;padding:.9rem 1.2rem;margin-bottom:1rem; color:{_txt};font-size:.9rem;line-height:1.6"> Predict the final crack pattern in a <b>heterogeneous plate with two circular inclusions</b> (PF-CZM), under Mode-I tension. Controls in this tab: <ul style="padding-left:1.2rem;margin:.4rem 0 0 0"> <li><b>Input source</b> — pick a <b>held-out test sample</b> (a real FEM simulation the models never saw in training, with stored ground truth for error comparison), or a <b>custom configuration</b>: toggle each inclusion <b>stiffer</b> (10&nbsp;E<sub>m</sub>) or <b>softer</b> (0.1&nbsp;E<sub>m</sub>) and place the initial crack tip with the <b>Tip&nbsp;x</b> / <b>Tip&nbsp;y</b> sliders.</li> <li><b>Architecture(s)</b> — run one or several surrogates (FNO, DeepONet, Latent DeepONet) side by side.</li> <li><b>Output</b> — press <b>Predict final crack path</b> to get the scalar phase-field d(x,t<sub>f</sub>) at the final load step; for held-out samples a <b>pixel-wise error</b> map |prediction − FEM| is shown beneath each model.</li> </ul> </div> """, unsafe_allow_html=True) col_in2, col_out2 = st.columns([1.4, 2.6], gap="large") with col_in2: ctrl_col, img_col = st.columns([2.1, 1], gap="medium") S2 = geo.d2_samples() with ctrl_col: d2_mode = st.radio( "Input source", ["Held-out test sample", "Custom configuration"], horizontal=True, key="d2_mode", help="Held-out samples include FEM ground truth for error comparison.") if d2_mode == "Held-out test sample": n_avail2 = S2["d0"].shape[0] def _d2_label(i): uh = bool(S2["upper_hard"][i]) lh = bool(S2["lower_hard"][i]) sid = int(S2["sample_ids"][i]) return (f"Sample #{sid} · upper {'stiffer' if uh else 'softer'}" f" / lower {'stiffer' if lh else 'softer'}") sample_idx2 = st.selectbox( "Held-out test simulation", list(range(n_avail2)), format_func=_d2_label, key="d2_sample_sel", ) d0_sel2 = S2["d0"][sample_idx2] # (256,128) float32 E = S2["E"][sample_idx2] # (256,128) float32 upper_hard = bool(S2["upper_hard"][sample_idx2]) lower_hard = bool(S2["lower_hard"][sample_idx2]) up, lo = geo.inclusion_masks() else: st.subheader("Inclusion configuration") upper_hard = st.toggle("Upper inclusion stiffer (10 × Eₘ)", value=False) lower_hard = st.toggle("Lower inclusion stiffer (10 × Eₘ)", value=True) st.subheader("Initial crack tip") xs, ys = geo.admissible_tip_region() tip_x = st.slider("Tip x (px)", xs.start, xs.stop - 1, 24) tip_y = st.slider("Tip y (px)", ys.start, ys.stop - 1, 133) d0_sel2 = geo.build_initial_crack(tip_x, tip_y) E = geo.build_modulus_field(upper_hard, lower_hard) up, lo = geo.inclusion_masks() # material distribution + pre-crack with img_col: st.pyplot(viz.plot_d2_config(d0_sel2, upper_hard, lower_hard, up, lo), width="stretch") st.subheader("Surrogate") d2_models = registry.playground_models(2) sel2 = st.multiselect("Architecture(s)", d2_models, default=["FNO", "DeepONet", "Latent DeepONet"], key="d2_models") st.caption("UNet and cDDPM will be added once their trained weights are released.") run_d2 = st.button("Predict final crack path", type="primary", width="stretch") with col_out2: if run_d2 and sel2: st.session_state["d2_preds"] = {} st.session_state["d2_has_truth"] = (d2_mode == "Held-out test sample") if d2_mode == "Held-out test sample": st.session_state["d2_truth"] = S2["d_tf"][sample_idx2] st.session_state["d2_sample"] = sample_idx2 for name in sel2: m = registry.get_model(name) with st.spinner(f"{name} predicting… ({m.info.inference_note})"): t0 = time.perf_counter() try: d_tf = m.predict_d2(d0_sel2, E) except NotImplementedError as e: st.error(f"{name}: {e}") continue dt = time.perf_counter() - t0 st.session_state["d2_preds"][name] = (d_tf, dt) preds2 = st.session_state.get("d2_preds", {}) if preds2: has_truth2 = st.session_state.get("d2_has_truth", False) row2 = {f"{n} · {dt*1e3:.0f} ms": d for n, (d, dt) in preds2.items()} if has_truth2: d_tf_true2 = st.session_state["d2_truth"] row2["Ground truth (FEM)"] = d_tf_true2 st.pyplot(viz.plot_comparison_row( row2, suptitle="Predicted d(x, t_f)", n_slots=len(d2_models) + 1), width="stretch") # Error row if has_truth2: d_tf_true2 = st.session_state["d2_truth"] err_row2 = { f"{n} · {dt*1e3:.0f} ms": np.abs(d - d_tf_true2) for n, (d, dt) in preds2.items() } ev2 = [v.ravel() for v in err_row2.values()] err_vmax2 = float(np.percentile(np.concatenate(ev2), 95)) if ev2 else 0.1 st.pyplot(viz.plot_comparison_row( err_row2, vmax=err_vmax2, cmap="Oranges", suptitle="|pred − FEM|", n_slots=len(d2_models) + 1, cbar_label="|pred − FEM|"), width="stretch") else: st.info("Choose a test sample or configure inclusions + crack tip, " "then press **Predict final crack path**.") if not EMBED: _footer()
"""Fracture-Bench Playground — interactive surrogate predictions for
phase-field fracture.
Run locally: streamlit run app.py
"""
from __future__ import annotations
import os
import time
import numpy as np
import streamlit as st
from models import registry
from utils import geometry as geo
from utils import plotting as viz
st.set_page_config(page_title="Fracture-Bench Playground",
page_icon="⚡", layout="wide")
# Pages, chosen by ?view=:
# home hero + project cards (only when run locally)
# playground datasets overview + interactive tabs
# embed the two dataset tabs only, for embedding in the github.io site
# When FRACTURE_BENCH_SITE is set (the hosted Hugging Face Space), that site is
# the home page, so the app opens on the playground and links home to the site.
SITE_URL = os.environ.get("FRACTURE_BENCH_SITE", "")
VIEW = st.query_params.get("view", "playground" if SITE_URL else "home")
if SITE_URL and VIEW not in ("playground", "embed"):
VIEW = "playground"
EMBED = VIEW == "embed"
ON_PLAYGROUND = VIEW in ("playground", "embed")
# ---------------------------------------------------------------- theme ---
NAVY, NAVY2, BLUE, MIST, WHITE = ("#0D1F45", "#16315E", "#245E94",
"#BCCBDC", "#FFFFFF")
INK, PALE, LINE = "#13294B", "#F4F8FC", "#D1DCF0"
with st.container(key="fb_toggle"):
dark_mode = st.toggle("🌙 Dark", value=False, key="theme_dark")
if dark_mode:
_css = f"""
.stApp {{ background: {NAVY}; color: {WHITE}; --fb-pg-bg:{NAVY};
--fb-pg-copy:#B9C9DE; --fb-pg-strong:#FFFFFF; }}
header[data-testid="stHeader"] {{ background: rgba(13,31,69,0.85); }}
.stApp h1, .stApp h2, .stApp h3, .stMarkdown p, label p,
[data-testid="stWidgetLabel"] p, .stRadio label p,
.stSelectbox label p {{ color: #E9F0F9 !important; }}
button[data-baseweb="tab"] p {{ color: {MIST} !important; font-weight: 600; }}
button[data-baseweb="tab"][aria-selected="true"] p {{ color: {WHITE} !important; }}
[data-testid="stAlertContainer"] {{
background: {NAVY2}; color: #E9F0F9; border-left: 4px solid {BLUE}; }}
[data-testid="stAlertContainer"] p {{ color: #E9F0F9 !important; }}
div[data-baseweb="select"] > div,
[data-testid="stNumberInputContainer"] {{
background: {NAVY2}; border-color: #2C4A7C; }}
div[data-baseweb="select"] div, div[data-baseweb="select"] span {{
color: #E9F0F9 !important; }}
div[data-baseweb="select"] svg {{ fill: #E9F0F9; }}
[data-testid="stNumberInputContainer"] input {{ color: #E9F0F9; }}
div[data-baseweb="input"], div[data-baseweb="base-input"] {{
background: {NAVY2} !important; }}
div[data-baseweb="input"] input, [data-testid="stNumberInputContainer"] input {{
color: #E9F0F9 !important;
-webkit-text-fill-color: #E9F0F9 !important;
background: {NAVY2} !important; }}
[data-testid="stNumberInputContainer"] button {{ background: {NAVY2}; }}
[data-testid="stNumberInputContainer"] button svg {{ fill: #E9F0F9; }}
hr {{ border-color: {NAVY2}; }}
.fb-eyebrow {{ color: #9AB4D4 !important; }}
.fb-sub {{ color: #B9C9DE !important; }}
.fb-chip {{ background: {NAVY2} !important; color: #D7E3F2 !important;
border-color: #2C4A7C !important; }}
div[data-baseweb="tab-list"] {{ gap: .35rem; }}
button[data-baseweb="tab"] {{
background: {NAVY2}; border: 1px solid #2C4A7C;
border-radius: 2px; padding: .6rem 1.05rem; }}
button[data-baseweb="tab"][aria-selected="true"] {{
background: {BLUE}; border-color: {BLUE}; }}
div[data-baseweb="tab-highlight"],
div[data-baseweb="tab-border"] {{ display: none; }}
"""
else:
_css = f"""
.stApp {{ background: {WHITE}; color: {NAVY}; --fb-pg-bg:#F4F8FC;
--fb-pg-copy:#446083; --fb-pg-strong:#16315E; }}
header[data-testid="stHeader"] {{ background: rgba(255,255,255,0.9); }}
button[data-baseweb="tab"] p {{ color: #5B7693; font-weight: 600; }}
button[data-baseweb="tab"][aria-selected="true"] p {{ color: {BLUE}; }}
[data-testid="stAlertContainer"] {{
background: #F4F8FC; color: #13294B; border-left: 4px solid {BLUE}; }}
.fb-eyebrow {{ color: #6E89A8; }}
.fb-sub {{ color: #446083; }}
.fb-chip {{ background: #F0F5FB; color: #2A4A74; border-color: #D6E2F0; }}
div[data-baseweb="tab-list"] {{ gap: .35rem; }}
button[data-baseweb="tab"] {{
background: #F0F5FB; border: 1px solid #C9D6E8;
border-radius: 2px; padding: .6rem 1.05rem; }}
button[data-baseweb="tab"][aria-selected="true"] {{