kaveh commited on
Commit
2b9ff22
·
0 Parent(s):
.gitattributes ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ *.7z filter=lfs diff=lfs merge=lfs -text
2
+ *.arrow filter=lfs diff=lfs merge=lfs -text
3
+ *.bin filter=lfs diff=lfs merge=lfs -text
4
+ *.bz2 filter=lfs diff=lfs merge=lfs -text
5
+ *.ckpt filter=lfs diff=lfs merge=lfs -text
6
+ *.ftz filter=lfs diff=lfs merge=lfs -text
7
+ *.gz filter=lfs diff=lfs merge=lfs -text
8
+ *.h5 filter=lfs diff=lfs merge=lfs -text
9
+ *.joblib filter=lfs diff=lfs merge=lfs -text
10
+ *.lfs.* filter=lfs diff=lfs merge=lfs -text
11
+ *.mlmodel filter=lfs diff=lfs merge=lfs -text
12
+ *.model filter=lfs diff=lfs merge=lfs -text
13
+ *.msgpack filter=lfs diff=lfs merge=lfs -text
14
+ *.npy filter=lfs diff=lfs merge=lfs -text
15
+ *.npz filter=lfs diff=lfs merge=lfs -text
16
+ *.onnx filter=lfs diff=lfs merge=lfs -text
17
+ *.ot filter=lfs diff=lfs merge=lfs -text
18
+ *.parquet filter=lfs diff=lfs merge=lfs -text
19
+ *.pb filter=lfs diff=lfs merge=lfs -text
20
+ *.pickle filter=lfs diff=lfs merge=lfs -text
21
+ *.pkl filter=lfs diff=lfs merge=lfs -text
22
+ *.pt filter=lfs diff=lfs merge=lfs -text
23
+ *.pth filter=lfs diff=lfs merge=lfs -text
24
+ *.rar filter=lfs diff=lfs merge=lfs -text
25
+ *.safetensors filter=lfs diff=lfs merge=lfs -text
26
+ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
27
+ *.tar.* filter=lfs diff=lfs merge=lfs -text
28
+ *.tar filter=lfs diff=lfs merge=lfs -text
29
+ *.tflite filter=lfs diff=lfs merge=lfs -text
30
+ *.tgz filter=lfs diff=lfs merge=lfs -text
31
+ *.wasm filter=lfs diff=lfs merge=lfs -text
32
+ *.xz filter=lfs diff=lfs merge=lfs -text
33
+ *.zip filter=lfs diff=lfs merge=lfs -text
34
+ *.zst filter=lfs diff=lfs merge=lfs -text
35
+ *tfevents* filter=lfs diff=lfs merge=lfs -text
36
+ *.tiff filter=lfs diff=lfs merge=lfs -text
37
+ *.tif filter=lfs diff=lfs merge=lfs -text
38
+ *.tiff filter=lfs diff=lfs merge=lfs -text
.gitignore ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ Archive/
2
+ .DS_Store
.gitmodules ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ [submodule "S2FApp"]
2
+ path = S2FApp
3
+ url = git@hf.co:spaces/kaveh/Shape2force
README.md ADDED
@@ -0,0 +1,75 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Shape2Force (S2F)
2
+
3
+ Predict force maps from bright-field microscopy images of single-cell or spheroid using deep learning.
4
+
5
+ **Web App:** The app is published to [Hugging Face Spaces](https://huggingface.co/spaces/kaveh/Shape2force). To work on it locally: `git clone git@hf.co:spaces/kaveh/Shape2force S2FApp`
6
+
7
+ ---
8
+
9
+ ## Quick Start
10
+
11
+ **Web app (local):**
12
+ ```bash
13
+ cd S2FApp
14
+ pip install -r requirements.txt
15
+ streamlit run app.py
16
+ ```
17
+
18
+ Or use the [online app](https://huggingface.co/spaces/kaveh/Shape2force) on Hugging Face. Place checkpoints (`.pth`) in `S2FApp/ckp/` for __local use__; the Space downloads them automatically.
19
+
20
+ ---
21
+
22
+ ## Ways to Use S2F
23
+
24
+ ### 1. Web App
25
+
26
+ Run the Streamlit GUI from `S2FApp/`:
27
+
28
+ ```bash
29
+ cd S2FApp && streamlit run app.py
30
+ ```
31
+
32
+ 1. Choose **Model type**: Single cell or Spheroid
33
+ 2. Select a **Checkpoint** from `ckp/`
34
+ 3. For single-cell: pick **Substrate** (e.g. fibroblasts_PDMS)
35
+ 4. Upload an image or pick from `sample/`
36
+ 5. Click **Run prediction**
37
+
38
+ Output: heatmap, cell force (sum), and basic stats.
39
+
40
+ ----
41
+
42
+ ### 2. Jupyter Notebook
43
+
44
+ For interactive usage and custom analysis, you may use the notebook:
45
+
46
+ - **`notebooks/evaluate_model.ipynb`** – Load data, run evaluation, plot predictions, and save per-sample metrics.
47
+
48
+ Once cloned the repo. open the notebook in Jupyter and adjust the configuration cell (paths, model type, substrate).
49
+
50
+ ---
51
+
52
+ ### 3. Training & Fine-Tuning
53
+
54
+ **Dataset layout:** A folder with `train/` and `test/` subfolders. Each subfolder has:
55
+ - `BF_001.tif` (bright-field image)
56
+ - `*_gray.jpg` (force map / heatmap)
57
+ - Optional `.txt` (cell_area, sum_force)
58
+
59
+ **Single-cell:**
60
+ ```bash
61
+ python -m training.train --data path/to/dataset --model single_cell --epochs 100 --substrate fibroblasts_PDMS
62
+ ```
63
+
64
+ **Spheroid:**
65
+ ```bash
66
+ python -m training.train --data path/to/dataset --model spheroid --epochs 100
67
+ ```
68
+
69
+ **Resume / fine-tune from checkpoint:**
70
+ ```bash
71
+ python -m training.train --data path/to/dataset --model single_cell --resume ckp/last_checkpoint.pth --epochs 150
72
+ ```
73
+
74
+ ---
75
+
S2FApp/.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
S2FApp/.gitattributes ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ *.tif filter=lfs diff=lfs merge=lfs -text
2
+ *.tiff filter=lfs diff=lfs merge=lfs -text
S2FApp/.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
S2FApp/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"]
S2FApp/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).
S2FApp/app.py ADDED
@@ -0,0 +1,205 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Shape2Force (S2F) - GUI for force map prediction from bright field microscopy images.
3
+ """
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")
S2FApp/ckp/.gitkeep ADDED
File without changes
S2FApp/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"}
S2FApp/models/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ from .s2f_model import create_s2f_model, S2FGenerator
S2FApp/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
S2FApp/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
S2FApp/models/s2f_model.py ADDED
@@ -0,0 +1,435 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ ndf=ndf,
433
+ n_layers=n_layers
434
+ )
435
+ return generator, discriminator
S2FApp/predictor.py ADDED
@@ -0,0 +1,164 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
S2FApp/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
S2FApp/sample/.gitkeep ADDED
File without changes
S2FApp/utils/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ from . import config
S2FApp/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
S2FApp/utils/metrics.py ADDED
@@ -0,0 +1,447 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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()
S2FApp/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
+ }
ckp/.gitkeep ADDED
File without changes
ckp/ckp_singlecell.pth ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:3e4daea628c86ab8dc04e1adff47584a48c3a0104abbc6a79a4296f55c571698
3
+ size 959538864
ckp/ckp_spheroid.pth ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:5764cd3e29209dcd49e186b1ae3432ed46822de14bf3e47443fc25873b5c096d
3
+ size 959520496
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"}
data/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ from .cell_dataset import prepare_data, load_folder_data, ImageDataset
data/augmentations.py ADDED
@@ -0,0 +1,101 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ import torchvision.transforms as T
3
+ import torchvision.transforms.functional as TF
4
+ import torch
5
+ from scipy.ndimage import gaussian_filter, map_coordinates
6
+
7
+
8
+ class AdvancedAugmentations:
9
+ def __init__(self, target_size=(1024, 1024)):
10
+ self.target_size = target_size
11
+
12
+ def __call__(self, image, heatmap):
13
+ image = TF.to_pil_image(image)
14
+ heatmap = TF.to_pil_image(heatmap)
15
+
16
+ if np.random.rand() > 0.5:
17
+ image = TF.hflip(image)
18
+ heatmap = TF.hflip(heatmap)
19
+ if np.random.rand() > 0.5:
20
+ image = TF.vflip(image)
21
+ heatmap = TF.vflip(heatmap)
22
+
23
+ if np.random.rand() > 0.5:
24
+ angle = np.random.uniform(-45, 45)
25
+ image = TF.rotate(image, angle, interpolation=TF.InterpolationMode.BILINEAR)
26
+ heatmap = TF.rotate(heatmap, angle, interpolation=TF.InterpolationMode.BILINEAR)
27
+
28
+ if np.random.rand() > 0.5:
29
+ width, height = image.size
30
+ crop_size = int(min(width, height) * np.random.uniform(0.8, 1.0))
31
+ i, j, h, w = T.RandomCrop.get_params(image, (crop_size, crop_size))
32
+ image = TF.crop(image, i, j, h, w)
33
+ heatmap = TF.crop(heatmap, i, j, h, w)
34
+ image = TF.resize(image, self.target_size, interpolation=TF.InterpolationMode.BILINEAR)
35
+ heatmap = TF.resize(heatmap, self.target_size, interpolation=TF.InterpolationMode.BILINEAR)
36
+
37
+ if np.random.rand() > 0.5:
38
+ image, heatmap = self.random_affine(image, heatmap)
39
+
40
+ if not isinstance(image, torch.Tensor):
41
+ image = TF.to_tensor(image)
42
+ if not isinstance(heatmap, torch.Tensor):
43
+ heatmap = TF.to_tensor(heatmap)
44
+
45
+ if np.random.rand() > 0.5:
46
+ brightness_factor = np.random.uniform(0.8, 1.2)
47
+ image = TF.adjust_brightness(image, brightness_factor)
48
+ if np.random.rand() > 0.5:
49
+ contrast_factor = np.random.uniform(0.8, 1.2)
50
+ image = TF.adjust_contrast(image, contrast_factor)
51
+
52
+ if np.random.rand() > 0.5:
53
+ noise_level = np.random.uniform(0.01, 0.05)
54
+ noise = torch.randn_like(image) * noise_level
55
+ image = torch.clamp(image + noise, 0, 1)
56
+
57
+ if np.random.rand() > 0.5:
58
+ image, heatmap = self.elastic_transform(image, heatmap)
59
+
60
+ return image, heatmap
61
+
62
+ def random_affine(self, image, heatmap):
63
+ degrees = [-10.0, 10.0]
64
+ translate = [0.05, 0.05]
65
+ scale = [0.95, 1.05]
66
+ shear = [-5.0, 5.0]
67
+ params = T.RandomAffine.get_params(degrees, translate, scale, shear, image.size)
68
+ angle, translate, scale, shear = params
69
+ translate = list(translate)
70
+ shear = list(shear)
71
+ image = TF.affine(image, angle, translate, scale, shear, interpolation=TF.InterpolationMode.BILINEAR)
72
+ heatmap = TF.affine(heatmap, angle, translate, scale, shear, interpolation=TF.InterpolationMode.BILINEAR)
73
+ return image, heatmap
74
+
75
+ def elastic_transform(self, image, heatmap, alpha=50, sigma=4):
76
+ if isinstance(image, torch.Tensor):
77
+ image_np = image.permute(1, 2, 0).numpy()
78
+ heatmap_np = heatmap.permute(1, 2, 0).numpy()
79
+ else:
80
+ image_np = np.asarray(image)
81
+ heatmap_np = np.asarray(heatmap)
82
+ if image_np.ndim == 2:
83
+ image_np = image_np[:, :, np.newaxis]
84
+ if heatmap_np.ndim == 2:
85
+ heatmap_np = heatmap_np[:, :, np.newaxis]
86
+
87
+ shape = image_np.shape[:2]
88
+ dx = gaussian_filter((np.random.rand(*shape) * 2 - 1), sigma, mode="constant", cval=0) * alpha
89
+ dy = gaussian_filter((np.random.rand(*shape) * 2 - 1), sigma, mode="constant", cval=0) * alpha
90
+ x, y = np.meshgrid(np.arange(shape[1]), np.arange(shape[0]))
91
+ indices = np.reshape(y + dy, (-1, 1)), np.reshape(x + dx, (-1, 1))
92
+
93
+ image_transformed = np.zeros_like(image_np)
94
+ heatmap_transformed = np.zeros_like(heatmap_np)
95
+ for i in range(image_np.shape[2]):
96
+ image_transformed[..., i] = map_coordinates(image_np[..., i], indices, order=1).reshape(shape)
97
+ for i in range(heatmap_np.shape[2]):
98
+ heatmap_transformed[..., i] = map_coordinates(heatmap_np[..., i], indices, order=1).reshape(shape)
99
+
100
+ return torch.from_numpy(image_transformed).float().permute(2, 0, 1), \
101
+ torch.from_numpy(heatmap_transformed).float().permute(2, 0, 1)
data/cell_dataset.py ADDED
@@ -0,0 +1,188 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Dataset and data loading for S2F training.
3
+ Expects folder structure: each subfolder has BF_001.tif (bright field), *_gray.jpg (heatmap), and optionally .txt (cell_area, sum_force).
4
+ """
5
+ import os
6
+ import cv2
7
+ import torch
8
+ from torch.utils.data import Dataset, DataLoader
9
+ from sklearn.model_selection import train_test_split
10
+ from concurrent.futures import ThreadPoolExecutor
11
+ import numpy as np
12
+
13
+ from utils import config
14
+
15
+
16
+ def blur_force_map(force_map, ksize=25, sigma=10):
17
+ if ksize % 2 == 0:
18
+ ksize += 1
19
+ if force_map.dim() == 3:
20
+ force_map = force_map.unsqueeze(0)
21
+ device = force_map.device
22
+ force_map = force_map.cpu()
23
+ blurred_maps = []
24
+ for i in range(force_map.size(0)):
25
+ force_np = force_map[i, 0].numpy().astype(np.float32)
26
+ blurred = cv2.GaussianBlur(force_np, (ksize, ksize), sigmaX=sigma)
27
+ blurred_maps.append(blurred)
28
+ return torch.from_numpy(np.stack(blurred_maps)).to(device)
29
+
30
+
31
+ class ImageDataset(Dataset):
32
+ def __init__(self, image_pairs, transform=None, channel_first=True,
33
+ blur_heatmap=False, threshold=0.0, return_metadata=False):
34
+ self.image_pairs = image_pairs
35
+ self.transform = transform
36
+ self.channel_first = channel_first
37
+ self.blur_heatmap = blur_heatmap
38
+ self.threshold = threshold
39
+ self.return_metadata = return_metadata
40
+
41
+ def __len__(self):
42
+ return len(self.image_pairs)
43
+
44
+ def __getitem__(self, idx):
45
+ if self.return_metadata:
46
+ bf_image, hm_image, numbers, metadata = self.image_pairs[idx]
47
+ else:
48
+ bf_image, hm_image, numbers = self.image_pairs[idx]
49
+ if isinstance(numbers, tuple):
50
+ cell_area, sum_force = numbers
51
+ else:
52
+ cell_area = 0
53
+ sum_force = numbers
54
+
55
+ image = torch.from_numpy(bf_image).float().unsqueeze(0)
56
+ heatmap = torch.from_numpy(hm_image).float().unsqueeze(0)
57
+ if self.transform:
58
+ image, heatmap = self.transform(image, heatmap)
59
+ cell_area = torch.tensor(cell_area, dtype=torch.float32)
60
+ sum_force = torch.tensor(sum_force, dtype=torch.float32)
61
+ heatmap[heatmap <= self.threshold] = 0
62
+ if self.blur_heatmap:
63
+ heatmap = blur_force_map(heatmap)
64
+ if not self.channel_first:
65
+ image = image.permute(2, 1, 0)
66
+ heatmap = heatmap.permute(2, 1, 0)
67
+ if self.return_metadata:
68
+ return image, heatmap, cell_area, sum_force, metadata
69
+ return image, heatmap, cell_area, sum_force
70
+
71
+
72
+ def load_image(filepath, target_size):
73
+ img = cv2.imread(filepath, cv2.IMREAD_GRAYSCALE)
74
+ if isinstance(target_size, int):
75
+ target_size = (target_size, target_size)
76
+ img = cv2.resize(img, target_size)
77
+ img = img / 255.0
78
+ return img.astype(np.float32)
79
+
80
+
81
+ def load_text_data(filepath):
82
+ with open(filepath, 'r') as f:
83
+ lines = [line.strip() for line in f if line.strip()]
84
+ cell_area_diff = float(lines[0].split(":")[1].strip()) * config.SCALE_FACTOR_AREA
85
+ sum_force_diff = float(lines[1].split(":")[1].strip()) * config.SCALE_FACTOR_FORCE
86
+ return (cell_area_diff, sum_force_diff)
87
+
88
+
89
+ def load_images_from_subfolders(root_folder, target_size, load_numerical_data=True,
90
+ load_force_sum=False, return_metadata=False, substrate=None):
91
+ paired_images = []
92
+ numerical_data = []
93
+ metadata = []
94
+ for subfolder in os.listdir(root_folder):
95
+ subfolder_path = os.path.join(root_folder, subfolder)
96
+ if not os.path.isdir(subfolder_path):
97
+ continue
98
+ bf_image_path = hm_image_path = txt_file_path = None
99
+ for filename in os.listdir(subfolder_path):
100
+ if filename.endswith("BF_001.tif"):
101
+ bf_image_path = os.path.join(subfolder_path, filename)
102
+ elif filename.endswith("_gray.jpg"):
103
+ hm_image_path = os.path.join(subfolder_path, filename)
104
+ elif filename.endswith(".txt"):
105
+ txt_file_path = os.path.join(subfolder_path, filename)
106
+
107
+ if return_metadata:
108
+ if substrate is None:
109
+ from utils.substrate_settings import list_substrates
110
+ raise ValueError("substrate must be passed when return_metadata=True. Options: " +
111
+ ", ".join(list_substrates()))
112
+ metadata.append({'folder_name': subfolder, 'substrate': substrate, 'root_folder': root_folder})
113
+
114
+ if load_numerical_data:
115
+ if bf_image_path and hm_image_path and txt_file_path:
116
+ paired_images.append((bf_image_path, hm_image_path))
117
+ numerical_data.append(load_text_data(txt_file_path))
118
+ elif load_force_sum:
119
+ if bf_image_path and hm_image_path:
120
+ paired_images.append((bf_image_path, hm_image_path))
121
+ hm = load_image(hm_image_path, target_size)
122
+ numerical_data.append((0, float(np.sum(hm)) * config.SCALE_FACTOR_FORCE))
123
+ else:
124
+ if bf_image_path and hm_image_path:
125
+ paired_images.append((bf_image_path, hm_image_path))
126
+
127
+ with ThreadPoolExecutor() as executor:
128
+ bf_loaded = list(executor.map(lambda p: load_image(p[0], target_size), paired_images))
129
+ hm_loaded = list(executor.map(lambda p: load_image(p[1], target_size), paired_images))
130
+ if not numerical_data:
131
+ numerical_data = [(0, 0)] * len(bf_loaded)
132
+ if return_metadata:
133
+ return list(zip(bf_loaded, hm_loaded, numerical_data, metadata))
134
+ return list(zip(bf_loaded, hm_loaded, numerical_data))
135
+
136
+
137
+ def prepare_data(input_folder, batch_size=8, target_size=(1024, 1024), split_size=0.2,
138
+ use_augmentations=True, train_test_sep_folder=True, channel_first=True,
139
+ load_numerical_data=False, load_force_sum=False, blur_heatmap=False,
140
+ threshold=0.0, return_metadata=False, substrate=None):
141
+ if load_numerical_data and load_force_sum:
142
+ raise ValueError("load_numerical_data and load_force_sum cannot be True at the same time")
143
+
144
+ if train_test_sep_folder:
145
+ train_folder = os.path.join(input_folder, 'train')
146
+ test_folder = os.path.join(input_folder, 'test')
147
+ if not (os.path.exists(train_folder) and os.path.exists(test_folder)):
148
+ raise ValueError(f"train/test folders not found in {input_folder}")
149
+ train_pairs = load_images_from_subfolders(train_folder, target_size=target_size,
150
+ load_numerical_data=load_numerical_data,
151
+ load_force_sum=load_force_sum,
152
+ return_metadata=return_metadata, substrate=substrate)
153
+ val_pairs = load_images_from_subfolders(test_folder, target_size=target_size,
154
+ load_numerical_data=load_numerical_data,
155
+ load_force_sum=load_force_sum,
156
+ return_metadata=return_metadata, substrate=substrate)
157
+ else:
158
+ image_pairs = load_images_from_subfolders(input_folder, target_size=target_size,
159
+ load_numerical_data=load_numerical_data,
160
+ load_force_sum=load_force_sum,
161
+ return_metadata=return_metadata, substrate=substrate)
162
+ train_pairs, val_pairs = train_test_split(image_pairs, test_size=split_size, random_state=42)
163
+
164
+ train_transform = None
165
+ if use_augmentations:
166
+ from .augmentations import AdvancedAugmentations
167
+ train_transform = AdvancedAugmentations(target_size)
168
+
169
+ train_dataset = ImageDataset(train_pairs, transform=train_transform, channel_first=channel_first,
170
+ blur_heatmap=blur_heatmap, threshold=threshold, return_metadata=return_metadata)
171
+ train_dataset.name = os.path.basename(input_folder)
172
+ val_dataset = ImageDataset(val_pairs, channel_first=channel_first,
173
+ blur_heatmap=blur_heatmap, threshold=threshold, return_metadata=return_metadata)
174
+ val_dataset.name = os.path.basename(input_folder)
175
+ train_loader = DataLoader(train_dataset, batch_size=batch_size, shuffle=True)
176
+ val_loader = DataLoader(val_dataset, batch_size=batch_size, shuffle=False)
177
+ return train_loader, val_loader
178
+
179
+
180
+ def load_folder_data(folder_path, substrate=None, img_size=1024, blur_heatmap=False,
181
+ batch_size=2, threshold=0.0, return_metadata=False):
182
+ val_pairs = load_images_from_subfolders(folder_path, target_size=img_size,
183
+ load_numerical_data=False, load_force_sum=False,
184
+ return_metadata=return_metadata, substrate=substrate)
185
+ val_dataset = ImageDataset(val_pairs, channel_first=True, blur_heatmap=blur_heatmap,
186
+ threshold=threshold, return_metadata=return_metadata)
187
+ val_dataset.name = os.path.basename(folder_path)
188
+ return DataLoader(val_dataset, batch_size=batch_size, shuffle=False)
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 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ ndf=ndf,
433
+ n_layers=n_layers
434
+ )
435
+ return generator, discriminator
notebooks/evaluate_model.ipynb ADDED
@@ -0,0 +1,248 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "markdown",
5
+ "metadata": {},
6
+ "source": [
7
+ "# S2F Model Evaluation\n",
8
+ "\n",
9
+ "This notebook shows how to evaluate a trained Shape2Force (S2F) model on your dataset.\n",
10
+ "\n",
11
+ "**Metrics computed:**\n",
12
+ "- **MSE** – Mean Squared Error\n",
13
+ "- **MS-SSIM** – Multi-Scale Structural Similarity\n",
14
+ "- **Pixel Correlation** – Pearson correlation between predicted and ground-truth heatmaps\n",
15
+ "- **Relative Magnitude Error** – WFM-style weighted relative error\n",
16
+ "- **Force Sum/Mean Correlation** – Correlation of total force per sample\n",
17
+ "\n",
18
+ "Run the cells below after adjusting paths and settings."
19
+ ]
20
+ },
21
+ {
22
+ "cell_type": "code",
23
+ "execution_count": null,
24
+ "metadata": {},
25
+ "outputs": [],
26
+ "source": [
27
+ "%load_ext autoreload\n",
28
+ "%autoreload 2\n",
29
+ "\n",
30
+ "import warnings\n",
31
+ "warnings.filterwarnings('ignore')\n",
32
+ "import sys\n",
33
+ "import os\n",
34
+ "import cv2\n",
35
+ "cv2.utils.logging.setLogLevel(cv2.utils.logging.LOG_LEVEL_ERROR)\n",
36
+ "\n",
37
+ "cwd = os.getcwd()\n",
38
+ "S2F_ROOT = cwd if os.path.exists(os.path.join(cwd, 'models')) else os.path.dirname(cwd)\n",
39
+ "sys.path.insert(0, S2F_ROOT)\n",
40
+ "\n",
41
+ "import torch\n",
42
+ "import matplotlib.pyplot as plt\n",
43
+ "\n",
44
+ "from data.cell_dataset import prepare_data, load_folder_data\n",
45
+ "from models.s2f_model import create_s2f_model, compute_settings_normalization\n",
46
+ "from utils.metrics import (\n",
47
+ " evaluate_metrics_on_dataset,\n",
48
+ " print_metrics_report,\n",
49
+ " gen_prediction_plots,\n",
50
+ " plot_predictions,\n",
51
+ ")\n",
52
+ "\n",
53
+ "print(f\"S2F root: {S2F_ROOT}\")"
54
+ ]
55
+ },
56
+ {
57
+ "cell_type": "markdown",
58
+ "metadata": {},
59
+ "source": [
60
+ "## Configuration"
61
+ ]
62
+ },
63
+ {
64
+ "cell_type": "code",
65
+ "execution_count": null,
66
+ "metadata": {},
67
+ "outputs": [],
68
+ "source": [
69
+ "# --- Adjust these paths ---\n",
70
+ "USE_SINGLE_CELL = True # True = single-cell (with substrate), False = spheroid\n",
71
+ "DATA_FOLDER = os.path.join(S2F_ROOT, 'sample') # or path to your dataset\n",
72
+ "CHECKPOINT_PATH = os.path.join(S2F_ROOT, 'ckp', 'best_checkpoint.pth')\n",
73
+ "\n",
74
+ "IMAGE_SIZE = 1024\n",
75
+ "BATCH_SIZE = 2\n",
76
+ "THRESHOLD = 0.0 # Threshold for heatmap metrics (0 = no threshold)\n",
77
+ "DEVICE = 'cuda' if torch.cuda.is_available() else 'cpu'\n",
78
+ "SUBSTRATE = 'fibroblasts_PDMS' # For single-cell mode"
79
+ ]
80
+ },
81
+ {
82
+ "cell_type": "markdown",
83
+ "metadata": {},
84
+ "source": [
85
+ "## Load Data"
86
+ ]
87
+ },
88
+ {
89
+ "cell_type": "code",
90
+ "execution_count": null,
91
+ "metadata": {},
92
+ "outputs": [],
93
+ "source": [
94
+ "# Option A: Load from folder with train/test subfolders\n",
95
+ "train_folder = os.path.join(DATA_FOLDER, 'train')\n",
96
+ "test_folder = os.path.join(DATA_FOLDER, 'test')\n",
97
+ "\n",
98
+ "if os.path.exists(train_folder) and os.path.exists(test_folder):\n",
99
+ " train_loader, val_loader = prepare_data(\n",
100
+ " DATA_FOLDER,\n",
101
+ " batch_size=BATCH_SIZE,\n",
102
+ " target_size=(IMAGE_SIZE, IMAGE_SIZE),\n",
103
+ " use_augmentations=False,\n",
104
+ " train_test_sep_folder=True,\n",
105
+ " return_metadata=USE_SINGLE_CELL,\n",
106
+ " substrate=SUBSTRATE if USE_SINGLE_CELL else None,\n",
107
+ " )\n",
108
+ " print(f\"Loaded train: {len(train_loader.dataset)} samples, val: {len(val_loader.dataset)} samples\")\n",
109
+ "else:\n",
110
+ " # Option B: Load from a single folder (e.g. test only)\n",
111
+ " val_loader = load_folder_data(\n",
112
+ " DATA_FOLDER,\n",
113
+ " substrate=SUBSTRATE if USE_SINGLE_CELL else None,\n",
114
+ " img_size=IMAGE_SIZE,\n",
115
+ " batch_size=BATCH_SIZE,\n",
116
+ " return_metadata=USE_SINGLE_CELL,\n",
117
+ " )\n",
118
+ " train_loader = None\n",
119
+ " print(f\"Loaded {len(val_loader.dataset)} samples from {DATA_FOLDER}\")"
120
+ ]
121
+ },
122
+ {
123
+ "cell_type": "markdown",
124
+ "metadata": {},
125
+ "source": [
126
+ "## Load Model"
127
+ ]
128
+ },
129
+ {
130
+ "cell_type": "code",
131
+ "execution_count": null,
132
+ "metadata": {},
133
+ "outputs": [],
134
+ "source": [
135
+ "in_channels = 3 if USE_SINGLE_CELL else 1\n",
136
+ "generator, _ = create_s2f_model(in_channels=in_channels)\n",
137
+ "checkpoint = torch.load(CHECKPOINT_PATH, map_location='cpu', weights_only=False)\n",
138
+ "generator.load_state_dict(checkpoint.get('generator_state_dict', checkpoint), strict=True)\n",
139
+ "generator = generator.to(DEVICE)\n",
140
+ "generator.eval()\n",
141
+ "\n",
142
+ "print(f\"Loaded checkpoint from {CHECKPOINT_PATH}\")\n",
143
+ "if 'epoch' in checkpoint:\n",
144
+ " print(f\" Epoch: {checkpoint['epoch']}\")"
145
+ ]
146
+ },
147
+ {
148
+ "cell_type": "markdown",
149
+ "metadata": {},
150
+ "source": [
151
+ "## Run Evaluation"
152
+ ]
153
+ },
154
+ {
155
+ "cell_type": "code",
156
+ "execution_count": null,
157
+ "metadata": {},
158
+ "outputs": [],
159
+ "source": [
160
+ "config_path = os.path.join(S2F_ROOT, 'config', 'substrate_settings.json')\n",
161
+ "normalization_params = compute_settings_normalization(config_path=config_path) if USE_SINGLE_CELL else None\n",
162
+ "\n",
163
+ "val_results = evaluate_metrics_on_dataset(\n",
164
+ " generator,\n",
165
+ " val_loader,\n",
166
+ " device=DEVICE,\n",
167
+ " description=\"Evaluating\",\n",
168
+ " save_predictions=True,\n",
169
+ " threshold=THRESHOLD,\n",
170
+ " use_settings=USE_SINGLE_CELL,\n",
171
+ " normalization_params=normalization_params,\n",
172
+ " config_path=config_path,\n",
173
+ " substrate_override=SUBSTRATE,\n",
174
+ ")\n",
175
+ "\n",
176
+ "report = {'validation': val_results}\n",
177
+ "if train_loader is not None:\n",
178
+ " train_results = evaluate_metrics_on_dataset(\n",
179
+ " generator, train_loader, device=DEVICE, description=\"Training\",\n",
180
+ " threshold=THRESHOLD, use_settings=USE_SINGLE_CELL,\n",
181
+ " normalization_params=normalization_params, config_path=config_path,\n",
182
+ " substrate_override=SUBSTRATE,\n",
183
+ " )\n",
184
+ " report = {'train': train_results, 'validation': val_results}\n",
185
+ "\n",
186
+ "print_metrics_report(report, threshold=THRESHOLD)"
187
+ ]
188
+ },
189
+ {
190
+ "cell_type": "markdown",
191
+ "metadata": {},
192
+ "source": [
193
+ "## Visualize Predictions"
194
+ ]
195
+ },
196
+ {
197
+ "cell_type": "code",
198
+ "execution_count": null,
199
+ "metadata": {},
200
+ "outputs": [],
201
+ "source": [
202
+ "# Quick preview: plot first few samples\n",
203
+ "plot_predictions(\n",
204
+ " val_loader,\n",
205
+ " generator,\n",
206
+ " n_samples=3,\n",
207
+ " device=DEVICE,\n",
208
+ " use_settings=USE_SINGLE_CELL,\n",
209
+ " normalization_params=normalization_params,\n",
210
+ " config_path=config_path,\n",
211
+ " substrate_override=SUBSTRATE,\n",
212
+ ")"
213
+ ]
214
+ },
215
+ {
216
+ "cell_type": "code",
217
+ "execution_count": null,
218
+ "metadata": {},
219
+ "outputs": [],
220
+ "source": [
221
+ "# Save individual prediction plots (sorted by MSE, best first)\n",
222
+ "plot_output_dir = os.path.join(S2F_ROOT, 'outputs', 'evaluation_plots')\n",
223
+ "if 'individual_predictions' in val_results:\n",
224
+ " gen_prediction_plots(\n",
225
+ " val_results['individual_predictions'],\n",
226
+ " save_dir=plot_output_dir,\n",
227
+ " sort_by='mse',\n",
228
+ " sort_order='asc',\n",
229
+ " threshold=THRESHOLD,\n",
230
+ " )\n",
231
+ " print(f\"Saved plots to {plot_output_dir}\")"
232
+ ]
233
+ }
234
+ ],
235
+ "metadata": {
236
+ "kernelspec": {
237
+ "display_name": "Python 3",
238
+ "language": "python",
239
+ "name": "python3"
240
+ },
241
+ "language_info": {
242
+ "name": "python",
243
+ "version": "3.10.0"
244
+ }
245
+ },
246
+ "nbformat": 4,
247
+ "nbformat_minor": 4
248
+ }
outputs/.gitkeep ADDED
File without changes
requirements.txt ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Shape2Force (S2F) - GUI and training
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
+
11
+ # Training & evaluation
12
+ torchmetrics>=1.0.0
13
+ diffusers>=0.20.0
14
+ tqdm>=4.65.0
15
+ scikit-image>=0.19.0
16
+ scipy>=1.9.0
17
+ scikit-learn>=1.0.0
18
+ pandas>=1.3.0
training/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ from .s2f_trainer import train_s2f, S2FLoss, calculate_soft_dice_loss
training/evaluate.py ADDED
@@ -0,0 +1,115 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ S2F evaluation script.
4
+ Metrics: MSE, MS-SSIM, Pixel Correlation, Relative Magnitude Error, Force Sum/Mean correlation.
5
+
6
+ Usage:
7
+ python -m training.evaluate --model single_cell --checkpoint ckp/best_checkpoint.pth --data path/to/test
8
+ python -m training.evaluate --model spheroid --checkpoint ckp/best_checkpoint.pth --data path/to/test
9
+ """
10
+ import os
11
+ import sys
12
+ import argparse
13
+
14
+ S2F_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
15
+ if S2F_ROOT not in sys.path:
16
+ sys.path.insert(0, S2F_ROOT)
17
+
18
+
19
+ def main():
20
+ parser = argparse.ArgumentParser(description='Evaluate S2F model')
21
+ parser.add_argument('--data', required=True, help='Path to test folder (subfolders with BF_001.tif, *_gray.jpg)')
22
+ parser.add_argument('--model', choices=['single_cell', 'spheroid'], default='single_cell')
23
+ parser.add_argument('--checkpoint', required=True, help='Path to .pth checkpoint')
24
+ parser.add_argument('--substrate', default='fibroblasts_PDMS', help='Substrate for single_cell')
25
+ parser.add_argument('--batch_size', type=int, default=2)
26
+ parser.add_argument('--img_size', type=int, default=1024)
27
+ parser.add_argument('--threshold', type=float, default=0.0, help='Threshold for heatmap metrics')
28
+ parser.add_argument('--output', default=None, help='Optional CSV path for per-sample metrics')
29
+ parser.add_argument('--save_plots', default=None, help='Directory to save prediction plots')
30
+ parser.add_argument('--device', default='cuda')
31
+ args = parser.parse_args()
32
+
33
+ from data.cell_dataset import load_folder_data
34
+ from models.s2f_model import create_s2f_model, compute_settings_normalization
35
+ from utils.metrics import (
36
+ evaluate_metrics_on_dataset,
37
+ print_metrics_report,
38
+ gen_prediction_plots,
39
+ detect_tanh_output_model,
40
+ )
41
+ import torch
42
+ import pandas as pd
43
+
44
+ use_settings = args.model == 'single_cell'
45
+ config_path = os.path.join(S2F_ROOT, 'config', 'substrate_settings.json')
46
+
47
+ print(f"Loading data from {args.data}")
48
+ val_loader = load_folder_data(
49
+ args.data,
50
+ substrate=args.substrate if use_settings else None,
51
+ img_size=args.img_size,
52
+ batch_size=args.batch_size,
53
+ return_metadata=use_settings,
54
+ )
55
+
56
+ in_channels = 3 if use_settings else 1
57
+ generator, _ = create_s2f_model(in_channels=in_channels)
58
+ ckpt = torch.load(args.checkpoint, map_location='cpu', weights_only=False)
59
+ generator.load_state_dict(ckpt.get('generator_state_dict', ckpt), strict=True)
60
+
61
+ norm_params = compute_settings_normalization(config_path=config_path) if use_settings else None
62
+ uses_tanh = detect_tanh_output_model(generator)
63
+
64
+ results = evaluate_metrics_on_dataset(
65
+ generator,
66
+ val_loader,
67
+ device=args.device,
68
+ description="Evaluating",
69
+ save_predictions=(args.save_plots is not None or args.output is not None),
70
+ threshold=args.threshold,
71
+ use_settings=use_settings,
72
+ normalization_params=norm_params,
73
+ config_path=config_path,
74
+ substrate_override=args.substrate,
75
+ )
76
+
77
+ report = {'validation': results}
78
+ print_metrics_report(report, threshold=args.threshold, uses_tanh=uses_tanh)
79
+ print(f"Samples: {len(val_loader.dataset)}")
80
+
81
+ if args.save_plots and 'individual_predictions' in results:
82
+ gen_prediction_plots(
83
+ results['individual_predictions'],
84
+ args.save_plots,
85
+ sort_by='mse',
86
+ sort_order='asc',
87
+ threshold=args.threshold,
88
+ )
89
+ print(f"Saved prediction plots to {args.save_plots}")
90
+
91
+ if args.output:
92
+ preds = results.get('individual_predictions', [])
93
+ if preds:
94
+ df = pd.DataFrame([{
95
+ 'mse': p['mse'],
96
+ 'ms_ssim': p['ms_ssim'],
97
+ 'pixel_correlation': p['pixel_correlation'],
98
+ 'relative_magnitude_error': p.get('wfm_relative_magnitude_error'),
99
+ 'force_sum_gt': p['force_sum_gt'],
100
+ 'force_sum_pred': p['force_sum_pred'],
101
+ } for p in preds])
102
+ df.to_csv(args.output, index=False)
103
+ print(f"Saved per-sample metrics to {args.output}")
104
+ else:
105
+ # Fallback: write summary only
106
+ with open(args.output.replace('.csv', '_summary.txt'), 'w') as f:
107
+ f.write(f"MSE: {results['heatmap']['mse']:.6f}\n")
108
+ f.write(f"MS-SSIM: {results['heatmap']['ms_ssim']:.4f}\n")
109
+ f.write(f"Pixel Corr: {results['heatmap']['pixel_correlation']:.4f}\n")
110
+ f.write(f"Rel Mag Error: {results['wfm']['relative_magnitude_error']:.4f}\n")
111
+ print(f"Saved summary to {args.output.replace('.csv', '_summary.txt')}")
112
+
113
+
114
+ if __name__ == '__main__':
115
+ main()
training/s2f_trainer.py ADDED
@@ -0,0 +1,278 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ S2F training logic: loss, metrics, and training loop.
3
+ """
4
+ import os
5
+ import sys
6
+ import torch
7
+ import torch.nn as nn
8
+ import torch.nn.functional as F
9
+ import matplotlib.pyplot as plt
10
+ from tqdm.auto import tqdm
11
+
12
+ # Add S2F root to path
13
+ S2F_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
14
+ if S2F_ROOT not in sys.path:
15
+ sys.path.insert(0, S2F_ROOT)
16
+
17
+ from models.s2f_model import create_settings_channels, compute_settings_normalization
18
+ from utils.metrics import calculate_psnr, calculate_ssim_tensor, calculate_pearson_correlation
19
+ from scipy.stats import pearsonr
20
+
21
+
22
+ class S2FLoss(nn.Module):
23
+ """S2F loss: reconstruction (L1) + GAN + optional force consistency."""
24
+ def __init__(self, lambda_L1=100.0, lambda_gan=1.0, lambda_force=1.0,
25
+ gan_mode='vanilla', custom_loss=None, use_force_consistency=False,
26
+ force_consistency_target='mean'):
27
+ super().__init__()
28
+ self.lambda_L1 = lambda_L1
29
+ self.lambda_gan = lambda_gan
30
+ self.lambda_force = lambda_force
31
+ self.gan_mode = gan_mode
32
+ self.use_force_consistency = use_force_consistency
33
+ self.force_consistency_target = force_consistency_target
34
+ self.reconstruction_loss = custom_loss if custom_loss is not None else nn.L1Loss()
35
+ self.force_consistency_loss = nn.MSELoss() if use_force_consistency else None
36
+ self.gan_loss = nn.BCEWithLogitsLoss() if gan_mode == 'vanilla' else nn.MSELoss()
37
+
38
+ def forward(self, pred, target, disc_pred=None, disc_target=None):
39
+ recon_loss = self.reconstruction_loss(pred, target)
40
+ gan_loss = 0.0
41
+ if disc_pred is not None and disc_target is not None:
42
+ gan_loss = self.gan_loss(disc_pred, disc_target)
43
+ force_loss = 0.0
44
+ if self.use_force_consistency and self.force_consistency_loss is not None:
45
+ if self.force_consistency_target == 'mean':
46
+ pred_global = torch.mean(pred.view(pred.size(0), -1), dim=1, keepdim=True)
47
+ target_global = torch.mean(target.view(target.size(0), -1), dim=1, keepdim=True)
48
+ else:
49
+ pred_global = torch.sum(pred.view(pred.size(0), -1), dim=1, keepdim=True)
50
+ target_global = torch.sum(target.view(target.size(0), -1), dim=1, keepdim=True)
51
+ force_loss = self.force_consistency_loss(pred_global, target_global)
52
+ total = self.lambda_L1 * recon_loss + self.lambda_gan * gan_loss + self.lambda_force * force_loss
53
+ return total, recon_loss, gan_loss, force_loss
54
+
55
+
56
+ def calculate_soft_dice_loss(pred, target, smooth=1e-6):
57
+ """Dice score (higher is better)."""
58
+ pred_flat = pred.view(pred.size(0), -1)
59
+ target_flat = target.view(target.size(0), -1)
60
+ intersection = (pred_flat * target_flat).sum(dim=1)
61
+ dice_scores = (2.0 * intersection + smooth) / (pred_flat.sum(dim=1) + target_flat.sum(dim=1) + smooth)
62
+ return dice_scores.mean().item()
63
+
64
+
65
+ def train_s2f(generator, discriminator, train_loader, val_loader, device='cuda',
66
+ num_epochs=100, g_lr=2e-4, d_lr=2e-4, beta1=0.5, beta2=0.999,
67
+ save_dir='ckp', lambda_L1=100.0, lambda_gan=1.0, lambda_force=1.0,
68
+ gan_mode='vanilla', save_predictions_every=5, custom_loss=None,
69
+ loaded_metadata=False, use_settings=False, use_force_consistency=False,
70
+ force_consistency_target='mean', config_path=None):
71
+ """
72
+ Train S2F model.
73
+ """
74
+ from diffusers.optimization import get_cosine_schedule_with_warmup
75
+
76
+ config_path = config_path or os.path.join(S2F_ROOT, 'config', 'substrate_settings.json')
77
+ normalization_params = None
78
+ if use_settings:
79
+ if not loaded_metadata:
80
+ raise ValueError("loaded_metadata must be True when use_settings=True")
81
+ normalization_params = compute_settings_normalization(config_path=config_path)
82
+
83
+ history = {'g_loss': [], 'd_loss': [], 'g_recon_loss': [], 'g_gan_loss': [], 'g_force_loss': [],
84
+ 'train_loss': [], 'val_loss': [], 'train_ssim': [], 'val_ssim': [],
85
+ 'train_psnr': [], 'val_psnr': [], 'train_mse': [], 'val_mse': [],
86
+ 'train_dice_score': [], 'val_dice_score': []}
87
+
88
+ if not torch.cuda.is_available() and device == 'cuda':
89
+ device = 'cpu'
90
+ generator = generator.to(device)
91
+ discriminator = discriminator.to(device)
92
+ criterion = S2FLoss(lambda_L1=lambda_L1, lambda_gan=lambda_gan, lambda_force=lambda_force,
93
+ gan_mode=gan_mode, custom_loss=custom_loss,
94
+ use_force_consistency=use_force_consistency,
95
+ force_consistency_target=force_consistency_target)
96
+ g_optimizer = torch.optim.Adam(generator.parameters(), lr=g_lr, betas=(beta1, beta2))
97
+ d_optimizer = torch.optim.Adam(discriminator.parameters(), lr=d_lr, betas=(beta1, beta2))
98
+ num_steps = len(train_loader) * num_epochs
99
+ g_scheduler = get_cosine_schedule_with_warmup(g_optimizer, int(num_steps * 0.1), num_steps)
100
+ d_scheduler = get_cosine_schedule_with_warmup(d_optimizer, int(num_steps * 0.1), num_steps)
101
+
102
+ os.makedirs(save_dir, exist_ok=True)
103
+ vis_dir = os.path.join(save_dir, 'visualizations')
104
+ os.makedirs(vis_dir, exist_ok=True)
105
+ best_val_loss = float('inf')
106
+ disc_output_shape = None
107
+
108
+ for epoch in range(num_epochs):
109
+ generator.train()
110
+ discriminator.train()
111
+ g_loss_total = d_loss_total = g_recon_total = g_gan_total = g_force_total = 0.0
112
+ train_ssim = train_psnr = train_mse = train_dice = 0.0
113
+ pbar = tqdm(train_loader, desc=f'Epoch {epoch}')
114
+
115
+ for batch_data in pbar:
116
+ if loaded_metadata:
117
+ input_images, target_images, _, _, metadata = batch_data
118
+ else:
119
+ input_images, target_images, _, _ = batch_data
120
+ input_images = input_images.to(device, dtype=torch.float32)
121
+ target_images = target_images.to(device, dtype=torch.float32)
122
+ batch_size = input_images.size(0)
123
+
124
+ if use_settings and normalization_params is not None:
125
+ settings_channels = create_settings_channels(
126
+ metadata, normalization_params, device, input_images.shape,
127
+ config_path=config_path
128
+ )
129
+ input_images = torch.cat([input_images, settings_channels], dim=1)
130
+
131
+ target_scaled = target_images * 2.0 - 1.0
132
+ if disc_output_shape is None:
133
+ with torch.no_grad():
134
+ dummy = torch.cat([input_images[:1], target_scaled[:1]], dim=1)
135
+ disc_output_shape = discriminator(dummy).shape[2:]
136
+ real_labels = torch.ones(batch_size, 1, *disc_output_shape).to(device)
137
+ fake_labels = torch.zeros(batch_size, 1, *disc_output_shape).to(device)
138
+
139
+ g_optimizer.zero_grad()
140
+ fake_images = generator(input_images)
141
+ fake_for_loss = (fake_images + 1.0) / 2.0
142
+ fake_input = torch.cat([input_images, fake_images], dim=1)
143
+ fake_pred = discriminator(fake_input)
144
+ g_loss, g_recon, g_gan, g_force = criterion(fake_for_loss, target_images, fake_pred, real_labels)
145
+ g_loss.backward()
146
+ g_optimizer.step()
147
+
148
+ d_optimizer.zero_grad()
149
+ real_input = torch.cat([input_images, target_scaled], dim=1)
150
+ real_pred = discriminator(real_input)
151
+ d_real = criterion.gan_loss(real_pred, real_labels)
152
+ fake_input_d = torch.cat([input_images, fake_images.detach()], dim=1)
153
+ fake_pred_d = discriminator(fake_input_d)
154
+ d_fake = criterion.gan_loss(fake_pred_d, fake_labels)
155
+ d_loss = (d_real + d_fake) * 0.5
156
+ d_loss.backward()
157
+ d_optimizer.step()
158
+ g_scheduler.step()
159
+ d_scheduler.step()
160
+
161
+ g_loss_total += g_loss.item()
162
+ d_loss_total += d_loss.item()
163
+ g_recon_total += g_recon.item()
164
+ g_gan_total += g_gan.item()
165
+ g_force_total += g_force.item() if isinstance(g_force, torch.Tensor) else g_force
166
+ train_ssim += calculate_ssim_tensor(fake_for_loss, target_images)
167
+ train_psnr += calculate_psnr(fake_for_loss, target_images)
168
+ train_mse += F.mse_loss(fake_for_loss, target_images).item()
169
+ train_dice += calculate_soft_dice_loss(fake_for_loss, target_images)
170
+ pbar.set_postfix({'G': g_loss.item(),
171
+ 'D': d_loss.item(), 'Dice': train_dice / (pbar.n + 1)})
172
+
173
+ n_train = len(train_loader)
174
+ g_loss_total /= n_train
175
+ d_loss_total /= n_train
176
+ train_ssim /= n_train
177
+ train_psnr /= n_train
178
+ train_mse /= n_train
179
+ train_dice /= n_train
180
+
181
+ generator.eval()
182
+ val_loss = val_ssim = val_psnr = val_mse = val_dice = 0.0
183
+ with torch.no_grad():
184
+ for batch_data in val_loader:
185
+ if loaded_metadata:
186
+ input_images, target_images, _, _, metadata = batch_data
187
+ else:
188
+ input_images, target_images, _, _ = batch_data
189
+ input_images = input_images.to(device, dtype=torch.float32)
190
+ target_images = target_images.to(device, dtype=torch.float32)
191
+ if use_settings and normalization_params is not None:
192
+ settings_channels = create_settings_channels(
193
+ metadata, normalization_params, device, input_images.shape,
194
+ config_path=config_path
195
+ )
196
+ input_images = torch.cat([input_images, settings_channels], dim=1)
197
+ fake_images = generator(input_images)
198
+ fake_for_loss = (fake_images + 1.0) / 2.0
199
+ _, recon_loss, _, force_loss = criterion(fake_for_loss, target_images)
200
+ val_loss += recon_loss.item()
201
+ val_ssim += calculate_ssim_tensor(fake_for_loss, target_images)
202
+ val_psnr += calculate_psnr(fake_for_loss, target_images)
203
+ val_mse += F.mse_loss(fake_for_loss, target_images).item()
204
+ val_dice += calculate_soft_dice_loss(fake_for_loss, target_images)
205
+ n_val = len(val_loader)
206
+ val_loss /= n_val
207
+ val_ssim /= n_val
208
+ val_psnr /= n_val
209
+ val_mse /= n_val
210
+ val_dice /= n_val
211
+
212
+ history['g_loss'].append(g_loss_total)
213
+ history['d_loss'].append(d_loss_total)
214
+ history['train_loss'].append(g_loss_total)
215
+ history['val_loss'].append(val_loss)
216
+ history['train_ssim'].append(train_ssim)
217
+ history['val_ssim'].append(val_ssim)
218
+ history['train_psnr'].append(train_psnr)
219
+ history['val_psnr'].append(val_psnr)
220
+ history['train_mse'].append(train_mse)
221
+ history['val_mse'].append(val_mse)
222
+ history['train_dice_score'].append(train_dice)
223
+ history['val_dice_score'].append(val_dice)
224
+
225
+ best_mark = "✓" if val_loss < best_val_loss else ""
226
+ print(f"Train: G_Loss:{g_loss_total:.4f} D_Loss:{d_loss_total:.4f} "
227
+ f"MSE:{train_mse:.4f} SSIM:{train_ssim:.4f} Dice:{train_dice:.4f}")
228
+ print(f"Valid: Loss:{val_loss:.4f} MSE:{val_mse:.4f} SSIM:{val_ssim:.4f} Dice:{val_dice:.4f} {best_mark}")
229
+
230
+ checkpoint = {
231
+ 'epoch': epoch,
232
+ 'generator_state_dict': generator.state_dict(),
233
+ 'discriminator_state_dict': discriminator.state_dict(),
234
+ 'g_optimizer_state_dict': g_optimizer.state_dict(),
235
+ 'd_optimizer_state_dict': d_optimizer.state_dict(),
236
+ 'val_loss': val_loss,
237
+ 'history': history
238
+ }
239
+ torch.save(checkpoint, os.path.join(save_dir, 'last_checkpoint.pth'))
240
+ if val_loss < best_val_loss:
241
+ best_val_loss = val_loss
242
+ torch.save(checkpoint, os.path.join(save_dir, 'best_checkpoint.pth'))
243
+
244
+ if epoch % save_predictions_every == 0:
245
+ generator.eval()
246
+ with torch.no_grad():
247
+ batch_data = next(iter(val_loader))
248
+ if loaded_metadata:
249
+ input_images, target_images, _, _, metadata = batch_data
250
+ else:
251
+ input_images, target_images, _, _ = batch_data
252
+ input_images = input_images.to(device, dtype=torch.float32)
253
+ target_images = target_images.to(device, dtype=torch.float32)
254
+ if use_settings and normalization_params is not None:
255
+ settings_channels = create_settings_channels(
256
+ metadata, normalization_params, device, input_images.shape,
257
+ config_path=config_path
258
+ )
259
+ input_images = torch.cat([input_images, settings_channels], dim=1)
260
+ fake_images = generator(input_images)
261
+ fake_vis = (fake_images + 1.0) / 2.0
262
+ n_vis = min(4, input_images.size(0))
263
+ fig, axes = plt.subplots(3, n_vis, figsize=(4 * n_vis, 12))
264
+ if n_vis == 1:
265
+ axes = axes.reshape(3, 1)
266
+ for i in range(n_vis):
267
+ axes[0, i].imshow(input_images[i, 0].cpu().numpy(), cmap='gray')
268
+ axes[0, i].axis('off')
269
+ axes[1, i].imshow(fake_vis[i, 0].cpu().numpy(), cmap='jet', vmin=0, vmax=1)
270
+ axes[1, i].axis('off')
271
+ axes[2, i].imshow(target_images[i, 0].cpu().numpy(), cmap='jet', vmin=0, vmax=1)
272
+ axes[2, i].axis('off')
273
+ plt.tight_layout()
274
+ plt.savefig(os.path.join(vis_dir, f'predictions_epoch_{epoch:02d}.png'), dpi=150, bbox_inches='tight')
275
+ plt.close()
276
+ print(f"Saved visualization for epoch {epoch}")
277
+
278
+ return history
training/train.py ADDED
@@ -0,0 +1,80 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ S2F training script.
4
+ Usage:
5
+ python -m training.train --data path/to/dataset --model single_cell --epochs 100
6
+ python -m training.train --data path/to/dataset --model spheroid --epochs 50
7
+ """
8
+ import os
9
+ import sys
10
+ import argparse
11
+
12
+ S2F_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
13
+ if S2F_ROOT not in sys.path:
14
+ sys.path.insert(0, S2F_ROOT)
15
+
16
+
17
+ def main():
18
+ parser = argparse.ArgumentParser(description='Train S2F model')
19
+ parser.add_argument('--data', required=True, help='Path to dataset (must have train/ and test/ subfolders)')
20
+ parser.add_argument('--model', choices=['single_cell', 'spheroid'], default='single_cell',
21
+ help='Model type: single_cell (with substrate) or spheroid')
22
+ parser.add_argument('--substrate', default=None,
23
+ help='Substrate name for single_cell when metadata not in dataset (e.g. fibroblasts_PDMS)')
24
+ parser.add_argument('--epochs', type=int, default=100)
25
+ parser.add_argument('--batch_size', type=int, default=4)
26
+ parser.add_argument('--img_size', type=int, default=1024)
27
+ parser.add_argument('--save_dir', default='ckp', help='Checkpoint save directory')
28
+ parser.add_argument('--g_lr', type=float, default=2e-4)
29
+ parser.add_argument('--d_lr', type=float, default=2e-4)
30
+ parser.add_argument('--resume', type=str, default=None, help='Path to checkpoint to resume from')
31
+ parser.add_argument('--device', default='cuda')
32
+ parser.add_argument('--no_augment', action='store_true', help='Disable augmentations')
33
+ parser.add_argument('--use_force_consistency', action='store_true')
34
+ parser.add_argument('--force_target', choices=['mean', 'sum'], default='mean')
35
+ args = parser.parse_args()
36
+
37
+ from data.cell_dataset import prepare_data
38
+ from models.s2f_model import create_s2f_model
39
+ from training.s2f_trainer import train_s2f
40
+
41
+ use_settings = args.model == 'single_cell'
42
+ substrate = args.substrate or 'fibroblasts_PDMS'
43
+ return_metadata = use_settings
44
+
45
+ print(f"Loading data from {args.data} (model={args.model})")
46
+ train_loader, val_loader = prepare_data(
47
+ args.data,
48
+ batch_size=args.batch_size,
49
+ target_size=(args.img_size, args.img_size),
50
+ use_augmentations=not args.no_augment,
51
+ train_test_sep_folder=True,
52
+ return_metadata=return_metadata,
53
+ substrate=substrate if use_settings else None,
54
+ )
55
+
56
+ in_channels = 3 if use_settings else 1
57
+ generator, discriminator = create_s2f_model(in_channels=in_channels)
58
+
59
+ if args.resume:
60
+ ckpt = __import__('torch').load(args.resume, map_location='cpu', weights_only=False)
61
+ generator.load_state_dict(ckpt.get('generator_state_dict', ckpt), strict=True)
62
+ print(f"Resumed from {args.resume}")
63
+
64
+ history = train_s2f(
65
+ generator, discriminator,
66
+ train_loader, val_loader,
67
+ device=args.device,
68
+ num_epochs=args.epochs,
69
+ g_lr=args.g_lr, d_lr=args.d_lr,
70
+ save_dir=args.save_dir,
71
+ loaded_metadata=return_metadata,
72
+ use_settings=use_settings,
73
+ use_force_consistency=args.use_force_consistency,
74
+ force_consistency_target=args.force_target,
75
+ )
76
+ print(f"Training complete. Checkpoints saved to {args.save_dir}")
77
+
78
+
79
+ if __name__ == '__main__':
80
+ main()
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 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ }