Spaces:
Running
Running
Commit ·
6cbe52d
0
Parent(s):
added
Browse files- .dockerignore +8 -0
- .gitattributes +2 -0
- .gitignore +8 -0
- Dockerfile +62 -0
- README.md +37 -0
- app.py +205 -0
- ckp/.gitkeep +0 -0
- config/substrate_settings.json +1 -0
- models/__init__.py +1 -0
- models/blocks.py +26 -0
- models/cbam.py +50 -0
- models/s2f_model.py +435 -0
- predictor.py +164 -0
- requirements.txt +10 -0
- sample/.gitkeep +0 -0
- utils/__init__.py +1 -0
- utils/config.py +3 -0
- utils/metrics.py +447 -0
- utils/substrate_settings.py +129 -0
.dockerignore
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
.git
|
| 2 |
+
.gitignore
|
| 3 |
+
__pycache__
|
| 4 |
+
*.py[cod]
|
| 5 |
+
.venv
|
| 6 |
+
venv
|
| 7 |
+
.DS_Store
|
| 8 |
+
ckp/*.pth
|
.gitattributes
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
|
|
|
|
|
|
|
| 1 |
+
*.tif filter=lfs diff=lfs merge=lfs -text
|
| 2 |
+
*.tiff filter=lfs diff=lfs merge=lfs -text
|
.gitignore
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
__pycache__
|
| 2 |
+
*.py[cod]
|
| 3 |
+
.venv
|
| 4 |
+
venv
|
| 5 |
+
.DS_Store
|
| 6 |
+
ckp/*.pth
|
| 7 |
+
sample/*.tif
|
| 8 |
+
sample/*.tiff
|
Dockerfile
ADDED
|
@@ -0,0 +1,62 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Shape2Force (S2F) - Hugging Face Spaces
|
| 2 |
+
FROM python:3.10-slim
|
| 3 |
+
|
| 4 |
+
# Create user for HF Spaces (runs as UID 1000)
|
| 5 |
+
RUN useradd -m -u 1000 user
|
| 6 |
+
|
| 7 |
+
WORKDIR /app
|
| 8 |
+
|
| 9 |
+
# Install system deps for OpenCV
|
| 10 |
+
RUN apt-get update && apt-get install -y --no-install-recommends \
|
| 11 |
+
libgl1-mesa-glx \
|
| 12 |
+
libglib2.0-0 \
|
| 13 |
+
&& rm -rf /var/lib/apt/lists/*
|
| 14 |
+
|
| 15 |
+
# Copy requirements first for better caching
|
| 16 |
+
COPY requirements.txt .
|
| 17 |
+
|
| 18 |
+
# Install Python dependencies (exclude heavy training deps for smaller image)
|
| 19 |
+
RUN pip install --no-cache-dir \
|
| 20 |
+
torch torchvision \
|
| 21 |
+
numpy opencv-python streamlit matplotlib Pillow plotly \
|
| 22 |
+
huggingface_hub
|
| 23 |
+
|
| 24 |
+
# Copy app code (chown for HF Spaces permissions)
|
| 25 |
+
COPY --chown=user:user app.py predictor.py ./
|
| 26 |
+
COPY --chown=user:user models/ models/
|
| 27 |
+
COPY --chown=user:user utils/ utils/
|
| 28 |
+
COPY --chown=user:user config/ config/
|
| 29 |
+
COPY --chown=user:user sample/ sample/
|
| 30 |
+
RUN mkdir -p ckp && chown user:user ckp
|
| 31 |
+
|
| 32 |
+
# Download checkpoints from Hugging Face if ckp is empty (for Space deployment)
|
| 33 |
+
# Set HF_MODEL_REPO env to your model repo, e.g. kaveh/Shape2Force
|
| 34 |
+
ARG HF_MODEL_REPO=kaveh/Shape2Force
|
| 35 |
+
ENV HF_MODEL_REPO=${HF_MODEL_REPO}
|
| 36 |
+
|
| 37 |
+
RUN python -c "
|
| 38 |
+
import os
|
| 39 |
+
from pathlib import Path
|
| 40 |
+
ckp = Path('/app/ckp')
|
| 41 |
+
if not list(ckp.glob('*.pth')):
|
| 42 |
+
try:
|
| 43 |
+
from huggingface_hub import hf_hub_download, list_repo_files
|
| 44 |
+
repo = os.environ.get('HF_MODEL_REPO', 'kaveh/Shape2Force')
|
| 45 |
+
files = list_repo_files(repo)
|
| 46 |
+
pth_files = [f for f in files if f.startswith('ckp/') and f.endswith('.pth')]
|
| 47 |
+
for f in pth_files:
|
| 48 |
+
hf_hub_download(repo_id=repo, filename=f, local_dir='/app')
|
| 49 |
+
print('Downloaded checkpoints from', repo)
|
| 50 |
+
except Exception as e:
|
| 51 |
+
print('Could not download checkpoints:', e)
|
| 52 |
+
else:
|
| 53 |
+
print('Checkpoints already present')
|
| 54 |
+
"
|
| 55 |
+
|
| 56 |
+
# Ensure ckp contents are readable by user
|
| 57 |
+
RUN chown -R user:user ckp
|
| 58 |
+
|
| 59 |
+
USER user
|
| 60 |
+
|
| 61 |
+
EXPOSE 8501
|
| 62 |
+
CMD ["streamlit", "run", "app.py", "--server.port=8501", "--server.address=0.0.0.0"]
|
README.md
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
tags:
|
| 3 |
+
- cell-mechanobiology
|
| 4 |
+
- microscopy
|
| 5 |
+
- image-to-image
|
| 6 |
+
- pytorch
|
| 7 |
+
license: cc-by-4.0
|
| 8 |
+
sdk: docker
|
| 9 |
+
app_port: 8501
|
| 10 |
+
---
|
| 11 |
+
|
| 12 |
+
# Shape2Force (S2F) App
|
| 13 |
+
|
| 14 |
+
Predict force maps from bright-field microscopy images using deep learning.
|
| 15 |
+
|
| 16 |
+
## Quick Start
|
| 17 |
+
|
| 18 |
+
```bash
|
| 19 |
+
pip install -r requirements.txt
|
| 20 |
+
streamlit run app.py
|
| 21 |
+
```
|
| 22 |
+
|
| 23 |
+
Checkpoints are downloaded automatically from the [Shape2Force model repo](https://huggingface.co/kaveh/Shape2Force) when running in Docker. For local use, place `.pth` files in `ckp/`.
|
| 24 |
+
|
| 25 |
+
## Usage
|
| 26 |
+
|
| 27 |
+
1. Choose **Model type**: Single cell or Spheroid
|
| 28 |
+
2. Select a **Checkpoint** from `ckp/`
|
| 29 |
+
3. For single-cell: pick **Substrate** (e.g. fibroblasts_PDMS)
|
| 30 |
+
4. Upload an image or pick from `sample/`
|
| 31 |
+
5. Click **Run prediction**
|
| 32 |
+
|
| 33 |
+
Output: heatmap, cell force (sum), and basic stats.
|
| 34 |
+
|
| 35 |
+
## Full Project
|
| 36 |
+
|
| 37 |
+
For training, evaluation, and notebooks, see the main [Shape2Force repository](https://github.com/Angione-Lab/Shape2Force).
|
app.py
ADDED
|
@@ -0,0 +1,205 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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+
"""
|
| 4 |
+
import os
|
| 5 |
+
import sys
|
| 6 |
+
import io
|
| 7 |
+
import cv2
|
| 8 |
+
cv2.utils.logging.setLogLevel(cv2.utils.logging.LOG_LEVEL_ERROR)
|
| 9 |
+
|
| 10 |
+
import numpy as np
|
| 11 |
+
import streamlit as st
|
| 12 |
+
from PIL import Image
|
| 13 |
+
import plotly.graph_objects as go
|
| 14 |
+
from plotly.subplots import make_subplots
|
| 15 |
+
|
| 16 |
+
# Ensure S2F is in path
|
| 17 |
+
S2F_ROOT = os.path.dirname(os.path.abspath(__file__))
|
| 18 |
+
if S2F_ROOT not in sys.path:
|
| 19 |
+
sys.path.insert(0, S2F_ROOT)
|
| 20 |
+
|
| 21 |
+
from predictor import S2FPredictor
|
| 22 |
+
from utils.substrate_settings import list_substrates
|
| 23 |
+
|
| 24 |
+
st.set_page_config(page_title="Shape2Force (S2F)", page_icon="🔬", layout="centered")
|
| 25 |
+
st.markdown("""
|
| 26 |
+
<style>
|
| 27 |
+
section[data-testid="stSidebar"] { width: 380px !important; }
|
| 28 |
+
</style>
|
| 29 |
+
""", unsafe_allow_html=True)
|
| 30 |
+
st.title("🔬 Shape2Force (S2F)")
|
| 31 |
+
st.caption("Predict force maps from bright field microscopy images")
|
| 32 |
+
|
| 33 |
+
# Folders
|
| 34 |
+
ckp_folder = os.path.join(S2F_ROOT, "ckp")
|
| 35 |
+
sample_folder = os.path.join(S2F_ROOT, "sample")
|
| 36 |
+
ckp_files = []
|
| 37 |
+
if os.path.isdir(ckp_folder):
|
| 38 |
+
ckp_files = sorted([f for f in os.listdir(ckp_folder) if f.endswith(".pth")])
|
| 39 |
+
SAMPLE_EXTENSIONS = (".tif", ".tiff", ".png", ".jpg", ".jpeg")
|
| 40 |
+
sample_files = []
|
| 41 |
+
if os.path.isdir(sample_folder):
|
| 42 |
+
sample_files = sorted([f for f in os.listdir(sample_folder)
|
| 43 |
+
if f.lower().endswith(SAMPLE_EXTENSIONS)])
|
| 44 |
+
|
| 45 |
+
# Sidebar: model configuration
|
| 46 |
+
with st.sidebar:
|
| 47 |
+
st.header("Model configuration")
|
| 48 |
+
model_type = st.radio(
|
| 49 |
+
"Model type",
|
| 50 |
+
["single_cell", "spheroid"],
|
| 51 |
+
format_func=lambda x: "Single cell" if x == "single_cell" else "Spheroid",
|
| 52 |
+
horizontal=False,
|
| 53 |
+
)
|
| 54 |
+
|
| 55 |
+
if ckp_files:
|
| 56 |
+
checkpoint = st.selectbox(
|
| 57 |
+
"Checkpoint",
|
| 58 |
+
ckp_files,
|
| 59 |
+
help="Select a .pth file from the ckp folder",
|
| 60 |
+
)
|
| 61 |
+
else:
|
| 62 |
+
st.warning("No .pth files in ckp/ folder. Add checkpoints to load.")
|
| 63 |
+
checkpoint = None
|
| 64 |
+
|
| 65 |
+
substrate_config = None
|
| 66 |
+
substrate_val = "fibroblasts_PDMS"
|
| 67 |
+
use_manual = False
|
| 68 |
+
if model_type == "single_cell":
|
| 69 |
+
try:
|
| 70 |
+
substrates = list_substrates()
|
| 71 |
+
substrate_val = st.selectbox(
|
| 72 |
+
"Substrate (from config)",
|
| 73 |
+
substrates,
|
| 74 |
+
help="Select a preset from config/substrate_settings.json",
|
| 75 |
+
)
|
| 76 |
+
use_manual = st.checkbox("Enter substrate values manually", value=False)
|
| 77 |
+
if use_manual:
|
| 78 |
+
st.caption("Enter pixelsize (µm/px) and Young's modulus (Pa)")
|
| 79 |
+
manual_pixelsize = st.number_input("Pixelsize (µm/px)", min_value=0.1, max_value=50.0,
|
| 80 |
+
value=3.0769, step=0.1, format="%.4f")
|
| 81 |
+
manual_young = st.number_input("Young's modulus (Pa)", min_value=100.0, max_value=100000.0,
|
| 82 |
+
value=6000.0, step=100.0, format="%.0f")
|
| 83 |
+
substrate_config = {"pixelsize": manual_pixelsize, "young": manual_young}
|
| 84 |
+
else:
|
| 85 |
+
substrate_config = None
|
| 86 |
+
except FileNotFoundError:
|
| 87 |
+
st.error("config/substrate_settings.json not found")
|
| 88 |
+
|
| 89 |
+
st.divider()
|
| 90 |
+
st.subheader("Display")
|
| 91 |
+
display_size = st.slider("Image size (px)", min_value=200, max_value=800, value=350, step=50,
|
| 92 |
+
help="Adjust display size. Drag to pan, scroll to zoom.")
|
| 93 |
+
|
| 94 |
+
st.divider()
|
| 95 |
+
|
| 96 |
+
# Main area: image input
|
| 97 |
+
img_source = st.radio("Image source", ["Upload", "Sample"], horizontal=True, label_visibility="collapsed")
|
| 98 |
+
img = None
|
| 99 |
+
uploaded = None
|
| 100 |
+
selected_sample = None
|
| 101 |
+
|
| 102 |
+
if img_source == "Upload":
|
| 103 |
+
uploaded = st.file_uploader(
|
| 104 |
+
"Upload bright field image",
|
| 105 |
+
type=["tif", "tiff", "png", "jpg", "jpeg"],
|
| 106 |
+
help="Bright field microscopy image (grayscale or RGB)",
|
| 107 |
+
)
|
| 108 |
+
if uploaded:
|
| 109 |
+
bytes_data = uploaded.read()
|
| 110 |
+
nparr = np.frombuffer(bytes_data, np.uint8)
|
| 111 |
+
img = cv2.imdecode(nparr, cv2.IMREAD_GRAYSCALE)
|
| 112 |
+
uploaded.seek(0) # reset for potential re-read
|
| 113 |
+
else:
|
| 114 |
+
if sample_files:
|
| 115 |
+
selected_sample = st.selectbox(
|
| 116 |
+
"Select sample image",
|
| 117 |
+
sample_files,
|
| 118 |
+
format_func=lambda x: x,
|
| 119 |
+
)
|
| 120 |
+
if selected_sample:
|
| 121 |
+
sample_path = os.path.join(sample_folder, selected_sample)
|
| 122 |
+
img = cv2.imread(sample_path, cv2.IMREAD_GRAYSCALE)
|
| 123 |
+
# Show sample thumbnails
|
| 124 |
+
st.caption("Sample images (add more to the `sample/` folder)")
|
| 125 |
+
n_cols = min(4, len(sample_files))
|
| 126 |
+
cols = st.columns(n_cols)
|
| 127 |
+
for i, fname in enumerate(sample_files[:8]): # show up to 8
|
| 128 |
+
with cols[i % n_cols]:
|
| 129 |
+
path = os.path.join(sample_folder, fname)
|
| 130 |
+
sample_img = cv2.imread(path, cv2.IMREAD_GRAYSCALE)
|
| 131 |
+
if sample_img is not None:
|
| 132 |
+
st.image(sample_img, caption=fname, width='content')
|
| 133 |
+
else:
|
| 134 |
+
st.info("No sample images found. Add images to the `sample/` folder, or use Upload.")
|
| 135 |
+
|
| 136 |
+
run = st.button("Run prediction", type="primary")
|
| 137 |
+
has_image = img is not None
|
| 138 |
+
|
| 139 |
+
if run and checkpoint and has_image:
|
| 140 |
+
with st.spinner("Loading model and predicting..."):
|
| 141 |
+
try:
|
| 142 |
+
predictor = S2FPredictor(
|
| 143 |
+
model_type=model_type,
|
| 144 |
+
checkpoint_path=checkpoint,
|
| 145 |
+
ckp_folder=ckp_folder,
|
| 146 |
+
)
|
| 147 |
+
if img is not None:
|
| 148 |
+
sub_val = substrate_val if model_type == "single_cell" and not use_manual else "fibroblasts_PDMS"
|
| 149 |
+
heatmap, force, pixel_sum = predictor.predict(
|
| 150 |
+
image_array=img,
|
| 151 |
+
substrate=sub_val,
|
| 152 |
+
substrate_config=substrate_config if model_type == "single_cell" else None,
|
| 153 |
+
)
|
| 154 |
+
|
| 155 |
+
st.success("Prediction complete!")
|
| 156 |
+
|
| 157 |
+
# Metrics
|
| 158 |
+
col1, col2, col3, col4 = st.columns(4)
|
| 159 |
+
with col1:
|
| 160 |
+
st.metric("Sum of all pixels", f"{pixel_sum:.2f}")
|
| 161 |
+
with col2:
|
| 162 |
+
st.metric("Cell force (scaled)", f"{force:.2f}")
|
| 163 |
+
with col3:
|
| 164 |
+
st.metric("Heatmap max", f"{np.max(heatmap):.4f}")
|
| 165 |
+
with col4:
|
| 166 |
+
st.metric("Heatmap mean", f"{np.mean(heatmap):.4f}")
|
| 167 |
+
|
| 168 |
+
# Visualization - Plotly with zoom/pan
|
| 169 |
+
fig_pl = make_subplots(rows=1, cols=2, subplot_titles=["", ""])
|
| 170 |
+
fig_pl.add_trace(go.Heatmap(z=img, colorscale="gray", showscale=False), row=1, col=1)
|
| 171 |
+
fig_pl.add_trace(go.Heatmap(z=heatmap, colorscale="Jet", zmin=0, zmax=1, showscale=True), row=1, col=2)
|
| 172 |
+
fig_pl.update_layout(
|
| 173 |
+
height=display_size,
|
| 174 |
+
margin=dict(l=10, r=10, t=10, b=10),
|
| 175 |
+
xaxis=dict(scaleanchor="y", scaleratio=1),
|
| 176 |
+
xaxis2=dict(scaleanchor="y2", scaleratio=1),
|
| 177 |
+
)
|
| 178 |
+
fig_pl.update_xaxes(showticklabels=False)
|
| 179 |
+
fig_pl.update_yaxes(showticklabels=False, autorange="reversed")
|
| 180 |
+
st.plotly_chart(fig_pl, use_container_width=True)
|
| 181 |
+
|
| 182 |
+
# Download
|
| 183 |
+
heatmap_uint8 = (np.clip(heatmap, 0, 1) * 255).astype(np.uint8)
|
| 184 |
+
heatmap_rgb = cv2.applyColorMap(heatmap_uint8, cv2.COLORMAP_JET)
|
| 185 |
+
heatmap_rgb = cv2.cvtColor(heatmap_rgb, cv2.COLOR_BGR2RGB)
|
| 186 |
+
pil_heatmap = Image.fromarray(heatmap_rgb)
|
| 187 |
+
buf_hm = io.BytesIO()
|
| 188 |
+
pil_heatmap.save(buf_hm, format="PNG")
|
| 189 |
+
buf_hm.seek(0)
|
| 190 |
+
st.download_button("Download Heatmap", data=buf_hm.getvalue(),
|
| 191 |
+
file_name="s2f_heatmap.png", mime="image/png")
|
| 192 |
+
|
| 193 |
+
except Exception as e:
|
| 194 |
+
st.error(f"Prediction failed: {e}")
|
| 195 |
+
import traceback
|
| 196 |
+
st.code(traceback.format_exc())
|
| 197 |
+
|
| 198 |
+
elif run and not checkpoint:
|
| 199 |
+
st.warning("Please add checkpoint files to the ckp/ folder and select one.")
|
| 200 |
+
elif run and not has_image:
|
| 201 |
+
st.warning("Please upload an image or select a sample.")
|
| 202 |
+
|
| 203 |
+
# Footer
|
| 204 |
+
st.sidebar.divider()
|
| 205 |
+
st.sidebar.caption("Place .pth checkpoints in the ckp/ folder")
|
ckp/.gitkeep
ADDED
|
File without changes
|
config/substrate_settings.json
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
{"substrates":{"fibroblasts_PDMS":{"name":"Fibroblasts on PDMS (6 kPa)","pixelsize":3.0769,"young":6000},"U2OS_PDMS":{"name":"U2OS cells on PDMS (6 kPa)","pixelsize":6.1538,"young":6000},"PDMS_1kPa":{"name":"PDMS soft hydrogel (1 kPa, 10 µm/px)","pixelsize":9.8138,"young":1000},"PDMS_10kPa":{"name":"PDMS stiff hydrogel (10 kPa, 10 µm/px)","pixelsize":9.8138,"young":10000},"PDMS_1kPa_3um":{"name":"PDMS soft hydrogel (1 kPa, 3 µm/px)","pixelsize":3.0769,"young":1000},"PDMS_10kPa_3um":{"name":"PDMS stiff hydrogel (10 kPa, 3 µm/px)","pixelsize":3.0769,"young":10000}},"default_substrate":"fibroblasts_PDMS"}
|
models/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
from .s2f_model import create_s2f_model, S2FGenerator
|
models/blocks.py
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch.nn as nn
|
| 2 |
+
import torch
|
| 3 |
+
|
| 4 |
+
|
| 5 |
+
class ResidualBlock(nn.Module):
|
| 6 |
+
def __init__(self, in_channels, out_channels):
|
| 7 |
+
super(ResidualBlock, self).__init__()
|
| 8 |
+
self.conv1 = nn.Conv2d(in_channels, out_channels, kernel_size=3, padding=1)
|
| 9 |
+
self.bn1 = nn.BatchNorm2d(out_channels)
|
| 10 |
+
self.conv2 = nn.Conv2d(out_channels, out_channels, kernel_size=3, padding=1)
|
| 11 |
+
self.bn2 = nn.BatchNorm2d(out_channels)
|
| 12 |
+
self.relu = nn.ReLU(inplace=True)
|
| 13 |
+
self.downsample = nn.Conv2d(in_channels, out_channels, kernel_size=1) if in_channels != out_channels else None
|
| 14 |
+
|
| 15 |
+
def forward(self, x):
|
| 16 |
+
residual = x
|
| 17 |
+
out = self.conv1(x)
|
| 18 |
+
out = self.bn1(out)
|
| 19 |
+
out = self.relu(out)
|
| 20 |
+
out = self.conv2(out)
|
| 21 |
+
out = self.bn2(out)
|
| 22 |
+
if self.downsample:
|
| 23 |
+
residual = self.downsample(x)
|
| 24 |
+
out += residual
|
| 25 |
+
out = self.relu(out)
|
| 26 |
+
return out
|
models/cbam.py
ADDED
|
@@ -0,0 +1,50 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
import torch.nn as nn
|
| 3 |
+
import torch.nn.functional as F
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
class ChannelAttention(nn.Module):
|
| 7 |
+
def __init__(self, in_planes, ratio=16):
|
| 8 |
+
super(ChannelAttention, self).__init__()
|
| 9 |
+
self.avg_pool = nn.AdaptiveAvgPool2d(1)
|
| 10 |
+
self.max_pool = nn.AdaptiveMaxPool2d(1)
|
| 11 |
+
|
| 12 |
+
self.fc = nn.Sequential(
|
| 13 |
+
nn.Conv2d(in_planes, in_planes // ratio, 1, bias=False),
|
| 14 |
+
nn.ReLU(),
|
| 15 |
+
nn.Conv2d(in_planes // ratio, in_planes, 1, bias=False)
|
| 16 |
+
)
|
| 17 |
+
self.sigmoid = nn.Sigmoid()
|
| 18 |
+
|
| 19 |
+
def forward(self, x):
|
| 20 |
+
avg_out = self.fc(self.avg_pool(x))
|
| 21 |
+
max_out = self.fc(self.max_pool(x))
|
| 22 |
+
out = avg_out + max_out
|
| 23 |
+
return self.sigmoid(out)
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
class SpatialAttention(nn.Module):
|
| 27 |
+
def __init__(self, kernel_size=7):
|
| 28 |
+
super(SpatialAttention, self).__init__()
|
| 29 |
+
padding = kernel_size // 2
|
| 30 |
+
self.conv = nn.Conv2d(2, 1, kernel_size, padding=padding, bias=False)
|
| 31 |
+
self.sigmoid = nn.Sigmoid()
|
| 32 |
+
|
| 33 |
+
def forward(self, x):
|
| 34 |
+
avg_out = torch.mean(x, dim=1, keepdim=True)
|
| 35 |
+
max_out, _ = torch.max(x, dim=1, keepdim=True)
|
| 36 |
+
x = torch.cat([avg_out, max_out], dim=1)
|
| 37 |
+
x = self.conv(x)
|
| 38 |
+
return self.sigmoid(x)
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
class CBAM(nn.Module):
|
| 42 |
+
def __init__(self, in_planes, ratio=16, kernel_size=7):
|
| 43 |
+
super(CBAM, self).__init__()
|
| 44 |
+
self.channel_attention = ChannelAttention(in_planes, ratio)
|
| 45 |
+
self.spatial_attention = SpatialAttention(kernel_size)
|
| 46 |
+
|
| 47 |
+
def forward(self, x):
|
| 48 |
+
x = x * self.channel_attention(x)
|
| 49 |
+
x = x * self.spatial_attention(x)
|
| 50 |
+
return x
|
models/s2f_model.py
ADDED
|
@@ -0,0 +1,435 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
S2F (Shape2Force) model for force map prediction (inference only).
|
| 3 |
+
Supports single-cell and spheroid modes.
|
| 4 |
+
"""
|
| 5 |
+
import torch
|
| 6 |
+
import torch.nn as nn
|
| 7 |
+
import torch.nn.functional as F
|
| 8 |
+
from .blocks import ResidualBlock
|
| 9 |
+
from .cbam import CBAM
|
| 10 |
+
|
| 11 |
+
from utils import config
|
| 12 |
+
from utils.substrate_settings import (
|
| 13 |
+
get_settings_of_category,
|
| 14 |
+
compute_settings_normalization,
|
| 15 |
+
load_substrate_config,
|
| 16 |
+
)
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
def normalize_settings(substrate_name, normalization_params, config=None, config_path=None):
|
| 20 |
+
"""
|
| 21 |
+
Normalize settings for a given substrate.
|
| 22 |
+
|
| 23 |
+
Args:
|
| 24 |
+
substrate_name (str): Name of the substrate
|
| 25 |
+
normalization_params (dict): Normalization parameters
|
| 26 |
+
|
| 27 |
+
Returns:
|
| 28 |
+
tuple: (normalized_pixelsize, normalized_young)
|
| 29 |
+
"""
|
| 30 |
+
settings = get_settings_of_category(substrate_name, config=config, config_path=config_path)
|
| 31 |
+
|
| 32 |
+
# Min-max normalization to [0, 1]
|
| 33 |
+
pixelsize_norm = (settings['pixelsize'] - normalization_params['pixelsize']['min']) / \
|
| 34 |
+
(normalization_params['pixelsize']['max'] - normalization_params['pixelsize']['min'])
|
| 35 |
+
|
| 36 |
+
young_norm = (settings['young'] - normalization_params['young']['min']) / \
|
| 37 |
+
(normalization_params['young']['max'] - normalization_params['young']['min'])
|
| 38 |
+
|
| 39 |
+
return pixelsize_norm, young_norm
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
def create_settings_channels(metadata, normalization_params, device, image_shape, config_path=None):
|
| 43 |
+
"""
|
| 44 |
+
Create settings channels for a batch of images.
|
| 45 |
+
|
| 46 |
+
Args:
|
| 47 |
+
metadata (dict): Batch metadata containing substrate information
|
| 48 |
+
normalization_params (dict): Normalization parameters
|
| 49 |
+
device: Device to create tensors on
|
| 50 |
+
image_shape (tuple): Shape of input images (B, C, H, W)
|
| 51 |
+
|
| 52 |
+
Returns:
|
| 53 |
+
torch.Tensor: Settings channels [B, 2, H, W] where channels are [pixelsize, young]
|
| 54 |
+
"""
|
| 55 |
+
batch_size, _, height, width = image_shape
|
| 56 |
+
|
| 57 |
+
# Create settings channels
|
| 58 |
+
pixelsize_channel = torch.zeros(batch_size, 1, height, width, device=device)
|
| 59 |
+
young_channel = torch.zeros(batch_size, 1, height, width, device=device)
|
| 60 |
+
|
| 61 |
+
for i in range(batch_size):
|
| 62 |
+
substrate = metadata['substrate'][i]
|
| 63 |
+
pixelsize_norm, young_norm = normalize_settings(
|
| 64 |
+
substrate, normalization_params, config_path=config_path
|
| 65 |
+
)
|
| 66 |
+
|
| 67 |
+
# Fill entire channel with normalized value
|
| 68 |
+
pixelsize_channel[i, 0] = pixelsize_norm
|
| 69 |
+
young_channel[i, 0] = young_norm
|
| 70 |
+
|
| 71 |
+
# Concatenate channels
|
| 72 |
+
settings_channels = torch.cat([pixelsize_channel, young_channel], dim=1) # [B, 2, H, W]
|
| 73 |
+
|
| 74 |
+
return settings_channels
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
class GlobalContextModule(nn.Module):
|
| 78 |
+
"""Global context module for capturing cell shape information"""
|
| 79 |
+
def __init__(self, in_channels):
|
| 80 |
+
super().__init__()
|
| 81 |
+
self.global_pool = nn.AdaptiveAvgPool2d(1)
|
| 82 |
+
self.global_conv = nn.Sequential(
|
| 83 |
+
nn.Conv2d(in_channels, in_channels//4, 1),
|
| 84 |
+
nn.ReLU(inplace=True),
|
| 85 |
+
nn.Conv2d(in_channels//4, in_channels, 1),
|
| 86 |
+
nn.Sigmoid()
|
| 87 |
+
)
|
| 88 |
+
self.large_kernel = nn.Sequential(
|
| 89 |
+
nn.Conv2d(in_channels, in_channels, 3, padding=1, groups=in_channels),
|
| 90 |
+
nn.Conv2d(in_channels, in_channels, 1),
|
| 91 |
+
nn.BatchNorm2d(in_channels),
|
| 92 |
+
nn.ReLU(inplace=True)
|
| 93 |
+
)
|
| 94 |
+
self.multi_scale = nn.ModuleList([
|
| 95 |
+
nn.Conv2d(in_channels, in_channels//4, 3, padding=1, dilation=1),
|
| 96 |
+
nn.Conv2d(in_channels, in_channels//4, 3, padding=2, dilation=2),
|
| 97 |
+
nn.Conv2d(in_channels, in_channels//4, 3, padding=4, dilation=4),
|
| 98 |
+
nn.Conv2d(in_channels, in_channels//4, 3, padding=8, dilation=8)
|
| 99 |
+
])
|
| 100 |
+
self.fusion = nn.Conv2d(in_channels, in_channels, 1)
|
| 101 |
+
|
| 102 |
+
def forward(self, x):
|
| 103 |
+
global_ctx = self.global_pool(x)
|
| 104 |
+
global_weight = self.global_conv(global_ctx)
|
| 105 |
+
large_features = self.large_kernel(x)
|
| 106 |
+
multi_scale_features = []
|
| 107 |
+
for conv in self.multi_scale:
|
| 108 |
+
multi_scale_features.append(conv(x))
|
| 109 |
+
multi_scale_out = torch.cat(multi_scale_features, dim=1)
|
| 110 |
+
multi_scale_out = self.fusion(multi_scale_out)
|
| 111 |
+
return x + (large_features * global_weight) + multi_scale_out
|
| 112 |
+
|
| 113 |
+
|
| 114 |
+
class HierarchicalAttention(nn.Module):
|
| 115 |
+
"""Hierarchical attention combining spatial and channel attention"""
|
| 116 |
+
def __init__(self, channels):
|
| 117 |
+
super().__init__()
|
| 118 |
+
self.spatial_att = nn.Sequential(
|
| 119 |
+
nn.Conv2d(channels, channels//8, 1),
|
| 120 |
+
nn.Conv2d(channels//8, 1, 3, padding=1),
|
| 121 |
+
nn.Sigmoid()
|
| 122 |
+
)
|
| 123 |
+
self.channel_att = nn.Sequential(
|
| 124 |
+
nn.AdaptiveAvgPool2d(1),
|
| 125 |
+
nn.Conv2d(channels, channels//16, 1),
|
| 126 |
+
nn.ReLU(inplace=True),
|
| 127 |
+
nn.Conv2d(channels//16, channels, 1),
|
| 128 |
+
nn.Sigmoid()
|
| 129 |
+
)
|
| 130 |
+
self.cross_att = nn.Sequential(
|
| 131 |
+
nn.Conv2d(channels, channels//4, 1),
|
| 132 |
+
nn.BatchNorm2d(channels//4),
|
| 133 |
+
nn.ReLU(inplace=True),
|
| 134 |
+
nn.Conv2d(channels//4, channels, 1),
|
| 135 |
+
nn.Sigmoid()
|
| 136 |
+
)
|
| 137 |
+
|
| 138 |
+
def forward(self, x):
|
| 139 |
+
spatial_weight = self.spatial_att(x)
|
| 140 |
+
channel_weight = self.channel_att(x)
|
| 141 |
+
attended = x * spatial_weight * channel_weight
|
| 142 |
+
cross_weight = self.cross_att(attended)
|
| 143 |
+
return x + (attended * cross_weight)
|
| 144 |
+
|
| 145 |
+
|
| 146 |
+
class EnhancedAttentionGate(nn.Module):
|
| 147 |
+
"""Enhanced attention gate with global context"""
|
| 148 |
+
def __init__(self, F_g, F_l, F_int):
|
| 149 |
+
super().__init__()
|
| 150 |
+
self.W_g = nn.Sequential(
|
| 151 |
+
nn.Conv2d(F_g, F_int, kernel_size=1),
|
| 152 |
+
nn.BatchNorm2d(F_int)
|
| 153 |
+
)
|
| 154 |
+
self.W_x = nn.Sequential(
|
| 155 |
+
nn.Conv2d(F_l, F_int, kernel_size=1),
|
| 156 |
+
nn.BatchNorm2d(F_int)
|
| 157 |
+
)
|
| 158 |
+
self.psi = nn.Sequential(
|
| 159 |
+
nn.ReLU(inplace=True),
|
| 160 |
+
nn.Conv2d(F_int, F_int//2, kernel_size=3, padding=1),
|
| 161 |
+
nn.BatchNorm2d(F_int//2),
|
| 162 |
+
nn.ReLU(inplace=True),
|
| 163 |
+
nn.Conv2d(F_int//2, 1, kernel_size=1),
|
| 164 |
+
nn.Sigmoid()
|
| 165 |
+
)
|
| 166 |
+
self.global_context = nn.Sequential(
|
| 167 |
+
nn.AdaptiveAvgPool2d(1),
|
| 168 |
+
nn.Conv2d(F_l, F_int//4, 1),
|
| 169 |
+
nn.ReLU(inplace=True),
|
| 170 |
+
nn.Conv2d(F_int//4, 1, 1),
|
| 171 |
+
nn.Sigmoid()
|
| 172 |
+
)
|
| 173 |
+
|
| 174 |
+
def forward(self, g, x):
|
| 175 |
+
g1 = self.W_g(g)
|
| 176 |
+
x1 = self.W_x(x)
|
| 177 |
+
if g1.shape[2:] != x1.shape[2:]:
|
| 178 |
+
g1 = F.interpolate(g1, size=x1.shape[2:], mode='bilinear', align_corners=False)
|
| 179 |
+
psi = self.psi(g1 + x1)
|
| 180 |
+
global_weight = self.global_context(x)
|
| 181 |
+
psi = psi * global_weight
|
| 182 |
+
if psi.shape[2:] != x.shape[2:]:
|
| 183 |
+
psi = F.interpolate(psi, size=x.shape[2:], mode='bilinear', align_corners=False)
|
| 184 |
+
return x * psi
|
| 185 |
+
|
| 186 |
+
|
| 187 |
+
class S2FGenerator(nn.Module):
|
| 188 |
+
"""
|
| 189 |
+
S2F (Shape2Force) model: U-Net generator for force map prediction.
|
| 190 |
+
Supports substrate-specific settings as additional input channels.
|
| 191 |
+
"""
|
| 192 |
+
def __init__(self,
|
| 193 |
+
in_channels=1,
|
| 194 |
+
out_channels=1,
|
| 195 |
+
img_size=1024,
|
| 196 |
+
bridge_type='cbam',
|
| 197 |
+
use_multi_scale_input=True):
|
| 198 |
+
super().__init__()
|
| 199 |
+
|
| 200 |
+
self.img_size = img_size
|
| 201 |
+
self.bridge_type = bridge_type
|
| 202 |
+
self.use_multi_scale_input = use_multi_scale_input
|
| 203 |
+
|
| 204 |
+
if self.use_multi_scale_input:
|
| 205 |
+
self.scale_pyramid = nn.ModuleList([
|
| 206 |
+
nn.Conv2d(in_channels, 32, 3, padding=1),
|
| 207 |
+
nn.Sequential(
|
| 208 |
+
nn.AvgPool2d(2, stride=2),
|
| 209 |
+
nn.Conv2d(in_channels, 32, 3, padding=1)
|
| 210 |
+
),
|
| 211 |
+
nn.Sequential(
|
| 212 |
+
nn.AvgPool2d(4, stride=4),
|
| 213 |
+
nn.Conv2d(in_channels, 32, 3, padding=1)
|
| 214 |
+
)
|
| 215 |
+
])
|
| 216 |
+
self.initial_conv = nn.Conv2d(96, 64, 1)
|
| 217 |
+
else:
|
| 218 |
+
self.initial_conv = nn.Conv2d(in_channels, 64, 3, padding=1)
|
| 219 |
+
|
| 220 |
+
def enhanced_conv_block(in_c, out_c, use_attention=True):
|
| 221 |
+
layers = [
|
| 222 |
+
nn.Conv2d(in_c, out_c, 3, padding=1),
|
| 223 |
+
nn.BatchNorm2d(out_c),
|
| 224 |
+
nn.ReLU(inplace=True),
|
| 225 |
+
ResidualBlock(out_c, out_c)
|
| 226 |
+
]
|
| 227 |
+
if use_attention:
|
| 228 |
+
layers.append(HierarchicalAttention(out_c))
|
| 229 |
+
return nn.Sequential(*layers)
|
| 230 |
+
|
| 231 |
+
def dilated_conv_block(in_c, out_c, use_global_context=False):
|
| 232 |
+
layers = [
|
| 233 |
+
nn.Conv2d(in_c, out_c, 3, padding=2, dilation=2),
|
| 234 |
+
nn.BatchNorm2d(out_c),
|
| 235 |
+
nn.ReLU(inplace=True),
|
| 236 |
+
ResidualBlock(out_c, out_c)
|
| 237 |
+
]
|
| 238 |
+
if use_global_context:
|
| 239 |
+
layers.append(GlobalContextModule(out_c))
|
| 240 |
+
return nn.Sequential(*layers)
|
| 241 |
+
|
| 242 |
+
self.encoder1 = enhanced_conv_block(64, 64, use_attention=False)
|
| 243 |
+
self.pool1 = nn.MaxPool2d(2)
|
| 244 |
+
self.encoder2 = enhanced_conv_block(64, 128, use_attention=True)
|
| 245 |
+
self.pool2 = nn.MaxPool2d(2)
|
| 246 |
+
self.encoder3 = dilated_conv_block(128, 256, use_global_context=True)
|
| 247 |
+
self.pool3 = nn.MaxPool2d(2)
|
| 248 |
+
self.encoder4 = dilated_conv_block(256, 512, use_global_context=True)
|
| 249 |
+
self.pool4 = nn.MaxPool2d(2)
|
| 250 |
+
|
| 251 |
+
if bridge_type == 'cbam':
|
| 252 |
+
self.bridge = nn.Sequential(
|
| 253 |
+
dilated_conv_block(512, 1024, use_global_context=True),
|
| 254 |
+
CBAM(1024),
|
| 255 |
+
GlobalContextModule(1024),
|
| 256 |
+
HierarchicalAttention(1024)
|
| 257 |
+
)
|
| 258 |
+
else:
|
| 259 |
+
self.bridge = nn.Sequential(
|
| 260 |
+
dilated_conv_block(512, 1024, use_global_context=True),
|
| 261 |
+
GlobalContextModule(1024),
|
| 262 |
+
HierarchicalAttention(1024)
|
| 263 |
+
)
|
| 264 |
+
|
| 265 |
+
self.att4 = EnhancedAttentionGate(512, 512, 256)
|
| 266 |
+
self.att3 = EnhancedAttentionGate(256, 256, 128)
|
| 267 |
+
self.att2 = EnhancedAttentionGate(128, 128, 64)
|
| 268 |
+
self.att1 = EnhancedAttentionGate(64, 64, 32)
|
| 269 |
+
|
| 270 |
+
self.up4 = nn.ConvTranspose2d(1024, 512, kernel_size=2, stride=2)
|
| 271 |
+
self.dec4 = enhanced_conv_block(1024, 512, use_attention=True)
|
| 272 |
+
self.refine4 = HierarchicalAttention(512)
|
| 273 |
+
self.up3 = nn.ConvTranspose2d(512, 256, kernel_size=2, stride=2)
|
| 274 |
+
self.dec3 = enhanced_conv_block(512, 256, use_attention=True)
|
| 275 |
+
self.refine3 = HierarchicalAttention(256)
|
| 276 |
+
self.up2 = nn.ConvTranspose2d(256, 128, kernel_size=2, stride=2)
|
| 277 |
+
self.dec2 = enhanced_conv_block(256, 128, use_attention=True)
|
| 278 |
+
self.refine2 = HierarchicalAttention(128)
|
| 279 |
+
self.up1 = nn.ConvTranspose2d(128, 64, kernel_size=2, stride=2)
|
| 280 |
+
self.dec1 = enhanced_conv_block(128, 64, use_attention=True)
|
| 281 |
+
self.refine1 = HierarchicalAttention(64)
|
| 282 |
+
|
| 283 |
+
self.final_conv = nn.Sequential(
|
| 284 |
+
nn.Conv2d(64, 32, 3, padding=1),
|
| 285 |
+
nn.BatchNorm2d(32),
|
| 286 |
+
nn.ReLU(inplace=True),
|
| 287 |
+
nn.Conv2d(32, out_channels, 1),
|
| 288 |
+
nn.Tanh()
|
| 289 |
+
)
|
| 290 |
+
|
| 291 |
+
def forward(self, x):
|
| 292 |
+
if self.use_multi_scale_input:
|
| 293 |
+
scale_features = []
|
| 294 |
+
for i, scale_conv in enumerate(self.scale_pyramid):
|
| 295 |
+
if i == 0:
|
| 296 |
+
scale_features.append(scale_conv(x))
|
| 297 |
+
else:
|
| 298 |
+
scale_out = scale_conv(x)
|
| 299 |
+
scale_out = F.interpolate(scale_out, size=x.shape[2:], mode='bilinear', align_corners=False)
|
| 300 |
+
scale_features.append(scale_out)
|
| 301 |
+
fused = torch.cat(scale_features, dim=1)
|
| 302 |
+
initial_features = self.initial_conv(fused)
|
| 303 |
+
else:
|
| 304 |
+
initial_features = self.initial_conv(x)
|
| 305 |
+
|
| 306 |
+
e1 = self.encoder1(initial_features)
|
| 307 |
+
e2 = self.encoder2(self.pool1(e1))
|
| 308 |
+
e3 = self.encoder3(self.pool2(e2))
|
| 309 |
+
e4 = self.encoder4(self.pool3(e3))
|
| 310 |
+
b = self.bridge(self.pool4(e4))
|
| 311 |
+
|
| 312 |
+
g4 = self.up4(b)
|
| 313 |
+
x4 = self.att4(g4, e4)
|
| 314 |
+
d4 = self.dec4(torch.cat([g4, x4], dim=1))
|
| 315 |
+
d4 = self.refine4(d4)
|
| 316 |
+
g3 = self.up3(d4)
|
| 317 |
+
x3 = self.att3(g3, e3)
|
| 318 |
+
d3 = self.dec3(torch.cat([g3, x3], dim=1))
|
| 319 |
+
d3 = self.refine3(d3)
|
| 320 |
+
g2 = self.up2(d3)
|
| 321 |
+
x2 = self.att2(g2, e2)
|
| 322 |
+
d2 = self.dec2(torch.cat([g2, x2], dim=1))
|
| 323 |
+
d2 = self.refine2(d2)
|
| 324 |
+
g1 = self.up1(d2)
|
| 325 |
+
x1 = self.att1(g1, e1)
|
| 326 |
+
d1 = self.dec1(torch.cat([g1, x1], dim=1))
|
| 327 |
+
d1 = self.refine1(d1)
|
| 328 |
+
out = self.final_conv(d1)
|
| 329 |
+
return out
|
| 330 |
+
|
| 331 |
+
def load_checkpoint_with_expansion(self, checkpoint_path, strict=False):
|
| 332 |
+
"""Load checkpoint and expand from 1-channel to 3-channel if needed."""
|
| 333 |
+
checkpoint = torch.load(checkpoint_path, map_location='cpu', weights_only=False)
|
| 334 |
+
generator_state = checkpoint['generator_state_dict']
|
| 335 |
+
needs_expansion = False
|
| 336 |
+
|
| 337 |
+
if 'scale_pyramid.0.weight' in generator_state:
|
| 338 |
+
old_shape = generator_state['scale_pyramid.0.weight'].shape
|
| 339 |
+
current_shape = self.scale_pyramid[0].weight.shape
|
| 340 |
+
if old_shape[1] != current_shape[1]:
|
| 341 |
+
needs_expansion = True
|
| 342 |
+
elif 'initial_conv.weight' in generator_state:
|
| 343 |
+
old_shape = generator_state['initial_conv.weight'].shape
|
| 344 |
+
current_shape = self.initial_conv.weight.shape
|
| 345 |
+
if old_shape[1] != current_shape[1]:
|
| 346 |
+
needs_expansion = True
|
| 347 |
+
|
| 348 |
+
if needs_expansion:
|
| 349 |
+
generator_state = self._expand_generator_state(generator_state)
|
| 350 |
+
|
| 351 |
+
self.load_state_dict(generator_state, strict=strict)
|
| 352 |
+
return checkpoint
|
| 353 |
+
|
| 354 |
+
def _expand_generator_state(self, generator_state):
|
| 355 |
+
"""Expand generator state dict from 1-channel to 3-channel input."""
|
| 356 |
+
expanded_state = generator_state.copy()
|
| 357 |
+
if 'scale_pyramid.0.weight' in generator_state:
|
| 358 |
+
for i in range(3):
|
| 359 |
+
key = f'scale_pyramid.{i}.weight' if i == 0 else f'scale_pyramid.{i}.1.weight'
|
| 360 |
+
if key in generator_state:
|
| 361 |
+
old_weight = generator_state[key]
|
| 362 |
+
new_weight = torch.zeros(32, 3, 3, 3)
|
| 363 |
+
new_weight[:, 0:1, :, :] = old_weight
|
| 364 |
+
expanded_state[key] = new_weight
|
| 365 |
+
elif 'initial_conv.weight' in generator_state:
|
| 366 |
+
old_weight = generator_state['initial_conv.weight']
|
| 367 |
+
new_weight = torch.zeros(64, 3, 3, 3)
|
| 368 |
+
new_weight[:, 0:1, :, :] = old_weight
|
| 369 |
+
expanded_state['initial_conv.weight'] = new_weight
|
| 370 |
+
return expanded_state
|
| 371 |
+
|
| 372 |
+
|
| 373 |
+
class PatchGANDiscriminator(nn.Module):
|
| 374 |
+
"""PatchGAN Discriminator (included for create_s2f_model compatibility)."""
|
| 375 |
+
def __init__(self, in_channels=2, ndf=64, n_layers=3, norm_layer=nn.BatchNorm2d):
|
| 376 |
+
super().__init__()
|
| 377 |
+
use_bias = norm_layer == nn.InstanceNorm2d
|
| 378 |
+
self.initial_conv = nn.Sequential(
|
| 379 |
+
nn.Conv2d(in_channels, ndf, kernel_size=4, stride=2, padding=1, bias=use_bias),
|
| 380 |
+
nn.LeakyReLU(0.2, inplace=True)
|
| 381 |
+
)
|
| 382 |
+
self.layers = nn.ModuleList()
|
| 383 |
+
nf_mult, nf_mult_prev = 1, 1
|
| 384 |
+
for n in range(1, n_layers):
|
| 385 |
+
nf_mult_prev, nf_mult = nf_mult, min(2 ** n, 8)
|
| 386 |
+
self.layers.append(nn.Sequential(
|
| 387 |
+
nn.Conv2d(ndf * nf_mult_prev, ndf * nf_mult, kernel_size=4, stride=2, padding=1, bias=use_bias),
|
| 388 |
+
norm_layer(ndf * nf_mult),
|
| 389 |
+
nn.LeakyReLU(0.2, inplace=True)
|
| 390 |
+
))
|
| 391 |
+
nf_mult_prev, nf_mult = nf_mult, min(2 ** n_layers, 8)
|
| 392 |
+
self.layers.append(nn.Sequential(
|
| 393 |
+
nn.Conv2d(ndf * nf_mult_prev, ndf * nf_mult, kernel_size=4, stride=1, padding=1, bias=use_bias),
|
| 394 |
+
norm_layer(ndf * nf_mult),
|
| 395 |
+
nn.LeakyReLU(0.2, inplace=True)
|
| 396 |
+
))
|
| 397 |
+
self.output_conv = nn.Conv2d(ndf * nf_mult, 1, kernel_size=4, stride=1, padding=1)
|
| 398 |
+
self.attention = nn.Sequential(
|
| 399 |
+
nn.Conv2d(ndf * nf_mult, ndf * nf_mult // 4, 1),
|
| 400 |
+
nn.ReLU(inplace=True),
|
| 401 |
+
nn.Conv2d(ndf * nf_mult // 4, ndf * nf_mult, 1),
|
| 402 |
+
nn.Sigmoid()
|
| 403 |
+
)
|
| 404 |
+
|
| 405 |
+
def forward(self, input):
|
| 406 |
+
x = self.initial_conv(input)
|
| 407 |
+
for layer in self.layers:
|
| 408 |
+
x = layer(x)
|
| 409 |
+
x = x * self.attention(x)
|
| 410 |
+
return self.output_conv(x)
|
| 411 |
+
|
| 412 |
+
|
| 413 |
+
def create_s2f_model(
|
| 414 |
+
in_channels=1,
|
| 415 |
+
out_channels=1,
|
| 416 |
+
img_size=1024,
|
| 417 |
+
bridge_type='cbam',
|
| 418 |
+
use_multi_scale_input=True,
|
| 419 |
+
ndf=64,
|
| 420 |
+
n_layers=3,
|
| 421 |
+
):
|
| 422 |
+
"""Create S2F model with generator and discriminator."""
|
| 423 |
+
generator = S2FGenerator(
|
| 424 |
+
in_channels=in_channels,
|
| 425 |
+
out_channels=out_channels,
|
| 426 |
+
img_size=img_size,
|
| 427 |
+
bridge_type=bridge_type,
|
| 428 |
+
use_multi_scale_input=use_multi_scale_input,
|
| 429 |
+
)
|
| 430 |
+
discriminator = PatchGANDiscriminator(
|
| 431 |
+
in_channels=in_channels + out_channels,
|
| 432 |
+
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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Core inference logic for S2F (Shape2Force).
|
| 3 |
+
Predicts force maps from bright field microscopy images.
|
| 4 |
+
"""
|
| 5 |
+
import os
|
| 6 |
+
import sys
|
| 7 |
+
import cv2
|
| 8 |
+
import torch
|
| 9 |
+
import numpy as np
|
| 10 |
+
|
| 11 |
+
# Ensure S2F is in path when running from project root or S2F
|
| 12 |
+
S2F_ROOT = os.path.dirname(os.path.abspath(__file__))
|
| 13 |
+
if S2F_ROOT not in sys.path:
|
| 14 |
+
sys.path.insert(0, S2F_ROOT)
|
| 15 |
+
|
| 16 |
+
from models.s2f_model import create_s2f_model
|
| 17 |
+
from utils.substrate_settings import get_settings_of_category, compute_settings_normalization
|
| 18 |
+
from utils import config
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
def load_image(filepath, target_size=1024):
|
| 22 |
+
"""Load and preprocess a bright field image."""
|
| 23 |
+
img = cv2.imread(filepath, cv2.IMREAD_GRAYSCALE)
|
| 24 |
+
if img is None:
|
| 25 |
+
raise ValueError(f"Could not load image: {filepath}")
|
| 26 |
+
if isinstance(target_size, int):
|
| 27 |
+
target_size = (target_size, target_size)
|
| 28 |
+
img = cv2.resize(img, target_size)
|
| 29 |
+
img = img.astype(np.float32) / 255.0
|
| 30 |
+
return img
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
def sum_force_map(force_map):
|
| 34 |
+
"""Compute cell force as sum of pixel values scaled by SCALE_FACTOR_FORCE."""
|
| 35 |
+
if isinstance(force_map, np.ndarray):
|
| 36 |
+
force_map = torch.from_numpy(force_map.astype(np.float32))
|
| 37 |
+
if force_map.dim() == 2:
|
| 38 |
+
force_map = force_map.unsqueeze(0).unsqueeze(0) # [1, 1, H, W]
|
| 39 |
+
elif force_map.dim() == 3:
|
| 40 |
+
force_map = force_map.unsqueeze(0) # [1, 1, H, W]
|
| 41 |
+
# force_map: [B, 1, H, W], sum over spatial dims (2, 3)
|
| 42 |
+
return torch.sum(force_map, dim=(2, 3)) * config.SCALE_FACTOR_FORCE
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
def create_settings_channels_single(substrate_name, device, height, width, config_path=None,
|
| 46 |
+
substrate_config=None):
|
| 47 |
+
"""
|
| 48 |
+
Create settings channels for a single image (single-cell mode).
|
| 49 |
+
|
| 50 |
+
Args:
|
| 51 |
+
substrate_name: Substrate name (used if substrate_config is None)
|
| 52 |
+
device: torch device
|
| 53 |
+
height, width: spatial dimensions
|
| 54 |
+
config_path: Path to substrate config JSON
|
| 55 |
+
substrate_config: Optional dict with 'pixelsize' and 'young'. If provided, overrides substrate_name.
|
| 56 |
+
"""
|
| 57 |
+
norm_params = compute_settings_normalization(config_path=config_path)
|
| 58 |
+
if substrate_config is not None and 'pixelsize' in substrate_config and 'young' in substrate_config:
|
| 59 |
+
settings = substrate_config
|
| 60 |
+
else:
|
| 61 |
+
settings = get_settings_of_category(substrate_name, config_path=config_path)
|
| 62 |
+
pmin, pmax = norm_params['pixelsize']['min'], norm_params['pixelsize']['max']
|
| 63 |
+
ymin, ymax = norm_params['young']['min'], norm_params['young']['max']
|
| 64 |
+
pixelsize_norm = (settings['pixelsize'] - pmin) / (pmax - pmin) if pmax > pmin else 0.5
|
| 65 |
+
young_norm = (settings['young'] - ymin) / (ymax - ymin) if ymax > ymin else 0.5
|
| 66 |
+
pixelsize_norm = max(0.0, min(1.0, pixelsize_norm))
|
| 67 |
+
young_norm = max(0.0, min(1.0, young_norm))
|
| 68 |
+
pixelsize_ch = torch.full(
|
| 69 |
+
(1, 1, height, width), pixelsize_norm, device=device, dtype=torch.float32
|
| 70 |
+
)
|
| 71 |
+
young_ch = torch.full(
|
| 72 |
+
(1, 1, height, width), young_norm, device=device, dtype=torch.float32
|
| 73 |
+
)
|
| 74 |
+
return torch.cat([pixelsize_ch, young_ch], dim=1)
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
class S2FPredictor:
|
| 78 |
+
"""
|
| 79 |
+
Shape2Force predictor for single-cell or spheroid force map prediction.
|
| 80 |
+
"""
|
| 81 |
+
|
| 82 |
+
def __init__(self, model_type="single_cell", checkpoint_path=None, ckp_folder=None, device=None):
|
| 83 |
+
"""
|
| 84 |
+
Args:
|
| 85 |
+
model_type: "single_cell" or "spheroid"
|
| 86 |
+
checkpoint_path: Path to .pth checkpoint (relative to ckp_folder or absolute)
|
| 87 |
+
ckp_folder: Folder containing checkpoints (default: S2F/ckp)
|
| 88 |
+
device: "cuda" or "cpu" (auto-detected if None)
|
| 89 |
+
"""
|
| 90 |
+
self.model_type = model_type
|
| 91 |
+
self.device = device or ("cuda" if torch.cuda.is_available() else "cpu")
|
| 92 |
+
ckp_folder = ckp_folder or os.path.join(S2F_ROOT, "ckp")
|
| 93 |
+
|
| 94 |
+
in_channels = 3 if model_type == "single_cell" else 1
|
| 95 |
+
generator, _ = create_s2f_model(in_channels=in_channels)
|
| 96 |
+
self.generator = generator
|
| 97 |
+
|
| 98 |
+
if checkpoint_path:
|
| 99 |
+
full_path = checkpoint_path
|
| 100 |
+
if not os.path.isabs(checkpoint_path):
|
| 101 |
+
full_path = os.path.join(ckp_folder, checkpoint_path)
|
| 102 |
+
if not os.path.exists(full_path):
|
| 103 |
+
raise FileNotFoundError(f"Checkpoint not found: {full_path}")
|
| 104 |
+
|
| 105 |
+
# Single-cell: use load_checkpoint_with_expansion (handles 1ch->3ch if needed)
|
| 106 |
+
if model_type == "single_cell":
|
| 107 |
+
self.generator.load_checkpoint_with_expansion(full_path, strict=True)
|
| 108 |
+
else:
|
| 109 |
+
checkpoint = torch.load(full_path, map_location="cpu", weights_only=False)
|
| 110 |
+
state = checkpoint.get("generator_state_dict", checkpoint)
|
| 111 |
+
self.generator.load_state_dict(state, strict=True)
|
| 112 |
+
|
| 113 |
+
self.generator = self.generator.to(self.device)
|
| 114 |
+
self.generator.eval()
|
| 115 |
+
|
| 116 |
+
self.norm_params = compute_settings_normalization() if model_type == "single_cell" else None
|
| 117 |
+
self.config_path = os.path.join(S2F_ROOT, "config", "substrate_settings.json")
|
| 118 |
+
|
| 119 |
+
def predict(self, image_path=None, image_array=None, substrate="fibroblasts_PDMS",
|
| 120 |
+
substrate_config=None):
|
| 121 |
+
"""
|
| 122 |
+
Run prediction on an image.
|
| 123 |
+
|
| 124 |
+
Args:
|
| 125 |
+
image_path: Path to bright field image (tif, png, jpg)
|
| 126 |
+
image_array: numpy array (H, W) or (H, W, C) in [0, 255] or [0, 1]
|
| 127 |
+
substrate: Substrate name for single-cell mode (used if substrate_config is None)
|
| 128 |
+
substrate_config: Optional dict with 'pixelsize' and 'young'. Overrides substrate lookup.
|
| 129 |
+
|
| 130 |
+
Returns:
|
| 131 |
+
heatmap: numpy array (1024, 1024) in [0, 1]
|
| 132 |
+
force: scalar cell force (sum of heatmap * SCALE_FACTOR_FORCE)
|
| 133 |
+
pixel_sum: raw sum of all pixel values in heatmap
|
| 134 |
+
"""
|
| 135 |
+
if image_path is not None:
|
| 136 |
+
img = load_image(image_path)
|
| 137 |
+
elif image_array is not None:
|
| 138 |
+
img = np.asarray(image_array, dtype=np.float32)
|
| 139 |
+
if img.ndim == 3:
|
| 140 |
+
img = img[:, :, 0] if img.shape[-1] >= 1 else img
|
| 141 |
+
if img.max() > 1.0:
|
| 142 |
+
img = img / 255.0
|
| 143 |
+
img = cv2.resize(img, (1024, 1024))
|
| 144 |
+
else:
|
| 145 |
+
raise ValueError("Provide image_path or image_array")
|
| 146 |
+
|
| 147 |
+
x = torch.from_numpy(img).float().unsqueeze(0).unsqueeze(0).to(self.device) # [1,1,H,W]
|
| 148 |
+
|
| 149 |
+
if self.model_type == "single_cell" and self.norm_params is not None:
|
| 150 |
+
settings_ch = create_settings_channels_single(
|
| 151 |
+
substrate, self.device, x.shape[2], x.shape[3],
|
| 152 |
+
config_path=self.config_path, substrate_config=substrate_config
|
| 153 |
+
)
|
| 154 |
+
x = torch.cat([x, settings_ch], dim=1) # [1,3,H,W]
|
| 155 |
+
|
| 156 |
+
with torch.no_grad():
|
| 157 |
+
pred = self.generator(x)
|
| 158 |
+
|
| 159 |
+
pred = (pred + 1.0) / 2.0 # Tanh to [0, 1]
|
| 160 |
+
heatmap = pred[0, 0].cpu().numpy()
|
| 161 |
+
force = sum_force_map(pred).item()
|
| 162 |
+
pixel_sum = float(np.sum(heatmap))
|
| 163 |
+
|
| 164 |
+
return heatmap, force, pixel_sum
|
requirements.txt
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Shape2Force App - inference only
|
| 2 |
+
torch>=2.0.0
|
| 3 |
+
torchvision>=0.15.0
|
| 4 |
+
numpy>=1.20.0
|
| 5 |
+
opencv-python>=4.5.0
|
| 6 |
+
streamlit>=1.28.0
|
| 7 |
+
matplotlib>=3.5.0
|
| 8 |
+
Pillow>=9.0.0
|
| 9 |
+
plotly>=5.14.0
|
| 10 |
+
huggingface_hub>=0.20.0
|
sample/.gitkeep
ADDED
|
File without changes
|
utils/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
from . import config
|
utils/config.py
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Constants for force and area scaling (used in force map prediction)
|
| 2 |
+
SCALE_FACTOR_FORCE = 1e-3
|
| 3 |
+
SCALE_FACTOR_AREA = 1e-4
|
utils/metrics.py
ADDED
|
@@ -0,0 +1,447 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Metrics for S2F training and evaluation.
|
| 2 |
+
|
| 3 |
+
Includes: MSE, MS-SSIM, Pixel Correlation (Pearson), Relative Magnitude Error (WFM),
|
| 4 |
+
and evaluation helpers for notebooks and scripts.
|
| 5 |
+
"""
|
| 6 |
+
import os
|
| 7 |
+
import torch
|
| 8 |
+
import torch.nn as nn
|
| 9 |
+
import torch.nn.functional as F
|
| 10 |
+
import numpy as np
|
| 11 |
+
from skimage.metrics import structural_similarity as ssim
|
| 12 |
+
from scipy.stats import pearsonr
|
| 13 |
+
from tqdm import tqdm
|
| 14 |
+
import matplotlib.pyplot as plt
|
| 15 |
+
|
| 16 |
+
try:
|
| 17 |
+
from torchmetrics import MultiScaleStructuralSimilarityIndexMeasure
|
| 18 |
+
from torchmetrics import MeanSquaredError
|
| 19 |
+
HAS_TORCHMETRICS = True
|
| 20 |
+
except ImportError:
|
| 21 |
+
HAS_TORCHMETRICS = False
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
def calculate_mse(y_true, y_pred):
|
| 25 |
+
if isinstance(y_true, torch.Tensor):
|
| 26 |
+
return F.mse_loss(y_pred, y_true).item()
|
| 27 |
+
return float(np.mean((np.asarray(y_true) - np.asarray(y_pred)) ** 2))
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
def calculate_psnr(y_true, y_pred, max_pixel_value=1.0):
|
| 31 |
+
mse = calculate_mse(y_true, y_pred)
|
| 32 |
+
if mse == 0:
|
| 33 |
+
return float('inf')
|
| 34 |
+
return 20 * np.log10(max_pixel_value / np.sqrt(mse))
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
def calculate_ssim_tensor(y_true, y_pred, data_range=1.0):
|
| 38 |
+
if isinstance(y_true, torch.Tensor):
|
| 39 |
+
y_true = y_true.detach().cpu().numpy()
|
| 40 |
+
if isinstance(y_pred, torch.Tensor):
|
| 41 |
+
y_pred = y_pred.detach().cpu().numpy()
|
| 42 |
+
ssim_values = []
|
| 43 |
+
batch_size = y_true.shape[0]
|
| 44 |
+
for i in range(batch_size):
|
| 45 |
+
if len(y_true.shape) == 4:
|
| 46 |
+
true_img = y_true[i, 0] if y_true.shape[1] == 1 else y_true[i, 0]
|
| 47 |
+
pred_img = y_pred[i, 0] if y_pred.shape[1] == 1 else y_pred[i, 0]
|
| 48 |
+
else:
|
| 49 |
+
true_img, pred_img = y_true[i], y_pred[i]
|
| 50 |
+
ssim_values.append(ssim(true_img, pred_img, data_range=data_range))
|
| 51 |
+
return np.mean(ssim_values)
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
def calculate_pearson_correlation(y_true, y_pred):
|
| 55 |
+
if isinstance(y_true, torch.Tensor):
|
| 56 |
+
y_true = y_true.cpu().numpy()
|
| 57 |
+
if isinstance(y_pred, torch.Tensor):
|
| 58 |
+
y_pred = y_pred.cpu().numpy()
|
| 59 |
+
correlation, _ = pearsonr(y_true.flatten(), y_pred.flatten())
|
| 60 |
+
return correlation
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
def calculate_individual_pixel_correlation(y_true, y_pred):
|
| 64 |
+
"""Pixel-wise Pearson correlation per sample in batch."""
|
| 65 |
+
if isinstance(y_true, torch.Tensor):
|
| 66 |
+
y_true = y_true.cpu().numpy()
|
| 67 |
+
if isinstance(y_pred, torch.Tensor):
|
| 68 |
+
y_pred = y_pred.cpu().numpy()
|
| 69 |
+
correlations = []
|
| 70 |
+
batch_size = y_true.shape[0]
|
| 71 |
+
for i in range(batch_size):
|
| 72 |
+
true_flat = y_true[i].flatten()
|
| 73 |
+
pred_flat = y_pred[i].flatten()
|
| 74 |
+
r, _ = pearsonr(true_flat, pred_flat)
|
| 75 |
+
correlations.append(r)
|
| 76 |
+
return correlations
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
# --- WFM (Wrinkle Force Microscopy) metrics for heatmap as magnitude ---
|
| 80 |
+
|
| 81 |
+
def _to_numpy_wfm(x):
|
| 82 |
+
if isinstance(x, torch.Tensor):
|
| 83 |
+
return x.detach().cpu().numpy()
|
| 84 |
+
return np.asarray(x)
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
def _ensure_shape_wfm(f):
|
| 88 |
+
"""Ensure (N, 2, H, W). Heatmap -> fx=magnitude, fy=0."""
|
| 89 |
+
if f.ndim == 3:
|
| 90 |
+
if f.shape[-1] == 2:
|
| 91 |
+
f = np.transpose(f, (2, 0, 1))[None, ...]
|
| 92 |
+
elif f.shape[0] == 2:
|
| 93 |
+
f = f[None, ...]
|
| 94 |
+
else:
|
| 95 |
+
raise ValueError(f"Unsupported 3D shape {f.shape}")
|
| 96 |
+
elif f.ndim == 4:
|
| 97 |
+
if f.shape[-1] == 2:
|
| 98 |
+
f = np.transpose(f, (0, 3, 1, 2))
|
| 99 |
+
else:
|
| 100 |
+
raise ValueError(f"Unsupported ndim={f.ndim}")
|
| 101 |
+
return f
|
| 102 |
+
|
| 103 |
+
|
| 104 |
+
def _force_mag_wfm(f):
|
| 105 |
+
fx, fy = f[:, 0], f[:, 1]
|
| 106 |
+
return np.sqrt(fx**2 + fy**2)
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
def wfm_correlation(y_true, y_pred, mode="magnitude"):
|
| 110 |
+
"""Pearson correlation between prediction and ground truth (magnitude mode for heatmaps)."""
|
| 111 |
+
t = _ensure_shape_wfm(_to_numpy_wfm(y_true))
|
| 112 |
+
p = _ensure_shape_wfm(_to_numpy_wfm(y_pred))
|
| 113 |
+
if t.shape != p.shape:
|
| 114 |
+
raise ValueError(f"Shape mismatch: true {t.shape} vs pred {p.shape}")
|
| 115 |
+
if mode == "magnitude":
|
| 116 |
+
tv = _force_mag_wfm(t).ravel()
|
| 117 |
+
pv = _force_mag_wfm(p).ravel()
|
| 118 |
+
else:
|
| 119 |
+
raise ValueError(f"Unknown mode '{mode}'")
|
| 120 |
+
tv, pv = tv.astype(np.float64), pv.astype(np.float64)
|
| 121 |
+
if np.allclose(tv.std(), 0) or np.allclose(pv.std(), 0):
|
| 122 |
+
return 0.0
|
| 123 |
+
return float(np.corrcoef(tv, pv)[0, 1])
|
| 124 |
+
|
| 125 |
+
|
| 126 |
+
def wfm_relative_magnitude_error(y_true, y_pred, eps=1e-8):
|
| 127 |
+
"""Relative magnitude error for heatmap-as-magnitude."""
|
| 128 |
+
t = _ensure_shape_wfm(_to_numpy_wfm(y_true))
|
| 129 |
+
p = _ensure_shape_wfm(_to_numpy_wfm(y_pred))
|
| 130 |
+
if t.shape != p.shape:
|
| 131 |
+
raise ValueError(f"Shape mismatch: true {t.shape} vs pred {p.shape}")
|
| 132 |
+
mag_t = _force_mag_wfm(t)
|
| 133 |
+
mag_p = _force_mag_wfm(p)
|
| 134 |
+
fbar = np.mean(mag_t)
|
| 135 |
+
if np.isclose(fbar, 0):
|
| 136 |
+
return 0.0
|
| 137 |
+
rel = np.abs(mag_p - mag_t) / (mag_t + eps)
|
| 138 |
+
w = mag_t / fbar
|
| 139 |
+
return float(np.mean(rel * w))
|
| 140 |
+
|
| 141 |
+
|
| 142 |
+
def apply_threshold_mask(tensor, threshold=0.0):
|
| 143 |
+
return tensor * (tensor >= threshold).float()
|
| 144 |
+
|
| 145 |
+
|
| 146 |
+
def detect_tanh_output_model(model):
|
| 147 |
+
"""Detect if model outputs [-1, 1] (Tanh)."""
|
| 148 |
+
if hasattr(model, 'use_sigmoid') and not model.use_sigmoid:
|
| 149 |
+
return True
|
| 150 |
+
if hasattr(model, 'use_tanh_output') and model.use_tanh_output:
|
| 151 |
+
return True
|
| 152 |
+
if hasattr(model, 'final_conv'):
|
| 153 |
+
fc = model.final_conv
|
| 154 |
+
if isinstance(fc, nn.Sequential):
|
| 155 |
+
if isinstance(fc[-1], nn.Tanh):
|
| 156 |
+
return True
|
| 157 |
+
elif isinstance(fc, nn.Tanh):
|
| 158 |
+
return True
|
| 159 |
+
return False
|
| 160 |
+
|
| 161 |
+
|
| 162 |
+
def convert_tanh_to_sigmoid_range(tensor):
|
| 163 |
+
return (tensor + 1.0) / 2.0
|
| 164 |
+
|
| 165 |
+
|
| 166 |
+
# --- TorchMetrics wrapper for MS-SSIM ---
|
| 167 |
+
|
| 168 |
+
class TorchMetricsWrapper:
|
| 169 |
+
def __init__(self, device='cpu'):
|
| 170 |
+
self.device = device
|
| 171 |
+
self.reset_metrics()
|
| 172 |
+
|
| 173 |
+
def reset_metrics(self):
|
| 174 |
+
if HAS_TORCHMETRICS:
|
| 175 |
+
self.ms_ssim = MultiScaleStructuralSimilarityIndexMeasure(data_range=1.0).to(self.device)
|
| 176 |
+
self.mse = MeanSquaredError().to(self.device)
|
| 177 |
+
else:
|
| 178 |
+
self.ms_ssim = None
|
| 179 |
+
self.mse = None
|
| 180 |
+
|
| 181 |
+
def compute_ms_ssim(self, y_true, y_pred):
|
| 182 |
+
if not HAS_TORCHMETRICS:
|
| 183 |
+
return float(calculate_ssim_tensor(y_true, y_pred)) # fallback to SSIM
|
| 184 |
+
y_true = y_true.to(self.device)
|
| 185 |
+
y_pred = y_pred.to(self.device)
|
| 186 |
+
if y_true.shape[1] == 1:
|
| 187 |
+
pass
|
| 188 |
+
else:
|
| 189 |
+
y_true, y_pred = y_true[:, 0:1], y_pred[:, 0:1]
|
| 190 |
+
return self.ms_ssim(y_pred, y_true).item()
|
| 191 |
+
|
| 192 |
+
def compute_mse(self, y_true, y_pred):
|
| 193 |
+
if not HAS_TORCHMETRICS:
|
| 194 |
+
return calculate_mse(y_true, y_pred)
|
| 195 |
+
y_true = y_true.to(self.device)
|
| 196 |
+
y_pred = y_pred.to(self.device)
|
| 197 |
+
return self.mse(y_pred, y_true).item()
|
| 198 |
+
|
| 199 |
+
|
| 200 |
+
# --- Full evaluation on dataset ---
|
| 201 |
+
|
| 202 |
+
def evaluate_metrics_on_dataset(generator, data_loader, device=None, description="Evaluating",
|
| 203 |
+
save_predictions=False, threshold=0.0, use_settings=False,
|
| 204 |
+
normalization_params=None, config_path=None, substrate_override=None):
|
| 205 |
+
"""
|
| 206 |
+
Evaluate S2F generator on a dataset. Returns MSE, MS-SSIM, Pixel Correlation,
|
| 207 |
+
Relative Magnitude Error, and force sum/mean correlations.
|
| 208 |
+
"""
|
| 209 |
+
if device is None:
|
| 210 |
+
device = torch.device('mps' if torch.backends.mps.is_available() else
|
| 211 |
+
'cuda' if torch.cuda.is_available() else 'cpu')
|
| 212 |
+
|
| 213 |
+
generator = generator.to(device)
|
| 214 |
+
generator.eval()
|
| 215 |
+
metrics_wrapper = TorchMetricsWrapper(device=device)
|
| 216 |
+
|
| 217 |
+
heatmap_mse = []
|
| 218 |
+
heatmap_ms_ssim = []
|
| 219 |
+
heatmap_pixel_corr = []
|
| 220 |
+
wfm_corr_mag = []
|
| 221 |
+
wfm_rel_mag_err = []
|
| 222 |
+
force_sum_gt, force_sum_pred = [], []
|
| 223 |
+
force_mean_gt, force_mean_pred = [], []
|
| 224 |
+
individual_predictions = [] if save_predictions else None
|
| 225 |
+
|
| 226 |
+
with torch.no_grad():
|
| 227 |
+
for batch_idx, batch_data in enumerate(tqdm(data_loader, desc=description)):
|
| 228 |
+
if len(batch_data) == 5:
|
| 229 |
+
images, heatmaps, _, _, metadata = batch_data
|
| 230 |
+
has_metadata = True
|
| 231 |
+
else:
|
| 232 |
+
images, heatmaps, _, _ = batch_data
|
| 233 |
+
has_metadata = False
|
| 234 |
+
|
| 235 |
+
images = images.to(device, dtype=torch.float32)
|
| 236 |
+
heatmaps = heatmaps.to(device, dtype=torch.float32)
|
| 237 |
+
|
| 238 |
+
if use_settings and normalization_params is not None:
|
| 239 |
+
from models.s2f_model import create_settings_channels
|
| 240 |
+
meta = metadata if has_metadata else {'substrate': [substrate_override or 'fibroblasts_PDMS'] * images.size(0)}
|
| 241 |
+
settings_ch = create_settings_channels(meta, normalization_params, device, images.shape, config_path=config_path)
|
| 242 |
+
images = torch.cat([images, settings_ch], dim=1)
|
| 243 |
+
|
| 244 |
+
pred = generator(images)
|
| 245 |
+
if detect_tanh_output_model(generator):
|
| 246 |
+
pred = convert_tanh_to_sigmoid_range(pred)
|
| 247 |
+
|
| 248 |
+
gt_thresh = apply_threshold_mask(heatmaps, threshold)
|
| 249 |
+
pred_thresh = pred # no threshold on pred for metrics
|
| 250 |
+
|
| 251 |
+
heatmap_mse.append(metrics_wrapper.compute_mse(gt_thresh, pred_thresh))
|
| 252 |
+
heatmap_ms_ssim.append(metrics_wrapper.compute_ms_ssim(gt_thresh, pred_thresh))
|
| 253 |
+
heatmap_pixel_corr.extend(calculate_individual_pixel_correlation(gt_thresh, pred_thresh))
|
| 254 |
+
|
| 255 |
+
# WFM: heatmap as magnitude (fx=magnitude, fy=0)
|
| 256 |
+
B, _, H, W = gt_thresh.shape
|
| 257 |
+
gt_ff = torch.zeros(B, 2, H, W, device=device)
|
| 258 |
+
pred_ff = torch.zeros(B, 2, H, W, device=device)
|
| 259 |
+
gt_ff[:, 0], pred_ff[:, 0] = gt_thresh[:, 0], pred_thresh[:, 0]
|
| 260 |
+
try:
|
| 261 |
+
wfm_corr_mag.append(wfm_correlation(gt_ff, pred_ff, mode="magnitude"))
|
| 262 |
+
wfm_rel_mag_err.append(wfm_relative_magnitude_error(gt_ff, pred_ff))
|
| 263 |
+
except Exception:
|
| 264 |
+
wfm_corr_mag.append(float('nan'))
|
| 265 |
+
wfm_rel_mag_err.append(float('nan'))
|
| 266 |
+
|
| 267 |
+
force_sum_gt.extend(torch.sum(gt_thresh, dim=[1, 2, 3]).cpu().numpy().tolist())
|
| 268 |
+
force_sum_pred.extend(torch.sum(pred_thresh, dim=[1, 2, 3]).cpu().numpy().tolist())
|
| 269 |
+
force_mean_gt.extend(torch.mean(gt_thresh, dim=[1, 2, 3]).cpu().numpy().tolist())
|
| 270 |
+
force_mean_pred.extend(torch.mean(pred_thresh, dim=[1, 2, 3]).cpu().numpy().tolist())
|
| 271 |
+
|
| 272 |
+
if save_predictions:
|
| 273 |
+
for i in range(images.size(0)):
|
| 274 |
+
p, t = pred_thresh[i:i+1], gt_thresh[i:i+1]
|
| 275 |
+
gt_ff_i = torch.zeros(1, 2, H, W, device=device)
|
| 276 |
+
pred_ff_i = torch.zeros(1, 2, H, W, device=device)
|
| 277 |
+
gt_ff_i[0, 0], pred_ff_i[0, 0] = t[0, 0], p[0, 0]
|
| 278 |
+
try:
|
| 279 |
+
rme = wfm_relative_magnitude_error(gt_ff_i, pred_ff_i)
|
| 280 |
+
except Exception:
|
| 281 |
+
rme = float('nan')
|
| 282 |
+
individual_predictions.append({
|
| 283 |
+
'batch_idx': batch_idx,
|
| 284 |
+
'sample_idx': i,
|
| 285 |
+
'original_image': images[i].cpu().numpy(),
|
| 286 |
+
'ground_truth': heatmaps[i].cpu().numpy(),
|
| 287 |
+
'ground_truth_thresholded': gt_thresh[i].cpu().numpy(),
|
| 288 |
+
'prediction': pred[i].cpu().numpy(),
|
| 289 |
+
'prediction_thresholded': pred_thresh[i].cpu().numpy(),
|
| 290 |
+
'mse': metrics_wrapper.compute_mse(t, p),
|
| 291 |
+
'ms_ssim': metrics_wrapper.compute_ms_ssim(t, p),
|
| 292 |
+
'pixel_correlation': calculate_pearson_correlation(t, p),
|
| 293 |
+
'wfm_relative_magnitude_error': rme,
|
| 294 |
+
'force_sum_gt': torch.sum(gt_thresh[i]).item(),
|
| 295 |
+
'force_sum_pred': torch.sum(pred_thresh[i]).item(),
|
| 296 |
+
'force_mean_gt': torch.mean(gt_thresh[i]).item(),
|
| 297 |
+
'force_mean_pred': torch.mean(pred_thresh[i]).item(),
|
| 298 |
+
})
|
| 299 |
+
|
| 300 |
+
valid_wfm_corr = [x for x in wfm_corr_mag if not np.isnan(x)]
|
| 301 |
+
valid_wfm_rme = [x for x in wfm_rel_mag_err if not np.isnan(x)]
|
| 302 |
+
try:
|
| 303 |
+
force_sum_corr, _ = pearsonr(force_sum_gt, force_sum_pred)
|
| 304 |
+
force_mean_corr, _ = pearsonr(force_mean_gt, force_mean_pred)
|
| 305 |
+
except Exception:
|
| 306 |
+
force_sum_corr = force_mean_corr = 0.0
|
| 307 |
+
if force_sum_corr is None or (isinstance(force_sum_corr, float) and np.isnan(force_sum_corr)):
|
| 308 |
+
force_sum_corr = 0.0
|
| 309 |
+
if force_mean_corr is None or (isinstance(force_mean_corr, float) and np.isnan(force_mean_corr)):
|
| 310 |
+
force_mean_corr = 0.0
|
| 311 |
+
|
| 312 |
+
results = {
|
| 313 |
+
'heatmap': {
|
| 314 |
+
'mse': np.mean(heatmap_mse),
|
| 315 |
+
'mse_std': np.std(heatmap_mse),
|
| 316 |
+
'ms_ssim': np.mean(heatmap_ms_ssim),
|
| 317 |
+
'ms_ssim_std': np.std(heatmap_ms_ssim),
|
| 318 |
+
'pixel_correlation': np.mean(heatmap_pixel_corr),
|
| 319 |
+
'pixel_correlation_std': np.std(heatmap_pixel_corr),
|
| 320 |
+
},
|
| 321 |
+
'wfm': {
|
| 322 |
+
'correlation_magnitude': np.mean(valid_wfm_corr) if valid_wfm_corr else float('nan'),
|
| 323 |
+
'correlation_magnitude_std': np.std(valid_wfm_corr) if valid_wfm_corr else float('nan'),
|
| 324 |
+
'relative_magnitude_error': np.mean(valid_wfm_rme) if valid_wfm_rme else float('nan'),
|
| 325 |
+
'relative_magnitude_error_std': np.std(valid_wfm_rme) if valid_wfm_rme else float('nan'),
|
| 326 |
+
},
|
| 327 |
+
'force_sum': {
|
| 328 |
+
'correlation': float(force_sum_corr),
|
| 329 |
+
'gt_mean': np.mean(force_sum_gt),
|
| 330 |
+
'pred_mean': np.mean(force_sum_pred),
|
| 331 |
+
'gt_std': np.std(force_sum_gt),
|
| 332 |
+
'pred_std': np.std(force_sum_pred),
|
| 333 |
+
},
|
| 334 |
+
'force_mean': {
|
| 335 |
+
'correlation': float(force_mean_corr),
|
| 336 |
+
'gt_mean': np.mean(force_mean_gt),
|
| 337 |
+
'pred_mean': np.mean(force_mean_pred),
|
| 338 |
+
},
|
| 339 |
+
}
|
| 340 |
+
|
| 341 |
+
if save_predictions:
|
| 342 |
+
results['individual_predictions'] = individual_predictions
|
| 343 |
+
return results
|
| 344 |
+
|
| 345 |
+
|
| 346 |
+
def print_metrics_report(report, threshold=0.0, uses_tanh=False):
|
| 347 |
+
"""Print formatted metrics report."""
|
| 348 |
+
for name, metrics in report.items():
|
| 349 |
+
print(f"\n🔸 {name.upper()} SET METRICS" + (f" (threshold={threshold})" if threshold > 0 else ""))
|
| 350 |
+
print("-" * 60)
|
| 351 |
+
print("HEATMAP METRICS:")
|
| 352 |
+
print(f" MSE: {metrics['heatmap']['mse']:.6f} ± {metrics['heatmap']['mse_std']:.6f}")
|
| 353 |
+
print(f" MS-SSIM: {metrics['heatmap']['ms_ssim']:.4f} ± {metrics['heatmap']['ms_ssim_std']:.4f}")
|
| 354 |
+
print(f" Pixel Corr: {metrics['heatmap']['pixel_correlation']:.4f} ± {metrics['heatmap']['pixel_correlation_std']:.4f}")
|
| 355 |
+
print("WFM METRICS (heatmap as magnitude):")
|
| 356 |
+
print(f" Correlation (Magnitude): {metrics['wfm']['correlation_magnitude']:.4f} ± {metrics['wfm']['correlation_magnitude_std']:.4f}")
|
| 357 |
+
print(f" Relative Magnitude Error: {metrics['wfm']['relative_magnitude_error']:.4f} ± {metrics['wfm']['relative_magnitude_error_std']:.4f}")
|
| 358 |
+
print("FORCE SUM CORRELATION:")
|
| 359 |
+
print(f" Correlation: {metrics['force_sum']['correlation']:.4f}")
|
| 360 |
+
print(f" GT Mean: {metrics['force_sum']['gt_mean']:.2f} ± {metrics['force_sum']['gt_std']:.2f}")
|
| 361 |
+
print(f" Pred Mean: {metrics['force_sum']['pred_mean']:.2f} ± {metrics['force_sum']['pred_std']:.2f}")
|
| 362 |
+
if uses_tanh:
|
| 363 |
+
print(" Note: Model outputs [-1,1], converted to [0,1] for evaluation")
|
| 364 |
+
print("=" * 60)
|
| 365 |
+
|
| 366 |
+
|
| 367 |
+
def gen_prediction_plots(individual_predictions, save_dir, sort_by='ms_ssim', sort_order='desc', threshold=0.0):
|
| 368 |
+
"""Generate prediction plots (BF | GT | Pred) sorted by metric."""
|
| 369 |
+
os.makedirs(save_dir, exist_ok=True)
|
| 370 |
+
reverse = (sort_order.lower() == 'desc') if sort_by.lower() not in ['mse', 'wfm_relative_magnitude_error'] else (sort_order.lower() == 'desc')
|
| 371 |
+
valid = [p for p in individual_predictions if not np.isnan(p.get(sort_by.lower(), 0))]
|
| 372 |
+
sorted_preds = sorted(valid, key=lambda x: x[sort_by.lower()], reverse=reverse)
|
| 373 |
+
print(f"Sorting {len(sorted_preds)} predictions by {sort_by} ({sort_order})")
|
| 374 |
+
for rank, p in enumerate(tqdm(sorted_preds, desc="Saving plots"), 1):
|
| 375 |
+
fig, axes = plt.subplots(1, 3, figsize=(15, 5))
|
| 376 |
+
img = p['original_image']
|
| 377 |
+
axes[0].imshow(img[0] if img.ndim == 3 else img, cmap='gray')
|
| 378 |
+
axes[0].set_title('Bright Field')
|
| 379 |
+
axes[0].axis('off')
|
| 380 |
+
gt = p['ground_truth']
|
| 381 |
+
axes[1].imshow(gt[0] if gt.ndim == 3 else gt, cmap='jet', vmin=0, vmax=1)
|
| 382 |
+
axes[1].set_title('Ground Truth')
|
| 383 |
+
axes[1].axis('off')
|
| 384 |
+
pr = p['prediction']
|
| 385 |
+
axes[2].imshow(pr[0] if pr.ndim == 3 else pr, cmap='jet', vmin=0, vmax=1)
|
| 386 |
+
axes[2].set_title('Prediction')
|
| 387 |
+
axes[2].axis('off')
|
| 388 |
+
m = (f"MSE: {p['mse']:.4f} | MS-SSIM: {p['ms_ssim']:.4f} | "
|
| 389 |
+
f"Pixel Corr: {p['pixel_correlation']:.4f} | Rel Mag Err: {p.get('wfm_relative_magnitude_error', 'N/A')}")
|
| 390 |
+
fig.suptitle(f"Rank {rank} (by {sort_by})\n{m}", fontsize=10, y=0.02)
|
| 391 |
+
plt.tight_layout()
|
| 392 |
+
plt.savefig(os.path.join(save_dir, f"rank{rank:03d}_batch{p['batch_idx']:03d}_sample{p['sample_idx']:02d}.png"), dpi=150, bbox_inches='tight')
|
| 393 |
+
plt.close()
|
| 394 |
+
|
| 395 |
+
|
| 396 |
+
def plot_predictions(loader, generator, n_samples, device, threshold=0.0,
|
| 397 |
+
use_settings=False, normalization_params=None, config_path=None, substrate_override=None):
|
| 398 |
+
"""Plot BF | GT | Pred for first n_samples from loader."""
|
| 399 |
+
generator = generator.to(device)
|
| 400 |
+
generator.eval()
|
| 401 |
+
bf_list, gt_list, meta_list = [], [], []
|
| 402 |
+
it = iter(loader)
|
| 403 |
+
while len(bf_list) < n_samples:
|
| 404 |
+
try:
|
| 405 |
+
batch = next(it)
|
| 406 |
+
except StopIteration:
|
| 407 |
+
break
|
| 408 |
+
if len(batch) == 5:
|
| 409 |
+
images, heatmaps, _, _, meta = batch
|
| 410 |
+
else:
|
| 411 |
+
images, heatmaps = batch[0], batch[1]
|
| 412 |
+
meta = None
|
| 413 |
+
for i in range(images.shape[0]):
|
| 414 |
+
if len(bf_list) >= n_samples:
|
| 415 |
+
break
|
| 416 |
+
bf_list.append(images[i])
|
| 417 |
+
gt_list.append(heatmaps[i])
|
| 418 |
+
meta_list.append(meta)
|
| 419 |
+
n = min(n_samples, len(bf_list))
|
| 420 |
+
bf_batch = torch.stack(bf_list[:n]).to(device, dtype=torch.float32)
|
| 421 |
+
if use_settings and normalization_params:
|
| 422 |
+
from models.s2f_model import create_settings_channels
|
| 423 |
+
sub = substrate_override or 'fibroblasts_PDMS'
|
| 424 |
+
meta_dict = {'substrate': [sub] * n}
|
| 425 |
+
settings_ch = create_settings_channels(meta_dict, normalization_params, device, bf_batch.shape, config_path=config_path)
|
| 426 |
+
bf_batch = torch.cat([bf_batch, settings_ch], dim=1)
|
| 427 |
+
with torch.no_grad():
|
| 428 |
+
pred = generator(bf_batch)
|
| 429 |
+
if detect_tanh_output_model(generator):
|
| 430 |
+
pred = convert_tanh_to_sigmoid_range(pred)
|
| 431 |
+
if threshold > 0:
|
| 432 |
+
pred = pred * (pred >= threshold).float()
|
| 433 |
+
fig, axes = plt.subplots(n, 3, figsize=(12, 4 * n))
|
| 434 |
+
if n == 1:
|
| 435 |
+
axes = axes.reshape(1, -1)
|
| 436 |
+
for i in range(n):
|
| 437 |
+
axes[i, 0].imshow(bf_list[i].squeeze().cpu().numpy(), cmap='gray')
|
| 438 |
+
axes[i, 0].set_title('Bright Field')
|
| 439 |
+
axes[i, 0].axis('off')
|
| 440 |
+
axes[i, 1].imshow(gt_list[i].squeeze().cpu().numpy(), cmap='jet', vmin=0, vmax=1)
|
| 441 |
+
axes[i, 1].set_title('Ground Truth')
|
| 442 |
+
axes[i, 1].axis('off')
|
| 443 |
+
axes[i, 2].imshow(pred[i].squeeze().cpu().numpy(), cmap='jet', vmin=0, vmax=1)
|
| 444 |
+
axes[i, 2].set_title('Prediction')
|
| 445 |
+
axes[i, 2].axis('off')
|
| 446 |
+
plt.tight_layout()
|
| 447 |
+
plt.show()
|
utils/substrate_settings.py
ADDED
|
@@ -0,0 +1,129 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Substrate settings for force map prediction.
|
| 3 |
+
Loads from config/substrate_settings.json - users can edit this file to add/modify substrates.
|
| 4 |
+
"""
|
| 5 |
+
import os
|
| 6 |
+
import json
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
def _default_config_path():
|
| 10 |
+
"""Default path to substrate settings config (S2F/config/substrate_settings.json)."""
|
| 11 |
+
this_dir = os.path.dirname(os.path.abspath(__file__))
|
| 12 |
+
project_root = os.path.dirname(this_dir) # S2F root
|
| 13 |
+
return os.path.join(project_root, 'config', 'substrate_settings.json')
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
def load_substrate_config(config_path=None):
|
| 17 |
+
"""
|
| 18 |
+
Load substrate settings from config file.
|
| 19 |
+
|
| 20 |
+
Args:
|
| 21 |
+
config_path: Path to JSON config. If None, uses config/substrate_settings.json in S2F root.
|
| 22 |
+
|
| 23 |
+
Returns:
|
| 24 |
+
dict: Config with 'substrates', 'default_substrate'
|
| 25 |
+
"""
|
| 26 |
+
path = config_path or _default_config_path()
|
| 27 |
+
if not os.path.exists(path):
|
| 28 |
+
raise FileNotFoundError(
|
| 29 |
+
f"Substrate config not found at {path}. "
|
| 30 |
+
"Create config/substrate_settings.json or pass config_path."
|
| 31 |
+
)
|
| 32 |
+
with open(path, 'r') as f:
|
| 33 |
+
return json.load(f)
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
def resolve_substrate(name, config=None, config_path=None):
|
| 37 |
+
"""
|
| 38 |
+
Resolve substrate name to a canonical substrate key.
|
| 39 |
+
|
| 40 |
+
Args:
|
| 41 |
+
name: Substrate key (e.g. 'fibroblasts_PDMS', 'PDMS_10kPa')
|
| 42 |
+
config: Pre-loaded config dict. If None, loads from config_path.
|
| 43 |
+
config_path: Path to config file (used if config is None).
|
| 44 |
+
|
| 45 |
+
Returns:
|
| 46 |
+
str: Canonical substrate key
|
| 47 |
+
"""
|
| 48 |
+
if config is None:
|
| 49 |
+
config = load_substrate_config(config_path)
|
| 50 |
+
|
| 51 |
+
s = (name or '').strip()
|
| 52 |
+
if not s:
|
| 53 |
+
return config.get('default_substrate', 'fibroblasts_PDMS')
|
| 54 |
+
|
| 55 |
+
substrates = config.get('substrates', {})
|
| 56 |
+
s_lower = s.lower()
|
| 57 |
+
for key in substrates:
|
| 58 |
+
if key.lower() == s_lower:
|
| 59 |
+
return key
|
| 60 |
+
for key in substrates:
|
| 61 |
+
if s_lower.startswith(key.lower()) or key.lower().startswith(s_lower):
|
| 62 |
+
return key
|
| 63 |
+
|
| 64 |
+
return config.get('default_substrate', 'fibroblasts_PDMS')
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
def get_settings_of_category(substrate_name, config=None, config_path=None):
|
| 68 |
+
"""
|
| 69 |
+
Get pixelsize and young's modulus for a substrate.
|
| 70 |
+
|
| 71 |
+
Args:
|
| 72 |
+
substrate_name: Substrate or folder name (case-insensitive)
|
| 73 |
+
config: Pre-loaded config dict. If None, loads from config_path.
|
| 74 |
+
config_path: Path to config file (used if config is None).
|
| 75 |
+
|
| 76 |
+
Returns:
|
| 77 |
+
dict: {'name': str, 'pixelsize': float, 'young': float}
|
| 78 |
+
"""
|
| 79 |
+
if config is None:
|
| 80 |
+
config = load_substrate_config(config_path)
|
| 81 |
+
|
| 82 |
+
substrate_key = resolve_substrate(substrate_name, config=config)
|
| 83 |
+
substrates = config.get('substrates', {})
|
| 84 |
+
default = config.get('default_substrate', 'fibroblasts_PDMS')
|
| 85 |
+
|
| 86 |
+
if substrate_key in substrates:
|
| 87 |
+
return substrates[substrate_key].copy()
|
| 88 |
+
|
| 89 |
+
default_settings = substrates.get(default, {'name': 'Fibroblasts on PDMS', 'pixelsize': 3.0769, 'young': 6000})
|
| 90 |
+
return default_settings.copy()
|
| 91 |
+
|
| 92 |
+
|
| 93 |
+
def list_substrates(config=None, config_path=None):
|
| 94 |
+
"""
|
| 95 |
+
Return list of available substrate keys for user selection.
|
| 96 |
+
|
| 97 |
+
Returns:
|
| 98 |
+
list: Substrate keys
|
| 99 |
+
"""
|
| 100 |
+
if config is None:
|
| 101 |
+
config = load_substrate_config(config_path)
|
| 102 |
+
return list(config.get('substrates', {}).keys())
|
| 103 |
+
|
| 104 |
+
|
| 105 |
+
def compute_settings_normalization(config=None, config_path=None):
|
| 106 |
+
"""
|
| 107 |
+
Compute min-max normalization parameters from all substrates in config.
|
| 108 |
+
|
| 109 |
+
Returns:
|
| 110 |
+
dict: {'pixelsize': {'min', 'max'}, 'young': {'min', 'max'}}
|
| 111 |
+
"""
|
| 112 |
+
if config is None:
|
| 113 |
+
config = load_substrate_config(config_path)
|
| 114 |
+
|
| 115 |
+
substrates = config.get('substrates', {})
|
| 116 |
+
all_pixelsizes = [s['pixelsize'] for s in substrates.values()]
|
| 117 |
+
all_youngs = [s['young'] for s in substrates.values()]
|
| 118 |
+
|
| 119 |
+
if not all_pixelsizes or not all_youngs:
|
| 120 |
+
pixelsize_min, pixelsize_max = 3.0769, 9.8138
|
| 121 |
+
young_min, young_max = 1000.0, 10000.0
|
| 122 |
+
else:
|
| 123 |
+
pixelsize_min, pixelsize_max = min(all_pixelsizes), max(all_pixelsizes)
|
| 124 |
+
young_min, young_max = min(all_youngs), max(all_youngs)
|
| 125 |
+
|
| 126 |
+
return {
|
| 127 |
+
'pixelsize': {'min': pixelsize_min, 'max': pixelsize_max},
|
| 128 |
+
'young': {'min': young_min, 'max': young_max}
|
| 129 |
+
}
|