S2FApp v1.1.0: units (Pa, µm, nN), provenance in reports, FN spheroid default, force-region metrics on, batch PDF report and TIFF (Pa) export
Browse files- S2FApp/README.md +25 -7
- S2FApp/app.py +121 -48
- S2FApp/config/constants.py +29 -1
- S2FApp/download_ckp.py +2 -6
- S2FApp/predictor.py +76 -29
- S2FApp/ui/heatmaps.py +25 -16
- S2FApp/ui/measure_tool.py +31 -74
- S2FApp/ui/result_display.py +207 -245
- S2FApp/utils/display.py +10 -22
- S2FApp/utils/report.py +223 -52
- S2FApp/utils/substrate_settings.py +5 -18
- S2FApp/utils/units.py +125 -0
S2FApp/README.md
CHANGED
|
@@ -29,13 +29,31 @@ Checkpoints are downloaded automatically from the [Shape2Force model repo](https
|
|
| 29 |
|
| 30 |
## Usage
|
| 31 |
|
| 32 |
-
1. Choose **Model type**: Single cell or Spheroid
|
| 33 |
-
2. Select a **Checkpoint** from `ckp/`
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 39 |
|
| 40 |
## Full Project
|
| 41 |
|
|
|
|
| 29 |
|
| 30 |
## Usage
|
| 31 |
|
| 32 |
+
1. Choose **Model type**: Single cell or Spheroid.
|
| 33 |
+
2. Select a **Checkpoint** from `ckp/`. The architecture is read from the checkpoint. For spheroids the default is
|
| 34 |
+
`ckp_spheroid_FN.pth`, a smaller supervised model (11.8 M parameters) with smoother maps and similar accuracy;
|
| 35 |
+
`ckp_spheroid_GN.pth` is the adversarial S2F model (77 M parameters).
|
| 36 |
+
3. Single cell: keep the **Substrate setting** at *Reference (6 kPa)*. The released model is most accurate with this
|
| 37 |
+
setting for every image, including cells on 1 or 10 kPa gels; presets and manual values are for exploration.
|
| 38 |
+
4. Enter the **Image pixel size** (µm/px) of your bright-field image, for the scale bar, area and total force
|
| 39 |
+
(0.325 µm/px for the single-cell training images).
|
| 40 |
+
5. Upload an image or pick one from `samples/`, then click **Run prediction**.
|
| 41 |
+
|
| 42 |
+
## Output and units
|
| 43 |
+
|
| 44 |
+
- The model predicts a normalised map in [0, 1] that converts to **traction stress** as
|
| 45 |
+
T = 500 Pa x value (single cells) or 50 Pa x value (spheroids), the fixed colour limits of the TFM ground-truth
|
| 46 |
+
maps used for training. All maps carry a colourbar in Pa and a µm scale bar.
|
| 47 |
+
- Metrics: mean and maximum traction stress (Pa), area (µm²) and total force (nN = Σ stress x pixel area). By default
|
| 48 |
+
(*Measure force region only*) they are computed inside the region of high predicted stress (red contour), estimated
|
| 49 |
+
from the predicted map, so that the background does not dilute them; switch it off for the whole image.
|
| 50 |
+
S2F predicts magnitude only, not direction.
|
| 51 |
+
- **Display range** narrows the colour window (e.g. 0–250 Pa); stresses above it saturate. Display only.
|
| 52 |
+
- **Downloads**: map PNG (scale bar + colourbar), CSV with metrics and parameters, and a PDF report that records the
|
| 53 |
+
input file, model, checkpoint SHA-256, substrate setting, pixel size, display and force-region settings and app
|
| 54 |
+
version. Batch mode gives a PDF (summary table + one page per image), a CSV, and a ZIP with, per image, the PNG and a
|
| 55 |
+
TIFF whose pixel values are traction stress in Pa (for measurements in Fiji/ImageJ). Set `S2F_APP_COMMIT` to add
|
| 56 |
+
the git commit.
|
| 57 |
|
| 58 |
## Full Project
|
| 59 |
|
S2FApp/app.py
CHANGED
|
@@ -17,18 +17,26 @@ S2F_ROOT = os.path.dirname(os.path.abspath(__file__))
|
|
| 17 |
if S2F_ROOT not in sys.path:
|
| 18 |
sys.path.insert(0, S2F_ROOT)
|
| 19 |
|
|
|
|
|
|
|
| 20 |
from config.constants import (
|
|
|
|
| 21 |
BATCH_INFERENCE_SIZE,
|
| 22 |
BATCH_MAX_IMAGES,
|
| 23 |
COLORMAPS,
|
|
|
|
| 24 |
DEFAULT_SUBSTRATE,
|
| 25 |
MODEL_TYPE_LABELS,
|
|
|
|
| 26 |
SAMPLE_EXTENSIONS,
|
| 27 |
SAMPLE_THUMBNAIL_LIMIT,
|
|
|
|
|
|
|
| 28 |
)
|
| 29 |
from utils.paths import get_ckp_base, get_ckp_folder, get_sample_folder, list_files_in_folder, model_subfolder
|
| 30 |
from utils.segmentation import estimate_cell_mask
|
| 31 |
-
from utils.substrate_settings import list_substrates
|
|
|
|
| 32 |
from utils.display import apply_display_scale
|
| 33 |
from ui.components import (
|
| 34 |
build_original_vals,
|
|
@@ -98,7 +106,7 @@ def _get_measure_dialog_fn():
|
|
| 98 |
|
| 99 |
def _populate_measure_session_state(heatmap, img, pixel_sum, force, key_img, colormap_name,
|
| 100 |
display_mode, auto_cell_boundary, cell_mask=None,
|
| 101 |
-
clip_min=0, clip_max=1, clamp_only=False):
|
| 102 |
"""Populate session state for the measure tool. If cell_mask is None and auto_cell_boundary, computes it."""
|
| 103 |
if cell_mask is None and auto_cell_boundary:
|
| 104 |
cell_mask = estimate_cell_mask(heatmap)
|
|
@@ -109,10 +117,10 @@ def _populate_measure_session_state(heatmap, img, pixel_sum, force, key_img, col
|
|
| 109 |
st.session_state["measure_clamp_only"] = clamp_only
|
| 110 |
st.session_state["measure_bf_img"] = img.copy()
|
| 111 |
st.session_state["measure_input_filename"] = key_img or "image"
|
| 112 |
-
st.session_state["measure_original_vals"] = build_original_vals(heatmap, pixel_sum, force)
|
| 113 |
st.session_state["measure_colormap"] = colormap_name
|
| 114 |
st.session_state["measure_auto_cell_on"] = auto_cell_boundary
|
| 115 |
-
st.session_state["measure_cell_vals"] = build_cell_vals(heatmap, cell_mask, pixel_sum, force) if auto_cell_boundary else None
|
| 116 |
st.session_state["measure_cell_mask"] = cell_mask if auto_cell_boundary else None
|
| 117 |
|
| 118 |
|
|
@@ -131,7 +139,7 @@ if os.path.exists(_css_path):
|
|
| 131 |
st.markdown("""
|
| 132 |
<div class="s2f-header">
|
| 133 |
<h1>🦠 Shape2Force (S2F)</h1>
|
| 134 |
-
<p>Predict traction
|
| 135 |
</div>
|
| 136 |
""", unsafe_allow_html=True)
|
| 137 |
|
|
@@ -228,12 +236,18 @@ with st.sidebar:
|
|
| 228 |
ckp_files = list_files_in_folder(ckp_folder, ".pth")
|
| 229 |
ckp_subfolder_name = model_subfolder(model_type)
|
| 230 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 231 |
if ckp_files:
|
| 232 |
checkpoint = st.selectbox(
|
| 233 |
"Checkpoint",
|
| 234 |
ckp_files,
|
| 235 |
key=f"checkpoint_{model_type}",
|
| 236 |
-
|
|
|
|
| 237 |
)
|
| 238 |
else:
|
| 239 |
st.warning(f"No .pth files in ckp/{ckp_subfolder_name}/. Add checkpoints to load.")
|
|
@@ -241,38 +255,60 @@ with st.sidebar:
|
|
| 241 |
|
| 242 |
substrate_config = None
|
| 243 |
substrate_val = DEFAULT_SUBSTRATE
|
| 244 |
-
use_manual =
|
|
|
|
| 245 |
if model_type == "single_cell":
|
| 246 |
try:
|
| 247 |
with st.container(border=False, key="s2f_grp_conditions"):
|
| 248 |
-
st.markdown('<p class="s2f-form-label s2f-form-label--section">
|
| 249 |
conditions_source = st.radio(
|
| 250 |
-
"
|
| 251 |
-
["
|
| 252 |
horizontal=True,
|
| 253 |
label_visibility="collapsed",
|
|
|
|
|
|
|
|
|
|
| 254 |
)
|
| 255 |
-
|
| 256 |
-
|
| 257 |
-
|
|
|
|
|
|
|
| 258 |
substrates = list_substrates()
|
| 259 |
substrate_val = st.selectbox(
|
| 260 |
-
"
|
| 261 |
-
substrates,
|
| 262 |
-
help="
|
| 263 |
-
label_visibility="collapsed",
|
| 264 |
)
|
| 265 |
-
|
|
|
|
|
|
|
| 266 |
else:
|
| 267 |
-
|
| 268 |
-
|
| 269 |
-
|
|
|
|
|
|
|
| 270 |
value=6000.0, step=100.0, format="%.0f")
|
| 271 |
substrate_config = {"pixelsize": manual_pixelsize, "young": manual_young}
|
| 272 |
use_manual = True
|
|
|
|
|
|
|
| 273 |
except FileNotFoundError:
|
| 274 |
st.error("config/substrate_settings.json not found")
|
| 275 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 276 |
batch_mode = st.toggle(
|
| 277 |
"Batch mode",
|
| 278 |
value=False,
|
|
@@ -280,18 +316,23 @@ with st.sidebar:
|
|
| 280 |
)
|
| 281 |
|
| 282 |
auto_cell_boundary = st.toggle(
|
| 283 |
-
"
|
| 284 |
-
value=
|
| 285 |
-
help="
|
|
|
|
|
|
|
|
|
|
| 286 |
)
|
| 287 |
|
|
|
|
| 288 |
with st.container(border=False, key="s2f_grp_force"):
|
| 289 |
force_scale_mode = st.radio(
|
| 290 |
-
"
|
| 291 |
["Default", "Range"],
|
| 292 |
horizontal=True,
|
| 293 |
key="s2f_force_scale",
|
| 294 |
-
help="Default:
|
|
|
|
| 295 |
)
|
| 296 |
if force_scale_mode == "Default":
|
| 297 |
clip_min, clip_max = 0.0, 1.0
|
|
@@ -300,29 +341,14 @@ with st.sidebar:
|
|
| 300 |
else:
|
| 301 |
mn_col, mx_col = st.columns(2)
|
| 302 |
with mn_col:
|
| 303 |
-
|
| 304 |
-
|
| 305 |
-
min_value=0.0,
|
| 306 |
-
max_value=1.0,
|
| 307 |
-
value=0.0,
|
| 308 |
-
step=0.01,
|
| 309 |
-
format="%.2f",
|
| 310 |
-
key="s2f_clip_min",
|
| 311 |
-
help="Lower bound of the display range (0–1).",
|
| 312 |
-
)
|
| 313 |
with mx_col:
|
| 314 |
-
|
| 315 |
-
|
| 316 |
-
|
| 317 |
-
max_value=1.0,
|
| 318 |
-
value=1.0,
|
| 319 |
-
step=0.01,
|
| 320 |
-
format="%.2f",
|
| 321 |
-
key="s2f_clip_max",
|
| 322 |
-
help="Upper bound of the display range (0–1).",
|
| 323 |
-
)
|
| 324 |
if clip_min >= clip_max:
|
| 325 |
-
st.warning("Min must be less than max. Using 0
|
| 326 |
clip_min, clip_max = 0.0, 1.0
|
| 327 |
display_mode = "Range"
|
| 328 |
clamp_only = False
|
|
@@ -429,12 +455,40 @@ def _load_predictor(model_type, checkpoint, ckp_folder):
|
|
| 429 |
)
|
| 430 |
|
| 431 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 432 |
def _prepare_and_render_cached_result(r, key_img, colormap_name, display_mode, auto_cell_boundary,
|
| 433 |
clip_min, clip_max, clamp_only,
|
| 434 |
download_key_suffix="", check_measure_dialog=False,
|
| 435 |
show_success=False):
|
| 436 |
"""Prepare display from cached result and render. Used by both just_ran and has_cached paths."""
|
| 437 |
img, heatmap, force, pixel_sum = r["img"], r["heatmap"], r["force"], r["pixel_sum"]
|
|
|
|
|
|
|
|
|
|
|
|
|
| 438 |
display_heatmap = apply_display_scale(
|
| 439 |
heatmap, display_mode,
|
| 440 |
clip_min=clip_min,
|
|
@@ -445,7 +499,7 @@ def _prepare_and_render_cached_result(r, key_img, colormap_name, display_mode, a
|
|
| 445 |
_populate_measure_session_state(
|
| 446 |
heatmap, img, pixel_sum, force, key_img, colormap_name,
|
| 447 |
display_mode, auto_cell_boundary, cell_mask=cell_mask,
|
| 448 |
-
clip_min=clip_min, clip_max=clip_max, clamp_only=clamp_only,
|
| 449 |
)
|
| 450 |
if check_measure_dialog and st.session_state.pop("open_measure_dialog", False):
|
| 451 |
measure_region_dialog()
|
|
@@ -460,9 +514,23 @@ def _prepare_and_render_cached_result(r, key_img, colormap_name, display_mode, a
|
|
| 460 |
auto_cell_boundary=auto_cell_boundary,
|
| 461 |
cell_mask=cell_mask,
|
| 462 |
clip_min=clip_min, clip_max=clip_max, clamp_only=clamp_only,
|
|
|
|
| 463 |
)
|
| 464 |
|
| 465 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 466 |
if just_ran_batch:
|
| 467 |
st.session_state["prediction_result"] = None
|
| 468 |
st.session_state["batch_results"] = None
|
|
@@ -484,6 +552,7 @@ if just_ran_batch:
|
|
| 484 |
pred_results.extend(chunk_results)
|
| 485 |
progress_bar.progress(min(start + len(chunk), n_images) / n_images,
|
| 486 |
text=f"Predicting {len(pred_results)} / {n_images} images")
|
|
|
|
| 487 |
batch_results = [
|
| 488 |
{
|
| 489 |
"img": img_b.copy(),
|
|
@@ -491,11 +560,13 @@ if just_ran_batch:
|
|
| 491 |
"force": force,
|
| 492 |
"pixel_sum": pixel_sum,
|
| 493 |
"key_img": key_b,
|
|
|
|
| 494 |
"cell_mask": estimate_cell_mask(heatmap) if auto_cell_boundary else None,
|
| 495 |
}
|
| 496 |
for (img_b, key_b), (heatmap, force, pixel_sum) in zip(imgs_batch, pred_results)
|
| 497 |
]
|
| 498 |
st.session_state["batch_results"] = batch_results
|
|
|
|
| 499 |
progress_bar.empty()
|
| 500 |
st.success(f"Prediction complete for {len(batch_results)} image(s)!")
|
| 501 |
render_batch_results(
|
|
@@ -514,6 +585,7 @@ if just_ran_batch:
|
|
| 514 |
st.code(traceback.format_exc())
|
| 515 |
|
| 516 |
elif batch_mode and st.session_state.get("batch_results"):
|
|
|
|
| 517 |
render_batch_results(
|
| 518 |
st.session_state["batch_results"],
|
| 519 |
colormap_name=colormap_name,
|
|
@@ -542,6 +614,7 @@ elif just_ran:
|
|
| 542 |
"force": force,
|
| 543 |
"pixel_sum": pixel_sum,
|
| 544 |
"cache_key": cache_key,
|
|
|
|
| 545 |
}
|
| 546 |
st.session_state["prediction_result"] = r
|
| 547 |
_prepare_and_render_cached_result(
|
|
|
|
| 17 |
if S2F_ROOT not in sys.path:
|
| 18 |
sys.path.insert(0, S2F_ROOT)
|
| 19 |
|
| 20 |
+
from datetime import datetime, timezone
|
| 21 |
+
|
| 22 |
from config.constants import (
|
| 23 |
+
APP_VERSION,
|
| 24 |
BATCH_INFERENCE_SIZE,
|
| 25 |
BATCH_MAX_IMAGES,
|
| 26 |
COLORMAPS,
|
| 27 |
+
DEFAULT_IMAGE_UM_PER_PX,
|
| 28 |
DEFAULT_SUBSTRATE,
|
| 29 |
MODEL_TYPE_LABELS,
|
| 30 |
+
REFERENCE_SUBSTRATE,
|
| 31 |
SAMPLE_EXTENSIONS,
|
| 32 |
SAMPLE_THUMBNAIL_LIMIT,
|
| 33 |
+
SPHEROID_DEFAULT_CKP,
|
| 34 |
+
STRESS_MAX_PA,
|
| 35 |
)
|
| 36 |
from utils.paths import get_ckp_base, get_ckp_folder, get_sample_folder, list_files_in_folder, model_subfolder
|
| 37 |
from utils.segmentation import estimate_cell_mask
|
| 38 |
+
from utils.substrate_settings import get_settings_of_category, list_substrates
|
| 39 |
+
from utils.units import make_scale
|
| 40 |
from utils.display import apply_display_scale
|
| 41 |
from ui.components import (
|
| 42 |
build_original_vals,
|
|
|
|
| 106 |
|
| 107 |
def _populate_measure_session_state(heatmap, img, pixel_sum, force, key_img, colormap_name,
|
| 108 |
display_mode, auto_cell_boundary, cell_mask=None,
|
| 109 |
+
clip_min=0, clip_max=1, clamp_only=False, scale=None):
|
| 110 |
"""Populate session state for the measure tool. If cell_mask is None and auto_cell_boundary, computes it."""
|
| 111 |
if cell_mask is None and auto_cell_boundary:
|
| 112 |
cell_mask = estimate_cell_mask(heatmap)
|
|
|
|
| 117 |
st.session_state["measure_clamp_only"] = clamp_only
|
| 118 |
st.session_state["measure_bf_img"] = img.copy()
|
| 119 |
st.session_state["measure_input_filename"] = key_img or "image"
|
| 120 |
+
st.session_state["measure_original_vals"] = build_original_vals(heatmap, pixel_sum, force, scale)
|
| 121 |
st.session_state["measure_colormap"] = colormap_name
|
| 122 |
st.session_state["measure_auto_cell_on"] = auto_cell_boundary
|
| 123 |
+
st.session_state["measure_cell_vals"] = build_cell_vals(heatmap, cell_mask, pixel_sum, force, scale) if auto_cell_boundary else None
|
| 124 |
st.session_state["measure_cell_mask"] = cell_mask if auto_cell_boundary else None
|
| 125 |
|
| 126 |
|
|
|
|
| 139 |
st.markdown("""
|
| 140 |
<div class="s2f-header">
|
| 141 |
<h1>🦠 Shape2Force (S2F)</h1>
|
| 142 |
+
<p>Predict traction-stress magnitude maps (Pa) from bright-field microscopy images of cells or spheroids</p>
|
| 143 |
</div>
|
| 144 |
""", unsafe_allow_html=True)
|
| 145 |
|
|
|
|
| 236 |
ckp_files = list_files_in_folder(ckp_folder, ".pth")
|
| 237 |
ckp_subfolder_name = model_subfolder(model_type)
|
| 238 |
|
| 239 |
+
if model_type == "spheroid" and SPHEROID_DEFAULT_CKP in ckp_files:
|
| 240 |
+
ckp_files = [SPHEROID_DEFAULT_CKP] + [f for f in ckp_files if f != SPHEROID_DEFAULT_CKP]
|
| 241 |
+
_ckp_notes = {"ckp_spheroid_FN.pth": "recommended: smoother maps, 11.8 M parameters",
|
| 242 |
+
"ckp_spheroid_GN.pth": "S2F adversarial model, 77 M parameters",
|
| 243 |
+
"ckp_singlecell_GN.pth": "S2F, as in the paper"}
|
| 244 |
if ckp_files:
|
| 245 |
checkpoint = st.selectbox(
|
| 246 |
"Checkpoint",
|
| 247 |
ckp_files,
|
| 248 |
key=f"checkpoint_{model_type}",
|
| 249 |
+
format_func=lambda f: f"{f} ({_ckp_notes[f]})" if f in _ckp_notes else f,
|
| 250 |
+
help=f"Select a .pth file from ckp/{ckp_subfolder_name}/. The architecture is read from the checkpoint.",
|
| 251 |
)
|
| 252 |
else:
|
| 253 |
st.warning(f"No .pth files in ckp/{ckp_subfolder_name}/. Add checkpoints to load.")
|
|
|
|
| 255 |
|
| 256 |
substrate_config = None
|
| 257 |
substrate_val = DEFAULT_SUBSTRATE
|
| 258 |
+
use_manual = False
|
| 259 |
+
substrate_mode_label = "reference"
|
| 260 |
if model_type == "single_cell":
|
| 261 |
try:
|
| 262 |
with st.container(border=False, key="s2f_grp_conditions"):
|
| 263 |
+
st.markdown('<p class="s2f-form-label s2f-form-label--section">Substrate setting (model input)</p>', unsafe_allow_html=True)
|
| 264 |
conditions_source = st.radio(
|
| 265 |
+
"Substrate setting",
|
| 266 |
+
["Reference (6 kPa)", "Preset", "Manual"],
|
| 267 |
horizontal=True,
|
| 268 |
label_visibility="collapsed",
|
| 269 |
+
help="The released model is most accurate with the 6 kPa reference setting for all images, "
|
| 270 |
+
"including cells on 1 or 10 kPa gels (sensitivity analysis in the paper). Other settings "
|
| 271 |
+
"rescale the prediction and are provided for exploration only.",
|
| 272 |
)
|
| 273 |
+
if conditions_source == "Reference (6 kPa)":
|
| 274 |
+
substrate_val = REFERENCE_SUBSTRATE
|
| 275 |
+
st.caption("Recommended. Used for all results in the paper.")
|
| 276 |
+
elif conditions_source == "Preset":
|
| 277 |
+
substrate_mode_label = "preset"
|
| 278 |
substrates = list_substrates()
|
| 279 |
substrate_val = st.selectbox(
|
| 280 |
+
"Preset", substrates,
|
| 281 |
+
index=substrates.index(REFERENCE_SUBSTRATE) if REFERENCE_SUBSTRATE in substrates else 0,
|
| 282 |
+
help="Presets from config/substrate_settings.json", label_visibility="collapsed",
|
|
|
|
| 283 |
)
|
| 284 |
+
if get_settings_of_category(substrate_val) != get_settings_of_category(REFERENCE_SUBSTRATE):
|
| 285 |
+
st.warning("Settings other than the 6 kPa reference reduce accuracy (e.g. the 1 kPa setting "
|
| 286 |
+
"makes predictions about 5 times smaller). Use for exploration only.")
|
| 287 |
else:
|
| 288 |
+
substrate_mode_label = "manual"
|
| 289 |
+
manual_pixelsize = st.number_input("Pixel-size setting (TFM units, as in training)", min_value=0.1,
|
| 290 |
+
max_value=50.0, value=3.0769, step=0.1, format="%.4f",
|
| 291 |
+
help="Training used 3.0769 (fibroblasts) to 9.8138.")
|
| 292 |
+
manual_young = st.number_input("Young's modulus (Pa)", min_value=100.0, max_value=100000.0,
|
| 293 |
value=6000.0, step=100.0, format="%.0f")
|
| 294 |
substrate_config = {"pixelsize": manual_pixelsize, "young": manual_young}
|
| 295 |
use_manual = True
|
| 296 |
+
if (abs(manual_pixelsize - 3.0769) > 1e-3) or manual_young != 6000.0:
|
| 297 |
+
st.warning("Settings other than the 6 kPa reference reduce accuracy. Use for exploration only.")
|
| 298 |
except FileNotFoundError:
|
| 299 |
st.error("config/substrate_settings.json not found")
|
| 300 |
|
| 301 |
+
with st.container(border=False, key="s2f_grp_pixel"):
|
| 302 |
+
_def_px = DEFAULT_IMAGE_UM_PER_PX.get(model_type) or 0.0
|
| 303 |
+
image_um_per_px = st.number_input(
|
| 304 |
+
"Image pixel size (µm/px)",
|
| 305 |
+
min_value=0.0, max_value=100.0, value=float(_def_px), step=0.005, format="%.4f",
|
| 306 |
+
key=f"s2f_um_per_px_{model_type}",
|
| 307 |
+
help="Pixel size of the uploaded bright-field image, for the scale bar, area (µm²) and total force (nN). "
|
| 308 |
+
"0 = unknown (only traction stress in Pa is reported). The single-cell training images "
|
| 309 |
+
"(2048 x 2048 px) have 0.325 µm/px.",
|
| 310 |
+
) or None
|
| 311 |
+
|
| 312 |
batch_mode = st.toggle(
|
| 313 |
"Batch mode",
|
| 314 |
value=False,
|
|
|
|
| 316 |
)
|
| 317 |
|
| 318 |
auto_cell_boundary = st.toggle(
|
| 319 |
+
"Measure force region only",
|
| 320 |
+
value=True,
|
| 321 |
+
help="On (recommended): the metrics are computed inside the region where the predicted traction stress is "
|
| 322 |
+
"high (red contour), so the empty background does not dilute the mean stress or the area. The region is "
|
| 323 |
+
"estimated automatically from the predicted map, not from the cell outline in the bright-field image. "
|
| 324 |
+
"Off: the metrics cover the whole image. For your own regions, use the Measure tool.",
|
| 325 |
)
|
| 326 |
|
| 327 |
+
_smax = STRESS_MAX_PA["spheroid" if model_type == "spheroid" else "single_cell"]
|
| 328 |
with st.container(border=False, key="s2f_grp_force"):
|
| 329 |
force_scale_mode = st.radio(
|
| 330 |
+
"Display range",
|
| 331 |
["Default", "Range"],
|
| 332 |
horizontal=True,
|
| 333 |
key="s2f_force_scale",
|
| 334 |
+
help=f"Default: 0–{_smax:.0f} Pa (the full output scale of this model). Range: show a narrower window, "
|
| 335 |
+
"e.g. 0–250 Pa; stresses above the window are shown in the top colour. Display only.",
|
| 336 |
)
|
| 337 |
if force_scale_mode == "Default":
|
| 338 |
clip_min, clip_max = 0.0, 1.0
|
|
|
|
| 341 |
else:
|
| 342 |
mn_col, mx_col = st.columns(2)
|
| 343 |
with mn_col:
|
| 344 |
+
lo_pa = st.number_input("Min (Pa)", min_value=0.0, max_value=_smax, value=0.0, step=_smax / 50,
|
| 345 |
+
format="%.0f", key=f"s2f_clip_min_pa_{model_type}")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 346 |
with mx_col:
|
| 347 |
+
hi_pa = st.number_input("Max (Pa)", min_value=0.0, max_value=_smax, value=_smax, step=_smax / 50,
|
| 348 |
+
format="%.0f", key=f"s2f_clip_max_pa_{model_type}")
|
| 349 |
+
clip_min, clip_max = lo_pa / _smax, hi_pa / _smax
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 350 |
if clip_min >= clip_max:
|
| 351 |
+
st.warning(f"Min must be less than max. Using 0–{_smax:.0f} Pa.")
|
| 352 |
clip_min, clip_max = 0.0, 1.0
|
| 353 |
display_mode = "Range"
|
| 354 |
clamp_only = False
|
|
|
|
| 455 |
)
|
| 456 |
|
| 457 |
|
| 458 |
+
def _build_info(predictor, key_img, img, pred_time, image_um_per_px, display_mode, clip_min, clip_max, colormap_name,
|
| 459 |
+
auto_cell_boundary):
|
| 460 |
+
"""Provenance of one prediction (shown in the app and written to CSV/PDF)."""
|
| 461 |
+
smax = STRESS_MAX_PA["spheroid" if predictor.model_type == "spheroid" else "single_cell"]
|
| 462 |
+
sub = None
|
| 463 |
+
if predictor.model_type == "single_cell":
|
| 464 |
+
settings = substrate_config if (use_manual and substrate_config) else get_settings_of_category(sub_val_for_info)
|
| 465 |
+
sub = {"mode": substrate_mode_label if substrate_mode_label != "reference" else "preset",
|
| 466 |
+
"name": None if use_manual else (sub_val_for_info + (" (reference)" if substrate_mode_label == "reference" else "")),
|
| 467 |
+
"pixelsize": float(settings["pixelsize"]), "young": float(settings["young"]),
|
| 468 |
+
**predictor.substrate_channels(sub_val_for_info, substrate_config if use_manual else None)}
|
| 469 |
+
rng = (clip_min * smax, clip_max * smax) if display_mode == "Range" else (0.0, smax)
|
| 470 |
+
return {
|
| 471 |
+
"input_file": key_img or "image", "time": pred_time, "model": predictor.describe(), "substrate": sub,
|
| 472 |
+
"image_shape": tuple(img.shape[:2]), "image_um_per_px": image_um_per_px, "stress_max_pa": smax,
|
| 473 |
+
"display": {"mode": display_mode, "range_pa": rng, "colormap": colormap_name},
|
| 474 |
+
"auto_boundary": bool(auto_cell_boundary), "app_version": APP_VERSION,
|
| 475 |
+
"app_commit": os.environ.get("S2F_APP_COMMIT", ""),
|
| 476 |
+
}
|
| 477 |
+
|
| 478 |
+
|
| 479 |
+
sub_val_for_info = substrate_val if (model_type == "single_cell" and not use_manual) else DEFAULT_SUBSTRATE
|
| 480 |
+
|
| 481 |
+
|
| 482 |
def _prepare_and_render_cached_result(r, key_img, colormap_name, display_mode, auto_cell_boundary,
|
| 483 |
clip_min, clip_max, clamp_only,
|
| 484 |
download_key_suffix="", check_measure_dialog=False,
|
| 485 |
show_success=False):
|
| 486 |
"""Prepare display from cached result and render. Used by both just_ran and has_cached paths."""
|
| 487 |
img, heatmap, force, pixel_sum = r["img"], r["heatmap"], r["force"], r["pixel_sum"]
|
| 488 |
+
predictor = _load_predictor(model_type, checkpoint, ckp_folder)
|
| 489 |
+
scale = make_scale(model_type, image_um_per_px, img.shape[:2], heatmap.shape)
|
| 490 |
+
info = _build_info(predictor, key_img, img, r.get("time", "–"), image_um_per_px, display_mode, clip_min, clip_max,
|
| 491 |
+
colormap_name, auto_cell_boundary)
|
| 492 |
display_heatmap = apply_display_scale(
|
| 493 |
heatmap, display_mode,
|
| 494 |
clip_min=clip_min,
|
|
|
|
| 499 |
_populate_measure_session_state(
|
| 500 |
heatmap, img, pixel_sum, force, key_img, colormap_name,
|
| 501 |
display_mode, auto_cell_boundary, cell_mask=cell_mask,
|
| 502 |
+
clip_min=clip_min, clip_max=clip_max, clamp_only=clamp_only, scale=scale,
|
| 503 |
)
|
| 504 |
if check_measure_dialog and st.session_state.pop("open_measure_dialog", False):
|
| 505 |
measure_region_dialog()
|
|
|
|
| 514 |
auto_cell_boundary=auto_cell_boundary,
|
| 515 |
cell_mask=cell_mask,
|
| 516 |
clip_min=clip_min, clip_max=clip_max, clamp_only=clamp_only,
|
| 517 |
+
scale=scale, info=info,
|
| 518 |
)
|
| 519 |
|
| 520 |
|
| 521 |
+
def _attach_batch_info(results):
|
| 522 |
+
"""Physical scale and provenance for each batch result (depends on current sidebar settings)."""
|
| 523 |
+
predictor = _load_predictor(model_type, checkpoint, ckp_folder)
|
| 524 |
+
for r in results:
|
| 525 |
+
r["scale"] = make_scale(model_type, image_um_per_px, r["img"].shape[:2], r["heatmap"].shape)
|
| 526 |
+
r["info"] = _build_info(predictor, r["key_img"], r["img"], r.get("time", "–"), image_um_per_px, display_mode,
|
| 527 |
+
clip_min, clip_max, colormap_name, auto_cell_boundary)
|
| 528 |
+
|
| 529 |
+
|
| 530 |
+
def _utc_now():
|
| 531 |
+
return datetime.now(timezone.utc).strftime("%Y-%m-%d %H:%M:%S")
|
| 532 |
+
|
| 533 |
+
|
| 534 |
if just_ran_batch:
|
| 535 |
st.session_state["prediction_result"] = None
|
| 536 |
st.session_state["batch_results"] = None
|
|
|
|
| 552 |
pred_results.extend(chunk_results)
|
| 553 |
progress_bar.progress(min(start + len(chunk), n_images) / n_images,
|
| 554 |
text=f"Predicting {len(pred_results)} / {n_images} images")
|
| 555 |
+
pred_time = _utc_now()
|
| 556 |
batch_results = [
|
| 557 |
{
|
| 558 |
"img": img_b.copy(),
|
|
|
|
| 560 |
"force": force,
|
| 561 |
"pixel_sum": pixel_sum,
|
| 562 |
"key_img": key_b,
|
| 563 |
+
"time": pred_time,
|
| 564 |
"cell_mask": estimate_cell_mask(heatmap) if auto_cell_boundary else None,
|
| 565 |
}
|
| 566 |
for (img_b, key_b), (heatmap, force, pixel_sum) in zip(imgs_batch, pred_results)
|
| 567 |
]
|
| 568 |
st.session_state["batch_results"] = batch_results
|
| 569 |
+
_attach_batch_info(batch_results)
|
| 570 |
progress_bar.empty()
|
| 571 |
st.success(f"Prediction complete for {len(batch_results)} image(s)!")
|
| 572 |
render_batch_results(
|
|
|
|
| 585 |
st.code(traceback.format_exc())
|
| 586 |
|
| 587 |
elif batch_mode and st.session_state.get("batch_results"):
|
| 588 |
+
_attach_batch_info(st.session_state["batch_results"])
|
| 589 |
render_batch_results(
|
| 590 |
st.session_state["batch_results"],
|
| 591 |
colormap_name=colormap_name,
|
|
|
|
| 614 |
"force": force,
|
| 615 |
"pixel_sum": pixel_sum,
|
| 616 |
"cache_key": cache_key,
|
| 617 |
+
"time": _utc_now(),
|
| 618 |
}
|
| 619 |
st.session_state["prediction_result"] = r
|
| 620 |
_prepare_and_render_cached_result(
|
S2FApp/config/constants.py
CHANGED
|
@@ -6,8 +6,36 @@ import cv2
|
|
| 6 |
# Model & paths
|
| 7 |
MODEL_INPUT_SIZE = 1024
|
| 8 |
|
| 9 |
-
#
|
|
|
|
|
|
|
|
|
|
|
|
|
| 10 |
DEFAULT_SUBSTRATE = "Fibroblasts_Fibronectin_6KPa"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 11 |
|
| 12 |
# UI
|
| 13 |
CANVAS_SIZE = 320
|
|
|
|
| 6 |
# Model & paths
|
| 7 |
MODEL_INPUT_SIZE = 1024
|
| 8 |
|
| 9 |
+
APP_VERSION = "1.1.0" # shown in reports; the git commit is added from S2F_APP_COMMIT if set
|
| 10 |
+
|
| 11 |
+
# Default substrate (used when config lookup fails or manual mode fallback).
|
| 12 |
+
# 6 kPa reference setting: the released single-cell model is most accurate with it for every image
|
| 13 |
+
# (sensitivity analysis in the paper's revision, Fig. S4), so it is the recommended input.
|
| 14 |
DEFAULT_SUBSTRATE = "Fibroblasts_Fibronectin_6KPa"
|
| 15 |
+
REFERENCE_SUBSTRATE = DEFAULT_SUBSTRATE
|
| 16 |
+
|
| 17 |
+
# Normalisation of the two substrate channels: the ranges used in training (S2F config/substrate_settings.json).
|
| 18 |
+
# Fixed here so that the model input does not depend on which presets the app lists.
|
| 19 |
+
SETTINGS_NORMALIZATION = {"pixelsize": {"min": 3.0769, "max": 9.8138}, "young": {"min": 1000.0, "max": 10000.0}}
|
| 20 |
+
|
| 21 |
+
# Physical scale of the output: the ground-truth maps were exported on a fixed colour scale,
|
| 22 |
+
# so a normalised value of 1 corresponds to this traction stress.
|
| 23 |
+
STRESS_MAX_PA = {"single_cell": 500.0, "spheroid": 50.0}
|
| 24 |
+
|
| 25 |
+
# Default pixel size of the bright-field image (µm/px) offered in the sidebar; None = ask the user.
|
| 26 |
+
# 0.325 µm/px is the pixel size of the 2048 x 2048 single-cell training images (TFM setting 3.0769 px/µm).
|
| 27 |
+
DEFAULT_IMAGE_UM_PER_PX = {"single_cell": 0.325, "spheroid": None}
|
| 28 |
+
|
| 29 |
+
# Spheroid checkpoints: default = the smaller supervised model (FN), which gives smoother maps and similar accuracy
|
| 30 |
+
# (validation, 28 spheroids: pixel r 0.88 vs 0.88, RME 0.44 vs 0.47, MS-SSIM 0.79 vs 0.74 for the S2F/GN model)
|
| 31 |
+
SPHEROID_DEFAULT_CKP = "ckp_spheroid_FN.pth"
|
| 32 |
+
ARCH_LABELS = {
|
| 33 |
+
"s2f": "S2F generator (attention U-Net + PatchGAN training), 77.0 M parameters",
|
| 34 |
+
"s2f_spheroid": "Supervised attention U-Net (no discriminator), 11.8 M parameters",
|
| 35 |
+
}
|
| 36 |
+
|
| 37 |
+
# Auto-boundary parameters (utils/segmentation.estimate_cell_mask defaults), recorded in reports
|
| 38 |
+
AUTO_BOUNDARY_DESCRIPTION = "high-stress region from the predicted map: Otsu threshold x 0.85 after Gaussian smoothing (sigma 2 px), dilated by 4 px"
|
| 39 |
|
| 40 |
# UI
|
| 41 |
CANVAS_SIZE = 320
|
S2FApp/download_ckp.py
CHANGED
|
@@ -14,12 +14,8 @@ if not has_any:
|
|
| 14 |
repo = os.environ.get("HF_MODEL_REPO", "Angione-Lab/Shape2Force")
|
| 15 |
files = list_repo_files(repo)
|
| 16 |
pth_files = [f for f in files if f.startswith("ckp/") and f.endswith(".pth")]
|
| 17 |
-
#
|
| 18 |
-
|
| 19 |
-
if "spheroid" in f and "ckp_spheroid_FN.pth" not in f:
|
| 20 |
-
return False
|
| 21 |
-
return True
|
| 22 |
-
pth_files = [f for f in pth_files if should_download(f)]
|
| 23 |
for f in pth_files:
|
| 24 |
hf_hub_download(repo_id=repo, filename=f, local_dir="/app")
|
| 25 |
print("Downloaded checkpoints from", repo)
|
|
|
|
| 14 |
repo = os.environ.get("HF_MODEL_REPO", "Angione-Lab/Shape2Force")
|
| 15 |
files = list_repo_files(repo)
|
| 16 |
pth_files = [f for f in files if f.startswith("ckp/") and f.endswith(".pth")]
|
| 17 |
+
# All checkpoints: single cell (S2F), spheroid S2F (ckp_spheroid_GN.pth, the model reported in the paper
|
| 18 |
+
# and the app default) and the smaller supervised spheroid model (ckp_spheroid_FN.pth).
|
|
|
|
|
|
|
|
|
|
|
|
|
| 19 |
for f in pth_files:
|
| 20 |
hf_hub_download(repo_id=repo, filename=f, local_dir="/app")
|
| 21 |
print("Downloaded checkpoints from", repo)
|
S2FApp/predictor.py
CHANGED
|
@@ -2,6 +2,7 @@
|
|
| 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
|
|
@@ -77,9 +78,34 @@ def create_settings_channels_single(substrate_name, device, height, width, confi
|
|
| 77 |
return torch.cat([pixelsize_ch, young_ch], dim=1)
|
| 78 |
|
| 79 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 80 |
class S2FPredictor:
|
| 81 |
"""
|
| 82 |
Shape2Force predictor for single-cell or spheroid force map prediction.
|
|
|
|
|
|
|
| 83 |
"""
|
| 84 |
|
| 85 |
def __init__(self, model_type="single_cell", checkpoint_path=None, ckp_folder=None, device=None):
|
|
@@ -97,37 +123,58 @@ class S2FPredictor:
|
|
| 97 |
ckp_dir = ckp_folder if ckp_folder else os.path.join(ckp_base, subfolder)
|
| 98 |
if not os.path.isdir(ckp_dir):
|
| 99 |
ckp_dir = ckp_base # fallback if subfolders not used
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
if
|
| 107 |
-
full_path = checkpoint_path
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
|
| 114 |
-
|
| 115 |
-
|
| 116 |
-
|
| 117 |
-
|
| 118 |
-
|
| 119 |
-
|
| 120 |
-
|
| 121 |
-
|
| 122 |
-
|
| 123 |
-
|
| 124 |
-
self.generator =
|
| 125 |
-
self.
|
| 126 |
-
|
|
|
|
|
|
|
| 127 |
self.norm_params = compute_settings_normalization() if model_type == "single_cell" else None
|
| 128 |
-
self._use_tanh_output = model_type == "single_cell" # single_cell uses tanh, spheroid uses sigmoid
|
| 129 |
self.config_path = os.path.join(S2F_ROOT, "config", "substrate_settings.json")
|
| 130 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 131 |
def predict(self, image_path=None, image_array=None, substrate=None,
|
| 132 |
substrate_config=None):
|
| 133 |
"""
|
|
@@ -171,7 +218,7 @@ class S2FPredictor:
|
|
| 171 |
|
| 172 |
if self._use_tanh_output:
|
| 173 |
pred = (pred + 1.0) / 2.0 # Tanh [-1,1] to [0, 1]
|
| 174 |
-
# else: spheroid already outputs sigmoid [0, 1]
|
| 175 |
heatmap = pred[0, 0].cpu().numpy()
|
| 176 |
force = sum_force_map(pred).item()
|
| 177 |
pixel_sum = float(np.sum(heatmap))
|
|
|
|
| 2 |
Core inference logic for S2F (Shape2Force).
|
| 3 |
Predicts force maps from bright field microscopy images.
|
| 4 |
"""
|
| 5 |
+
import hashlib
|
| 6 |
import os
|
| 7 |
import sys
|
| 8 |
import cv2
|
|
|
|
| 78 |
return torch.cat([pixelsize_ch, young_ch], dim=1)
|
| 79 |
|
| 80 |
|
| 81 |
+
def file_sha256(path, chunk=1 << 20):
|
| 82 |
+
"""SHA-256 of a file (recorded in reports so a prediction can be traced to its checkpoint)."""
|
| 83 |
+
h = hashlib.sha256()
|
| 84 |
+
with open(path, "rb") as f:
|
| 85 |
+
for block in iter(lambda: f.read(chunk), b""):
|
| 86 |
+
h.update(block)
|
| 87 |
+
return h.hexdigest()
|
| 88 |
+
|
| 89 |
+
|
| 90 |
+
def detect_architecture(state_dict):
|
| 91 |
+
"""
|
| 92 |
+
Generator architecture from the checkpoint keys:
|
| 93 |
+
's2f' S2FGenerator (multi-scale input 'scale_pyramid.*'); tanh output -> (y + 1) / 2
|
| 94 |
+
's2f_spheroid' supervised attention U-Net ('encoder1.*'); sigmoid output in [0, 1]
|
| 95 |
+
"""
|
| 96 |
+
keys = list(state_dict.keys())
|
| 97 |
+
if any(k.startswith("scale_pyramid.") or k.startswith("initial_conv.") for k in keys):
|
| 98 |
+
return "s2f"
|
| 99 |
+
if any(k.startswith("encoder1.") for k in keys):
|
| 100 |
+
return "s2f_spheroid"
|
| 101 |
+
raise ValueError("Unrecognised checkpoint: neither S2FGenerator nor the supervised spheroid model")
|
| 102 |
+
|
| 103 |
+
|
| 104 |
class S2FPredictor:
|
| 105 |
"""
|
| 106 |
Shape2Force predictor for single-cell or spheroid force map prediction.
|
| 107 |
+
The generator architecture is selected from the checkpoint itself, so both spheroid checkpoints
|
| 108 |
+
(ckp_spheroid_GN.pth = S2F generator as in the paper, ckp_spheroid_FN.pth = smaller supervised model) load.
|
| 109 |
"""
|
| 110 |
|
| 111 |
def __init__(self, model_type="single_cell", checkpoint_path=None, ckp_folder=None, device=None):
|
|
|
|
| 123 |
ckp_dir = ckp_folder if ckp_folder else os.path.join(ckp_base, subfolder)
|
| 124 |
if not os.path.isdir(ckp_dir):
|
| 125 |
ckp_dir = ckp_base # fallback if subfolders not used
|
| 126 |
+
if not checkpoint_path:
|
| 127 |
+
raise ValueError("checkpoint_path is required")
|
| 128 |
+
|
| 129 |
+
full_path = checkpoint_path
|
| 130 |
+
if not os.path.isabs(checkpoint_path):
|
| 131 |
+
full_path = os.path.join(ckp_dir, checkpoint_path)
|
| 132 |
+
if not os.path.exists(full_path):
|
| 133 |
+
full_path = os.path.join(ckp_base, checkpoint_path) # try base folder
|
| 134 |
+
if not os.path.exists(full_path):
|
| 135 |
+
raise FileNotFoundError(f"Checkpoint not found: {full_path}")
|
| 136 |
+
|
| 137 |
+
checkpoint = torch.load(full_path, map_location="cpu", weights_only=False)
|
| 138 |
+
state = checkpoint.get("generator_state_dict") or checkpoint.get("model_state_dict") or checkpoint
|
| 139 |
+
self.architecture = detect_architecture(state)
|
| 140 |
+
self.in_channels = 3 if model_type == "single_cell" else 1
|
| 141 |
+
generator, _ = create_s2f_model(in_channels=self.in_channels, model_type=self.architecture)
|
| 142 |
+
if model_type == "single_cell":
|
| 143 |
+
generator.load_checkpoint_with_expansion(full_path, strict=True)
|
| 144 |
+
else:
|
| 145 |
+
generator.load_state_dict(state, strict=True)
|
| 146 |
+
if self.architecture == "s2f_spheroid" and hasattr(generator, "set_output_mode"):
|
| 147 |
+
generator.set_output_mode(use_tanh=False) # trained with sigmoid output in [0, 1]
|
| 148 |
+
self._use_tanh_output = self.architecture == "s2f" # S2FGenerator: tanh in [-1, 1]
|
| 149 |
+
|
| 150 |
+
self.generator = generator.to(self.device).eval()
|
| 151 |
+
self.checkpoint_name = os.path.basename(full_path)
|
| 152 |
+
self.checkpoint_sha256 = file_sha256(full_path)
|
| 153 |
+
self.checkpoint_epoch = checkpoint.get("epoch") if isinstance(checkpoint, dict) else None
|
| 154 |
+
self.n_params = sum(p.numel() for p in self.generator.parameters())
|
| 155 |
self.norm_params = compute_settings_normalization() if model_type == "single_cell" else None
|
|
|
|
| 156 |
self.config_path = os.path.join(S2F_ROOT, "config", "substrate_settings.json")
|
| 157 |
|
| 158 |
+
def describe(self):
|
| 159 |
+
"""Model information for reports."""
|
| 160 |
+
return {
|
| 161 |
+
"model_type": self.model_type,
|
| 162 |
+
"architecture": self.architecture,
|
| 163 |
+
"checkpoint": self.checkpoint_name,
|
| 164 |
+
"checkpoint_sha256": self.checkpoint_sha256,
|
| 165 |
+
"checkpoint_epoch": self.checkpoint_epoch,
|
| 166 |
+
"n_params_M": round(self.n_params / 1e6, 1),
|
| 167 |
+
"device": str(self.device),
|
| 168 |
+
}
|
| 169 |
+
|
| 170 |
+
def substrate_channels(self, substrate=None, substrate_config=None):
|
| 171 |
+
"""Values of the two substrate input channels (normalised pixel-size and Young's-modulus settings)."""
|
| 172 |
+
if self.model_type != "single_cell":
|
| 173 |
+
return None
|
| 174 |
+
ch = create_settings_channels_single(substrate if substrate is not None else DEFAULT_SUBSTRATE, "cpu", 1, 1,
|
| 175 |
+
config_path=self.config_path, substrate_config=substrate_config)
|
| 176 |
+
return {"pixelsize_norm": float(ch[0, 0, 0, 0]), "young_norm": float(ch[0, 1, 0, 0])}
|
| 177 |
+
|
| 178 |
def predict(self, image_path=None, image_array=None, substrate=None,
|
| 179 |
substrate_config=None):
|
| 180 |
"""
|
|
|
|
| 218 |
|
| 219 |
if self._use_tanh_output:
|
| 220 |
pred = (pred + 1.0) / 2.0 # Tanh [-1,1] to [0, 1]
|
| 221 |
+
# else: the supervised spheroid model already outputs sigmoid [0, 1]
|
| 222 |
heatmap = pred[0, 0].cpu().numpy()
|
| 223 |
force = sum_force_map(pred).item()
|
| 224 |
pixel_sum = float(np.sum(heatmap))
|
S2FApp/ui/heatmaps.py
CHANGED
|
@@ -44,22 +44,32 @@ def _draw_region_overlay(annotated, mask, color, fill_alpha=0.3, stroke_width=2)
|
|
| 44 |
cv2.drawContours(annotated, contours, -1, color, stroke_width)
|
| 45 |
|
| 46 |
|
| 47 |
-
def
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 48 |
"""
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
When ``is_rescale`` is True (Force scale **Range** with a strict sub-interval), tick labels show
|
| 52 |
-
model force values in ``[clip_min, clip_max]``. The gradient still spans the full colormap because
|
| 53 |
-
the heatmap has already been **rescaled** so the lowest (highest) value in your range maps to
|
| 54 |
-
the colormap minimum (maximum)—same convention as the main Plotly view.
|
| 55 |
"""
|
| 56 |
-
ticks =
|
| 57 |
-
if is_rescale:
|
| 58 |
-
|
| 59 |
-
labels = [f"{clip_min + t * rng:.2f}" for t in ticks]
|
| 60 |
-
else:
|
| 61 |
-
labels = [f"{t:.2f}" for t in ticks]
|
| 62 |
-
|
| 63 |
data_url = _colormap_gradient_base64(colormap_name)
|
| 64 |
labels_html = "".join(f'<span class="cb-tick">{l}</span>' for l in labels)
|
| 65 |
html = f"""
|
|
@@ -69,8 +79,7 @@ def render_horizontal_colorbar(colormap_name, clip_min=0, clip_max=1, is_rescale
|
|
| 69 |
</div>
|
| 70 |
"""
|
| 71 |
st.markdown(html, unsafe_allow_html=True)
|
| 72 |
-
|
| 73 |
-
st.caption(caption)
|
| 74 |
|
| 75 |
|
| 76 |
def make_annotated_heatmap(heatmap_rgb, mask, fill_alpha=0.3, stroke_color=(0, 188, 212), stroke_width=2):
|
|
|
|
| 44 |
cv2.drawContours(annotated, contours, -1, color, stroke_width)
|
| 45 |
|
| 46 |
|
| 47 |
+
def colorbar_ticks_pa(clip_min=0.0, clip_max=1.0, stress_max_pa=500.0, n=5):
|
| 48 |
+
"""Tick positions (0-1 along the colormap) and labels in Pa at round values for the displayed window."""
|
| 49 |
+
lo, hi = float(clip_min), float(clip_max)
|
| 50 |
+
if not hi > lo:
|
| 51 |
+
lo, hi = 0.0, 1.0
|
| 52 |
+
lo_pa, hi_pa = lo * stress_max_pa, hi * stress_max_pa
|
| 53 |
+
span = hi_pa - lo_pa
|
| 54 |
+
raw = span / max(n - 1, 1)
|
| 55 |
+
k = 10 ** np.floor(np.log10(raw))
|
| 56 |
+
step = min((m * k for m in (1, 2, 2.5, 5, 10)), key=lambda st_: abs(st_ - raw))
|
| 57 |
+
first = np.ceil(lo_pa / step - 1e-9) * step
|
| 58 |
+
vals = np.arange(first, hi_pa + 1e-9, step) + 0.0 # +0.0 turns -0 into 0
|
| 59 |
+
pos = [float((v - lo_pa) / span) for v in vals]
|
| 60 |
+
labels = [f"{v:g}" for v in vals]
|
| 61 |
+
return pos, labels
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
def render_horizontal_colorbar(colormap_name, clip_min=0, clip_max=1, is_rescale=False, caption=None,
|
| 65 |
+
stress_max_pa=500.0):
|
| 66 |
"""
|
| 67 |
+
Compact horizontal colorbar (batch mode) labelled in Pa. With a display window (Range mode) the gradient
|
| 68 |
+
spans the window [clip_min, clip_max]; values above it are shown in the top colour.
|
|
|
|
|
|
|
|
|
|
|
|
|
| 69 |
"""
|
| 70 |
+
ticks, labels = colorbar_ticks_pa(clip_min, clip_max, stress_max_pa)
|
| 71 |
+
if not is_rescale:
|
| 72 |
+
ticks, labels = colorbar_ticks_pa(0.0, 1.0, stress_max_pa)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 73 |
data_url = _colormap_gradient_base64(colormap_name)
|
| 74 |
labels_html = "".join(f'<span class="cb-tick">{l}</span>' for l in labels)
|
| 75 |
html = f"""
|
|
|
|
| 79 |
</div>
|
| 80 |
"""
|
| 81 |
st.markdown(html, unsafe_allow_html=True)
|
| 82 |
+
st.caption(caption or "Traction stress (Pa)")
|
|
|
|
| 83 |
|
| 84 |
|
| 85 |
def make_annotated_heatmap(heatmap_rgb, mask, fill_alpha=0.3, stroke_color=(0, 188, 212), stroke_width=2):
|
S2FApp/ui/measure_tool.py
CHANGED
|
@@ -12,6 +12,7 @@ from PIL import Image
|
|
| 12 |
from config.constants import CANVAS_SIZE, DRAW_TOOLS, TOOL_LABELS
|
| 13 |
from utils.report import heatmap_to_rgb_with_contour, create_measure_pdf_report
|
| 14 |
from ui.heatmaps import make_annotated_heatmap_multi_regions
|
|
|
|
| 15 |
|
| 16 |
try:
|
| 17 |
from streamlit_drawable_canvas import st_canvas
|
|
@@ -94,66 +95,32 @@ def parse_canvas_shapes_to_masks(json_data, canvas_h, canvas_w, heatmap_h, heatm
|
|
| 94 |
return masks
|
| 95 |
|
| 96 |
|
| 97 |
-
def build_original_vals(raw_heatmap, pixel_sum, force):
|
| 98 |
-
"""
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
"max": float(np.max(raw_heatmap)),
|
| 103 |
-
"mean": float(np.mean(raw_heatmap)),
|
| 104 |
-
}
|
| 105 |
|
| 106 |
|
| 107 |
-
def _compute_cell_metrics(raw_heatmap, cell_mask, pixel_sum, force):
|
| 108 |
-
"""
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
region_values = raw_heatmap * cell_mask
|
| 113 |
-
cell_pixel_sum = float(np.sum(region_values))
|
| 114 |
-
cell_force = cell_pixel_sum * (force / pixel_sum) if pixel_sum > 0 else cell_pixel_sum
|
| 115 |
-
cell_mean = cell_pixel_sum / area_px
|
| 116 |
-
return cell_pixel_sum, cell_force, cell_mean
|
| 117 |
|
| 118 |
|
| 119 |
-
def build_cell_vals(raw_heatmap, cell_mask, pixel_sum, force):
|
| 120 |
-
"""
|
| 121 |
-
|
| 122 |
-
if
|
| 123 |
return None
|
| 124 |
-
|
| 125 |
-
region_nonzero = region_values[cell_mask > 0]
|
| 126 |
-
cell_max = float(np.max(region_nonzero)) if len(region_nonzero) > 0 else 0
|
| 127 |
-
return {
|
| 128 |
-
"pixel_sum": cell_pixel_sum,
|
| 129 |
-
"force": cell_force,
|
| 130 |
-
"max": cell_max,
|
| 131 |
-
"mean": cell_mean,
|
| 132 |
-
}
|
| 133 |
|
| 134 |
|
| 135 |
def compute_region_metrics(raw_heatmap, mask, original_vals=None):
|
| 136 |
-
"""
|
| 137 |
-
|
| 138 |
-
|
| 139 |
-
region_nonzero = region_values[mask > 0]
|
| 140 |
-
force_sum = float(np.sum(region_values))
|
| 141 |
-
density = force_sum / area_px if area_px > 0 else 0
|
| 142 |
-
region_max = float(np.max(region_nonzero)) if len(region_nonzero) > 0 else 0
|
| 143 |
-
region_mean = float(np.mean(region_nonzero)) if len(region_nonzero) > 0 else 0
|
| 144 |
-
region_force_scaled = (
|
| 145 |
-
force_sum * (original_vals["force"] / original_vals["pixel_sum"])
|
| 146 |
-
if original_vals and original_vals.get("pixel_sum", 0) > 0
|
| 147 |
-
else force_sum
|
| 148 |
-
)
|
| 149 |
-
return {
|
| 150 |
-
"area_px": area_px,
|
| 151 |
-
"force_sum": force_sum,
|
| 152 |
-
"density": density,
|
| 153 |
-
"max": region_max,
|
| 154 |
-
"mean": region_mean,
|
| 155 |
-
"force_scaled": region_force_scaled,
|
| 156 |
-
}
|
| 157 |
|
| 158 |
|
| 159 |
def _draw_contour_on_image(img_rgb, mask, stroke_color=(255, 0, 0), stroke_width=3):
|
|
@@ -171,29 +138,19 @@ def render_region_metrics_and_downloads(metrics_list, masks, heatmap_rgb, input_
|
|
| 171 |
first_region_label=None, bf_img=None, cell_mask=None, colormap_name="Jet"):
|
| 172 |
"""
|
| 173 |
Render per-shape metrics table and download buttons.
|
| 174 |
-
first_region_label: custom label for first row (e.g. '
|
| 175 |
masks: list of region masks (user-drawn only; used for labeled heatmap with R1, R2...).
|
| 176 |
"""
|
| 177 |
base_name = os.path.splitext(input_filename or "image")[0]
|
| 178 |
st.markdown("**Regions (each selection = one row)**")
|
| 179 |
-
|
| 180 |
-
|
| 181 |
-
csv_rows = [["image", "region"] + headers[1:]]
|
| 182 |
-
else:
|
| 183 |
-
headers = ["Region", "Area (px²)", "Force sum", "Mean"]
|
| 184 |
-
csv_rows = [["image", "region", "Area", "Force sum", "Mean"]]
|
| 185 |
table_rows = [headers]
|
| 186 |
for i, metrics in enumerate(metrics_list, 1):
|
| 187 |
region_label = first_region_label if (i == 1 and first_region_label) else f"Region {i - (1 if first_region_label else 0)}"
|
| 188 |
-
|
| 189 |
-
|
| 190 |
-
|
| 191 |
-
csv_rows.append([base_name, region_label, metrics["area_px"], f"{metrics['force_sum']:.3f}",
|
| 192 |
-
f"{metrics['force_scaled']:.1f}", f"{metrics['max']:.3f}", f"{metrics['mean']:.4f}"])
|
| 193 |
-
else:
|
| 194 |
-
row = [region_label, str(metrics["area_px"]), f"{metrics['force_sum']:.4f}", f"{metrics['mean']:.6f}"]
|
| 195 |
-
csv_rows.append([base_name, region_label, metrics["area_px"], f"{metrics['force_sum']:.4f}",
|
| 196 |
-
f"{metrics['mean']:.6f}"])
|
| 197 |
table_rows.append(row)
|
| 198 |
# Render as HTML table to avoid Streamlit's default row/column indices
|
| 199 |
header = table_rows[0]
|
|
@@ -273,14 +230,14 @@ def render_region_canvas(display_heatmap, raw_heatmap=None, bf_img=None, origina
|
|
| 273 |
with right_col:
|
| 274 |
vals = cell_vals if cell_vals else original_vals
|
| 275 |
if vals:
|
| 276 |
-
label = "
|
| 277 |
st.markdown(
|
| 278 |
f'<p class="s2f-measure-vals-heading">{html.escape(label)}</p>'
|
| 279 |
f'<div class="s2f-measure-vals-panel"><div class="s2f-measure-vals-grid">'
|
| 280 |
-
f"<span><strong>
|
| 281 |
-
f"<span><strong>
|
| 282 |
-
f"<span><strong>
|
| 283 |
-
f"<span><strong>
|
| 284 |
f"</div></div>",
|
| 285 |
unsafe_allow_html=True,
|
| 286 |
)
|
|
@@ -311,6 +268,6 @@ def render_region_canvas(display_heatmap, raw_heatmap=None, bf_img=None, origina
|
|
| 311 |
metrics_list = [cell_metrics] + metrics_list
|
| 312 |
render_region_metrics_and_downloads(
|
| 313 |
metrics_list, masks, heatmap_rgb, input_filename, key_suffix, original_vals is not None,
|
| 314 |
-
first_region_label="
|
| 315 |
bf_img=bf_img, cell_mask=cell_mask, colormap_name=colormap_name,
|
| 316 |
)
|
|
|
|
| 12 |
from config.constants import CANVAS_SIZE, DRAW_TOOLS, TOOL_LABELS
|
| 13 |
from utils.report import heatmap_to_rgb_with_contour, create_measure_pdf_report
|
| 14 |
from ui.heatmaps import make_annotated_heatmap_multi_regions
|
| 15 |
+
from utils.units import fmt, make_scale, region_metrics
|
| 16 |
|
| 17 |
try:
|
| 18 |
from streamlit_drawable_canvas import st_canvas
|
|
|
|
| 95 |
return masks
|
| 96 |
|
| 97 |
|
| 98 |
+
def build_original_vals(raw_heatmap, pixel_sum, force, scale=None):
|
| 99 |
+
"""Whole-map values for the measure tool (physical units when `scale` is given; see utils/units.py)."""
|
| 100 |
+
scale = scale or make_scale("single_cell")
|
| 101 |
+
m = region_metrics(raw_heatmap, None, scale)
|
| 102 |
+
return {"pixel_sum": pixel_sum, "force": force, "scale": scale, **m}
|
|
|
|
|
|
|
|
|
|
| 103 |
|
| 104 |
|
| 105 |
+
def _compute_cell_metrics(raw_heatmap, cell_mask, pixel_sum, force, scale=None):
|
| 106 |
+
"""Metrics over the estimated cell area: dict from utils.units.region_metrics, or None if the mask is empty."""
|
| 107 |
+
if cell_mask is None or int(np.sum(cell_mask)) == 0:
|
| 108 |
+
return None
|
| 109 |
+
return region_metrics(raw_heatmap, cell_mask, scale or make_scale("single_cell"))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 110 |
|
| 111 |
|
| 112 |
+
def build_cell_vals(raw_heatmap, cell_mask, pixel_sum, force, scale=None):
|
| 113 |
+
"""Values over the estimated cell area for the measure tool. Returns None if invalid."""
|
| 114 |
+
m = _compute_cell_metrics(raw_heatmap, cell_mask, pixel_sum, force, scale)
|
| 115 |
+
if m is None:
|
| 116 |
return None
|
| 117 |
+
return {"scale": scale, **m}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 118 |
|
| 119 |
|
| 120 |
def compute_region_metrics(raw_heatmap, mask, original_vals=None):
|
| 121 |
+
"""Region metrics in physical units (area µm², total force nN, mean/max traction stress Pa)."""
|
| 122 |
+
scale = (original_vals or {}).get("scale") or make_scale("single_cell")
|
| 123 |
+
return region_metrics(raw_heatmap, mask, scale)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 124 |
|
| 125 |
|
| 126 |
def _draw_contour_on_image(img_rgb, mask, stroke_color=(255, 0, 0), stroke_width=3):
|
|
|
|
| 138 |
first_region_label=None, bf_img=None, cell_mask=None, colormap_name="Jet"):
|
| 139 |
"""
|
| 140 |
Render per-shape metrics table and download buttons.
|
| 141 |
+
first_region_label: custom label for first row (e.g. 'Force region').
|
| 142 |
masks: list of region masks (user-drawn only; used for labeled heatmap with R1, R2...).
|
| 143 |
"""
|
| 144 |
base_name = os.path.splitext(input_filename or "image")[0]
|
| 145 |
st.markdown("**Regions (each selection = one row)**")
|
| 146 |
+
headers = ["Region", "Area (µm²)", "Total force (nN)", "Mean stress (Pa)", "Max stress (Pa)"]
|
| 147 |
+
csv_rows = [["image", "region", "area_um2", "total_force_nN", "mean_stress_Pa", "max_stress_Pa", "n_pixels"]]
|
|
|
|
|
|
|
|
|
|
|
|
|
| 148 |
table_rows = [headers]
|
| 149 |
for i, metrics in enumerate(metrics_list, 1):
|
| 150 |
region_label = first_region_label if (i == 1 and first_region_label) else f"Region {i - (1 if first_region_label else 0)}"
|
| 151 |
+
row = [region_label, fmt(metrics["area_um2"], nd=0), fmt(metrics["total_force_nN"], nd=2),
|
| 152 |
+
fmt(metrics["mean_pa"], nd=1), fmt(metrics["max_pa"], nd=1)]
|
| 153 |
+
csv_rows.append([base_name, region_label] + row[1:] + [metrics["n_px"]])
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 154 |
table_rows.append(row)
|
| 155 |
# Render as HTML table to avoid Streamlit's default row/column indices
|
| 156 |
header = table_rows[0]
|
|
|
|
| 230 |
with right_col:
|
| 231 |
vals = cell_vals if cell_vals else original_vals
|
| 232 |
if vals:
|
| 233 |
+
label = "Force region" if cell_vals else "Full map"
|
| 234 |
st.markdown(
|
| 235 |
f'<p class="s2f-measure-vals-heading">{html.escape(label)}</p>'
|
| 236 |
f'<div class="s2f-measure-vals-panel"><div class="s2f-measure-vals-grid">'
|
| 237 |
+
f"<span><strong>Mean:</strong> {fmt(vals.get('mean_pa'), 'Pa')}</span>"
|
| 238 |
+
f"<span><strong>Max:</strong> {fmt(vals.get('max_pa'), 'Pa')}</span>"
|
| 239 |
+
f"<span><strong>Area:</strong> {fmt(vals.get('area_um2'), 'µm²', 0)}</span>"
|
| 240 |
+
f"<span><strong>Force:</strong> {fmt(vals.get('total_force_nN'), 'nN', 2)}</span>"
|
| 241 |
f"</div></div>",
|
| 242 |
unsafe_allow_html=True,
|
| 243 |
)
|
|
|
|
| 268 |
metrics_list = [cell_metrics] + metrics_list
|
| 269 |
render_region_metrics_and_downloads(
|
| 270 |
metrics_list, masks, heatmap_rgb, input_filename, key_suffix, original_vals is not None,
|
| 271 |
+
first_region_label="Force region" if (cell_mask is not None and np.any(cell_mask > 0)) else None,
|
| 272 |
bf_img=bf_img, cell_mask=cell_mask, colormap_name=colormap_name,
|
| 273 |
)
|
S2FApp/ui/result_display.py
CHANGED
|
@@ -1,4 +1,4 @@
|
|
| 1 |
-
"""Result display: single and batch prediction views."""
|
| 2 |
import csv
|
| 3 |
import io
|
| 4 |
import os
|
|
@@ -11,21 +11,29 @@ import plotly.graph_objects as go
|
|
| 11 |
from plotly.subplots import make_subplots
|
| 12 |
|
| 13 |
from utils.display import apply_display_scale, cv_colormap_to_plotly_colorscale, is_display_range_remapped
|
| 14 |
-
from utils.report import
|
|
|
|
| 15 |
from utils.segmentation import estimate_cell_mask
|
| 16 |
-
from
|
|
|
|
| 17 |
from ui.measure_tool import (
|
| 18 |
build_original_vals,
|
| 19 |
build_cell_vals,
|
| 20 |
render_region_canvas,
|
| 21 |
-
_compute_cell_metrics,
|
| 22 |
HAS_DRAWABLE_CANVAS,
|
| 23 |
)
|
| 24 |
|
| 25 |
# Histogram bar color (matches static/s2f_styles.css accent)
|
| 26 |
_HISTOGRAM_ACCENT = "#0d9488"
|
| 27 |
-
_RESULT_FIG_HEIGHT =
|
| 28 |
_HISTOGRAM_HEIGHT = 180
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 29 |
|
| 30 |
|
| 31 |
def _result_banner(badge: str, badge_class: str, title: str) -> str:
|
|
@@ -35,284 +43,266 @@ def _result_banner(badge: str, badge_class: str, title: str) -> str:
|
|
| 35 |
)
|
| 36 |
|
| 37 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 38 |
def render_batch_results(batch_results, colormap_name="Jet", display_mode="Default",
|
| 39 |
-
|
| 40 |
-
|
| 41 |
"""
|
| 42 |
-
Render batch prediction results: summary table, bright-field row, heatmap row
|
| 43 |
-
batch_results: list of dicts with img, heatmap,
|
| 44 |
-
cell_mask is computed on-the-fly when auto_cell_boundary is True and not stored.
|
| 45 |
"""
|
| 46 |
if not batch_results:
|
| 47 |
return
|
| 48 |
|
| 49 |
-
# Resolve cell_mask and precompute display_heatmap for each result
|
| 50 |
for r in batch_results:
|
| 51 |
if auto_cell_boundary and (r.get("cell_mask") is None or not np.any(r.get("cell_mask", 0) > 0)):
|
| 52 |
r["_cell_mask"] = estimate_cell_mask(r["heatmap"])
|
| 53 |
else:
|
| 54 |
r["_cell_mask"] = r.get("cell_mask") if auto_cell_boundary else None
|
| 55 |
-
r["_display_heatmap"] = apply_display_scale(
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
headers = ["Image", "Force", "Sum", "Max", "Mean"]
|
| 61 |
rows = []
|
| 62 |
-
csv_rows = [["image"
|
|
|
|
|
|
|
| 63 |
for r in batch_results:
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
else:
|
| 75 |
-
row = [key, f"{r['force']:.2f}", f"{r['pixel_sum']:.2f}",
|
| 76 |
-
f"{np.max(heatmap):.4f}", f"{np.mean(heatmap):.4f}"]
|
| 77 |
-
rows.append(row)
|
| 78 |
-
csv_rows.append([os.path.splitext(key)[0]] + row[1:])
|
| 79 |
st.markdown(_result_banner("INPUT", "input", "Bright-field images"), unsafe_allow_html=True)
|
| 80 |
n_cols = min(5, len(batch_results))
|
| 81 |
bf_cols = st.columns(n_cols)
|
| 82 |
for i, r in enumerate(batch_results):
|
| 83 |
img = r["img"]
|
| 84 |
-
if img.ndim == 2
|
| 85 |
-
img_rgb = cv2.cvtColor(img, cv2.COLOR_GRAY2RGB)
|
| 86 |
-
else:
|
| 87 |
-
img_rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
|
| 88 |
with bf_cols[i % n_cols]:
|
| 89 |
st.image(img_rgb, caption=r["key_img"], use_container_width=True)
|
| 90 |
is_rescale_b = is_display_range_remapped(display_mode, clip_min, clip_max)
|
| 91 |
-
st.markdown(_result_banner("OUTPUT", "output", "Predicted
|
| 92 |
hm_cols = st.columns(n_cols)
|
| 93 |
for i, r in enumerate(batch_results):
|
| 94 |
-
hm_rgb = heatmap_to_rgb_with_contour(
|
| 95 |
-
|
| 96 |
-
r.get("_cell_mask") if auto_cell_boundary else None,
|
| 97 |
-
)
|
| 98 |
with hm_cols[i % n_cols]:
|
| 99 |
st.image(hm_rgb, caption=r["key_img"], use_container_width=True)
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
st.dataframe(
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
hide_index=True,
|
| 106 |
-
)
|
| 107 |
-
# Histograms in accordion (one per row for visibility)
|
| 108 |
-
with st.expander("Force distribution (histograms)", expanded=False):
|
| 109 |
for i, r in enumerate(batch_results):
|
| 110 |
-
heatmap = r["heatmap"]
|
| 111 |
cell_mask = r.get("_cell_mask")
|
| 112 |
-
vals =
|
|
|
|
| 113 |
vals = vals[vals > 0] if np.any(vals > 0) else vals
|
| 114 |
st.markdown(f"**{r['key_img']}**")
|
| 115 |
if len(vals) > 0:
|
| 116 |
fig = go.Figure(data=[go.Histogram(x=vals, nbinsx=50, marker_color=_HISTOGRAM_ACCENT)])
|
| 117 |
-
fig.update_layout(
|
| 118 |
-
|
| 119 |
-
xaxis_title="Force value", yaxis_title="Count",
|
| 120 |
-
showlegend=False,
|
| 121 |
-
)
|
| 122 |
st.plotly_chart(fig, use_container_width=True, config={"displayModeBar": False})
|
| 123 |
else:
|
| 124 |
st.caption("No data")
|
| 125 |
if i < len(batch_results) - 1:
|
| 126 |
st.divider()
|
| 127 |
-
# Bulk downloads: CSV and heatmaps (zip)
|
| 128 |
buf_csv = io.StringIO()
|
| 129 |
csv.writer(buf_csv).writerows(csv_rows)
|
|
|
|
| 130 |
zip_buf = io.BytesIO()
|
| 131 |
with zipfile.ZipFile(zip_buf, "w", zipfile.ZIP_DEFLATED) as zf:
|
| 132 |
for r in batch_results:
|
| 133 |
-
hm_bytes = heatmap_to_png_bytes(
|
| 134 |
-
r["_display_heatmap"], colormap_name,
|
| 135 |
-
r.get("_cell_mask") if auto_cell_boundary else None,
|
| 136 |
-
)
|
| 137 |
base = os.path.splitext(r["key_img"] or "image")[0]
|
| 138 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 139 |
zip_buf.seek(0)
|
| 140 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 141 |
with dl_col1:
|
| 142 |
-
st.download_button(
|
| 143 |
-
|
| 144 |
-
|
| 145 |
-
file_name="s2f_batch_results.csv",
|
| 146 |
-
mime="text/csv",
|
| 147 |
-
key="download_batch_csv",
|
| 148 |
-
icon=":material/download:",
|
| 149 |
-
)
|
| 150 |
with dl_col2:
|
| 151 |
-
st.download_button(
|
| 152 |
-
|
| 153 |
-
|
| 154 |
-
|
| 155 |
-
|
| 156 |
-
|
| 157 |
-
|
| 158 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 159 |
|
| 160 |
|
| 161 |
def render_result_display(img, raw_heatmap, display_heatmap, pixel_sum, force, key_img, download_key_suffix="",
|
| 162 |
-
|
| 163 |
-
|
| 164 |
"""
|
| 165 |
-
Render
|
| 166 |
-
|
| 167 |
-
|
| 168 |
-
cell_mask: optional precomputed cell mask; if None and auto_cell_boundary, will be computed.
|
| 169 |
"""
|
|
|
|
|
|
|
| 170 |
if cell_mask is None and auto_cell_boundary:
|
| 171 |
cell_mask = estimate_cell_mask(raw_heatmap)
|
| 172 |
elif not auto_cell_boundary:
|
| 173 |
cell_mask = None
|
| 174 |
-
|
| 175 |
-
|
| 176 |
-
|
| 177 |
base_name = os.path.splitext(key_img or "image")[0]
|
| 178 |
-
if use_cell_metrics:
|
| 179 |
-
main_csv_rows = [
|
| 180 |
-
["image", "Cell sum", "Cell force (scaled)", "Heatmap max", "Heatmap mean"],
|
| 181 |
-
[base_name, f"{cell_pixel_sum:.2f}", f"{cell_force:.2f}",
|
| 182 |
-
f"{np.max(raw_heatmap):.4f}", f"{cell_mean:.4f}"],
|
| 183 |
-
]
|
| 184 |
-
else:
|
| 185 |
-
main_csv_rows = [
|
| 186 |
-
["image", "Sum of all pixels", "Force (scaled)", "Heatmap max", "Heatmap mean"],
|
| 187 |
-
[base_name, f"{pixel_sum:.2f}", f"{force:.2f}",
|
| 188 |
-
f"{np.max(raw_heatmap):.4f}", f"{np.mean(raw_heatmap):.4f}"],
|
| 189 |
-
]
|
| 190 |
-
buf_main_csv = io.StringIO()
|
| 191 |
-
csv.writer(buf_main_csv).writerows(main_csv_rows)
|
| 192 |
-
|
| 193 |
-
buf_hm = heatmap_to_png_bytes(display_heatmap, colormap_name, cell_mask=cell_mask)
|
| 194 |
-
|
| 195 |
is_rescale = is_display_range_remapped(display_mode, clip_min, clip_max)
|
|
|
|
| 196 |
|
| 197 |
tit1, tit2 = st.columns(2)
|
| 198 |
with tit1:
|
| 199 |
st.markdown(_result_banner("INPUT", "input", "Bright-field image"), unsafe_allow_html=True)
|
| 200 |
with tit2:
|
| 201 |
-
st.markdown(_result_banner("OUTPUT", "output", "Predicted
|
| 202 |
fig_pl = make_subplots(rows=1, cols=2)
|
| 203 |
-
fig_pl.add_trace(go.Heatmap(z=img, colorscale="gray", showscale=False), row=1, col=1)
|
| 204 |
-
|
| 205 |
-
colorbar_cfg = dict(len=0.
|
| 206 |
-
|
| 207 |
-
|
| 208 |
-
|
| 209 |
-
|
| 210 |
-
|
| 211 |
-
else:
|
| 212 |
-
colorbar_cfg["tickvals"] = tick_positions
|
| 213 |
-
colorbar_cfg["ticktext"] = [f"{t:.2f}" for t in tick_positions]
|
| 214 |
-
fig_pl.add_trace(go.Heatmap(z=display_heatmap, colorscale=plotly_colorscale, zmin=0.0, zmax=1.0, showscale=True,
|
| 215 |
-
colorbar=colorbar_cfg), row=1, col=2)
|
| 216 |
add_cell_contour_to_fig(fig_pl, cell_mask, row=1, col=2)
|
| 217 |
-
fig_pl.
|
| 218 |
-
|
| 219 |
-
|
| 220 |
-
|
| 221 |
-
xaxis2=dict(scaleanchor="y2", scaleratio=1),
|
| 222 |
-
)
|
| 223 |
fig_pl.update_xaxes(showticklabels=False, showgrid=False, zeroline=False)
|
| 224 |
fig_pl.update_yaxes(showticklabels=False, autorange="reversed", showgrid=False, zeroline=False)
|
| 225 |
st.plotly_chart(fig_pl, use_container_width=True, config={"displayModeBar": True, "responsive": True})
|
|
|
|
|
|
|
|
|
|
| 226 |
|
| 227 |
-
|
| 228 |
-
|
| 229 |
-
with
|
| 230 |
-
st.metric(
|
| 231 |
-
|
| 232 |
-
|
| 233 |
-
|
| 234 |
-
st.metric("Heatmap max", f"{np.max(raw_heatmap):.4f}", help="Peak force intensity in the map")
|
| 235 |
-
with col4:
|
| 236 |
-
st.metric("Heatmap mean", f"{cell_mean:.4f}", help="Mean force over estimated cell area")
|
| 237 |
-
else:
|
| 238 |
-
with col1:
|
| 239 |
-
st.metric("Sum of all pixels", f"{pixel_sum:.2f}", help="Raw sum of all pixel values in the force map")
|
| 240 |
-
with col2:
|
| 241 |
-
st.metric("Force (scaled)", f"{force:.2f}", help="Total traction force in physical units (full field of view)")
|
| 242 |
-
with col3:
|
| 243 |
-
st.metric("Heatmap max", f"{np.max(raw_heatmap):.4f}", help="Peak force intensity in the map")
|
| 244 |
-
with col4:
|
| 245 |
-
st.metric("Heatmap mean", f"{np.mean(raw_heatmap):.4f}", help="Average force intensity (full FOV)")
|
| 246 |
|
| 247 |
-
# Statistics panel (mean, std, percentiles, histogram)
|
| 248 |
with st.expander("Statistics"):
|
| 249 |
-
vals = raw_heatmap
|
|
|
|
| 250 |
if len(vals) > 0:
|
| 251 |
-
|
| 252 |
-
p25, p50, p75, p90 = (
|
| 253 |
-
|
| 254 |
-
|
| 255 |
-
|
| 256 |
-
with
|
| 257 |
-
st.metric("
|
| 258 |
-
st.metric("
|
| 259 |
-
with
|
| 260 |
-
st.metric("
|
| 261 |
-
st.metric("
|
| 262 |
-
with stat_col3:
|
| 263 |
-
st.metric("P75", f"{p75:.4f}")
|
| 264 |
-
st.metric("P90", f"{p90:.4f}")
|
| 265 |
-
st.markdown("**Histogram**")
|
| 266 |
hist_fig = go.Figure(data=[go.Histogram(x=vals, nbinsx=50, marker_color=_HISTOGRAM_ACCENT)])
|
| 267 |
-
hist_fig.update_layout(
|
| 268 |
-
|
| 269 |
-
xaxis_title="Force value", yaxis_title="Count",
|
| 270 |
-
showlegend=False,
|
| 271 |
-
)
|
| 272 |
st.plotly_chart(hist_fig, use_container_width=True, config={"displayModeBar": False})
|
| 273 |
else:
|
| 274 |
-
st.caption("No
|
| 275 |
-
|
| 276 |
-
with st.expander("How to read the results"):
|
| 277 |
-
if use_cell_metrics:
|
| 278 |
-
st.markdown("""
|
| 279 |
-
**Input (left):** Bright-field microscopy image of a cell or spheroid on a substrate.
|
| 280 |
-
This is the raw image you provided—it shows cell shape but not forces.
|
| 281 |
|
| 282 |
-
|
| 283 |
-
|
| 284 |
-
- **Brighter/warmer colors** = stronger forces exerted by the cell on the substrate
|
| 285 |
-
- **Red border = estimated cell area** (background excluded from metrics)
|
| 286 |
-
- Values are normalized to [0, 1] for visualization
|
| 287 |
|
| 288 |
-
|
| 289 |
-
|
| 290 |
-
|
| 291 |
-
- **Heatmap max:** Peak force intensity in the map
|
| 292 |
-
- **Heatmap mean:** Mean force over the estimated cell area
|
| 293 |
-
""")
|
| 294 |
-
else:
|
| 295 |
-
st.markdown("""
|
| 296 |
-
**Input (left):** Bright-field microscopy image of a cell or spheroid on a substrate.
|
| 297 |
-
This is the raw image you provided—it shows cell shape but not forces.
|
| 298 |
-
|
| 299 |
-
**Output (right):** Predicted traction force map.
|
| 300 |
-
- **Color** indicates force magnitude: blue = low, red = high
|
| 301 |
-
- **Brighter/warmer colors** = stronger forces exerted by the cell on the substrate
|
| 302 |
-
- Values are normalized to [0, 1] for visualization
|
| 303 |
|
| 304 |
-
**
|
| 305 |
-
-
|
| 306 |
-
-
|
| 307 |
-
-
|
| 308 |
-
|
|
|
|
|
|
|
|
|
|
| 309 |
|
| 310 |
-
|
|
|
|
|
|
|
| 311 |
|
| 312 |
-
|
| 313 |
-
|
| 314 |
-
|
| 315 |
-
|
|
|
|
|
|
|
| 316 |
|
| 317 |
btn_col1, btn_col2, btn_col3, btn_col4 = st.columns(4)
|
| 318 |
with btn_col1:
|
|
@@ -322,48 +312,20 @@ This is the raw image you provided—it shows cell shape but not forces.
|
|
| 322 |
st.rerun()
|
| 323 |
elif HAS_DRAWABLE_CANVAS:
|
| 324 |
with st.expander("Measure tool"):
|
| 325 |
-
expander_cell_vals = build_cell_vals(raw_heatmap, cell_mask, pixel_sum, force) if (auto_cell_boundary and cell_mask is not None) else None
|
| 326 |
-
|
| 327 |
-
|
| 328 |
-
|
| 329 |
-
raw_heatmap=raw_heatmap,
|
| 330 |
-
bf_img=img,
|
| 331 |
-
original_vals=original_vals,
|
| 332 |
-
cell_vals=expander_cell_vals,
|
| 333 |
-
cell_mask=expander_cell_mask,
|
| 334 |
-
key_suffix="expander",
|
| 335 |
-
input_filename=key_img,
|
| 336 |
-
colormap_name=colormap_name,
|
| 337 |
-
)
|
| 338 |
else:
|
| 339 |
st.caption("Install `streamlit-drawable-canvas-fix` for region measurement: `pip install streamlit-drawable-canvas-fix`")
|
| 340 |
with btn_col2:
|
| 341 |
-
st.download_button(
|
| 342 |
-
|
| 343 |
-
|
| 344 |
-
data=buf_hm.getvalue(),
|
| 345 |
-
file_name="s2f_heatmap.png",
|
| 346 |
-
mime="image/png",
|
| 347 |
-
key=f"download_heatmap{download_key_suffix}",
|
| 348 |
-
icon=":material/download:",
|
| 349 |
-
)
|
| 350 |
with btn_col3:
|
| 351 |
-
st.download_button(
|
| 352 |
-
|
| 353 |
-
width="stretch",
|
| 354 |
-
data=buf_main_csv.getvalue(),
|
| 355 |
-
file_name=f"{base_name}_main_values.csv",
|
| 356 |
-
mime="text/csv",
|
| 357 |
-
key=f"download_main_values{download_key_suffix}",
|
| 358 |
-
icon=":material/download:",
|
| 359 |
-
)
|
| 360 |
with btn_col4:
|
| 361 |
-
st.download_button(
|
| 362 |
-
|
| 363 |
-
|
| 364 |
-
data=pdf_bytes,
|
| 365 |
-
file_name=f"{base_name}_report.pdf",
|
| 366 |
-
mime="application/pdf",
|
| 367 |
-
key=f"download_pdf{download_key_suffix}",
|
| 368 |
-
icon=":material/picture_as_pdf:",
|
| 369 |
-
)
|
|
|
|
| 1 |
+
"""Result display: single and batch prediction views (traction stress in Pa, areas in µm², forces in nN)."""
|
| 2 |
import csv
|
| 3 |
import io
|
| 4 |
import os
|
|
|
|
| 11 |
from plotly.subplots import make_subplots
|
| 12 |
|
| 13 |
from utils.display import apply_display_scale, cv_colormap_to_plotly_colorscale, is_display_range_remapped
|
| 14 |
+
from utils.report import (create_batch_pdf_report, create_pdf_report, heatmap_figure_png_bytes,
|
| 15 |
+
heatmap_to_rgb_with_contour, info_rows)
|
| 16 |
from utils.segmentation import estimate_cell_mask
|
| 17 |
+
from utils.units import fmt, make_scale, metric_rows, nice_scale_bar_um, region_metrics, to_pa
|
| 18 |
+
from ui.heatmaps import colorbar_ticks_pa, render_horizontal_colorbar, add_cell_contour_to_fig
|
| 19 |
from ui.measure_tool import (
|
| 20 |
build_original_vals,
|
| 21 |
build_cell_vals,
|
| 22 |
render_region_canvas,
|
|
|
|
| 23 |
HAS_DRAWABLE_CANVAS,
|
| 24 |
)
|
| 25 |
|
| 26 |
# Histogram bar color (matches static/s2f_styles.css accent)
|
| 27 |
_HISTOGRAM_ACCENT = "#0d9488"
|
| 28 |
+
_RESULT_FIG_HEIGHT = 340
|
| 29 |
_HISTOGRAM_HEIGHT = 180
|
| 30 |
+
_METRIC_HELP = {
|
| 31 |
+
"Mean traction stress": "Mean predicted traction-stress magnitude over the region (Pa)",
|
| 32 |
+
"Max traction stress": "Peak predicted traction-stress magnitude (Pa)",
|
| 33 |
+
"Area": "Region area in µm² (needs the image pixel size)",
|
| 34 |
+
"Total force": "Sum of traction stress × pixel area, in nN (needs the image pixel size). Magnitudes only: "
|
| 35 |
+
"vector cancellation is not taken into account",
|
| 36 |
+
}
|
| 37 |
|
| 38 |
|
| 39 |
def _result_banner(badge: str, badge_class: str, title: str) -> str:
|
|
|
|
| 43 |
)
|
| 44 |
|
| 45 |
|
| 46 |
+
def _metrics_csv(base_name, metrics_full, metrics_cell, info):
|
| 47 |
+
"""CSV: one row of metrics with units, then the parameters needed to reproduce the prediction."""
|
| 48 |
+
rows = [["image", "region", "mean_stress_Pa", "max_stress_Pa", "area_um2", "total_force_nN", "n_pixels"]]
|
| 49 |
+
for region, m in [("whole_field", metrics_full), ("force_region", metrics_cell)]:
|
| 50 |
+
if m:
|
| 51 |
+
rows.append([base_name, region, fmt(m["mean_pa"], nd=2), fmt(m["max_pa"], nd=2), fmt(m["area_um2"], nd=1),
|
| 52 |
+
fmt(m["total_force_nN"], nd=3), m["n_px"]])
|
| 53 |
+
rows += [[], ["parameter", "value"]] + [[k.strip(), v] for k, v in info_rows(info)]
|
| 54 |
+
buf = io.StringIO()
|
| 55 |
+
csv.writer(buf).writerows(rows)
|
| 56 |
+
return buf.getvalue()
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
def _add_scale_bar_to_fig(fig, width_px, height_px, um_per_px, row, col):
|
| 60 |
+
"""Draw a µm scale bar (bottom right) on a Plotly image subplot whose axes are in pixels."""
|
| 61 |
+
if not um_per_px:
|
| 62 |
+
return
|
| 63 |
+
length_um = nice_scale_bar_um(width_px * um_per_px)
|
| 64 |
+
if not length_um:
|
| 65 |
+
return
|
| 66 |
+
length_px = length_um / um_per_px
|
| 67 |
+
m = 0.05 * width_px
|
| 68 |
+
x1, y = width_px - m, height_px - m
|
| 69 |
+
xref = "x" if (row, col) == (1, 1) else "x2"
|
| 70 |
+
yref = "y" if (row, col) == (1, 1) else "y2"
|
| 71 |
+
fig.add_shape(type="line", x0=x1 - length_px, x1=x1, y0=y, y1=y, xref=xref, yref=yref,
|
| 72 |
+
line=dict(color="white", width=4))
|
| 73 |
+
fig.add_annotation(x=x1 - length_px / 2, y=y - 0.03 * height_px, xref=xref, yref=yref, text=f"{length_um:g} µm",
|
| 74 |
+
showarrow=False, font=dict(color="white", size=11))
|
| 75 |
+
|
| 76 |
+
|
| 77 |
def render_batch_results(batch_results, colormap_name="Jet", display_mode="Default",
|
| 78 |
+
clip_min=0, clip_max=1,
|
| 79 |
+
auto_cell_boundary=False, clamp_only=False):
|
| 80 |
"""
|
| 81 |
+
Render batch prediction results: summary table (units), bright-field row, heatmap row and bulk downloads.
|
| 82 |
+
batch_results: list of dicts with img, heatmap, key_img, cell_mask, scale, info.
|
|
|
|
| 83 |
"""
|
| 84 |
if not batch_results:
|
| 85 |
return
|
| 86 |
|
|
|
|
| 87 |
for r in batch_results:
|
| 88 |
if auto_cell_boundary and (r.get("cell_mask") is None or not np.any(r.get("cell_mask", 0) > 0)):
|
| 89 |
r["_cell_mask"] = estimate_cell_mask(r["heatmap"])
|
| 90 |
else:
|
| 91 |
r["_cell_mask"] = r.get("cell_mask") if auto_cell_boundary else None
|
| 92 |
+
r["_display_heatmap"] = apply_display_scale(r["heatmap"], display_mode, clip_min=clip_min, clip_max=clip_max)
|
| 93 |
+
r["_metrics"] = region_metrics(r["heatmap"], r["_cell_mask"] if auto_cell_boundary else None, r["scale"])
|
| 94 |
+
|
| 95 |
+
region = "force region (red contour)" if auto_cell_boundary else "whole field"
|
| 96 |
+
headers = ["Image", "Mean stress (Pa)", "Max stress (Pa)", "Area (µm²)", "Total force (nN)"]
|
|
|
|
| 97 |
rows = []
|
| 98 |
+
csv_rows = [["image", "region", "mean_stress_Pa", "max_stress_Pa", "area_um2", "total_force_nN", "n_pixels",
|
| 99 |
+
"model", "checkpoint", "checkpoint_sha256", "substrate_setting", "image_um_per_px", "stress_max_Pa",
|
| 100 |
+
"app_version"]]
|
| 101 |
for r in batch_results:
|
| 102 |
+
m, key, info = r["_metrics"], r["key_img"] or "image", r.get("info", {})
|
| 103 |
+
rows.append([key, fmt(m["mean_pa"], nd=1), fmt(m["max_pa"], nd=1), fmt(m["area_um2"], nd=0),
|
| 104 |
+
fmt(m["total_force_nN"], nd=2)])
|
| 105 |
+
sub = info.get("substrate") or {}
|
| 106 |
+
csv_rows.append([os.path.splitext(key)[0], region, fmt(m["mean_pa"], nd=2), fmt(m["max_pa"], nd=2),
|
| 107 |
+
fmt(m["area_um2"], nd=1), fmt(m["total_force_nN"], nd=3), m["n_px"],
|
| 108 |
+
info.get("model", {}).get("architecture", ""), info.get("model", {}).get("checkpoint", ""),
|
| 109 |
+
info.get("model", {}).get("checkpoint_sha256", ""),
|
| 110 |
+
sub.get("name") or (f"manual {sub.get('pixelsize')}/{sub.get('young')}" if sub else ""),
|
| 111 |
+
info.get("image_um_per_px") or "", info.get("stress_max_pa", ""), info.get("app_version", "")])
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 112 |
st.markdown(_result_banner("INPUT", "input", "Bright-field images"), unsafe_allow_html=True)
|
| 113 |
n_cols = min(5, len(batch_results))
|
| 114 |
bf_cols = st.columns(n_cols)
|
| 115 |
for i, r in enumerate(batch_results):
|
| 116 |
img = r["img"]
|
| 117 |
+
img_rgb = cv2.cvtColor(img, cv2.COLOR_GRAY2RGB) if img.ndim == 2 else cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
|
|
|
|
|
|
|
|
|
|
| 118 |
with bf_cols[i % n_cols]:
|
| 119 |
st.image(img_rgb, caption=r["key_img"], use_container_width=True)
|
| 120 |
is_rescale_b = is_display_range_remapped(display_mode, clip_min, clip_max)
|
| 121 |
+
st.markdown(_result_banner("OUTPUT", "output", "Predicted traction-stress maps"), unsafe_allow_html=True)
|
| 122 |
hm_cols = st.columns(n_cols)
|
| 123 |
for i, r in enumerate(batch_results):
|
| 124 |
+
hm_rgb = heatmap_to_rgb_with_contour(r["_display_heatmap"], colormap_name,
|
| 125 |
+
r.get("_cell_mask") if auto_cell_boundary else None)
|
|
|
|
|
|
|
| 126 |
with hm_cols[i % n_cols]:
|
| 127 |
st.image(hm_rgb, caption=r["key_img"], use_container_width=True)
|
| 128 |
+
smax = batch_results[0]["scale"]["stress_max_pa"]
|
| 129 |
+
render_horizontal_colorbar(colormap_name, clip_min, clip_max, is_rescale_b, stress_max_pa=smax)
|
| 130 |
+
st.dataframe({h: [row[i] for row in rows] for i, h in enumerate(headers)}, use_container_width=True, hide_index=True)
|
| 131 |
+
st.caption(f"Metrics over the {region}. Area and total force need the image pixel size (sidebar).")
|
| 132 |
+
with st.expander("Traction-stress distribution (histograms)", expanded=False):
|
|
|
|
|
|
|
|
|
|
|
|
|
| 133 |
for i, r in enumerate(batch_results):
|
|
|
|
| 134 |
cell_mask = r.get("_cell_mask")
|
| 135 |
+
vals = to_pa(r["heatmap"], r["scale"])
|
| 136 |
+
vals = vals[cell_mask > 0] if (cell_mask is not None and np.any(cell_mask > 0) and auto_cell_boundary) else vals.ravel()
|
| 137 |
vals = vals[vals > 0] if np.any(vals > 0) else vals
|
| 138 |
st.markdown(f"**{r['key_img']}**")
|
| 139 |
if len(vals) > 0:
|
| 140 |
fig = go.Figure(data=[go.Histogram(x=vals, nbinsx=50, marker_color=_HISTOGRAM_ACCENT)])
|
| 141 |
+
fig.update_layout(height=_HISTOGRAM_HEIGHT, margin=dict(l=40, r=20, t=10, b=40),
|
| 142 |
+
xaxis_title="Traction stress (Pa)", yaxis_title="Pixels", showlegend=False)
|
|
|
|
|
|
|
|
|
|
| 143 |
st.plotly_chart(fig, use_container_width=True, config={"displayModeBar": False})
|
| 144 |
else:
|
| 145 |
st.caption("No data")
|
| 146 |
if i < len(batch_results) - 1:
|
| 147 |
st.divider()
|
|
|
|
| 148 |
buf_csv = io.StringIO()
|
| 149 |
csv.writer(buf_csv).writerows(csv_rows)
|
| 150 |
+
lo_b, hi_b = (clip_min, clip_max) if is_rescale_b else (0.0, 1.0)
|
| 151 |
zip_buf = io.BytesIO()
|
| 152 |
with zipfile.ZipFile(zip_buf, "w", zipfile.ZIP_DEFLATED) as zf:
|
| 153 |
for r in batch_results:
|
|
|
|
|
|
|
|
|
|
|
|
|
| 154 |
base = os.path.splitext(r["key_img"] or "image")[0]
|
| 155 |
+
png = heatmap_figure_png_bytes(r["_display_heatmap"], colormap_name,
|
| 156 |
+
r.get("_cell_mask") if auto_cell_boundary else None, r["scale"], lo_b, hi_b)
|
| 157 |
+
zf.writestr(f"{base}_traction_stress.png", png.getvalue())
|
| 158 |
+
zf.writestr(f"{base}_traction_stress_Pa.tif", _tiff_pa_bytes(r["heatmap"], r["scale"]))
|
| 159 |
+
zf.writestr("README.txt", _ZIP_README.format(smax=smax))
|
| 160 |
zip_buf.seek(0)
|
| 161 |
+
pdf_items = [dict(img=r["img"], display_heatmap=r["_display_heatmap"], raw_heatmap=r["heatmap"],
|
| 162 |
+
base_name=os.path.splitext(r["key_img"] or "image")[0],
|
| 163 |
+
cell_mask=r.get("_cell_mask") if auto_cell_boundary else None,
|
| 164 |
+
metrics_full=region_metrics(r["heatmap"], None, r["scale"]),
|
| 165 |
+
metrics_cell=r["_metrics"] if auto_cell_boundary else None,
|
| 166 |
+
info=r.get("info"), scale=r["scale"]) for r in batch_results]
|
| 167 |
+
pdf_bytes = create_batch_pdf_report(pdf_items, colormap_name, lo_b, hi_b, auto_cell_boundary)
|
| 168 |
+
dl_col1, dl_col2, dl_col3 = st.columns(3)
|
| 169 |
with dl_col1:
|
| 170 |
+
st.download_button("Download report (PDF)", data=pdf_bytes, file_name="s2f_batch_report.pdf",
|
| 171 |
+
mime="application/pdf", key="download_batch_pdf", icon=":material/picture_as_pdf:",
|
| 172 |
+
help="Summary table of all images, then one page per image with maps, metrics and parameters.")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 173 |
with dl_col2:
|
| 174 |
+
st.download_button("Download values (CSV)", data=buf_csv.getvalue(), file_name="s2f_batch_results.csv",
|
| 175 |
+
mime="text/csv", key="download_batch_csv", icon=":material/download:",
|
| 176 |
+
help="One row per image: metrics with units and the parameters used.")
|
| 177 |
+
with dl_col3:
|
| 178 |
+
st.download_button("Download maps (ZIP)", data=zip_buf.getvalue(), file_name="s2f_batch_maps.zip",
|
| 179 |
+
mime="application/zip", key="download_batch_heatmaps", icon=":material/image:",
|
| 180 |
+
help="For each image: a PNG to view (colourbar and scale bar) and a TIFF whose pixel "
|
| 181 |
+
"values are traction stress in Pa, for measurements in Fiji/ImageJ.")
|
| 182 |
+
|
| 183 |
+
|
| 184 |
+
_ZIP_README = """Shape2Force (S2F) - predicted traction-stress maps
|
| 185 |
+
|
| 186 |
+
For each image:
|
| 187 |
+
<name>_traction_stress.png picture of the map with colourbar (Pa) and scale bar, for viewing and figures
|
| 188 |
+
<name>_traction_stress_Pa.tif the same map as numbers: each pixel value is the predicted traction stress in Pa
|
| 189 |
+
(32-bit, 1024 x 1024). Open it in Fiji/ImageJ to measure regions yourself
|
| 190 |
+
(e.g. draw an ROI and use Analyze > Measure: Mean = mean traction stress in Pa).
|
| 191 |
+
|
| 192 |
+
Scale: model output 1.0 = {smax:.0f} Pa. S2F predicts the magnitude of the traction stress, not its direction.
|
| 193 |
+
The TIFF covers the whole image resized to 1024 x 1024 pixels; one TIFF pixel = (image width x pixel size / 1024) um.
|
| 194 |
+
"""
|
| 195 |
+
|
| 196 |
+
|
| 197 |
+
def _tiff_pa_bytes(heatmap, scale):
|
| 198 |
+
"""Traction-stress map in Pa as a 32-bit float TIFF (readable by Fiji/ImageJ)."""
|
| 199 |
+
ok, enc = cv2.imencode(".tif", to_pa(heatmap, scale).astype(np.float32))
|
| 200 |
+
return enc.tobytes() if ok else b""
|
| 201 |
|
| 202 |
|
| 203 |
def render_result_display(img, raw_heatmap, display_heatmap, pixel_sum, force, key_img, download_key_suffix="",
|
| 204 |
+
colormap_name="Jet", display_mode="Default", measure_region_dialog=None, auto_cell_boundary=True,
|
| 205 |
+
cell_mask=None, clip_min=0.0, clip_max=1.0, clamp_only=False, scale=None, info=None):
|
| 206 |
"""
|
| 207 |
+
Render one prediction: bright field + traction-stress map (µm scale bars, colourbar in Pa), metrics with
|
| 208 |
+
units, statistics, and downloads (PNG with scale bar and colourbar, CSV and PDF report with all parameters).
|
| 209 |
+
scale: utils.units.make_scale(...); info: provenance dict (see app.py).
|
|
|
|
| 210 |
"""
|
| 211 |
+
scale = scale or make_scale("single_cell", image_shape=img.shape[:2])
|
| 212 |
+
smax = scale["stress_max_pa"]
|
| 213 |
if cell_mask is None and auto_cell_boundary:
|
| 214 |
cell_mask = estimate_cell_mask(raw_heatmap)
|
| 215 |
elif not auto_cell_boundary:
|
| 216 |
cell_mask = None
|
| 217 |
+
metrics_full = region_metrics(raw_heatmap, None, scale)
|
| 218 |
+
metrics_cell = region_metrics(raw_heatmap, cell_mask, scale) if (cell_mask is not None and np.any(cell_mask > 0)) else None
|
| 219 |
+
shown = metrics_cell if (auto_cell_boundary and metrics_cell) else metrics_full
|
| 220 |
base_name = os.path.splitext(key_img or "image")[0]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 221 |
is_rescale = is_display_range_remapped(display_mode, clip_min, clip_max)
|
| 222 |
+
lo, hi = (clip_min, clip_max) if is_rescale else (0.0, 1.0)
|
| 223 |
|
| 224 |
tit1, tit2 = st.columns(2)
|
| 225 |
with tit1:
|
| 226 |
st.markdown(_result_banner("INPUT", "input", "Bright-field image"), unsafe_allow_html=True)
|
| 227 |
with tit2:
|
| 228 |
+
st.markdown(_result_banner("OUTPUT", "output", "Predicted traction-stress map"), unsafe_allow_html=True)
|
| 229 |
fig_pl = make_subplots(rows=1, cols=2)
|
| 230 |
+
fig_pl.add_trace(go.Heatmap(z=img, colorscale="gray", showscale=False, hoverinfo="skip"), row=1, col=1)
|
| 231 |
+
ticks, labels = colorbar_ticks_pa(lo, hi, smax)
|
| 232 |
+
colorbar_cfg = dict(len=0.8, thickness=12, tickmode="array", tickvals=ticks, ticktext=labels,
|
| 233 |
+
title=dict(text="Pa", side="top"))
|
| 234 |
+
fig_pl.add_trace(go.Heatmap(z=display_heatmap, colorscale=cv_colormap_to_plotly_colorscale(colormap_name),
|
| 235 |
+
zmin=0.0, zmax=1.0, showscale=True, colorbar=colorbar_cfg,
|
| 236 |
+
customdata=to_pa(raw_heatmap, scale),
|
| 237 |
+
hovertemplate="x %{x}, y %{y}<br>%{customdata:.1f} Pa<extra></extra>"), row=1, col=2)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 238 |
add_cell_contour_to_fig(fig_pl, cell_mask, row=1, col=2)
|
| 239 |
+
_add_scale_bar_to_fig(fig_pl, img.shape[1], img.shape[0], scale.get("image_um_per_px"), 1, 1)
|
| 240 |
+
_add_scale_bar_to_fig(fig_pl, display_heatmap.shape[1], display_heatmap.shape[0], scale.get("hm_um_per_px_x"), 1, 2)
|
| 241 |
+
fig_pl.update_layout(height=_RESULT_FIG_HEIGHT, margin=dict(l=10, r=10, t=10, b=10),
|
| 242 |
+
xaxis=dict(scaleanchor="y", scaleratio=1), xaxis2=dict(scaleanchor="y2", scaleratio=1))
|
|
|
|
|
|
|
| 243 |
fig_pl.update_xaxes(showticklabels=False, showgrid=False, zeroline=False)
|
| 244 |
fig_pl.update_yaxes(showticklabels=False, autorange="reversed", showgrid=False, zeroline=False)
|
| 245 |
st.plotly_chart(fig_pl, use_container_width=True, config={"displayModeBar": True, "responsive": True})
|
| 246 |
+
if is_rescale:
|
| 247 |
+
st.caption(f"Display range {lo * smax:.0f}–{hi * smax:.0f} Pa; stresses above {hi * smax:.0f} Pa are shown "
|
| 248 |
+
"in the top colour. Metrics always use the full prediction.")
|
| 249 |
|
| 250 |
+
cols = st.columns(4)
|
| 251 |
+
for col, (label, value) in zip(cols, metric_rows(shown)):
|
| 252 |
+
with col:
|
| 253 |
+
st.metric(label, value, help=_METRIC_HELP[label])
|
| 254 |
+
st.caption(("Metrics inside the force region (red contour), estimated from the predicted map." if shown is metrics_cell else
|
| 255 |
+
"Metrics over the whole field of view.")
|
| 256 |
+
+ ("" if scale.get("hm_px_area_um2") else " Enter the image pixel size in the sidebar to get area and total force."))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 257 |
|
|
|
|
| 258 |
with st.expander("Statistics"):
|
| 259 |
+
vals = to_pa(raw_heatmap, scale)
|
| 260 |
+
vals = vals[cell_mask > 0] if (shown is metrics_cell and cell_mask is not None) else vals.ravel()
|
| 261 |
if len(vals) > 0:
|
| 262 |
+
c1, c2, c3 = st.columns(3)
|
| 263 |
+
p25, p50, p75, p90 = (float(np.percentile(vals, q)) for q in (25, 50, 75, 90))
|
| 264 |
+
with c1:
|
| 265 |
+
st.metric("Mean", f"{float(np.mean(vals)):.1f} Pa")
|
| 266 |
+
st.metric("Std", f"{float(np.std(vals)):.1f} Pa")
|
| 267 |
+
with c2:
|
| 268 |
+
st.metric("P25", f"{p25:.1f} Pa")
|
| 269 |
+
st.metric("P50 (median)", f"{p50:.1f} Pa")
|
| 270 |
+
with c3:
|
| 271 |
+
st.metric("P75", f"{p75:.1f} Pa")
|
| 272 |
+
st.metric("P90", f"{p90:.1f} Pa")
|
|
|
|
|
|
|
|
|
|
|
|
|
| 273 |
hist_fig = go.Figure(data=[go.Histogram(x=vals, nbinsx=50, marker_color=_HISTOGRAM_ACCENT)])
|
| 274 |
+
hist_fig.update_layout(height=_HISTOGRAM_HEIGHT, margin=dict(l=40, r=20, t=20, b=40),
|
| 275 |
+
xaxis_title="Traction stress (Pa)", yaxis_title="Pixels", showlegend=False)
|
|
|
|
|
|
|
|
|
|
| 276 |
st.plotly_chart(hist_fig, use_container_width=True, config={"displayModeBar": False})
|
| 277 |
else:
|
| 278 |
+
st.caption("No values to compute statistics.")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 279 |
|
| 280 |
+
with st.expander("Parameters of this prediction"):
|
| 281 |
+
st.table({"Parameter": [k for k, _ in info_rows(info)], "Value": [str(v) for _, v in info_rows(info)]})
|
|
|
|
|
|
|
|
|
|
| 282 |
|
| 283 |
+
with st.expander("How to read the results"):
|
| 284 |
+
st.markdown(f"""
|
| 285 |
+
**Input (left):** the bright-field image you provided (cell shape only, no force information).
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 286 |
|
| 287 |
+
**Output (right):** predicted **traction-stress magnitude** (Pa).
|
| 288 |
+
- The model output is normalised to 0–1, with 1 = **{smax:.0f} Pa**, the fixed colour limit of the
|
| 289 |
+
{'single-cell' if smax >= 500 else 'spheroid'} ground-truth TFM maps used for training. The colourbar shows Pa.
|
| 290 |
+
- S2F predicts the magnitude only, not the direction, and predictions tend to underestimate the highest stresses.
|
| 291 |
+
- **Range** (sidebar) narrows the displayed window, e.g. 0–250 Pa, to show low-stress patterns; stresses above the
|
| 292 |
+
window saturate. The metrics are always computed from the full prediction.
|
| 293 |
+
- **Red contour** ("Measure force region only", on by default): the region of high predicted stress, estimated from
|
| 294 |
+
the map (not the cell outline); the metrics refer to this region so the background does not dilute them.
|
| 295 |
|
| 296 |
+
**Metrics:** mean and maximum traction stress (Pa); area (µm²) and total force (nN = Σ stress × pixel area)
|
| 297 |
+
need the image pixel size. Total force sums magnitudes, so it is not the net force.
|
| 298 |
+
""")
|
| 299 |
|
| 300 |
+
original_vals = build_original_vals(raw_heatmap, pixel_sum, force, scale)
|
| 301 |
+
buf_hm = heatmap_figure_png_bytes(display_heatmap, colormap_name, cell_mask, scale, lo, hi)
|
| 302 |
+
csv_text = _metrics_csv(base_name, metrics_full, metrics_cell, info)
|
| 303 |
+
pdf_bytes = create_pdf_report(img, display_heatmap, raw_heatmap, base_name, colormap_name, cell_mask=cell_mask,
|
| 304 |
+
metrics_full=metrics_full, metrics_cell=metrics_cell, info=info, scale=scale,
|
| 305 |
+
clip_min=lo, clip_max=hi)
|
| 306 |
|
| 307 |
btn_col1, btn_col2, btn_col3, btn_col4 = st.columns(4)
|
| 308 |
with btn_col1:
|
|
|
|
| 312 |
st.rerun()
|
| 313 |
elif HAS_DRAWABLE_CANVAS:
|
| 314 |
with st.expander("Measure tool"):
|
| 315 |
+
expander_cell_vals = build_cell_vals(raw_heatmap, cell_mask, pixel_sum, force, scale) if (auto_cell_boundary and cell_mask is not None) else None
|
| 316 |
+
render_region_canvas(display_heatmap, raw_heatmap=raw_heatmap, bf_img=img, original_vals=original_vals,
|
| 317 |
+
cell_vals=expander_cell_vals, cell_mask=cell_mask if auto_cell_boundary else None,
|
| 318 |
+
key_suffix="expander", input_filename=key_img, colormap_name=colormap_name)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 319 |
else:
|
| 320 |
st.caption("Install `streamlit-drawable-canvas-fix` for region measurement: `pip install streamlit-drawable-canvas-fix`")
|
| 321 |
with btn_col2:
|
| 322 |
+
st.download_button("Download map", width="stretch", data=buf_hm.getvalue(),
|
| 323 |
+
file_name=f"{base_name}_traction_stress.png", mime="image/png",
|
| 324 |
+
key=f"download_heatmap{download_key_suffix}", icon=":material/download:")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 325 |
with btn_col3:
|
| 326 |
+
st.download_button("Download values", width="stretch", data=csv_text, file_name=f"{base_name}_values.csv",
|
| 327 |
+
mime="text/csv", key=f"download_main_values{download_key_suffix}", icon=":material/download:")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 328 |
with btn_col4:
|
| 329 |
+
st.download_button("Download report", width="stretch", data=pdf_bytes, file_name=f"{base_name}_report.pdf",
|
| 330 |
+
mime="application/pdf", key=f"download_pdf{download_key_suffix}",
|
| 331 |
+
icon=":material/picture_as_pdf:")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
S2FApp/utils/display.py
CHANGED
|
@@ -32,30 +32,18 @@ def is_display_range_remapped(display_mode, clip_min, clip_max):
|
|
| 32 |
|
| 33 |
def apply_display_scale(heatmap, mode, clip_min=0, clip_max=1, clamp_only=False):
|
| 34 |
"""
|
| 35 |
-
|
| 36 |
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
clamp_only : bool
|
| 43 |
-
For ``mode == "Range"`` when ``clip_max > clip_min``:
|
| 44 |
-
|
| 45 |
-
- **False** (default in the app for Range): pixels outside ``[clip_min, clip_max]`` are set
|
| 46 |
-
to 0; values inside are linearly mapped to ``[0, 1]`` for the colormap.
|
| 47 |
-
- **True**: values are clamped to ``[clip_min, clip_max]`` without rescaling to ``[0, 1]``.
|
| 48 |
"""
|
|
|
|
| 49 |
if mode != "Range":
|
| 50 |
-
return np.clip(
|
| 51 |
-
# Range
|
| 52 |
vmin, vmax = float(clip_min), float(clip_max)
|
| 53 |
if vmax > vmin:
|
| 54 |
-
h
|
| 55 |
-
|
| 56 |
-
return np.clip(h, vmin, vmax).astype(np.float32)
|
| 57 |
-
mask = (h >= vmin) & (h <= vmax)
|
| 58 |
-
out = np.zeros_like(h)
|
| 59 |
-
out[mask] = (h[mask] - vmin) / (vmax - vmin)
|
| 60 |
-
return np.clip(out, 0, 1).astype(np.float32)
|
| 61 |
-
return np.clip(heatmap, 0, 1).astype(np.float32)
|
|
|
|
| 32 |
|
| 33 |
def apply_display_scale(heatmap, mode, clip_min=0, clip_max=1, clamp_only=False):
|
| 34 |
"""
|
| 35 |
+
Map the normalised prediction (0-1) to colormap positions. Display only; values are unchanged.
|
| 36 |
|
| 37 |
+
``Default``: the full scale, 0-1 (= 0-500 Pa single cells, 0-50 Pa spheroids).
|
| 38 |
+
``Range``: the window [clip_min, clip_max] is stretched over the whole colormap; values below the window
|
| 39 |
+
are shown as the lowest colour and values above it **saturate at the highest colour**. (Earlier versions set
|
| 40 |
+
values above the window to 0, which displayed the strongest stresses as zero.)
|
| 41 |
+
``clamp_only`` is kept for backward compatibility and ignored.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 42 |
"""
|
| 43 |
+
h = np.asarray(heatmap, dtype=np.float32)
|
| 44 |
if mode != "Range":
|
| 45 |
+
return np.clip(h, 0, 1).astype(np.float32)
|
|
|
|
| 46 |
vmin, vmax = float(clip_min), float(clip_max)
|
| 47 |
if vmax > vmin:
|
| 48 |
+
return np.clip((h - vmin) / (vmax - vmin), 0, 1).astype(np.float32)
|
| 49 |
+
return np.clip(h, 0, 1).astype(np.float32)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
S2FApp/utils/report.py
CHANGED
|
@@ -1,5 +1,6 @@
|
|
| 1 |
"""Report and heatmap export utilities."""
|
| 2 |
import io
|
|
|
|
| 3 |
from datetime import datetime
|
| 4 |
|
| 5 |
import cv2
|
|
@@ -10,7 +11,7 @@ from reportlab.lib.units import inch
|
|
| 10 |
from reportlab.lib.utils import ImageReader
|
| 11 |
from reportlab.pdfgen import canvas
|
| 12 |
|
| 13 |
-
from config.constants import COLORMAPS
|
| 14 |
|
| 15 |
|
| 16 |
def _draw_pdf_footer(c, margin=72, footer_y=40, include_web_app=False):
|
|
@@ -82,73 +83,243 @@ def heatmap_to_png_bytes(scaled_heatmap, colormap_name="Jet", cell_mask=None, zm
|
|
| 82 |
return buf
|
| 83 |
|
| 84 |
|
| 85 |
-
def
|
| 86 |
-
|
| 87 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 88 |
buf = io.BytesIO()
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 92 |
page_w_pt, page_h_pt = A4[0], A4[1]
|
| 93 |
-
margin =
|
| 94 |
layout = _pdf_image_layout(page_w_pt, page_h_pt, margin)
|
| 95 |
-
img_w = layout["img_w"]
|
| 96 |
-
|
| 97 |
-
bf_x = layout["bf_x"]
|
| 98 |
-
hm_x = layout["hm_x"]
|
| 99 |
img_bottom = layout["img_bottom"]
|
| 100 |
-
y_top = layout["y_top"]
|
| 101 |
|
| 102 |
_draw_pdf_footer(c, margin=margin, include_web_app=True)
|
| 103 |
-
c.setFont("Helvetica-Bold",
|
| 104 |
c.drawString(margin, y_top, "Shape2Force (S2F) - Prediction Report")
|
| 105 |
c.setFont("Helvetica", 10)
|
| 106 |
-
c.drawString(margin, y_top - 14, f"Image: {base_name}")
|
| 107 |
-
y_top -= 35
|
| 108 |
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 114 |
c.setFont("Helvetica", 9)
|
| 115 |
-
|
| 116 |
-
c.drawString(bf_x + (img_w - bf_label_w) / 2, img_bottom - 14, "Bright-field")
|
| 117 |
|
| 118 |
-
|
| 119 |
-
|
| 120 |
-
Image.fromarray(
|
| 121 |
-
|
| 122 |
-
|
| 123 |
-
|
| 124 |
-
|
| 125 |
-
c.drawString(hm_x + (img_w - hm_label_w) / 2, img_bottom - 14, hm_label)
|
| 126 |
|
| 127 |
-
|
| 128 |
-
row_height = 14
|
| 129 |
-
y = img_bottom - 14 - row_height
|
| 130 |
c.setFont("Helvetica-Bold", 10)
|
| 131 |
c.drawString(margin, y, "Metrics")
|
|
|
|
| 132 |
c.setFont("Helvetica", 9)
|
| 133 |
-
|
| 134 |
-
|
| 135 |
-
|
| 136 |
-
|
| 137 |
-
|
| 138 |
-
|
| 139 |
-
|
| 140 |
-
|
| 141 |
-
|
| 142 |
-
|
| 143 |
-
(
|
| 144 |
-
|
| 145 |
-
|
| 146 |
-
|
| 147 |
-
|
| 148 |
-
|
| 149 |
-
|
| 150 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 151 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 152 |
c.save()
|
| 153 |
buf.seek(0)
|
| 154 |
return buf.getvalue()
|
|
|
|
| 1 |
"""Report and heatmap export utilities."""
|
| 2 |
import io
|
| 3 |
+
import textwrap
|
| 4 |
from datetime import datetime
|
| 5 |
|
| 6 |
import cv2
|
|
|
|
| 11 |
from reportlab.lib.utils import ImageReader
|
| 12 |
from reportlab.pdfgen import canvas
|
| 13 |
|
| 14 |
+
from config.constants import ARCH_LABELS, AUTO_BOUNDARY_DESCRIPTION, COLORMAPS
|
| 15 |
|
| 16 |
|
| 17 |
def _draw_pdf_footer(c, margin=72, footer_y=40, include_web_app=False):
|
|
|
|
| 83 |
return buf
|
| 84 |
|
| 85 |
|
| 86 |
+
def info_rows(info):
|
| 87 |
+
"""Provenance of a prediction as (label, value) rows: everything needed to reproduce it."""
|
| 88 |
+
if not info:
|
| 89 |
+
return []
|
| 90 |
+
m = info.get("model", {})
|
| 91 |
+
rows = [
|
| 92 |
+
("Input file", info.get("input_file", "–")),
|
| 93 |
+
("Prediction time (UTC)", info.get("time", "–")),
|
| 94 |
+
("Model type", {"single_cell": "Single cell", "spheroid": "Spheroid"}.get(m.get("model_type"), "–")),
|
| 95 |
+
("Architecture", ARCH_LABELS.get(m.get("architecture"), m.get("architecture", "–"))),
|
| 96 |
+
("Checkpoint", m.get("checkpoint", "–")),
|
| 97 |
+
("Checkpoint SHA-256", m.get("checkpoint_sha256", "–")),
|
| 98 |
+
]
|
| 99 |
+
sub = info.get("substrate")
|
| 100 |
+
if sub:
|
| 101 |
+
if sub.get("mode") == "preset":
|
| 102 |
+
rows.append(("Substrate setting (preset)", sub.get("name", "–")))
|
| 103 |
+
else:
|
| 104 |
+
rows.append(("Substrate setting (manual)", "–"))
|
| 105 |
+
rows.append((" pixel-size setting / Young's modulus", f"{sub.get('pixelsize'):.4f} / {sub.get('young'):.0f} Pa"))
|
| 106 |
+
rows.append((" model input channels (normalised)",
|
| 107 |
+
f"{sub.get('pixelsize_norm'):.3f} / {sub.get('young_norm'):.3f}"))
|
| 108 |
+
shp = info.get("image_shape")
|
| 109 |
+
rows += [
|
| 110 |
+
("Image size (px)", f"{shp[1]} x {shp[0]}" if shp else "–"),
|
| 111 |
+
("Image pixel size", f"{info['image_um_per_px']:.4f} µm/px (user input)" if info.get("image_um_per_px") else "not set"),
|
| 112 |
+
("Stress scale", f"normalised output 1.0 = {info.get('stress_max_pa', 0):.0f} Pa"),
|
| 113 |
+
]
|
| 114 |
+
d = info.get("display", {})
|
| 115 |
+
if d:
|
| 116 |
+
rows.append(("Display", f"{d.get('colormap', '–')}, {d.get('range_pa', ('–', '–'))[0]:.0f}-{d.get('range_pa', ('–', '–'))[1]:.0f} Pa"
|
| 117 |
+
+ (" (values above the range shown in the top colour)" if d.get("mode") == "Range" else "")))
|
| 118 |
+
rows.append(("Measure force region only", f"on ({AUTO_BOUNDARY_DESCRIPTION})" if info.get("auto_boundary") else "off (whole field of view)"))
|
| 119 |
+
rows.append(("App version", f"{info.get('app_version', '–')}" + (f" (commit {info['app_commit']})" if info.get("app_commit") else "")))
|
| 120 |
+
return rows
|
| 121 |
+
|
| 122 |
+
|
| 123 |
+
def colorbar_strip_rgb(width, colormap_name, clip_min=0.0, clip_max=1.0, stress_max_pa=500.0, height=70):
|
| 124 |
+
"""Horizontal colourbar with tick labels in Pa, as an RGB image (white background)."""
|
| 125 |
+
from ui.heatmaps import colorbar_ticks_pa
|
| 126 |
+
strip = np.full((height, width, 3), 255, np.uint8)
|
| 127 |
+
pad = max(10, width // 30)
|
| 128 |
+
bar_w = width - 2 * pad
|
| 129 |
+
grad = np.linspace(0, 255, bar_w).astype(np.uint8).reshape(1, -1)
|
| 130 |
+
rgb = cv2.cvtColor(cv2.applyColorMap(grad, COLORMAPS.get(colormap_name, cv2.COLORMAP_JET)), cv2.COLOR_BGR2RGB)
|
| 131 |
+
bar_h = height // 4
|
| 132 |
+
strip[6:6 + bar_h, pad:pad + bar_w] = np.repeat(rgb, bar_h, axis=0)
|
| 133 |
+
pos, labels = colorbar_ticks_pa(clip_min, clip_max, stress_max_pa)
|
| 134 |
+
fs = max(0.4, width / 950)
|
| 135 |
+
lw = max(1, int(round(fs * 1.6)))
|
| 136 |
+
for t, lab in zip(pos, labels):
|
| 137 |
+
x = pad + int(t * (bar_w - 1))
|
| 138 |
+
cv2.line(strip, (x, 6 + bar_h), (x, 12 + bar_h), (0, 0, 0), lw)
|
| 139 |
+
(tw, th), _ = cv2.getTextSize(lab, cv2.FONT_HERSHEY_SIMPLEX, fs, lw)
|
| 140 |
+
cv2.putText(strip, lab, (min(max(x - tw // 2, 0), width - tw), 18 + bar_h + th), cv2.FONT_HERSHEY_SIMPLEX, fs,
|
| 141 |
+
(0, 0, 0), lw, cv2.LINE_AA)
|
| 142 |
+
title = "Traction stress (Pa)"
|
| 143 |
+
(tw, th), _ = cv2.getTextSize(title, cv2.FONT_HERSHEY_SIMPLEX, fs, lw)
|
| 144 |
+
cv2.putText(strip, title, ((width - tw) // 2, height - 8), cv2.FONT_HERSHEY_SIMPLEX, fs, (0, 0, 0), lw, cv2.LINE_AA)
|
| 145 |
+
return strip
|
| 146 |
+
|
| 147 |
+
|
| 148 |
+
def heatmap_figure_rgb(display_heatmap, colormap_name="Jet", cell_mask=None, scale=None, clip_min=0.0, clip_max=1.0):
|
| 149 |
+
"""Heatmap with optional red boundary, µm scale bar and a Pa colourbar underneath (for PNG/PDF export)."""
|
| 150 |
+
from utils.units import draw_scale_bar
|
| 151 |
+
hm = heatmap_to_rgb_with_contour(display_heatmap, colormap_name, cell_mask)
|
| 152 |
+
if scale is not None and scale.get("hm_um_per_px_x"):
|
| 153 |
+
draw_scale_bar(hm, scale["hm_um_per_px_x"])
|
| 154 |
+
smax = scale["stress_max_pa"] if scale else 1.0
|
| 155 |
+
bar = colorbar_strip_rgb(hm.shape[1], colormap_name, clip_min, clip_max, smax, height=max(80, hm.shape[0] // 6))
|
| 156 |
+
return np.vstack([hm, bar])
|
| 157 |
+
|
| 158 |
+
|
| 159 |
+
def heatmap_figure_png_bytes(display_heatmap, colormap_name="Jet", cell_mask=None, scale=None, clip_min=0.0, clip_max=1.0):
|
| 160 |
buf = io.BytesIO()
|
| 161 |
+
Image.fromarray(heatmap_figure_rgb(display_heatmap, colormap_name, cell_mask, scale, clip_min, clip_max)).save(buf, format="PNG")
|
| 162 |
+
buf.seek(0)
|
| 163 |
+
return buf
|
| 164 |
+
|
| 165 |
+
|
| 166 |
+
def _draw_prediction_page(c, img, display_heatmap, raw_heatmap, base_name, colormap_name="Jet", cell_mask=None,
|
| 167 |
+
metrics_full=None, metrics_cell=None, info=None, scale=None, clip_min=0.0, clip_max=1.0,
|
| 168 |
+
page_label=None):
|
| 169 |
+
"""Draw one prediction (images, metrics, parameters) on the current page of canvas `c`."""
|
| 170 |
+
from utils.units import draw_scale_bar, metric_rows
|
| 171 |
page_w_pt, page_h_pt = A4[0], A4[1]
|
| 172 |
+
margin = 60
|
| 173 |
layout = _pdf_image_layout(page_w_pt, page_h_pt, margin)
|
| 174 |
+
img_w, img_h = layout["img_w"], layout["img_h"]
|
| 175 |
+
bf_x, hm_x, y_top = layout["bf_x"], layout["hm_x"], layout["y_top"]
|
|
|
|
|
|
|
| 176 |
img_bottom = layout["img_bottom"]
|
|
|
|
| 177 |
|
| 178 |
_draw_pdf_footer(c, margin=margin, include_web_app=True)
|
| 179 |
+
c.setFont("Helvetica-Bold", 15)
|
| 180 |
c.drawString(margin, y_top, "Shape2Force (S2F) - Prediction Report")
|
| 181 |
c.setFont("Helvetica", 10)
|
| 182 |
+
c.drawString(margin, y_top - 14, f"Image: {base_name}" + (f" ({page_label})" if page_label else ""))
|
|
|
|
| 183 |
|
| 184 |
+
bf = img if img.ndim == 3 else cv2.cvtColor(img, cv2.COLOR_GRAY2RGB)
|
| 185 |
+
bf_um_per_px = scale.get("image_um_per_px") if scale else None
|
| 186 |
+
if max(bf.shape[:2]) > 1024: # keep the PDF small; the scale bar follows the resampling
|
| 187 |
+
f = 1024 / max(bf.shape[:2])
|
| 188 |
+
bf = cv2.resize(bf, (int(bf.shape[1] * f), int(bf.shape[0] * f)), interpolation=cv2.INTER_AREA)
|
| 189 |
+
bf_um_per_px = bf_um_per_px / f if bf_um_per_px else None
|
| 190 |
+
bf = np.ascontiguousarray(bf.copy())
|
| 191 |
+
if bf_um_per_px:
|
| 192 |
+
draw_scale_bar(bf, bf_um_per_px)
|
| 193 |
+
bf_buf = io.BytesIO(); Image.fromarray(bf).save(bf_buf, format="PNG"); bf_buf.seek(0)
|
| 194 |
+
c.drawImage(ImageReader(bf_buf), bf_x, img_bottom, width=img_w, height=img_h, preserveAspectRatio=True)
|
| 195 |
c.setFont("Helvetica", 9)
|
| 196 |
+
c.drawCentredString(bf_x + img_w / 2, img_bottom - 12, "Bright field")
|
|
|
|
| 197 |
|
| 198 |
+
fig = heatmap_figure_rgb(display_heatmap, colormap_name, cell_mask, scale, clip_min, clip_max)
|
| 199 |
+
fig_h = img_h * fig.shape[0] / fig.shape[1]
|
| 200 |
+
hm_buf = io.BytesIO(); Image.fromarray(fig).save(hm_buf, format="PNG", optimize=True); hm_buf.seek(0)
|
| 201 |
+
c.drawImage(ImageReader(hm_buf), hm_x, img_bottom + img_h - fig_h, width=img_w, height=fig_h, preserveAspectRatio=True)
|
| 202 |
+
hm_label = "Predicted traction stress (red = force region)" if cell_mask is not None and np.any(cell_mask > 0) \
|
| 203 |
+
else "Predicted traction stress"
|
| 204 |
+
c.drawCentredString(hm_x + img_w / 2, img_bottom + img_h - fig_h - 12, hm_label)
|
|
|
|
| 205 |
|
| 206 |
+
y = img_bottom + img_h - fig_h - 40
|
|
|
|
|
|
|
| 207 |
c.setFont("Helvetica-Bold", 10)
|
| 208 |
c.drawString(margin, y, "Metrics")
|
| 209 |
+
y -= 15
|
| 210 |
c.setFont("Helvetica", 9)
|
| 211 |
+
cols = [("Whole field of view", metrics_full)] + ([("Force region (red)", metrics_cell)] if metrics_cell else [])
|
| 212 |
+
x_cols = [margin + 170 + i * 150 for i in range(len(cols))]
|
| 213 |
+
for xc, (title, _) in zip(x_cols, cols):
|
| 214 |
+
c.setFont("Helvetica-Bold", 9); c.drawString(xc, y, title)
|
| 215 |
+
c.setFont("Helvetica", 9)
|
| 216 |
+
y -= 13
|
| 217 |
+
labels = [r[0] for r in metric_rows(metrics_full or {})]
|
| 218 |
+
for li, lab in enumerate(labels):
|
| 219 |
+
c.drawString(margin, y, lab)
|
| 220 |
+
for xc, (_, m) in zip(x_cols, cols):
|
| 221 |
+
c.drawString(xc, y, metric_rows(m or {})[li][1])
|
| 222 |
+
y -= 13
|
| 223 |
+
if scale is None or not scale.get("hm_px_area_um2"):
|
| 224 |
+
c.setFont("Helvetica-Oblique", 8)
|
| 225 |
+
c.drawString(margin, y, "Area and total force need the image pixel size (sidebar).")
|
| 226 |
+
y -= 12
|
| 227 |
+
c.setFont("Helvetica-Oblique", 8)
|
| 228 |
+
c.drawString(margin, y, "Total force = sum of traction stress x pixel area. S2F predicts magnitude only (no direction).")
|
| 229 |
+
y -= 20
|
| 230 |
+
|
| 231 |
+
c.setFont("Helvetica-Bold", 10)
|
| 232 |
+
c.drawString(margin, y, "Parameters (for reproducibility)")
|
| 233 |
+
y -= 14
|
| 234 |
+
c.setFont("Helvetica", 8)
|
| 235 |
+
for lab, val in info_rows(info):
|
| 236 |
+
c.drawString(margin, y, f"{lab}:")
|
| 237 |
+
for line in textwrap.wrap(str(val), 82) or ["–"]:
|
| 238 |
+
c.drawString(margin + 175, y, line)
|
| 239 |
+
y -= 11
|
| 240 |
+
if y < 70:
|
| 241 |
+
c.showPage(); _draw_pdf_footer(c, margin=margin, include_web_app=True); y = page_h_pt - 60; c.setFont("Helvetica", 8)
|
| 242 |
+
|
| 243 |
+
|
| 244 |
+
def create_pdf_report(img, display_heatmap, raw_heatmap, base_name, colormap_name="Jet", cell_mask=None,
|
| 245 |
+
metrics_full=None, metrics_cell=None, info=None, scale=None, clip_min=0.0, clip_max=1.0):
|
| 246 |
+
"""
|
| 247 |
+
PDF report: bright field and predicted traction-stress map (with µm scale bar and Pa colourbar),
|
| 248 |
+
metrics with units, and every parameter needed to reproduce the prediction (Reviewer 1).
|
| 249 |
+
"""
|
| 250 |
+
buf = io.BytesIO()
|
| 251 |
+
c = canvas.Canvas(buf, pagesize=A4)
|
| 252 |
+
c.setTitle("Shape2Force prediction report")
|
| 253 |
+
c.setAuthor("Angione-Lab")
|
| 254 |
+
_draw_prediction_page(c, img, display_heatmap, raw_heatmap, base_name, colormap_name, cell_mask,
|
| 255 |
+
metrics_full, metrics_cell, info, scale, clip_min, clip_max)
|
| 256 |
+
c.save()
|
| 257 |
+
buf.seek(0)
|
| 258 |
+
return buf.getvalue()
|
| 259 |
+
|
| 260 |
+
|
| 261 |
+
_SHARED_KEYS = ("Model type", "Architecture", "Checkpoint", "Checkpoint SHA-256", "Substrate setting (preset)",
|
| 262 |
+
"Substrate setting (manual)", " pixel-size setting / Young's modulus",
|
| 263 |
+
" model input channels (normalised)", "Image pixel size", "Stress scale", "Display", "Measure force region only",
|
| 264 |
+
"App version")
|
| 265 |
|
| 266 |
+
|
| 267 |
+
def create_batch_pdf_report(items, colormap_name="Jet", clip_min=0.0, clip_max=1.0, auto_cell_boundary=False):
|
| 268 |
+
"""
|
| 269 |
+
Batch PDF: page 1 = summary table of all images (metrics with units) and the shared parameters;
|
| 270 |
+
then one page per image with the same layout as the single-image report.
|
| 271 |
+
items: list of dicts with img, display_heatmap, raw_heatmap, base_name, cell_mask, metrics_full,
|
| 272 |
+
metrics_cell, info, scale.
|
| 273 |
+
"""
|
| 274 |
+
from utils.units import fmt
|
| 275 |
+
buf = io.BytesIO()
|
| 276 |
+
c = canvas.Canvas(buf, pagesize=A4)
|
| 277 |
+
c.setTitle("Shape2Force batch report")
|
| 278 |
+
c.setAuthor("Angione-Lab")
|
| 279 |
+
page_w_pt, page_h_pt = A4
|
| 280 |
+
margin = 60
|
| 281 |
+
_draw_pdf_footer(c, margin=margin, include_web_app=True)
|
| 282 |
+
y = page_h_pt - 50
|
| 283 |
+
c.setFont("Helvetica-Bold", 15)
|
| 284 |
+
c.drawString(margin, y, "Shape2Force (S2F) - Batch Report")
|
| 285 |
+
y -= 16
|
| 286 |
+
c.setFont("Helvetica", 10)
|
| 287 |
+
region = "force region (red contour)" if auto_cell_boundary else "whole field of view"
|
| 288 |
+
c.drawString(margin, y, f"{len(items)} images; metrics over the {region}. One page per image follows.")
|
| 289 |
+
y -= 26
|
| 290 |
+
headers = ["#", "Image", "Mean stress (Pa)", "Max stress (Pa)", "Area (µm²)", "Total force (nN)"]
|
| 291 |
+
xs = [margin, margin + 22, margin + 210, margin + 290, margin + 370, margin + 440]
|
| 292 |
+
c.setFont("Helvetica-Bold", 9)
|
| 293 |
+
for x, h in zip(xs, headers):
|
| 294 |
+
c.drawString(x, y, h)
|
| 295 |
+
y -= 4
|
| 296 |
+
c.line(margin, y, page_w_pt - margin, y)
|
| 297 |
+
y -= 12
|
| 298 |
+
c.setFont("Helvetica", 9)
|
| 299 |
+
for i, it in enumerate(items, 1):
|
| 300 |
+
m = (it["metrics_cell"] if (auto_cell_boundary and it.get("metrics_cell")) else it["metrics_full"]) or {}
|
| 301 |
+
vals = [str(i), it["base_name"][:34], fmt(m.get("mean_pa"), nd=1), fmt(m.get("max_pa"), nd=1),
|
| 302 |
+
fmt(m.get("area_um2"), nd=0), fmt(m.get("total_force_nN"), nd=2)]
|
| 303 |
+
for x, v in zip(xs, vals):
|
| 304 |
+
c.drawString(x, y, v)
|
| 305 |
+
y -= 13
|
| 306 |
+
y -= 18
|
| 307 |
+
c.setFont("Helvetica-Bold", 10)
|
| 308 |
+
c.drawString(margin, y, "Parameters (shared by all images)")
|
| 309 |
+
y -= 14
|
| 310 |
+
c.setFont("Helvetica", 8)
|
| 311 |
+
for lab, val in info_rows(items[0]["info"] if items else None):
|
| 312 |
+
if lab in _SHARED_KEYS:
|
| 313 |
+
c.drawString(margin, y, f"{lab}:")
|
| 314 |
+
for line in textwrap.wrap(str(val), 82) or ["–"]:
|
| 315 |
+
c.drawString(margin + 175, y, line)
|
| 316 |
+
y -= 11
|
| 317 |
+
c.showPage()
|
| 318 |
+
for i, it in enumerate(items, 1):
|
| 319 |
+
_draw_prediction_page(c, it["img"], it["display_heatmap"], it["raw_heatmap"], it["base_name"], colormap_name,
|
| 320 |
+
it.get("cell_mask"), it["metrics_full"], it.get("metrics_cell"), it["info"], it["scale"],
|
| 321 |
+
clip_min, clip_max, page_label=f"image {i} of {len(items)}")
|
| 322 |
+
c.showPage()
|
| 323 |
c.save()
|
| 324 |
buf.seek(0)
|
| 325 |
return buf.getvalue()
|
S2FApp/utils/substrate_settings.py
CHANGED
|
@@ -114,21 +114,8 @@ def compute_settings_normalization(config=None, config_path=None):
|
|
| 114 |
Returns:
|
| 115 |
dict: {'pixelsize': {'min', 'max'}, 'young': {'min', 'max'}}
|
| 116 |
"""
|
| 117 |
-
|
| 118 |
-
|
| 119 |
-
|
| 120 |
-
|
| 121 |
-
|
| 122 |
-
all_youngs = [s['young'] for s in substrates.values()]
|
| 123 |
-
|
| 124 |
-
if not all_pixelsizes or not all_youngs:
|
| 125 |
-
pixelsize_min, pixelsize_max = 3.0769, 9.8138
|
| 126 |
-
young_min, young_max = 1000.0, 10000.0
|
| 127 |
-
else:
|
| 128 |
-
pixelsize_min, pixelsize_max = min(all_pixelsizes), max(all_pixelsizes)
|
| 129 |
-
young_min, young_max = min(all_youngs), max(all_youngs)
|
| 130 |
-
|
| 131 |
-
return {
|
| 132 |
-
'pixelsize': {'min': pixelsize_min, 'max': pixelsize_max},
|
| 133 |
-
'young': {'min': young_min, 'max': young_max}
|
| 134 |
-
}
|
|
|
|
| 114 |
Returns:
|
| 115 |
dict: {'pixelsize': {'min', 'max'}, 'young': {'min', 'max'}}
|
| 116 |
"""
|
| 117 |
+
# The ranges must be those used in training (pixel size 3.0769-9.8138, Young's modulus 1-10 kPa),
|
| 118 |
+
# not the min/max of the presets listed by the app: previously the app normalised the pixel size over
|
| 119 |
+
# its own presets (3.0769-6.1538), which gave a different input for any pixel size other than 3.0769.
|
| 120 |
+
from config.constants import SETTINGS_NORMALIZATION
|
| 121 |
+
return {k: dict(v) for k, v in SETTINGS_NORMALIZATION.items()}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
S2FApp/utils/units.py
ADDED
|
@@ -0,0 +1,125 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Physical units for S2F predictions.
|
| 3 |
+
|
| 4 |
+
The network output is a normalised map y_hat in [0, 1]. The ground-truth traction-stress maps used for
|
| 5 |
+
training were exported by the TFM software on a fixed colour scale, so
|
| 6 |
+
|
| 7 |
+
traction stress T [Pa] = y_hat * STRESS_MAX_PA[model_type] (500 Pa single cells, 50 Pa spheroids).
|
| 8 |
+
|
| 9 |
+
Areas and forces additionally need the pixel size of the bright-field image (µm per pixel, entered by the
|
| 10 |
+
user). The prediction is made on a MODEL_INPUT_SIZE x MODEL_INPUT_SIZE grid, so one heatmap pixel covers
|
| 11 |
+
(image width * pixel size / MODEL_INPUT_SIZE) µm in x, and likewise in y.
|
| 12 |
+
|
| 13 |
+
area [µm²] = number of pixels * heatmap pixel area
|
| 14 |
+
force [nN] = sum(T [Pa] * heatmap pixel area [µm²]) * 1e-3 (1 Pa · µm² = 1e-12 N = 1e-3 nN)
|
| 15 |
+
"""
|
| 16 |
+
import numpy as np
|
| 17 |
+
|
| 18 |
+
from config.constants import MODEL_INPUT_SIZE, STRESS_MAX_PA
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
def stress_max_pa(model_type):
|
| 22 |
+
return STRESS_MAX_PA["spheroid" if model_type == "spheroid" else "single_cell"]
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
def make_scale(model_type, image_um_per_px=None, image_shape=None, heatmap_shape=(MODEL_INPUT_SIZE, MODEL_INPUT_SIZE)):
|
| 26 |
+
"""
|
| 27 |
+
Physical scale of one prediction.
|
| 28 |
+
|
| 29 |
+
image_um_per_px: pixel size of the uploaded bright-field image (µm/px); None or <= 0 if unknown.
|
| 30 |
+
image_shape: (height, width) of the uploaded image, before resizing to the model input.
|
| 31 |
+
Returns a dict used by the display, report and measurement code.
|
| 32 |
+
"""
|
| 33 |
+
smax = stress_max_pa(model_type)
|
| 34 |
+
s = {"stress_max_pa": smax, "image_um_per_px": None, "image_shape": None,
|
| 35 |
+
"hm_um_per_px_x": None, "hm_um_per_px_y": None, "hm_px_area_um2": None}
|
| 36 |
+
if image_shape is not None:
|
| 37 |
+
s["image_shape"] = (int(image_shape[0]), int(image_shape[1]))
|
| 38 |
+
if image_um_per_px and image_um_per_px > 0 and image_shape is not None:
|
| 39 |
+
h, w = image_shape[:2]
|
| 40 |
+
hh, hw = heatmap_shape[:2]
|
| 41 |
+
sx = image_um_per_px * w / hw
|
| 42 |
+
sy = image_um_per_px * h / hh
|
| 43 |
+
s.update(image_um_per_px=float(image_um_per_px), hm_um_per_px_x=sx, hm_um_per_px_y=sy, hm_px_area_um2=sx * sy)
|
| 44 |
+
return s
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
def has_physical_size(scale):
|
| 48 |
+
return scale is not None and scale.get("hm_px_area_um2") is not None
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
def to_pa(heatmap, scale):
|
| 52 |
+
"""Normalised map -> traction stress in Pa."""
|
| 53 |
+
return np.clip(np.asarray(heatmap, dtype=np.float64), 0, 1) * scale["stress_max_pa"]
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
def region_metrics(heatmap, mask, scale):
|
| 57 |
+
"""
|
| 58 |
+
Metrics over a region (mask = 1) or the whole map (mask = None).
|
| 59 |
+
Keys: n_px, area_um2, mean_pa, max_pa, total_force_nN (area and force are None without a pixel size).
|
| 60 |
+
"""
|
| 61 |
+
t = to_pa(heatmap, scale)
|
| 62 |
+
m = np.ones(t.shape, dtype=bool) if mask is None else (np.asarray(mask) > 0)
|
| 63 |
+
n = int(m.sum())
|
| 64 |
+
if n == 0:
|
| 65 |
+
return {"n_px": 0, "area_um2": None, "mean_pa": None, "max_pa": None, "total_force_nN": None}
|
| 66 |
+
vals = t[m]
|
| 67 |
+
out = {"n_px": n, "mean_pa": float(vals.mean()), "max_pa": float(vals.max()), "area_um2": None, "total_force_nN": None}
|
| 68 |
+
if has_physical_size(scale):
|
| 69 |
+
a = scale["hm_px_area_um2"]
|
| 70 |
+
out["area_um2"] = n * a
|
| 71 |
+
out["total_force_nN"] = float(vals.sum()) * a * 1e-3
|
| 72 |
+
return out
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
def fmt(value, unit="", nd=1):
|
| 76 |
+
"""Format a metric value; '–' when not available."""
|
| 77 |
+
if value is None:
|
| 78 |
+
return "–"
|
| 79 |
+
return f"{value:.{nd}f}{(' ' + unit) if unit else ''}"
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
def metric_rows(metrics):
|
| 83 |
+
"""(label, formatted value) pairs, in the order used everywhere in the app."""
|
| 84 |
+
return [
|
| 85 |
+
("Mean traction stress", fmt(metrics.get("mean_pa"), "Pa")),
|
| 86 |
+
("Max traction stress", fmt(metrics.get("max_pa"), "Pa")),
|
| 87 |
+
("Area", fmt(metrics.get("area_um2"), "µm²", 0)),
|
| 88 |
+
("Total force", fmt(metrics.get("total_force_nN"), "nN", 2)),
|
| 89 |
+
]
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
def nice_scale_bar_um(field_width_um, fraction=0.2):
|
| 93 |
+
"""Scale-bar length (µm) from {1, 2, 5} x 10^k closest to `fraction` of the field width."""
|
| 94 |
+
target = field_width_um * fraction
|
| 95 |
+
if target <= 0:
|
| 96 |
+
return None
|
| 97 |
+
k = np.floor(np.log10(target))
|
| 98 |
+
candidates = [m * 10 ** k for m in (1, 2, 5, 10)]
|
| 99 |
+
return float(min(candidates, key=lambda c: abs(c - target)))
|
| 100 |
+
|
| 101 |
+
|
| 102 |
+
def draw_scale_bar(rgb, um_per_px, color=(255, 255, 255), margin_frac=0.04):
|
| 103 |
+
"""Draw a µm scale bar (bottom right) on an RGB uint8 image in place. Returns (rgb, length_um)."""
|
| 104 |
+
import cv2
|
| 105 |
+
|
| 106 |
+
if not um_per_px or um_per_px <= 0:
|
| 107 |
+
return rgb, None
|
| 108 |
+
h, w = rgb.shape[:2]
|
| 109 |
+
length_um = nice_scale_bar_um(w * um_per_px)
|
| 110 |
+
if length_um is None:
|
| 111 |
+
return rgb, None
|
| 112 |
+
length_px = int(round(length_um / um_per_px))
|
| 113 |
+
thick = max(2, h // 120)
|
| 114 |
+
m = int(margin_frac * w)
|
| 115 |
+
x1, y = w - m, h - m
|
| 116 |
+
x0 = x1 - length_px
|
| 117 |
+
cv2.rectangle(rgb, (x0 - 1, y - thick - 1), (x1 + 1, y + 1), (0, 0, 0), -1)
|
| 118 |
+
cv2.rectangle(rgb, (x0, y - thick), (x1, y), color, -1)
|
| 119 |
+
label = f"{length_um:g} um" # OpenCV fonts have no µ glyph
|
| 120 |
+
font_scale = max(0.4, w / 1100)
|
| 121 |
+
(tw, th), _ = cv2.getTextSize(label, cv2.FONT_HERSHEY_SIMPLEX, font_scale, max(1, thick // 2))
|
| 122 |
+
tx, ty = x0 + (length_px - tw) // 2, y - thick - 6
|
| 123 |
+
cv2.putText(rgb, label, (tx, ty), cv2.FONT_HERSHEY_SIMPLEX, font_scale, (0, 0, 0), max(2, thick), cv2.LINE_AA)
|
| 124 |
+
cv2.putText(rgb, label, (tx, ty), cv2.FONT_HERSHEY_SIMPLEX, font_scale, color, max(1, thick // 2), cv2.LINE_AA)
|
| 125 |
+
return rgb, length_um
|