From 790ecb4e7edd34b4008998829e0d37e3b306f233 Mon Sep 17 00:00:00 2001 From: d33bs Date: Thu, 12 Nov 2026 12:12:48 -0700 Subject: [PATCH 1/6] Add post-QC object image crop warehouse --- .gitignore | 4 + .../0.generate_object_crops.ipynb | 245 +++++++++++ .../1.build_crop_index.ipynb | 104 +++++ 5a.object_image_crops/2.validate_joins.ipynb | 171 ++++++++ 5a.object_image_crops/README.md | 153 +++++++ .../nbconverted/0.generate_object_crops.py | 190 +++++++++ .../nbconverted/1.build_crop_index.py | 65 +++ .../nbconverted/2.validate_joins.py | 116 +++++ 5a.object_image_crops/run_crop_pipeline.sh | 54 +++ README.md | 3 +- utils/crop_warehouse.py | 400 ++++++++++++++++++ utils/morphem_utils.py | 230 +--------- utils/nucleocentric_crops.py | 230 ++++++++++ utils/pyproject.toml | 2 + utils/tests/test_crop_pipeline.py | 280 ++++++++++++ utils/tests/test_crop_warehouse.py | 111 +++++ 16 files changed, 2139 insertions(+), 219 deletions(-) create mode 100644 5a.object_image_crops/0.generate_object_crops.ipynb create mode 100644 5a.object_image_crops/1.build_crop_index.ipynb create mode 100644 5a.object_image_crops/2.validate_joins.ipynb create mode 100644 5a.object_image_crops/README.md create mode 100644 5a.object_image_crops/nbconverted/0.generate_object_crops.py create mode 100644 5a.object_image_crops/nbconverted/1.build_crop_index.py create mode 100644 5a.object_image_crops/nbconverted/2.validate_joins.py create mode 100755 5a.object_image_crops/run_crop_pipeline.sh create mode 100644 utils/crop_warehouse.py create mode 100644 utils/nucleocentric_crops.py create mode 100644 utils/tests/test_crop_pipeline.py create mode 100644 utils/tests/test_crop_warehouse.py diff --git a/.gitignore b/.gitignore index 78fd599..783901d 100644 --- a/.gitignore +++ b/.gitignore @@ -35,6 +35,10 @@ runinfo/ # Ignore MorphEm profiles (large parquet files) 5.morphem_featurization/data/ +# Ignore the image-crop warehouse (the JPG crops and their manifests; see 5a.object_image_crops/README.md) +5a.object_image_crops/data/ +5a.object_image_crops/logs/ + # Ignore the crop size evaluation tables (regenerated by 0.evaluate_crop_sizes.ipynb; the figures summarize them) 5.morphem_featurization/crop_evaluation/ diff --git a/5a.object_image_crops/0.generate_object_crops.ipynb b/5a.object_image_crops/0.generate_object_crops.ipynb new file mode 100644 index 0000000..e365055 --- /dev/null +++ b/5a.object_image_crops/0.generate_object_crops.ipynb @@ -0,0 +1,245 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "id": "overview", + "source": [ + "# Generate post-QC nucleocentric JPG crops\n\nWrite five grayscale channels and one RGB composite for each QC-passing cell. Crop geometry,\nillumination correction and pre-JPEG rescaling match the MorphEm extraction. JPEG is lossy;\nthese are display derivatives, not replacements for the original TIFFs or model inputs.\nOne job processes a cell line on a plate; source images are read once per field of view.\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "id": "heading-0", + "source": [ + "## Imports and job settings\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "id": "code-0", + "source": [ + "import argparse\n", + "import os\n", + "import pathlib\n", + "import shutil\n", + "import time\n", + "\n", + "import numpy as np\n", + "import pandas as pd\n", + "from crop_warehouse import (\n", + " CHANNELS, PATH_COLUMNS, PROFILE_KEY_COLUMNS, UMAP_KEY_COLUMNS,\n", + " crop_id, make_cell_crops, manifest_row, read_corrected_field,\n", + " require_unique_keys, resolve_image_path, save_cell_crops, select_passing_cells,\n", + " validate_crop_files,\n", + ")\n", + "from path_utils import get_root_dir\n", + "\n", + "try:\n", + " get_ipython()\n", + " in_notebook = True\n", + "except NameError:\n", + " in_notebook = False\n", + "\n", + "root_dir = get_root_dir()\n", + "module_dir = root_dir / '5a.object_image_crops'\n", + "images_dir = pathlib.Path(os.environ.get('PCCMA_IMAGES_DIR',\n", + " '~/mnt/bandicoot/PCCMA_data/Atlas_v2_screen')).expanduser().resolve()\n", + "warehouse_dir = pathlib.Path(os.environ.get('PCCMA_CROPS_DIR',\n", + " str(module_dir / 'data/object_image_crops'))).expanduser().resolve()\n", + "\n", + "if not in_notebook:\n", + " parser = argparse.ArgumentParser(description='Write post-QC nucleocentric JPG crops for one job')\n", + " parser.add_argument('--plate', required=True)\n", + " parser.add_argument('--cell_line', required=True)\n", + " parser.add_argument('--overwrite', action='store_true')\n", + " args = parser.parse_args()\n", + " plate, cell_line, overwrite = args.plate, args.cell_line, args.overwrite\n", + "else:\n", + " plate, cell_line, overwrite = 'BR00150698', 'A673', False\n", + "\n", + "# Identifiers are path components, never paths supplied by a job.\n", + "for value in (plate, cell_line):\n", + " if pathlib.Path(value).name != value or value in ('.', '..'):\n", + " raise ValueError(f'Invalid job identifier: {value}')\n", + "converted_path = root_dir / '4.preprocess_features/data/converted_profiles' / cell_line / f'{plate}_{cell_line}_converted.parquet'\n", + "qc_path = root_dir / '4.preprocess_features/qc_results' / f'{cell_line}_qc_annotations.parquet'\n", + "illum_dir = root_dir / '2.illumination_correction/illum_directory' / plate\n", + "illum_paths = {ch: illum_dir / f'{plate}_Illum{ch}.npy' for ch in CHANNELS}\n", + "manifest_path = warehouse_dir / 'manifests' / f'{plate}_{cell_line}_manifest.parquet'" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "id": "heading-1", + "source": [ + "## Load metadata and apply QC\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "id": "code-1", + "source": [ + "image_columns = [f'Image_{kind}_Orig{ch}' for ch in CHANNELS for kind in ('FileName', 'PathName')]\n", + "columns = sorted(set(PROFILE_KEY_COLUMNS + UMAP_KEY_COLUMNS + image_columns))\n", + "cells = pd.read_parquet(converted_path, columns=columns)\n", + "qc = pd.read_parquet(qc_path)\n", + "qc = qc.loc[qc['Image_Metadata_Plate'] == plate]\n", + "single_cell_df = select_passing_cells(cells, qc)\n", + "if not cells['Image_Metadata_Plate'].eq(plate).all():\n", + " raise ValueError('Converted profile contains a different plate')\n", + "require_unique_keys(single_cell_df, PROFILE_KEY_COLUMNS, 'Post-QC cells')\n", + "require_unique_keys(single_cell_df, UMAP_KEY_COLUMNS, 'Post-QC positions')\n", + "if not np.isfinite(single_cell_df[UMAP_KEY_COLUMNS[3:]].to_numpy()).all():\n", + " raise ValueError('Non-finite nucleus centers')\n", + "single_cell_df = single_cell_df.assign(Metadata_cell_line=cell_line)\n", + "if single_cell_df.apply(crop_id, axis=1).duplicated().any():\n", + " raise ValueError('Duplicate crop filenames in a job')\n", + "for well in single_cell_df['Image_Metadata_Well']:\n", + " if pathlib.Path(well).name != well or well in ('.', '..'):\n", + " raise ValueError(f'Invalid well path component: {well}')\n", + "\n", + "# A field must refer to the same five TIFFs for every cell in it.\n", + "for _, field in single_cell_df.groupby('Metadata_ImageNumber'):\n", + " if (field[image_columns].nunique(dropna=False) != 1).any():\n", + " raise ValueError('Inconsistent source images within a field')\n", + "\n", + "inputs = [converted_path, qc_path, *illum_paths.values(),\n", + " module_dir / '0.generate_object_crops.ipynb',\n", + " pathlib.Path(__import__('crop_warehouse').__file__),\n", + " pathlib.Path(__import__('nucleocentric_crops').__file__)]\n", + "for record in single_cell_df.drop_duplicates('Metadata_ImageNumber').to_dict('records'):\n", + " inputs.extend(resolve_image_path(record, ch, images_dir) for ch in CHANNELS)\n", + "write_crops = True\n", + "if manifest_path.is_file() and not overwrite:\n", + " fresh = all(path.is_file() and path.stat().st_mtime_ns <= manifest_path.stat().st_mtime_ns for path in inputs)\n", + " if fresh:\n", + " existing = pd.read_parquet(manifest_path)\n", + " try:\n", + " validate_crop_files(existing, warehouse_dir)\n", + " require_unique_keys(existing, PROFILE_KEY_COLUMNS, 'Existing manifest')\n", + " same_keys = existing[PROFILE_KEY_COLUMNS].merge(single_cell_df[PROFILE_KEY_COLUMNS],\n", + " on=PROFILE_KEY_COLUMNS, how='outer', validate='one_to_one', indicator=True)\n", + " write_crops = not same_keys['_merge'].eq('both').all()\n", + " except ValueError:\n", + " write_crops = True\n", + "print(f'{plate} {cell_line}: {len(single_cell_df)} of {len(cells)} cells passed QC')\n", + "if not write_crops:\n", + " print(f'Skipping {plate} {cell_line}: manifest and all six crop files are up to date')" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "id": "heading-2", + "source": [ + "## Generate one field at a time and publish the job manifest last\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "id": "code-2", + "source": [ + "if write_crops:\n", + " start = time.monotonic()\n", + " # Invalidate published summaries before changing files. A failed run is not a complete warehouse.\n", + " manifest_path.parent.mkdir(parents=True, exist_ok=True)\n", + " manifest_path.unlink(missing_ok=True)\n", + " (warehouse_dir / 'crops_index.parquet').unlink(missing_ok=True)\n", + " (warehouse_dir / 'validation.json').unlink(missing_ok=True)\n", + " functions = {ch: np.load(path) for ch, path in illum_paths.items()}\n", + " job_dir = warehouse_dir / 'crops' / plate / cell_line\n", + " stage = warehouse_dir / '.staging' / f'{plate}_{cell_line}'\n", + " if stage.exists():\n", + " shutil.rmtree(stage)\n", + " stage.mkdir(parents=True)\n", + " rows = []\n", + " for _, field in single_cell_df.groupby('Metadata_ImageNumber', sort=True):\n", + " corrected, saturated = read_corrected_field(field.iloc[0].to_dict(), functions, images_dir)\n", + " for record in field.to_dict('records'):\n", + " crops, padding = make_cell_crops(record, corrected, saturated)\n", + " subdir = pathlib.Path(record['Image_Metadata_Well']) / f\"f{int(record['Image_Metadata_Site']):02d}\"\n", + " written = save_cell_crops(crops, stage / subdir, crop_id(record))\n", + " final_paths = {key: str(job_dir / pathlib.Path(path).relative_to(stage)) for key, path in written.items()}\n", + " row = manifest_row(record, final_paths, warehouse_dir)\n", + " row['Metadata_Nucleocentric_Pad_Fraction'] = padding\n", + " rows.append(row)\n", + "\n", + " # Preserve the schema even for a job where all cells failed QC.\n", + " template = {key: 0 for key in set(PROFILE_KEY_COLUMNS + UMAP_KEY_COLUMNS)}\n", + " template.update(Image_Metadata_Plate=plate, Image_Metadata_Well='', Metadata_cell_line=cell_line)\n", + " template.update({column: '' for column in image_columns})\n", + " empty = manifest_row(template, {key: str(warehouse_dir / key) for key in PATH_COLUMNS}, warehouse_dir)\n", + " empty['Metadata_Nucleocentric_Pad_Fraction'] = 0.0\n", + " manifest_df = pd.DataFrame(rows, columns=list(empty)) if rows else pd.DataFrame(columns=list(empty))\n", + " require_unique_keys(manifest_df, PROFILE_KEY_COLUMNS, 'Job manifest')\n", + " job_dir.parent.mkdir(parents=True, exist_ok=True)\n", + " if job_dir.exists():\n", + " shutil.rmtree(job_dir)\n", + " stage.replace(job_dir)\n", + " validate_crop_files(manifest_df, warehouse_dir)\n", + " temporary = manifest_path.with_suffix('.tmp.parquet')\n", + " manifest_df.to_parquet(temporary, index=False)\n", + " temporary.replace(manifest_path)\n", + " print(f'Saved {len(rows)} cells / {len(rows) * len(PATH_COLUMNS)} JPGs in {time.monotonic() - start:.1f}s')" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "id": "heading-3", + "source": [ + "## Preview composites (notebook only)\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "id": "code-3", + "source": [ + "if in_notebook:\n", + " import matplotlib.pyplot as plt\n", + " from PIL import Image\n", + "\n", + " preview = pd.read_parquet(manifest_path).head(4)\n", + " if not preview.empty:\n", + " fig, axes = plt.subplots(1, len(preview), squeeze=False, figsize=(4 * len(preview), 4))\n", + " for ax, row in zip(axes.flat, preview.to_dict('records')):\n", + " with Image.open(warehouse_dir / row['composite']) as image:\n", + " ax.imshow(np.array(image))\n", + " ax.set_title(f\"{row['Metadata_Well']} / cell {row['Metadata_Cells_Number_Object_Number']}\")\n", + " ax.axis('off')\n", + " plt.show()" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "name": "python", + "file_extension": ".py", + "mimetype": "text/x-python", + "pygments_lexer": "ipython3", + "nbconvert_exporter": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 5 +} diff --git a/5a.object_image_crops/1.build_crop_index.ipynb b/5a.object_image_crops/1.build_crop_index.ipynb new file mode 100644 index 0000000..a12e4ff --- /dev/null +++ b/5a.object_image_crops/1.build_crop_index.ipynb @@ -0,0 +1,104 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "id": "overview", + "source": [ + "# Build the independent crop index\n\nConcatenate job manifests, verify that every converted-profile job has a manifest, annotate\nwells from platemaps, and check every path before atomically publishing the index.\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "id": "heading-0", + "source": [ + "## Paths and inputs\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "id": "code-0", + "source": [ + "import os\n", + "import pathlib\n", + "import pandas as pd\n", + "from crop_warehouse import FINAL_PROFILE_KEY, POSITION_KEY, PATH_COLUMNS, require_unique_keys, validate_crop_files\n", + "from path_utils import get_root_dir\n", + "\n", + "root_dir = get_root_dir()\n", + "module_dir = root_dir / '5a.object_image_crops'\n", + "warehouse_dir = pathlib.Path(os.environ.get('PCCMA_CROPS_DIR',\n", + " str(module_dir / 'data/object_image_crops'))).expanduser().resolve()\n", + "index_path = warehouse_dir / 'crops_index.parquet'\n", + "manifest_dir = warehouse_dir / 'manifests'\n", + "converted_dir = root_dir / '4.preprocess_features/data/converted_profiles'\n", + "converted = sorted(converted_dir.glob('*/*_converted.parquet'))\n", + "if not converted:\n", + " raise FileNotFoundError(f'No converted profiles in {converted_dir}')\n", + "expected = {path.name.replace('_converted.parquet', '_manifest.parquet') for path in converted}\n", + "manifest_paths = sorted(manifest_dir.glob('*_manifest.parquet'))\n", + "if expected != {path.name for path in manifest_paths}:\n", + " raise ValueError('Missing or stale job manifests; generate every converted-profile job first')" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "id": "heading-1", + "source": [ + "## Build, annotate and validate\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "id": "code-1", + "source": [ + "index_df = pd.concat([pd.read_parquet(path) for path in manifest_paths], ignore_index=True)\n", + "# Drop placeholder annotations before adding authoritative platemap values, not afterwards.\n", + "index_df = index_df.drop(columns=['Metadata_cell_line', 'Metadata_time_point'])\n", + "platemaps = sorted((root_dir / '0.download_data/metadata/platemaps').glob('BR*_platemap.csv'))\n", + "if not platemaps:\n", + " raise FileNotFoundError('No platemaps')\n", + "wells = pd.concat([pd.read_csv(path)[['plate_barcode', 'well_position', 'cell_line', 'time_point']]\n", + " for path in platemaps], ignore_index=True).rename(columns={\n", + " 'plate_barcode': 'Metadata_Plate', 'well_position': 'Metadata_Well',\n", + " 'cell_line': 'Metadata_cell_line', 'time_point': 'Metadata_time_point'})\n", + "require_unique_keys(wells, ['Metadata_Plate', 'Metadata_Well'], 'Platemaps')\n", + "index_df = index_df.merge(wells, on=['Metadata_Plate', 'Metadata_Well'], how='left', validate='many_to_one')\n", + "if index_df[['Metadata_cell_line', 'Metadata_time_point']].isna().any().any():\n", + " raise ValueError('Crop cells missing platemap annotations')\n", + "require_unique_keys(index_df, FINAL_PROFILE_KEY, 'Crop index')\n", + "require_unique_keys(index_df, POSITION_KEY, 'Crop positions')\n", + "validate_crop_files(index_df, warehouse_dir)\n", + "temporary = index_path.with_suffix('.tmp.parquet')\n", + "index_df.to_parquet(temporary, index=False)\n", + "temporary.replace(index_path)\n", + "(warehouse_dir / 'validation.json').unlink(missing_ok=True)\n", + "print(f'Saved {index_path}: {len(index_df)} cells, {len(index_df) * len(PATH_COLUMNS)} JPGs, {len(manifest_paths)} jobs')" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "name": "python", + "file_extension": ".py", + "mimetype": "text/x-python", + "pygments_lexer": "ipython3", + "nbconvert_exporter": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 5 +} diff --git a/5a.object_image_crops/2.validate_joins.ipynb b/5a.object_image_crops/2.validate_joins.ipynb new file mode 100644 index 0000000..50bd1b1 --- /dev/null +++ b/5a.object_image_crops/2.validate_joins.ipynb @@ -0,0 +1,171 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "id": "overview", + "source": [ + "# Validate crop files, joins and sampled pixels\n\nRequire exact post-QC coverage of the available CellProfiler single-cell profiles. Check MorphEm\nprofiles and UMAP subsets when present; report absent optional inputs as skipped, never verified.\nRecompute sampled crops from TIFFs and compare against a fresh JPEG encode/decode in this environment.\nNo profiles or embeddings are modified, recomputed or required for crop generation itself.\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "id": "heading-0", + "source": [ + "## Paths and crop integrity\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "id": "code-0", + "source": [ + "import json\n", + "import os\n", + "import pathlib\n", + "import pandas as pd\n", + "from crop_warehouse import (\n", + " FINAL_PROFILE_KEY, POSITION_KEY, PATH_COLUMNS, join_crop_paths, require_unique_keys,\n", + " validate_crop_files, validate_profile_join, validate_sample_pixels,\n", + ")\n", + "from path_utils import get_root_dir\n", + "\n", + "root_dir = get_root_dir()\n", + "module_dir = root_dir / '5a.object_image_crops'\n", + "warehouse_dir = pathlib.Path(os.environ.get('PCCMA_CROPS_DIR',\n", + " str(module_dir / 'data/object_image_crops'))).expanduser().resolve()\n", + "report_path = warehouse_dir / 'validation.json'\n", + "report_path.unlink(missing_ok=True)\n", + "index_df = pd.read_parquet(warehouse_dir / 'crops_index.parquet')\n", + "require_unique_keys(index_df, FINAL_PROFILE_KEY, 'Crop index')\n", + "require_unique_keys(index_df, POSITION_KEY, 'Crop positions')\n", + "validate_crop_files(index_df, warehouse_dir)\n", + "report = {'cells': len(index_df), 'jpg_files': len(index_df) * len(PATH_COLUMNS)}\n", + "\n", + "local = root_dir / '4.preprocess_features/data/single_cell_profiles'\n", + "mount = pathlib.Path('~/mnt/bandicoot/PCCMA_data/Atlas_v2_profiles/single_cell_profiles').expanduser()\n", + "profile_dir = pathlib.Path(os.environ.get('PCCMA_PROFILES_DIR',\n", + " str(local if any(local.glob('BR*_sc_feature_selected.parquet')) else mount))).expanduser()" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "id": "heading-1", + "source": [ + "## CellProfiler profiles: both directions, one-to-one\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "id": "code-1", + "source": [ + "profile_paths = sorted(profile_dir.glob('BR*_sc_feature_selected.parquet'))\n", + "if not profile_paths:\n", + " raise FileNotFoundError(f'No CellProfiler single-cell profiles in {profile_dir}')\n", + "profile_plates = {path.name.split('_')[0] for path in profile_paths}\n", + "if not set(index_df['Metadata_Plate']).issubset(profile_plates):\n", + " raise ValueError('Crop plates without CellProfiler profiles')\n", + "for path in profile_paths:\n", + " plate = path.name.split('_')[0]\n", + " profiles = pd.read_parquet(path, columns=FINAL_PROFILE_KEY)\n", + " validate_profile_join(index_df.loc[index_df['Metadata_Plate'] == plate], profiles, f'CellProfiler {plate}')\n", + " print(f'CellProfiler {plate}: {len(profiles)} profile rows matched one-to-one')\n", + "report['cellprofiler'] = 'verified'" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "id": "heading-2", + "source": [ + "## Optional MorphEm and UMAP joins\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "id": "code-2", + "source": [ + "morphem_dir = root_dir / '5.morphem_featurization/data/morphem_single_cell_profiles'\n", + "morphem_paths = sorted(morphem_dir.glob('BR*_morphem_sc_feature_selected.parquet'))\n", + "if morphem_paths:\n", + " checked = []\n", + " for path in morphem_paths:\n", + " plate = path.name.split('_')[0]\n", + " profiles = pd.read_parquet(path, columns=FINAL_PROFILE_KEY)\n", + " validate_profile_join(index_df.loc[index_df['Metadata_Plate'] == plate], profiles, f'MorphEm {plate}')\n", + " checked.append(plate)\n", + " report['morphem'] = {'verified_plates': checked,\n", + " 'missing_plates': sorted(profile_plates - set(checked))}\n", + " print(f'MorphEm: checked {len(checked)} available plates')\n", + "else:\n", + " report['morphem'] = 'skipped: profiles unavailable'\n", + " print('MorphEm joins skipped: profiles unavailable')\n", + "\n", + "umap_dir = root_dir / '6.profile_analysis/results/3.single_cell_embedding'\n", + "report['umap'] = {}\n", + "for filename in ('single_cell_umap_coordinates_by_cancer_group.parquet', 'single_cell_umap_example_cells.parquet'):\n", + " path = umap_dir / filename\n", + " if not path.is_file():\n", + " report['umap'][filename] = 'skipped: table unavailable'\n", + " print(f'UMAP join skipped: {filename} unavailable')\n", + " continue\n", + " table = pd.read_parquet(path)\n", + " joined = join_crop_paths(table, index_df)\n", + " report['umap'][filename] = len(joined)\n", + " print(f'UMAP {filename}: all {len(joined)} cells matched one-to-one')" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "id": "heading-3", + "source": [ + "## Recompute sampled pixels and save the validation report\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "id": "code-3", + "source": [ + "images_dir = pathlib.Path(os.environ.get('PCCMA_IMAGES_DIR',\n", + " '~/mnt/bandicoot/PCCMA_data/Atlas_v2_screen')).expanduser()\n", + "report['pixel_samples'] = validate_sample_pixels(index_df, warehouse_dir,\n", + " root_dir / '2.illumination_correction/illum_directory', images_dir)\n", + "temporary = report_path.with_suffix('.tmp.json')\n", + "temporary.write_text(json.dumps(report, indent=2) + '\\n')\n", + "temporary.replace(report_path)\n", + "print(f\"Checked all six images for {report['pixel_samples']} sampled cells against recomputed JPEG pixels\")\n", + "print(f'Saved {report_path}')" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "name": "python", + "file_extension": ".py", + "mimetype": "text/x-python", + "pygments_lexer": "ipython3", + "nbconvert_exporter": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 5 +} diff --git a/5a.object_image_crops/README.md b/5a.object_image_crops/README.md new file mode 100644 index 0000000..8f64a4a --- /dev/null +++ b/5a.object_image_crops/README.md @@ -0,0 +1,153 @@ +# Object image crops + +This lettered module produces an independent image folder within the atlas data warehouse. +It uses CellProfiler's object coordinates and the existing per-cell QC decisions; it does not +run segmentation, MorphEm inference, profile processing, or UMAP again. Existing parquet files +are never modified. + +Each QC-passing cell has six 224 x 224 JPGs centered on its nucleus: DNA, ER, RNA, AGP and Mito +in grayscale, plus one RGB composite. The crop uses the same illumination correction, edge +padding and pre-JPEG 8-bit rescaling as `5.morphem_featurization`. Shared NumPy-only geometry +lives in `utils/nucleocentric_crops.py`; `morphem_utils` re-exports it for existing callers. + +JPEG quality is 95; RGB uses no chroma subsampling. JPEG is lossy. These are display derivatives, +not lossless model inputs: JPEG can change pixel values, including the value 255 used to mark +camera saturation before compression. Do not use the JPGs to reproduce MorphEm embeddings or +quantitative intensity measurements without a separate validation. Composite colors use the +profile-analysis palette and screen blending, with a per-crop 1st–99.8th percentile stretch. + +## Local output + +Default root: `5a.object_image_crops/data/object_image_crops/` (gitignored). + + crops////f/ + __f_nuc_cell_DNA.jpg + ..._ER.jpg, ..._RNA.jpg, ..._AGP.jpg, ..._Mito.jpg + ..._composite.jpg + manifests/__manifest.parquet + crops_index.parquet + validation.json + +Plate/cell-line/well/site folders avoid putting millions of JPGs into one directory. Paths in +the manifests are relative to this root, so moving the warehouse does not break them. The manifest +carries both the original `Image_Metadata_*` names and processed `Metadata_*` names, object +numbers, nucleus coordinates, cell line, time point, crop bounds/padding, JPEG settings, source +TIFF references and six paths. Viewing the images needs neither profiles nor UMAP data. + +The job manifest is published last. Interrupted jobs are regenerated; missing crop files or newer +TIFFs, QC, converted profiles, illumination functions or crop code invalidate a cached job. +An overwritten job replaces its own image folder, including removal of crops for newly QC-failing +cells. Zero-passing-cell jobs still receive an empty manifest with a schema. The combined index +requires a manifest for every converted-profile job. + +## Run + +Inputs are the converted profiles and QC annotations in `4.preprocess_features`, illumination +functions in `2.illumination_correction`, raw TIFFs referenced by the converted profiles, and +platemaps in `0.download_data/metadata/platemaps`. Processed profiles are used only for validation. + +From the repository root: + +```bash +./5a.object_image_crops/run_crop_pipeline.sh +``` + +The script uses the locked `environments/preprocessing` environment through uv. Alternatively, +use an existing Python with NumPy, pandas, PyArrow, Pillow, tifffile, imagecodecs and nbconvert: + +```bash +PCCMA_PYTHON=/path/to/python ./5a.object_image_crops/run_crop_pipeline.sh +``` + +Optional environment variables: + +| Variable | Purpose | +| --- | --- | +| `OVERWRITE=1` | Regenerate every crop job. | +| `PCCMA_IMAGES_DIR` | Raw-image root for relocating recorded TIFF paths, preserving the exact plate-measurement folder. Defaults to `~/mnt/bandicoot/PCCMA_data/Atlas_v2_screen`. Existing recorded TIFF paths are used first. | +| `PCCMA_CROPS_DIR` | Local output root, e.g. a sufficiently large local work disk. | +| `PCCMA_PROFILES_DIR` | CellProfiler single-cell profiles for validation; defaults to local profiles, then the bandicoot profiles folder. | + +Do a one-job pilot before a full run. After converting the notebooks, run: + +```bash +PYTHONPATH=utils python 5a.object_image_crops/nbconverted/0.generate_object_crops.py \ + --plate BR00150698 --cell_line A673 +``` + +| Notebook | Purpose | +| --- | --- | +| `0.generate_object_crops.ipynb` | One plate/cell-line job, reading each field once and writing six images per QC-passing cell. Includes a notebook-only preview. | +| `1.build_crop_index.ipynb` | Combine manifests, annotate wells, validate unique keys and all six paths, and publish the index atomically. Requires all converted-profile jobs; not a partial-run index builder. | +| `2.validate_joins.ipynb` | Exact two-way CellProfiler profile coverage; optional MorphEm and UMAP joins; all paths; fresh pixel recomputation for up to three cells per plate. Writes a validation report. | + +Absent MorphEm/UMAP inputs are explicitly reported as skipped, not verified. Missing CellProfiler +validation profiles fail rather than claiming a vacuous success. UMAP joins use exact saved +nucleus coordinates, not rounded or nearest-neighbor matches, and ambiguous keys are rejected. +Pixel validation compares decoded images against a fresh JPEG roundtrip in the same environment; +codec-version differences may require validation with the original generation environment. + +The tracked cell-count summary lists 1,204,712 post-QC cells. Six images each means 7,228,272 JPGs. +Actual space and runtime must be measured on a real-image pilot; no full-dataset size or runtime +has been established. Check free space and file-count limits before a full run. + +## Join without modifying source tables + +Both key naming schemes are in the index. Processed single-cell profiles use `Metadata_Plate`, +`Metadata_Well` and `Metadata_Site`, not the converted profiles' `Image_Metadata_*` names. +Select only join keys and paths to avoid suffixing overlapping metadata columns: + +```python +import pandas as pd +from crop_warehouse import FINAL_PROFILE_KEY, PATH_COLUMNS, join_crop_paths + +index = pd.read_parquet('5a.object_image_crops/data/object_image_crops/crops_index.parquet') +profiles = pd.read_parquet('path/to/BR00150698_sc_feature_selected.parquet') +joined = profiles.merge(index[FINAL_PROFILE_KEY + PATH_COLUMNS], + on=FINAL_PROFILE_KEY, how='left', validate='one_to_one') + +umap = pd.read_parquet('6.profile_analysis/results/3.single_cell_embedding/' + 'single_cell_umap_coordinates_by_cancer_group.parquet') +with_images = join_crop_paths(umap, index) # retains all six image paths +``` + +Import helpers from the installed utils package or run with `PYTHONPATH=utils` from the repo root. +Bulk profiles and bulk UMAP points represent groups, not individual cells; they do not have a +one-to-one crop join. Filter the crop index by plate/well/cell line to inspect their constituent cells. + +## Sync to bandicoot after validation + +Proposed destination: `~/mnt/bandicoot/PCCMA_data/Atlas_v2_object_crops/`, beside `Atlas_v2_screen` +and `Atlas_v2_profiles`. Confirm that the real lab mount is available first; an empty local +`~/mnt/bandicoot` placeholder is not a mount. No automatic sync is performed by the pipeline. + +After a complete run and review of `validation.json`, preview the copy (set the source to +`PCCMA_CROPS_DIR` if you changed it): + +```bash +rsync -an --stats --exclude='.staging/' --exclude='*.tmp.*' \ + 5a.object_image_crops/data/object_image_crops/ \ + ~/mnt/bandicoot/PCCMA_data/Atlas_v2_object_crops/ +``` + +Remove `n` from `-an` to copy. Then verify destination contents with a checksum dry run: + +```bash +rsync -rnc --itemize-changes --exclude='.staging/' --exclude='*.tmp.*' \ + 5a.object_image_crops/data/object_image_crops/ \ + ~/mnt/bandicoot/PCCMA_data/Atlas_v2_object_crops/ +``` + +The verification should report no changed/missing source files. These commands do not delete +extra destination files; the index defines the current published cell set. Do not sync while +crop generation is running. Consumers prepend the destination root to the same relative paths. + +## Tests + +```bash +python -m pytest utils/tests +``` + +Pipeline tests create explicitly synthetic TIFFs/parquet inputs under pytest's temporary folder, +then execute the real notebook scripts and shell runner, without a mount, torch or model downloads. +They do not substitute for a real atlas pilot or demonstrate biological embedding equivalence. diff --git a/5a.object_image_crops/nbconverted/0.generate_object_crops.py b/5a.object_image_crops/nbconverted/0.generate_object_crops.py new file mode 100644 index 0000000..61fac34 --- /dev/null +++ b/5a.object_image_crops/nbconverted/0.generate_object_crops.py @@ -0,0 +1,190 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Generate post-QC nucleocentric JPG crops +# +# Write five grayscale channels and one RGB composite for each QC-passing cell. Crop geometry, +# illumination correction and pre-JPEG rescaling match the MorphEm extraction. JPEG is lossy; +# these are display derivatives, not replacements for the original TIFFs or model inputs. +# One job processes a cell line on a plate; source images are read once per field of view. +# + +# ## Imports and job settings +# + +# In[ ]: + + +import argparse +import os +import pathlib +import shutil +import time + +import numpy as np +import pandas as pd +from crop_warehouse import ( + CHANNELS, PATH_COLUMNS, PROFILE_KEY_COLUMNS, UMAP_KEY_COLUMNS, + crop_id, make_cell_crops, manifest_row, read_corrected_field, + require_unique_keys, resolve_image_path, save_cell_crops, select_passing_cells, + validate_crop_files, +) +from path_utils import get_root_dir + +try: + get_ipython() + in_notebook = True +except NameError: + in_notebook = False + +root_dir = get_root_dir() +module_dir = root_dir / '5a.object_image_crops' +images_dir = pathlib.Path(os.environ.get('PCCMA_IMAGES_DIR', + '~/mnt/bandicoot/PCCMA_data/Atlas_v2_screen')).expanduser().resolve() +warehouse_dir = pathlib.Path(os.environ.get('PCCMA_CROPS_DIR', + str(module_dir / 'data/object_image_crops'))).expanduser().resolve() + +if not in_notebook: + parser = argparse.ArgumentParser(description='Write post-QC nucleocentric JPG crops for one job') + parser.add_argument('--plate', required=True) + parser.add_argument('--cell_line', required=True) + parser.add_argument('--overwrite', action='store_true') + args = parser.parse_args() + plate, cell_line, overwrite = args.plate, args.cell_line, args.overwrite +else: + plate, cell_line, overwrite = 'BR00150698', 'A673', False + +# Identifiers are path components, never paths supplied by a job. +for value in (plate, cell_line): + if pathlib.Path(value).name != value or value in ('.', '..'): + raise ValueError(f'Invalid job identifier: {value}') +converted_path = root_dir / '4.preprocess_features/data/converted_profiles' / cell_line / f'{plate}_{cell_line}_converted.parquet' +qc_path = root_dir / '4.preprocess_features/qc_results' / f'{cell_line}_qc_annotations.parquet' +illum_dir = root_dir / '2.illumination_correction/illum_directory' / plate +illum_paths = {ch: illum_dir / f'{plate}_Illum{ch}.npy' for ch in CHANNELS} +manifest_path = warehouse_dir / 'manifests' / f'{plate}_{cell_line}_manifest.parquet' + + +# ## Load metadata and apply QC +# + +# In[ ]: + + +image_columns = [f'Image_{kind}_Orig{ch}' for ch in CHANNELS for kind in ('FileName', 'PathName')] +columns = sorted(set(PROFILE_KEY_COLUMNS + UMAP_KEY_COLUMNS + image_columns)) +cells = pd.read_parquet(converted_path, columns=columns) +qc = pd.read_parquet(qc_path) +qc = qc.loc[qc['Image_Metadata_Plate'] == plate] +single_cell_df = select_passing_cells(cells, qc) +if not cells['Image_Metadata_Plate'].eq(plate).all(): + raise ValueError('Converted profile contains a different plate') +require_unique_keys(single_cell_df, PROFILE_KEY_COLUMNS, 'Post-QC cells') +require_unique_keys(single_cell_df, UMAP_KEY_COLUMNS, 'Post-QC positions') +if not np.isfinite(single_cell_df[UMAP_KEY_COLUMNS[3:]].to_numpy()).all(): + raise ValueError('Non-finite nucleus centers') +single_cell_df = single_cell_df.assign(Metadata_cell_line=cell_line) +if single_cell_df.apply(crop_id, axis=1).duplicated().any(): + raise ValueError('Duplicate crop filenames in a job') +for well in single_cell_df['Image_Metadata_Well']: + if pathlib.Path(well).name != well or well in ('.', '..'): + raise ValueError(f'Invalid well path component: {well}') + +# A field must refer to the same five TIFFs for every cell in it. +for _, field in single_cell_df.groupby('Metadata_ImageNumber'): + if (field[image_columns].nunique(dropna=False) != 1).any(): + raise ValueError('Inconsistent source images within a field') + +inputs = [converted_path, qc_path, *illum_paths.values(), + module_dir / '0.generate_object_crops.ipynb', + pathlib.Path(__import__('crop_warehouse').__file__), + pathlib.Path(__import__('nucleocentric_crops').__file__)] +for record in single_cell_df.drop_duplicates('Metadata_ImageNumber').to_dict('records'): + inputs.extend(resolve_image_path(record, ch, images_dir) for ch in CHANNELS) +write_crops = True +if manifest_path.is_file() and not overwrite: + fresh = all(path.is_file() and path.stat().st_mtime_ns <= manifest_path.stat().st_mtime_ns for path in inputs) + if fresh: + existing = pd.read_parquet(manifest_path) + try: + validate_crop_files(existing, warehouse_dir) + require_unique_keys(existing, PROFILE_KEY_COLUMNS, 'Existing manifest') + same_keys = existing[PROFILE_KEY_COLUMNS].merge(single_cell_df[PROFILE_KEY_COLUMNS], + on=PROFILE_KEY_COLUMNS, how='outer', validate='one_to_one', indicator=True) + write_crops = not same_keys['_merge'].eq('both').all() + except ValueError: + write_crops = True +print(f'{plate} {cell_line}: {len(single_cell_df)} of {len(cells)} cells passed QC') +if not write_crops: + print(f'Skipping {plate} {cell_line}: manifest and all six crop files are up to date') + + +# ## Generate one field at a time and publish the job manifest last +# + +# In[ ]: + + +if write_crops: + start = time.monotonic() + # Invalidate published summaries before changing files. A failed run is not a complete warehouse. + manifest_path.parent.mkdir(parents=True, exist_ok=True) + manifest_path.unlink(missing_ok=True) + (warehouse_dir / 'crops_index.parquet').unlink(missing_ok=True) + (warehouse_dir / 'validation.json').unlink(missing_ok=True) + functions = {ch: np.load(path) for ch, path in illum_paths.items()} + job_dir = warehouse_dir / 'crops' / plate / cell_line + stage = warehouse_dir / '.staging' / f'{plate}_{cell_line}' + if stage.exists(): + shutil.rmtree(stage) + stage.mkdir(parents=True) + rows = [] + for _, field in single_cell_df.groupby('Metadata_ImageNumber', sort=True): + corrected, saturated = read_corrected_field(field.iloc[0].to_dict(), functions, images_dir) + for record in field.to_dict('records'): + crops, padding = make_cell_crops(record, corrected, saturated) + subdir = pathlib.Path(record['Image_Metadata_Well']) / f"f{int(record['Image_Metadata_Site']):02d}" + written = save_cell_crops(crops, stage / subdir, crop_id(record)) + final_paths = {key: str(job_dir / pathlib.Path(path).relative_to(stage)) for key, path in written.items()} + row = manifest_row(record, final_paths, warehouse_dir) + row['Metadata_Nucleocentric_Pad_Fraction'] = padding + rows.append(row) + + # Preserve the schema even for a job where all cells failed QC. + template = {key: 0 for key in set(PROFILE_KEY_COLUMNS + UMAP_KEY_COLUMNS)} + template.update(Image_Metadata_Plate=plate, Image_Metadata_Well='', Metadata_cell_line=cell_line) + template.update({column: '' for column in image_columns}) + empty = manifest_row(template, {key: str(warehouse_dir / key) for key in PATH_COLUMNS}, warehouse_dir) + empty['Metadata_Nucleocentric_Pad_Fraction'] = 0.0 + manifest_df = pd.DataFrame(rows, columns=list(empty)) if rows else pd.DataFrame(columns=list(empty)) + require_unique_keys(manifest_df, PROFILE_KEY_COLUMNS, 'Job manifest') + job_dir.parent.mkdir(parents=True, exist_ok=True) + if job_dir.exists(): + shutil.rmtree(job_dir) + stage.replace(job_dir) + validate_crop_files(manifest_df, warehouse_dir) + temporary = manifest_path.with_suffix('.tmp.parquet') + manifest_df.to_parquet(temporary, index=False) + temporary.replace(manifest_path) + print(f'Saved {len(rows)} cells / {len(rows) * len(PATH_COLUMNS)} JPGs in {time.monotonic() - start:.1f}s') + + +# ## Preview composites (notebook only) +# + +# In[ ]: + + +if in_notebook: + import matplotlib.pyplot as plt + from PIL import Image + + preview = pd.read_parquet(manifest_path).head(4) + if not preview.empty: + fig, axes = plt.subplots(1, len(preview), squeeze=False, figsize=(4 * len(preview), 4)) + for ax, row in zip(axes.flat, preview.to_dict('records')): + with Image.open(warehouse_dir / row['composite']) as image: + ax.imshow(np.array(image)) + ax.set_title(f"{row['Metadata_Well']} / cell {row['Metadata_Cells_Number_Object_Number']}") + ax.axis('off') + plt.show() diff --git a/5a.object_image_crops/nbconverted/1.build_crop_index.py b/5a.object_image_crops/nbconverted/1.build_crop_index.py new file mode 100644 index 0000000..5640c7c --- /dev/null +++ b/5a.object_image_crops/nbconverted/1.build_crop_index.py @@ -0,0 +1,65 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Build the independent crop index +# +# Concatenate job manifests, verify that every converted-profile job has a manifest, annotate +# wells from platemaps, and check every path before atomically publishing the index. +# + +# ## Paths and inputs +# + +# In[ ]: + + +import os +import pathlib +import pandas as pd +from crop_warehouse import FINAL_PROFILE_KEY, POSITION_KEY, PATH_COLUMNS, require_unique_keys, validate_crop_files +from path_utils import get_root_dir + +root_dir = get_root_dir() +module_dir = root_dir / '5a.object_image_crops' +warehouse_dir = pathlib.Path(os.environ.get('PCCMA_CROPS_DIR', + str(module_dir / 'data/object_image_crops'))).expanduser().resolve() +index_path = warehouse_dir / 'crops_index.parquet' +manifest_dir = warehouse_dir / 'manifests' +converted_dir = root_dir / '4.preprocess_features/data/converted_profiles' +converted = sorted(converted_dir.glob('*/*_converted.parquet')) +if not converted: + raise FileNotFoundError(f'No converted profiles in {converted_dir}') +expected = {path.name.replace('_converted.parquet', '_manifest.parquet') for path in converted} +manifest_paths = sorted(manifest_dir.glob('*_manifest.parquet')) +if expected != {path.name for path in manifest_paths}: + raise ValueError('Missing or stale job manifests; generate every converted-profile job first') + + +# ## Build, annotate and validate +# + +# In[ ]: + + +index_df = pd.concat([pd.read_parquet(path) for path in manifest_paths], ignore_index=True) +# Drop placeholder annotations before adding authoritative platemap values, not afterwards. +index_df = index_df.drop(columns=['Metadata_cell_line', 'Metadata_time_point']) +platemaps = sorted((root_dir / '0.download_data/metadata/platemaps').glob('BR*_platemap.csv')) +if not platemaps: + raise FileNotFoundError('No platemaps') +wells = pd.concat([pd.read_csv(path)[['plate_barcode', 'well_position', 'cell_line', 'time_point']] + for path in platemaps], ignore_index=True).rename(columns={ + 'plate_barcode': 'Metadata_Plate', 'well_position': 'Metadata_Well', + 'cell_line': 'Metadata_cell_line', 'time_point': 'Metadata_time_point'}) +require_unique_keys(wells, ['Metadata_Plate', 'Metadata_Well'], 'Platemaps') +index_df = index_df.merge(wells, on=['Metadata_Plate', 'Metadata_Well'], how='left', validate='many_to_one') +if index_df[['Metadata_cell_line', 'Metadata_time_point']].isna().any().any(): + raise ValueError('Crop cells missing platemap annotations') +require_unique_keys(index_df, FINAL_PROFILE_KEY, 'Crop index') +require_unique_keys(index_df, POSITION_KEY, 'Crop positions') +validate_crop_files(index_df, warehouse_dir) +temporary = index_path.with_suffix('.tmp.parquet') +index_df.to_parquet(temporary, index=False) +temporary.replace(index_path) +(warehouse_dir / 'validation.json').unlink(missing_ok=True) +print(f'Saved {index_path}: {len(index_df)} cells, {len(index_df) * len(PATH_COLUMNS)} JPGs, {len(manifest_paths)} jobs') diff --git a/5a.object_image_crops/nbconverted/2.validate_joins.py b/5a.object_image_crops/nbconverted/2.validate_joins.py new file mode 100644 index 0000000..f0ae9b6 --- /dev/null +++ b/5a.object_image_crops/nbconverted/2.validate_joins.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Validate crop files, joins and sampled pixels +# +# Require exact post-QC coverage of the available CellProfiler single-cell profiles. Check MorphEm +# profiles and UMAP subsets when present; report absent optional inputs as skipped, never verified. +# Recompute sampled crops from TIFFs and compare against a fresh JPEG encode/decode in this environment. +# No profiles or embeddings are modified, recomputed or required for crop generation itself. +# + +# ## Paths and crop integrity +# + +# In[ ]: + + +import json +import os +import pathlib +import pandas as pd +from crop_warehouse import ( + FINAL_PROFILE_KEY, POSITION_KEY, PATH_COLUMNS, join_crop_paths, require_unique_keys, + validate_crop_files, validate_profile_join, validate_sample_pixels, +) +from path_utils import get_root_dir + +root_dir = get_root_dir() +module_dir = root_dir / '5a.object_image_crops' +warehouse_dir = pathlib.Path(os.environ.get('PCCMA_CROPS_DIR', + str(module_dir / 'data/object_image_crops'))).expanduser().resolve() +report_path = warehouse_dir / 'validation.json' +report_path.unlink(missing_ok=True) +index_df = pd.read_parquet(warehouse_dir / 'crops_index.parquet') +require_unique_keys(index_df, FINAL_PROFILE_KEY, 'Crop index') +require_unique_keys(index_df, POSITION_KEY, 'Crop positions') +validate_crop_files(index_df, warehouse_dir) +report = {'cells': len(index_df), 'jpg_files': len(index_df) * len(PATH_COLUMNS)} + +local = root_dir / '4.preprocess_features/data/single_cell_profiles' +mount = pathlib.Path('~/mnt/bandicoot/PCCMA_data/Atlas_v2_profiles/single_cell_profiles').expanduser() +profile_dir = pathlib.Path(os.environ.get('PCCMA_PROFILES_DIR', + str(local if any(local.glob('BR*_sc_feature_selected.parquet')) else mount))).expanduser() + + +# ## CellProfiler profiles: both directions, one-to-one +# + +# In[ ]: + + +profile_paths = sorted(profile_dir.glob('BR*_sc_feature_selected.parquet')) +if not profile_paths: + raise FileNotFoundError(f'No CellProfiler single-cell profiles in {profile_dir}') +profile_plates = {path.name.split('_')[0] for path in profile_paths} +if not set(index_df['Metadata_Plate']).issubset(profile_plates): + raise ValueError('Crop plates without CellProfiler profiles') +for path in profile_paths: + plate = path.name.split('_')[0] + profiles = pd.read_parquet(path, columns=FINAL_PROFILE_KEY) + validate_profile_join(index_df.loc[index_df['Metadata_Plate'] == plate], profiles, f'CellProfiler {plate}') + print(f'CellProfiler {plate}: {len(profiles)} profile rows matched one-to-one') +report['cellprofiler'] = 'verified' + + +# ## Optional MorphEm and UMAP joins +# + +# In[ ]: + + +morphem_dir = root_dir / '5.morphem_featurization/data/morphem_single_cell_profiles' +morphem_paths = sorted(morphem_dir.glob('BR*_morphem_sc_feature_selected.parquet')) +if morphem_paths: + checked = [] + for path in morphem_paths: + plate = path.name.split('_')[0] + profiles = pd.read_parquet(path, columns=FINAL_PROFILE_KEY) + validate_profile_join(index_df.loc[index_df['Metadata_Plate'] == plate], profiles, f'MorphEm {plate}') + checked.append(plate) + report['morphem'] = {'verified_plates': checked, + 'missing_plates': sorted(profile_plates - set(checked))} + print(f'MorphEm: checked {len(checked)} available plates') +else: + report['morphem'] = 'skipped: profiles unavailable' + print('MorphEm joins skipped: profiles unavailable') + +umap_dir = root_dir / '6.profile_analysis/results/3.single_cell_embedding' +report['umap'] = {} +for filename in ('single_cell_umap_coordinates_by_cancer_group.parquet', 'single_cell_umap_example_cells.parquet'): + path = umap_dir / filename + if not path.is_file(): + report['umap'][filename] = 'skipped: table unavailable' + print(f'UMAP join skipped: {filename} unavailable') + continue + table = pd.read_parquet(path) + joined = join_crop_paths(table, index_df) + report['umap'][filename] = len(joined) + print(f'UMAP {filename}: all {len(joined)} cells matched one-to-one') + + +# ## Recompute sampled pixels and save the validation report +# + +# In[ ]: + + +images_dir = pathlib.Path(os.environ.get('PCCMA_IMAGES_DIR', + '~/mnt/bandicoot/PCCMA_data/Atlas_v2_screen')).expanduser() +report['pixel_samples'] = validate_sample_pixels(index_df, warehouse_dir, + root_dir / '2.illumination_correction/illum_directory', images_dir) +temporary = report_path.with_suffix('.tmp.json') +temporary.write_text(json.dumps(report, indent=2) + '\n') +temporary.replace(report_path) +print(f"Checked all six images for {report['pixel_samples']} sampled cells against recomputed JPEG pixels") +print(f'Saved {report_path}') diff --git a/5a.object_image_crops/run_crop_pipeline.sh b/5a.object_image_crops/run_crop_pipeline.sh new file mode 100755 index 0000000..c876891 --- /dev/null +++ b/5a.object_image_crops/run_crop_pipeline.sh @@ -0,0 +1,54 @@ +#!/bin/bash +# Generate the local crop warehouse; validation never modifies profiles or UMAP results. +# Optional: PCCMA_PYTHON=/path/to/python to use an existing environment instead of uv. +# OVERWRITE=1 forces regeneration. See README.md for input/output path overrides. +set -euo pipefail + +cd "$(dirname "${BASH_SOURCE[0]}")/.." +module="5a.object_image_crops" +mkdir -p "${module}/logs" +run_log="${module}/logs/run_crop_pipeline_$(date +%Y%m%d_%H%M%S).log" +exec > >(tee -a "$run_log") 2>&1 +export PYTHONPATH="$PWD/utils${PYTHONPATH:+:$PYTHONPATH}" + +run_python() { + if [ -n "${PCCMA_PYTHON:-}" ]; then + "$PCCMA_PYTHON" "$@" + else + uv run --locked --project environments/preprocessing python "$@" + fi +} + +shopt -s nullglob +converted_files=(4.preprocess_features/data/converted_profiles/*/*_converted.parquet) +if [ "${#converted_files[@]}" -eq 0 ]; then + printf 'ERROR: No converted profiles found; run conversion and single-cell QC first.\n' >&2 + exit 1 +fi +run_python -m nbconvert --to python --output-dir="${module}/nbconverted" "${module}"/*.ipynb + +extra=() +case "${OVERWRITE:-}" in + 1|true|yes) extra+=(--overwrite) ;; +esac +failed=0 +for converted in "${converted_files[@]}"; do + name="${converted##*/}" + plate="${name%%_*}" + directory="${converted%/*}" + cell_line="${directory##*/}" + printf 'Generating %s %s\n' "$plate" "$cell_line" + # The generator checks freshness of profiles, QC, TIFFs, illumination and code, and all six paths. + if ! run_python "${module}/nbconverted/0.generate_object_crops.py" \ + --plate "$plate" --cell_line "$cell_line" "${extra[@]+"${extra[@]}"}"; then + printf 'ERROR: Crop job failed: %s %s\n' "$plate" "$cell_line" >&2 + failed=1 + fi +done +if [ "$failed" -ne 0 ]; then + printf 'ERROR: Not publishing an index from failed crop jobs.\n' >&2 + exit 1 +fi +run_python "${module}/nbconverted/1.build_crop_index.py" +run_python "${module}/nbconverted/2.validate_joins.py" +printf 'Local crop warehouse validated. No files have been synced to bandicoot.\n' diff --git a/README.md b/README.md index eff217f..88a9f66 100644 --- a/README.md +++ b/README.md @@ -96,9 +96,10 @@ The module numbers follow the order in which we run them. | [3.cp_analysis](./3.cp_analysis/) | Perform illumination correction, segmentation, and feature extraction with CellProfiler, where each cell line has its own pipeline. | | [4.preprocess_features](./4.preprocess_features/) | Convert the CellProfiler outputs to single-cell parquet files with CytoTable, remove poor quality single cells with coSMicQC, and process the profiles with pycytominer into single-cell (normalized and feature-selected) and bulk (aggregated, normalized, and feature-selected) profiles, with a QC report per cell line and plate. | | [5.morphem_featurization](./5.morphem_featurization/) | Extract nucleocentric deep learning features with MorphEm using the nuclei from CellProfiler, and process them into single-cell and bulk profiles. | +| [5a.object_image_crops](./5a.object_image_crops/) | Write the nucleocentric crop of every single cell that passed QC to a standalone image-crop warehouse (JPGs plus a manifest), joinable with the single-cell profiles and the UMAP tables. | | [cell_lines](./cell_lines/) | Build the consolidated cell line metadata table and create the descriptive figures of the cell lines. | | [environments](./environments/) | Conda environment files and a script to create the environments on an HPC cluster. | -| [utils](./utils/) | Shared functions for creating LoadData CSVs, running CellProfiler in parallel, loading the single cells that passed QC, and extracting MorphEm features. The uv environments install it as a package in editable mode (`pccma-atlas-utils`), so notebooks import it without changing `sys.path`. | +| [utils](./utils/) | Shared functions for creating LoadData CSVs, running CellProfiler in parallel, loading the single cells that passed QC, extracting MorphEm features, and writing the image-crop warehouse. The uv environments install it as a package in editable mode (`pccma-atlas-utils`), so notebooks import it without changing `sys.path`. | ## Quality control (QC) of poor quality images diff --git a/utils/crop_warehouse.py b/utils/crop_warehouse.py new file mode 100644 index 0000000..b2b142f --- /dev/null +++ b/utils/crop_warehouse.py @@ -0,0 +1,400 @@ +"""Write the nucleocentric crop of each single cell to the image-crop warehouse. + +The warehouse (built by `5a.object_image_crops`) is a folder of JPG images of the single cells of +the atlas: five grayscale crops (one per Cell Painting channel) and one color composite per cell. +It is decoupled from the parquet files of the other modules: nothing here reads or writes the +profiles, and a manifest parquet shipped with the images carries the join keys, so any crop can be +joined back to the single-cell profiles and the UMAP tables (see the README of the module). + +The crops are the same nucleocentric crops as the MorphEm features (`5.morphem_featurization`): +the same center, the same padding at the edge of the image, the same illumination correction, and +the same 8-bit rescaling before JPEG compression. JPEG is lossy: these are visualization +crops, not lossless model inputs. Geometry is shared through `nucleocentric_crops`. +""" + +import io +import pathlib + +import pandas as pd + +import numpy as np +import tifffile +from PIL import Image, __version__ as pillow_version + +from nucleocentric_crops import ( + MORPHEM_INPUT_SIZE, + get_nucleocentric_crop_box, + rescale_crop_to_8bit, + crop_with_padding, +) + +# channels of the Cell Painting assay, in the order of the profiles (Image_FileName_Orig) +CHANNELS = ["DNA", "ER", "RNA", "AGP", "Mito"] + +# display color of each channel in the composite crop (RGB, 0-1), the same as the colors of the +# profile-analysis figures (utils/pccma_utils/cell_images.py CHANNELS) +CHANNEL_COLORS = { + "DNA": (0.0, 0.35, 1.0), + "ER": (0.0, 1.0, 0.0), + "RNA": (1.0, 1.0, 0.0), + "AGP": (1.0, 0.15, 0.0), + "Mito": (1.0, 0.0, 1.0), +} + +# JPEG display derivatives; do not infer model-input equivalence from the quality setting. +JPEG_QUALITY = 95 + +# side of the square crop centered on the nucleus, the same as the MorphEm features +CROP_SIZE = MORPHEM_INPUT_SIZE + +# identifier of each cell within its plate (unique across the warehouse): plate, well, site +# (field of view), and the object numbers of the cell and its nucleus from CellProfiler. +# The profiles and the QC annotations join on the same columns (QC_MERGE_KEYS in +# preprocess_utils.py), and the UMAP tables of the profile analysis join on the plate, +# well, site, and nucleus center. +PROFILE_KEY_COLUMNS = [ + "Image_Metadata_Plate", + "Image_Metadata_Well", + "Image_Metadata_Site", + "Metadata_ImageNumber", + "Metadata_Nuclei_Number_Object_Number", + "Metadata_Cells_Number_Object_Number", +] + +# the position of the nucleus in the image, which the UMAP tables carry +# (6.profile_analysis/results/3.single_cell_embedding) +UMAP_KEY_COLUMNS = [ + "Image_Metadata_Plate", + "Image_Metadata_Well", + "Image_Metadata_Site", + "Metadata_Nuclei_Location_Center_X", + "Metadata_Nuclei_Location_Center_Y", +] + + +def correct_illumination(image: np.ndarray, illum_function: np.ndarray) -> np.ndarray: + """Apply the illumination correction function of a channel to one field of view. + + The same as CorrectIlluminationApply in the CellProfiler pipelines, but in the 16-bit range + instead of 0 to 1 (CellProfiler divides the images by 65535 when loading them); the constant + factor cancels out in the 8-bit rescaling of each crop. Copied from the MorphEm extraction + (`5.morphem_featurization/2.extract_morphem_features.ipynb`) so both use the same pixels. + + Parameters + ---------- + image : np.ndarray + Raw image of one channel of one field of view. + illum_function : np.ndarray + Illumination correction function of the channel (from 2.illumination_correction). + + Returns + ------- + np.ndarray + The corrected image, float32, clipped to the 16-bit range. + """ + if image.ndim != 2 or image.dtype != np.uint16: + raise ValueError("Expected a 2D uint16 source image") + if image.shape != illum_function.shape: + raise ValueError("Image and illumination function shapes differ") + if not np.isfinite(illum_function).all() or (illum_function <= 0).any(): + raise ValueError("Illumination functions must be finite and positive") + return np.clip( + image.astype(np.float32) / illum_function, 0, np.iinfo(image.dtype).max + ) + + +def composite_crops( + crops: dict[str, np.ndarray], colors: dict[str, tuple[float, float, float]] | None = None +) -> np.ndarray: + """Combine the five channel crops into one RGB image with the Cell Painting colors. + + Each channel is stretched between the 1st and 99.8th percentile of its own crop (the same + stretch as the example-cell images of the profile analysis, `pccma_utils.cell_images.crop_cell`) + and the channels are blended with the screen blend (`1 - (1 - a)(1 - b)`), so a bright pixel in + any channel makes the composite bright. The blend uses 0.85 of the full strength, like the + example-cell images, so overlapping channels stay colorful. + + Parameters + ---------- + crops : dict[str, np.ndarray] + The 8-bit crop of each channel, keyed by channel name (DNA, ER, RNA, AGP, Mito). + colors : dict[str, tuple[float, float, float]] | None + RGB color (0-1) of each channel. If None, use CHANNEL_COLORS. + + Returns + ------- + np.ndarray + The composite image, height x width x 3, uint8 (0 is black, 255 is the full channel color). + """ + if colors is None: + colors = CHANNEL_COLORS + screen = np.ones((*crops[CHANNELS[0]].shape, 3), dtype=np.float32) + for channel in CHANNELS: + crop = crops[channel].astype(np.float32) + lower, upper = np.percentile(crop, [1, 99.8]) + # a crop without contrast (flat background, all padding) would divide by zero; show its + # flat level directly instead, so a dark crop stays dark and a bright one keeps its color + if upper <= lower: + stretched = crop / 255.0 + else: + stretched = np.clip((crop - lower) / (upper - lower), 0, 1) + screen *= 1 - 0.85 * stretched[..., None] * np.asarray(colors[channel], dtype=np.float32) + return np.round((1 - screen) * 255).astype(np.uint8) + + +def crop_id(record: dict) -> str: + """File-stable identifier of one cell within the whole warehouse. + + The plate, well, site, and the object numbers of the cell and its nucleus from CellProfiler, + joined with underscores, so the file name says which cell it is even without the manifest. + + Parameters + ---------- + record : dict + One row of the single-cell table (the columns of PROFILE_KEY_COLUMNS). + + Returns + ------- + str + The identifier, for example "BR00150698_C05_f02_nuc0005_cell0005". + """ + return ( + f"{record['Image_Metadata_Plate']}_{record['Image_Metadata_Well']}" + f"_f{int(record['Image_Metadata_Site']):02d}" + f"_nuc{int(record['Metadata_Nuclei_Number_Object_Number']):04d}" + f"_cell{int(record['Metadata_Cells_Number_Object_Number']):04d}" + ) + + +def save_cell_crops( + crops: dict[str, np.ndarray], + crop_dir: pathlib.Path, + identifier: str, + quality: int = JPEG_QUALITY, +) -> dict[str, str]: + """Write the crops of one cell to its own folder: five grayscale JPGs and one composite JPG. + + Parameters + ---------- + crops : dict[str, np.ndarray] + The 8-bit crop of each channel, keyed by channel name. + crop_dir : pathlib.Path + Folder that holds the crops of the cell (created when missing). + identifier : str + Identifier of the cell (crop_id). + quality : int + JPEG quality, 0 to 100. + + Returns + ------- + dict[str, str] + The path of each written file, keyed by "grayscale_" and "composite". + """ + crop_dir.mkdir(parents=True, exist_ok=True) + paths = {} + for channel in CHANNELS: + path = crop_dir / f"{identifier}_{channel}.jpg" + path.write_bytes(encode_jpeg(crops[channel], quality)) + paths[f"grayscale_{channel}"] = str(path) + composite_path = crop_dir / f"{identifier}_composite.jpg" + composite_path.write_bytes(encode_jpeg(composite_crops(crops), quality)) + paths["composite"] = str(composite_path) + return paths + + +def manifest_row(record: dict, crop_paths: dict[str, str], warehouse_dir: pathlib.Path) -> dict: + """Build one row of the warehouse manifest from a cell record and its written crop paths. + + The row carries both key sets (PROFILE_KEY_COLUMNS and UMAP_KEY_COLUMNS), the cell line and + time point, and the crop file paths relative to the warehouse, so the manifest alone can find + every image and join every crop back to the profiles and the UMAP tables. + + Parameters + ---------- + record : dict + One row of the single-cell table. + crop_paths : dict[str, str] + The written file paths of the cell (from save_cell_crops). + warehouse_dir : pathlib.Path + Root folder of the warehouse (crop paths are stored relative to it). + + Returns + ------- + dict + One row of the manifest. + """ + row = {column: record[column] for column in PROFILE_KEY_COLUMNS + UMAP_KEY_COLUMNS} + row["Metadata_cell_line"] = record.get("Metadata_cell_line") + row["Metadata_time_point"] = record.get("Metadata_time_point") + row.update({f"Metadata_{name}": record[f"Image_Metadata_{name}"] + for name in ("Plate", "Well", "Site")}) + row["Metadata_Nucleocentric_Crop_Size"] = CROP_SIZE + row["Metadata_Crop_Generator"] = "nucleocentric_jpeg_v1" + row["Metadata_Pillow_Version"] = pillow_version + row["Metadata_NumPy_Version"] = np.__version__ + row["Metadata_JPEG_Quality"] = JPEG_QUALITY + row["Metadata_JPEG_Subsampling"] = 0 + row["Metadata_Crop_Format"] = "JPEG" + row["Metadata_Crop_Rescaling"] = "unsaturated_minmax_0_254_camera_saturated_255" + box = get_nucleocentric_crop_box(record["Metadata_Nuclei_Location_Center_X"], + record["Metadata_Nuclei_Location_Center_Y"]) + row.update(dict(zip(GEOMETRY_COLUMNS, box))) + for channel in CHANNELS: + for kind in ("FileName", "PathName"): + column = f"Image_{kind}_Orig{channel}" + if column in record: + row[column] = record[column] + row.update( + { + key: pathlib.Path(path).relative_to(warehouse_dir).as_posix() + for key, path in crop_paths.items() + } + ) + return row + + +FINAL_PROFILE_KEY = [ + "Metadata_Plate", "Metadata_Well", "Metadata_Site", "Metadata_ImageNumber", + "Metadata_Nuclei_Number_Object_Number", "Metadata_Cells_Number_Object_Number", +] +POSITION_KEY = FINAL_PROFILE_KEY[:3] + UMAP_KEY_COLUMNS[3:] +PATH_COLUMNS = [f"grayscale_{channel}" for channel in CHANNELS] + ["composite"] +GEOMETRY_COLUMNS = [ + f"Metadata_Nucleocentric_Crop_{bound}_{axis}" + for axis in ("Y", "X") for bound in ("Minimum", "Maximum") +] + + +def encode_jpeg(array: np.ndarray, quality: int = JPEG_QUALITY) -> bytes: + """Encode a grayscale or RGB uint8 image; keep composite colors without subsampling.""" + buffer = io.BytesIO() + Image.fromarray(array).save(buffer, format="JPEG", quality=quality, subsampling=0) + return buffer.getvalue() + + +def require_unique_keys(frame: pd.DataFrame, keys: list[str], label: str) -> None: + """Reject missing/null keys and duplicates rather than silently multiplying a join.""" + missing = set(keys) - set(frame.columns) + if missing or frame[keys].isna().any().any() or frame.duplicated(keys).any(): + raise ValueError(f"{label}: missing, null or duplicate keys ({sorted(missing)})") + + +def select_passing_cells(cells: pd.DataFrame, annotations: pd.DataFrame) -> pd.DataFrame: + """Apply the same per-cell QC flags as the profile pipeline, failing closed on absent QC.""" + from preprocess_utils import QC_MERGE_KEYS + + require_unique_keys(cells, QC_MERGE_KEYS, "Converted cells") + require_unique_keys(annotations, QC_MERGE_KEYS, "QC annotations") + flags = [name for name in annotations if name.endswith("_is_outlier")] + if not flags: + raise ValueError("QC annotations have no _is_outlier flags") + merged = cells.merge(annotations[QC_MERGE_KEYS + flags], on=QC_MERGE_KEYS, + how="left", validate="one_to_one") + if merged[flags].isna().any().any() or not merged[flags].isin([True, False]).all().all(): + raise ValueError("Missing or invalid QC flags for converted cells") + return merged.loc[~merged[flags].astype(bool).any(axis=1)].drop(columns=flags) + + +def resolve_image_path(record: dict, channel: str, images_dir: pathlib.Path) -> pathlib.Path: + """Use the recorded TIFF, or relocate its plate-measurement suffix to an explicit root.""" + folder = pathlib.Path(record[f"Image_PathName_Orig{channel}"]) + name = record[f"Image_FileName_Orig{channel}"] + if (folder / name).is_file(): + return folder / name + # Match a measurement folder explicitly: do not silently choose a different measurement. + parts = folder.parts + plate = record["Image_Metadata_Plate"] + measurement = next((i for i, part in enumerate(parts) if part.startswith(f"{plate}__")), None) + if measurement is not None: + candidate = images_dir.joinpath(*parts[measurement:], name) + if candidate.is_file(): + return candidate + raise FileNotFoundError(f"Missing source TIFF: {folder / name}; image root: {images_dir}") + + +def read_corrected_field(record: dict, illum_functions: dict, + images_dir: pathlib.Path) -> tuple[dict, dict]: + """Read each TIFF once for a FOV, retaining the camera-saturation mask before correction.""" + corrected, saturated = {}, {} + for channel in CHANNELS: + image = tifffile.imread(resolve_image_path(record, channel, images_dir)) + corrected[channel] = correct_illumination(image, illum_functions[channel]) + saturated[channel] = image == np.iinfo(image.dtype).max + if len({image.shape for image in corrected.values()}) != 1: + raise ValueError("Source channels have different shapes") + return corrected, saturated + + +def make_cell_crops(record: dict, corrected: dict, saturated: dict) -> tuple[dict, float]: + """Make the five pre-JPEG crops with exactly the shared MorphEm geometry and rescaling.""" + x, y = record[UMAP_KEY_COLUMNS[3]], record[UMAP_KEY_COLUMNS[4]] + height, width = corrected[CHANNELS[0]].shape + if not (np.isfinite(x) and np.isfinite(y) and 0 <= x < width and 0 <= y < height): + raise ValueError(f"Nucleus center {(x, y)} is outside image {(height, width)}") + box = get_nucleocentric_crop_box(x, y) + crops = {} + padding = 0.0 + for channel in CHANNELS: + crop, padding = crop_with_padding(corrected[channel], box) + mask = crop_with_padding(saturated[channel], box, pad_value=False)[0] + crops[channel] = rescale_crop_to_8bit(crop, mask) + return crops, padding + + +def validate_crop_files(index: pd.DataFrame, warehouse: pathlib.Path) -> None: + """Check all six paths per row; no absolute paths, traversal, reused paths or absent files.""" + for column in PATH_COLUMNS: + if column not in index or index[column].isna().any() or index[column].duplicated().any(): + raise ValueError(f"Missing or duplicate crop paths: {column}") + for relative in index[column]: + path = pathlib.Path(relative) + if path.is_absolute() or ".." in path.parts or not (warehouse / path).is_file(): + raise ValueError(f"Missing or invalid crop file: {relative}") + + +def validate_profile_join(index: pd.DataFrame, profiles: pd.DataFrame, label: str) -> None: + """Require identical post-QC cell sets (both directions), not just matching row counts.""" + require_unique_keys(index, FINAL_PROFILE_KEY, "Crop index") + require_unique_keys(profiles, FINAL_PROFILE_KEY, label) + merged = index[FINAL_PROFILE_KEY].merge(profiles[FINAL_PROFILE_KEY], + on=FINAL_PROFILE_KEY, how="outer", validate="one_to_one", indicator=True) + if not merged["_merge"].eq("both").all(): + raise ValueError(f"{label}: crop/profile cell sets differ: {merged['_merge'].value_counts().to_dict()}") + + +def join_crop_paths(table: pd.DataFrame, index: pd.DataFrame) -> pd.DataFrame: + """Attach all six paths to a sampled single-cell table via its exact nucleus position.""" + require_unique_keys(index, POSITION_KEY, "Crop index positions") + require_unique_keys(table, POSITION_KEY, "UMAP positions") + joined = table.merge(index[POSITION_KEY + PATH_COLUMNS], on=POSITION_KEY, + how="left", validate="one_to_one", indicator=True) + if not joined["_merge"].eq("both").all(): + raise ValueError("UMAP cells without a crop") + return joined.drop(columns="_merge") + + +def validate_sample_pixels(index: pd.DataFrame, warehouse: pathlib.Path, + illum_dir: pathlib.Path, images_dir: pathlib.Path) -> int: + """Recompute sampled crops and compare decoded JPEG pixels to a fresh local JPEG roundtrip. + + Comparing to the same codec roundtrip catches wrong images without pretending JPEG is lossless. + Different codec/library versions can change pixels; rerun with the generation environment then. + """ + checked = 0 + for plate, plate_df in index.groupby("Metadata_Plate"): + functions = {ch: np.load(illum_dir / plate / f"{plate}_Illum{ch}.npy") for ch in CHANNELS} + sample = plate_df.sample(min(3, len(plate_df)), random_state=0) + for record in sample.to_dict("records"): + corrected, saturated = read_corrected_field(record, functions, images_dir) + crops, _ = make_cell_crops(record, corrected, saturated) + arrays = {f"grayscale_{ch}": crops[ch] for ch in CHANNELS} + arrays["composite"] = composite_crops(crops) + for column, expected in arrays.items(): + with Image.open(warehouse / record[column]) as image: + actual = np.array(image) + with Image.open(io.BytesIO(encode_jpeg(expected, int(record["Metadata_JPEG_Quality"])))) as image: + reference = np.array(image) + if not np.array_equal(actual, reference): + raise ValueError(f"Wrong crop pixels: {record[column]}") + checked += 1 + return checked diff --git a/utils/morphem_utils.py b/utils/morphem_utils.py index fc2ce61..8052472 100644 --- a/utils/morphem_utils.py +++ b/utils/morphem_utils.py @@ -31,13 +31,22 @@ import torch.nn as nn from torchvision.transforms import v2 +# the numpy-only crop geometry functions live in nucleocentric_crops, which does not need torch, +# so modules that only crop images (5a.object_image_crops) can import them without the MorphEm +# environment; they are re-exported here so the MorphEm notebooks import them from one place +from nucleocentric_crops import ( # noqa: F401 + MORPHEM_INPUT_SIZE, + count_other_nuclei, + crop_with_padding, + get_nucleocentric_crop_box, + get_other_cell_overlap, + rescale_crop_to_8bit, +) + # Hugging Face model ID and revision (commit) of MorphEm, set so the features are reproducible MORPHEM_MODEL_ID = "CaicedoLab/MorphEm" MORPHEM_REVISION = "0e8d58787421f83f975634d72420d85c5dfc9c2c" -# size of the input images that MorphEm expects -MORPHEM_INPUT_SIZE = 224 - def get_morphem_model(device: str) -> torch.nn.Module: """ @@ -112,221 +121,6 @@ def forward(self, x: torch.Tensor) -> torch.Tensor: ] ) - -def rescale_crop_to_8bit(crop: np.ndarray, saturated: np.ndarray) -> np.ndarray: - """ - Rescale one channel of a crop to 8-bit, where only the saturated pixels become 255. - - MorphEm was trained on 8-bit images and SaturationNoiseInjector replaces the pixels with the - value 255 with noise, so we keep 255 for the pixels that were saturated in the camera and - linearly rescale the other pixels of the crop from their minimum and maximum to 0 to 254. - PerImageNormalize (instance normalization) removes any linear rescaling, so rescaling each crop - on its own only sets the 8-bit precision and does not change the scale of the features. - We do not rescale the whole FOV with percentile clipping, since it sets many pixels of the - cells to 255 in FOVs with few cells, which MorphEm then replaces with noise. - - Parameters - ---------- - crop : np.ndarray - 2D crop of one channel (e.g., 16-bit after illumination correction). - saturated : np.ndarray - 2D boolean mask of the crop with the pixels that were saturated in the raw image. - - Returns - ------- - np.ndarray - 2D uint8 crop. - """ - # Load in crop as float32 for rescaling - crop = crop.astype(np.float32) - # Rescale to 8-bit to match MorphEm's expectations on what it was trained on - rescaled = np.zeros(crop.shape, dtype=np.uint8) - # Clip the unsaturated pixels to the range [0, 254] after rescaling - unsaturated = crop[~saturated] - if unsaturated.size > 0 and unsaturated.max() > unsaturated.min(): - lower, upper = unsaturated.min(), unsaturated.max() - rescaled = np.round(np.clip((crop - lower) / (upper - lower), 0, 1) * 254).astype(np.uint8) - rescaled[saturated] = 255 - return rescaled - - -def get_nucleocentric_crop_box( - center_x: float, center_y: float, crop_size: int = MORPHEM_INPUT_SIZE -) -> tuple[int, int, int, int]: - """ - Find the square crop of `crop_size` pixels centered on the nucleus. - - Every crop has the same size as the MorphEm input (224 x 224 pixels), so MorphEm does not resize - the crops and every single cell has the same scale. We do not move crops at the edge of the image - back inside the image, so the nucleus is always in the center of the crop. The part of the crop - outside the image is padded by crop_with_padding. - - Parameters - ---------- - center_x, center_y : float - Center of the nucleus from CellProfiler (Nuclei_Location_Center_X/Y). - crop_size : int - Side of the square crop in pixels. - - Returns - ------- - tuple[int, int, int, int] - (y_min, y_max, x_min, x_max) of the crop, where the max values are exclusive. The values can - be outside the image when the nucleus is near the edge. - """ - x_min = round(center_x - crop_size / 2) - y_min = round(center_y - crop_size / 2) - return y_min, y_min + crop_size, x_min, x_min + crop_size - - -def crop_with_padding( - image: np.ndarray, - crop_box: tuple[int, int, int, int], - pad_value: float | bool | None = None, -) -> tuple[np.ndarray, float]: - """ - Crop an image and pad the part of the crop that is outside the image. - - Parameters - ---------- - image : np.ndarray - 2D image (one channel of a FOV, or a mask of the FOV). - crop_box : tuple[int, int, int, int] - (y_min, y_max, x_min, x_max) of the crop from get_nucleocentric_crop_box. - pad_value : float | bool | None - Value of the padded pixels. If None, use the minimum of the pixels inside the image, so the - padded pixels become 0 when we rescale the crop to 8-bit (the same as a dark background). - - Returns - ------- - tuple[np.ndarray, float] - The crop and the fraction of the crop that is padding (0 when the crop is inside the image). - """ - y_min, y_max, x_min, x_max = crop_box - height, width = image.shape - inside = image[max(y_min, 0) : min(y_max, height), max(x_min, 0) : min(x_max, width)] - # in theory this should never happen: the crop is centered on a nucleus inside the image, so at least - # about half of the crop is always inside the image (we check in case of a bad nucleus center) - if inside.size == 0: - raise ValueError(f"The crop {crop_box} is completely outside the image of shape {image.shape}") - if pad_value is None: - pad_value = inside.min() - pad_widths = ( - (max(-y_min, 0), max(y_max - height, 0)), - (max(-x_min, 0), max(x_max - width, 0)), - ) - crop = np.pad(inside, pad_widths, mode="constant", constant_values=pad_value) - pad_fraction = 1 - inside.size / crop.size - return crop, pad_fraction - - -def count_other_nuclei( - crop_boxes: np.ndarray, center_x: np.ndarray, center_y: np.ndarray -) -> np.ndarray: - """ - Count the other nuclei in the crop of each single cell of one FOV. - - A nucleus counts when its center is inside the crop, so a neighbor only counts when a large part - of it is in the crop (not just the tip of a protrusion). - - Parameters - ---------- - crop_boxes : np.ndarray - (number of single cells, 4) array of (y_min, y_max, x_min, x_max) of each crop. - center_x, center_y : np.ndarray - Center of the nucleus of each single cell, in the same order as crop_boxes. - - Returns - ------- - np.ndarray - Number of other nuclei in each crop (not counting the nucleus of the single cell). - """ - y_min, y_max, x_min, x_max = np.asarray(crop_boxes).T - inside = ( - (center_x[None, :] >= x_min[:, None]) - & (center_x[None, :] < x_max[:, None]) - & (center_y[None, :] >= y_min[:, None]) - & (center_y[None, :] < y_max[:, None]) - ) - np.fill_diagonal(inside, False) - return inside.sum(axis=1) - - -def _sum_in_boxes( - summed: np.ndarray, y_min: np.ndarray, y_max: np.ndarray, x_min: np.ndarray, x_max: np.ndarray -) -> np.ndarray: - # sum of a mask inside each box from its summed-area table (boxes are clipped to the image) - height, width = summed.shape[0] - 1, summed.shape[1] - 1 - y_min, y_max = np.clip(y_min, 0, height), np.clip(y_max, 0, height) - x_min, x_max = np.clip(x_min, 0, width), np.clip(x_max, 0, width) - y_max, x_max = np.maximum(y_max, y_min), np.maximum(x_max, x_min) - return summed[y_max, x_max] - summed[y_min, x_max] - summed[y_max, x_min] + summed[y_min, x_min] - - -def get_other_cell_overlap( - crop_boxes: np.ndarray, cell_boxes: np.ndarray, image_shape: tuple[int, int] -) -> tuple[np.ndarray, np.ndarray]: - """ - Measure how much of each crop and each single cell overlaps the other single cells of one FOV. - - We use the bounding boxes of the cells from CellProfiler, so the overlap is an upper bound of the - overlap of the cells themselves (a bounding box also covers the background around a cell). - - Parameters - ---------- - crop_boxes : np.ndarray - (number of single cells, 4) array of (y_min, y_max, x_min, x_max) of each crop. - cell_boxes : np.ndarray - (number of single cells, 4) array of (y_min, y_max, x_min, x_max) of the bounding box of each - cell (Cells_AreaShape_BoundingBox*, max values exclusive), in the same order as crop_boxes. - image_shape : tuple[int, int] - Shape of the FOV (height, width). - - Returns - ------- - tuple[np.ndarray, np.ndarray] - The fraction of each crop covered by the bounding boxes of the other cells, and the fraction - of the bounding box of each cell that overlaps the bounding boxes of the other cells. - """ - height, width = image_shape - crop_boxes = np.asarray(crop_boxes, dtype=int) - cell_boxes = np.clip(np.asarray(cell_boxes, dtype=int), 0, [height, height, width, width]) - cell_y_min, cell_y_max, cell_x_min, cell_x_max = cell_boxes.T - crop_y_min, crop_y_max, crop_x_min, crop_x_max = crop_boxes.T - - # number of cell bounding boxes that cover each pixel of the FOV - corners = np.zeros((height + 1, width + 1), dtype=np.int32) - np.add.at(corners, (cell_y_min, cell_x_min), 1) - np.add.at(corners, (cell_y_min, cell_x_max), -1) - np.add.at(corners, (cell_y_max, cell_x_min), -1) - np.add.at(corners, (cell_y_max, cell_x_max), 1) - coverage = corners.cumsum(axis=0).cumsum(axis=1)[:height, :width] - - # summed-area tables of the pixels covered by at least one and at least two bounding boxes - def summed_area(mask: np.ndarray) -> np.ndarray: - summed = np.zeros((height + 1, width + 1), dtype=np.int64) - summed[1:, 1:] = mask.cumsum(axis=0).cumsum(axis=1) - return summed - - at_least_one, at_least_two = summed_area(coverage >= 1), summed_area(coverage >= 2) - - # pixels of the crop covered by another cell: outside the cell's own box, any box counts; - # inside its own box, only pixels covered by at least two boxes (its own and another one) - own_y_min, own_y_max = np.maximum(cell_y_min, crop_y_min), np.minimum(cell_y_max, crop_y_max) - own_x_min, own_x_max = np.maximum(cell_x_min, crop_x_min), np.minimum(cell_x_max, crop_x_max) - covered_in_crop = ( - _sum_in_boxes(at_least_one, crop_y_min, crop_y_max, crop_x_min, crop_x_max) - - _sum_in_boxes(at_least_one, own_y_min, own_y_max, own_x_min, own_x_max) - + _sum_in_boxes(at_least_two, own_y_min, own_y_max, own_x_min, own_x_max) - ) - crop_area = (crop_y_max - crop_y_min) * (crop_x_max - crop_x_min) - - cell_area = np.maximum((cell_y_max - cell_y_min) * (cell_x_max - cell_x_min), 1) - overlap_in_cell = _sum_in_boxes(at_least_two, cell_y_min, cell_y_max, cell_x_min, cell_x_max) - - return covered_in_crop / crop_area, overlap_in_cell / cell_area - - def preprocess_crops(crops: list[np.ndarray]) -> torch.Tensor: """ Apply the MorphEm transforms to each crop on its own and stack them into one batch. diff --git a/utils/nucleocentric_crops.py b/utils/nucleocentric_crops.py new file mode 100644 index 0000000..df2b93c --- /dev/null +++ b/utils/nucleocentric_crops.py @@ -0,0 +1,230 @@ +"""Nucleocentric crop geometry and 8-bit rescaling, numpy only. + +These functions were part of `morphem_utils`; they moved here so that modules which only crop +images (the image-crop warehouse in `5a.object_image_crops`) can use the exact same crop +geometry, padding, and 8-bit rescaling as the MorphEm feature extraction +(`5.morphem_featurization`) without installing torch. `morphem_utils` re-exports them, so the +MorphEm notebooks keep importing them from one place. + +See `morphem_utils` for the design notes of the nucleocentric crop (224 x 224 centered on the +nucleus, padding at the edge of the image, and only the camera-saturated pixels at 255). +""" + +import numpy as np + +# size of the input images that MorphEm expects (the side of every nucleocentric crop) +MORPHEM_INPUT_SIZE = 224 + + +def rescale_crop_to_8bit(crop: np.ndarray, saturated: np.ndarray) -> np.ndarray: + """ + Rescale one channel of a crop to 8-bit, where only the saturated pixels become 255. + + MorphEm was trained on 8-bit images and SaturationNoiseInjector replaces the pixels with the + value 255 with noise, so we keep 255 for the pixels that were saturated in the camera and + linearly rescale the other pixels of the crop from their minimum and maximum to 0 to 254. + PerImageNormalize (instance normalization) removes any linear rescaling, so rescaling each crop + on its own only sets the 8-bit precision and does not change the scale of the features. + We do not rescale the whole FOV with percentile clipping, since it sets many pixels of the + cells to 255 in FOVs with few cells, which MorphEm then replaces with noise. + + Parameters + ---------- + crop : np.ndarray + 2D crop of one channel (e.g., 16-bit after illumination correction). + saturated : np.ndarray + 2D boolean mask of the crop with the pixels that were saturated in the raw image. + + Returns + ------- + np.ndarray + 2D uint8 crop. + """ + # Load in crop as float32 for rescaling + crop = crop.astype(np.float32) + # Rescale to 8-bit to match MorphEm's expectations on what it was trained on + rescaled = np.zeros(crop.shape, dtype=np.uint8) + # Clip the unsaturated pixels to the range [0, 254] after rescaling + unsaturated = crop[~saturated] + if unsaturated.size > 0 and unsaturated.max() > unsaturated.min(): + lower, upper = unsaturated.min(), unsaturated.max() + rescaled = np.round(np.clip((crop - lower) / (upper - lower), 0, 1) * 254).astype(np.uint8) + rescaled[saturated] = 255 + return rescaled + + +def get_nucleocentric_crop_box( + center_x: float, center_y: float, crop_size: int = MORPHEM_INPUT_SIZE +) -> tuple[int, int, int, int]: + """ + Find the square crop of `crop_size` pixels centered on the nucleus. + + Every crop has the same size as the MorphEm input (224 x 224 pixels), so MorphEm does not resize + the crops and every single cell has the same scale. We do not move crops at the edge of the image + back inside the image, so the nucleus is always in the center of the crop. The part of the crop + outside the image is padded by crop_with_padding. + + Parameters + ---------- + center_x, center_y : float + Center of the nucleus from CellProfiler (Nuclei_Location_Center_X/Y). + crop_size : int + Side of the square crop in pixels. + + Returns + ------- + tuple[int, int, int, int] + (y_min, y_max, x_min, x_max) of the crop, where the max values are exclusive. The values can + be outside the image when the nucleus is near the edge. + """ + x_min = round(center_x - crop_size / 2) + y_min = round(center_y - crop_size / 2) + return y_min, y_min + crop_size, x_min, x_min + crop_size + + +def crop_with_padding( + image: np.ndarray, + crop_box: tuple[int, int, int, int], + pad_value: float | bool | None = None, +) -> tuple[np.ndarray, float]: + """ + Crop an image and pad the part of the crop that is outside the image. + + Parameters + ---------- + image : np.ndarray + 2D image (one channel of a FOV, or a mask of the FOV). + crop_box : tuple[int, int, int, int] + (y_min, y_max, x_min, x_max) of the crop from get_nucleocentric_crop_box. + pad_value : float | bool | None + Value of the padded pixels. If None, use the minimum of the pixels inside the image, so the + padded pixels become 0 when we rescale the crop to 8-bit (the same as a dark background). + + Returns + ------- + tuple[np.ndarray, float] + The crop and the fraction of the crop that is padding (0 when the crop is inside the image). + """ + y_min, y_max, x_min, x_max = crop_box + height, width = image.shape + inside = image[max(y_min, 0) : min(y_max, height), max(x_min, 0) : min(x_max, width)] + # in theory this should never happen: the crop is centered on a nucleus inside the image, so at least + # about half of the crop is always inside the image (we check in case of a bad nucleus center) + if inside.size == 0: + raise ValueError(f"The crop {crop_box} is completely outside the image of shape {image.shape}") + if pad_value is None: + pad_value = inside.min() + pad_widths = ( + (max(-y_min, 0), max(y_max - height, 0)), + (max(-x_min, 0), max(x_max - width, 0)), + ) + crop = np.pad(inside, pad_widths, mode="constant", constant_values=pad_value) + pad_fraction = 1 - inside.size / crop.size + return crop, pad_fraction + + +def count_other_nuclei( + crop_boxes: np.ndarray, center_x: np.ndarray, center_y: np.ndarray +) -> np.ndarray: + """ + Count the other nuclei in the crop of each single cell of one FOV. + + A nucleus counts when its center is inside the crop, so a neighbor only counts when a large part + of it is in the crop (not just the tip of a protrusion). + + Parameters + ---------- + crop_boxes : np.ndarray + (number of single cells, 4) array of (y_min, y_max, x_min, x_max) of each crop. + center_x, center_y : np.ndarray + Center of the nucleus of each single cell, in the same order as crop_boxes. + + Returns + ------- + np.ndarray + Number of other nuclei in each crop (not counting the nucleus of the single cell). + """ + y_min, y_max, x_min, x_max = np.asarray(crop_boxes).T + inside = ( + (center_x[None, :] >= x_min[:, None]) + & (center_x[None, :] < x_max[:, None]) + & (center_y[None, :] >= y_min[:, None]) + & (center_y[None, :] < y_max[:, None]) + ) + np.fill_diagonal(inside, False) + return inside.sum(axis=1) + + +def _sum_in_boxes( + summed: np.ndarray, y_min: np.ndarray, y_max: np.ndarray, x_min: np.ndarray, x_max: np.ndarray +) -> np.ndarray: + # sum of a mask inside each box from its summed-area table (boxes are clipped to the image) + height, width = summed.shape[0] - 1, summed.shape[1] - 1 + y_min, y_max = np.clip(y_min, 0, height), np.clip(y_max, 0, height) + x_min, x_max = np.clip(x_min, 0, width), np.clip(x_max, 0, width) + y_max, x_max = np.maximum(y_max, y_min), np.maximum(x_max, x_min) + return summed[y_max, x_max] - summed[y_min, x_max] - summed[y_max, x_min] + summed[y_min, x_min] + + +def get_other_cell_overlap( + crop_boxes: np.ndarray, cell_boxes: np.ndarray, image_shape: tuple[int, int] +) -> tuple[np.ndarray, np.ndarray]: + """ + Measure how much of each crop and each single cell overlaps the other single cells of one FOV. + + We use the bounding boxes of the cells from CellProfiler, so the overlap is an upper bound of the + overlap of the cells themselves (a bounding box also covers the background around a cell). + + Parameters + ---------- + crop_boxes : np.ndarray + (number of single cells, 4) array of (y_min, y_max, x_min, x_max) of each crop. + cell_boxes : np.ndarray + (number of single cells, 4) array of (y_min, y_max, x_min, x_max) of the bounding box of each + cell (Cells_AreaShape_BoundingBox*, max values exclusive), in the same order as crop_boxes. + image_shape : tuple[int, int] + Shape of the FOV (height, width). + + Returns + ------- + tuple[np.ndarray, np.ndarray] + The fraction of each crop covered by the bounding boxes of the other cells, and the fraction + of the bounding box of each cell that overlaps the bounding boxes of the other cells. + """ + height, width = image_shape + crop_boxes = np.asarray(crop_boxes, dtype=int) + cell_boxes = np.clip(np.asarray(cell_boxes, dtype=int), 0, [height, height, width, width]) + cell_y_min, cell_y_max, cell_x_min, cell_x_max = cell_boxes.T + crop_y_min, crop_y_max, crop_x_min, crop_x_max = crop_boxes.T + + # number of cell bounding boxes that cover each pixel of the FOV + corners = np.zeros((height + 1, width + 1), dtype=np.int32) + np.add.at(corners, (cell_y_min, cell_x_min), 1) + np.add.at(corners, (cell_y_min, cell_x_max), -1) + np.add.at(corners, (cell_y_max, cell_x_min), -1) + np.add.at(corners, (cell_y_max, cell_x_max), 1) + coverage = corners.cumsum(axis=0).cumsum(axis=1)[:height, :width] + + # summed-area tables of the pixels covered by at least one and at least two bounding boxes + def summed_area(mask: np.ndarray) -> np.ndarray: + summed = np.zeros((height + 1, width + 1), dtype=np.int64) + summed[1:, 1:] = mask.cumsum(axis=0).cumsum(axis=1) + return summed + + at_least_one, at_least_two = summed_area(coverage >= 1), summed_area(coverage >= 2) + + # pixels of the crop covered by another cell: outside the cell's own box, any box counts; + # inside its own box, only pixels covered by at least two boxes (its own and another one) + own_y_min, own_y_max = np.maximum(cell_y_min, crop_y_min), np.minimum(cell_y_max, crop_y_max) + own_x_min, own_x_max = np.maximum(cell_x_min, crop_x_min), np.minimum(cell_x_max, crop_x_max) + covered_in_crop = ( + _sum_in_boxes(at_least_one, crop_y_min, crop_y_max, crop_x_min, crop_x_max) + - _sum_in_boxes(at_least_one, own_y_min, own_y_max, own_x_min, own_x_max) + + _sum_in_boxes(at_least_two, own_y_min, own_y_max, own_x_min, own_x_max) + ) + crop_area = (crop_y_max - crop_y_min) * (crop_x_max - crop_x_min) + + cell_area = np.maximum((cell_y_max - cell_y_min) * (cell_x_max - cell_x_min), 1) + overlap_in_cell = _sum_in_boxes(at_least_two, cell_y_min, cell_y_max, cell_x_min, cell_x_max) + + return covered_in_crop / crop_area, overlap_in_cell / cell_area diff --git a/utils/pyproject.toml b/utils/pyproject.toml index 7bc41f6..db53c10 100644 --- a/utils/pyproject.toml +++ b/utils/pyproject.toml @@ -19,8 +19,10 @@ build-backend = "setuptools.build_meta" py-modules = [ "bandicoot_utils", "cp_parallel", + "crop_warehouse", "loaddata_utils", "morphem_utils", + "nucleocentric_crops", "path_utils", "preprocess_utils", ] diff --git a/utils/tests/test_crop_pipeline.py b/utils/tests/test_crop_pipeline.py new file mode 100644 index 0000000..e0cc981 --- /dev/null +++ b/utils/tests/test_crop_pipeline.py @@ -0,0 +1,280 @@ +"""Run the real notebook scripts on explicitly synthetic TIFFs and parquet inputs.""" + +import os +import pathlib +import shutil +import subprocess +import sys + +import nbformat +import numpy as np +import pandas as pd +import pytest +import tifffile +from nbconvert import PythonExporter +from PIL import Image + +REPO = pathlib.Path(__file__).resolve().parents[2] +MODULE = "5a.object_image_crops" +NOTEBOOKS = ("0.generate_object_crops", "1.build_crop_index", "2.validate_joins") +FINAL_KEY = ["Metadata_Plate", "Metadata_Well", "Metadata_Site", + "Metadata_ImageNumber", "Metadata_Nuclei_Number_Object_Number", + "Metadata_Cells_Number_Object_Number"] +RENAME = {f"Image_Metadata_{name}": f"Metadata_{name}" for name in ("Plate", "Well", "Site")} + + +@pytest.fixture +def atlas(tmp_path): + """Three synthetic objects: two pass QC, including one near an image edge.""" + root = tmp_path / "synthetic atlas" + root.mkdir() + (root / ".git").mkdir() + script_dir = root / MODULE / "nbconverted" + script_dir.mkdir(parents=True) + for name in NOTEBOOKS: + shutil.copyfile(REPO / MODULE / f"{name}.ipynb", script_dir.parent / f"{name}.ipynb") + notebook = nbformat.read(REPO / MODULE / f"{name}.ipynb", as_version=4) + script, _ = PythonExporter().from_notebook_node(notebook) + (script_dir / f"{name}.py").write_text(script) + rows = [] + image_dir = root / "source images" / "BR00150698__measurement" / "Images" + image_dir.mkdir(parents=True) + illum_dir = root / "2.illumination_correction/illum_directory/BR00150698" + illum_dir.mkdir(parents=True) + yy, xx = np.mgrid[:256, :256] + for channel, number in zip(("DNA", "ER", "RNA", "AGP", "Mito"), (5, 2, 6, 3, 4)): + image = (100 + number * xx + yy * 8).astype(np.uint16) + image[125:130, 125:130] = 65535 + tifffile.imwrite(image_dir / f"ch{number}.tiff", image) + np.save(illum_dir / f"BR00150698_Illum{channel}.npy", np.full((256, 256), 1.25, np.float32)) + for obj, center in enumerate((128.25, 8.5, 150.75), start=1): + row = {"Image_Metadata_Plate": "BR00150698", "Image_Metadata_Well": "C05", + "Image_Metadata_Site": 2, "Metadata_ImageNumber": 7, + "Metadata_Nuclei_Number_Object_Number": obj, + "Metadata_Cells_Number_Object_Number": obj, + "Metadata_Nuclei_Location_Center_X": center, + "Metadata_Nuclei_Location_Center_Y": center} + for channel, number in zip(("DNA", "ER", "RNA", "AGP", "Mito"), (5, 2, 6, 3, 4)): + row[f"Image_FileName_Orig{channel}"] = f"ch{number}.tiff" + row[f"Image_PathName_Orig{channel}"] = str(image_dir) + rows.append(row) + converted = pd.DataFrame(rows) + converted_dir = root / "4.preprocess_features/data/converted_profiles/A673" + converted_dir.mkdir(parents=True) + converted.to_parquet(converted_dir / "BR00150698_A673_converted.parquet", index=False) + qc_dir = root / "4.preprocess_features/qc_results" + qc_dir.mkdir(parents=True) + qc = converted[["Image_Metadata_Plate", "Image_Metadata_Well", "Image_Metadata_Site", + "Metadata_Cells_Number_Object_Number"]].copy() + qc["area_is_outlier"] = [False, False, True] + qc["blur_is_outlier"] = [False, False, False] + qc.to_parquet(qc_dir / "A673_qc_annotations.parquet", index=False) + platemaps = root / "0.download_data/metadata/platemaps" + platemaps.mkdir(parents=True) + pd.DataFrame([{"plate_barcode": "BR00150698", "well_position": "C05", + "cell_line": "A673", "time_point": 24}]).to_csv( + platemaps / "BR00150698_platemap.csv", index=False) + passing = converted.iloc[:2].rename(columns=RENAME) + for directory, filename in ( + ("4.preprocess_features/data/single_cell_profiles", "BR00150698_sc_feature_selected.parquet"), + ("5.morphem_featurization/data/morphem_single_cell_profiles", "BR00150698_morphem_sc_feature_selected.parquet"), + ): + target = root / directory + target.mkdir(parents=True) + passing.to_parquet(target / filename, index=False) + umap_dir = root / "6.profile_analysis/results/3.single_cell_embedding" + umap_dir.mkdir(parents=True) + position = ["Metadata_Plate", "Metadata_Well", "Metadata_Site", + "Metadata_Nuclei_Location_Center_X", "Metadata_Nuclei_Location_Center_Y"] + umap = passing[position].copy() + umap["umap_1"], umap["umap_2"] = [0.1, 0.2], [0.3, 0.4] + umap.to_parquet(umap_dir / "single_cell_umap_coordinates_by_cancer_group.parquet", index=False) + umap.iloc[:1].to_parquet(umap_dir / "single_cell_umap_example_cells.parquet", index=False) + return root + + +def run_stage(root, number, *args, ok=True): + env = dict(os.environ, PYTHONPATH=str(REPO / "utils")) + result = subprocess.run( + [sys.executable, str(root / MODULE / "nbconverted" / f"{NOTEBOOKS[number]}.py"), *args], + cwd=root, env=env, capture_output=True, text=True, timeout=45, + ) + output = result.stdout + result.stderr + if ok: + assert result.returncode == 0, output + else: + assert result.returncode != 0, output + return output + + +def generate(root, *args, ok=True): + return run_stage(root, 0, "--plate", "BR00150698", "--cell_line", "A673", *args, ok=ok) + + +def warehouse(root): + return root / MODULE / "data/object_image_crops" + + +def test_notebooks_end_to_end(atlas): + generate(atlas) + run_stage(atlas, 1) + output = run_stage(atlas, 2) + index = pd.read_parquet(warehouse(atlas) / "crops_index.parquet") + assert len(index) == 2 + assert index.columns.is_unique + assert index["Metadata_cell_line"].tolist() == ["A673", "A673"] + assert index["Metadata_time_point"].tolist() == [24, 24] + assert not index.duplicated(FINAL_KEY).any() + assert len(list(warehouse(atlas).rglob("*.jpg"))) == 12 + for row in index.to_dict("records"): + for name in ("grayscale_DNA", "grayscale_ER", "grayscale_RNA", "grayscale_AGP", "grayscale_Mito", "composite"): + with Image.open(warehouse(atlas) / row[name]) as image: + assert image.size == (224, 224) + assert image.mode == ("RGB" if name == "composite" else "L") + assert "MorphEm" in output + assert "UMAP" in output + + +def test_missing_qc_flags_fails_before_writing(atlas): + qc_path = atlas / "4.preprocess_features/qc_results/A673_qc_annotations.parquet" + qc = pd.read_parquet(qc_path).drop(columns=["area_is_outlier", "blur_is_outlier"]) + qc.to_parquet(qc_path, index=False) + output = generate(atlas, ok=False) + assert "QC" in output + assert not list(warehouse(atlas).rglob("*.jpg")) + + +def test_zero_passing_cells_have_empty_manifest(atlas): + qc_path = atlas / "4.preprocess_features/qc_results/A673_qc_annotations.parquet" + qc = pd.read_parquet(qc_path) + qc["area_is_outlier"] = True + qc.to_parquet(qc_path, index=False) + generate(atlas) + manifest = pd.read_parquet(warehouse(atlas) / "manifests/BR00150698_A673_manifest.parquet") + assert manifest.empty + assert "composite" in manifest.columns + assert not list(warehouse(atlas).rglob("*.jpg")) + + +def test_index_rejects_missing_grayscale(atlas): + generate(atlas) + next(warehouse(atlas).rglob("*_DNA.jpg")).unlink() + assert "missing" in run_stage(atlas, 1, ok=False).lower() + + +def test_validation_rejects_missing_post_qc_cell(atlas): + generate(atlas) + run_stage(atlas, 1) + path = warehouse(atlas) / "crops_index.parquet" + pd.read_parquet(path).iloc[:1].to_parquet(path, index=False) + assert "profile" in run_stage(atlas, 2, ok=False).lower() + + +def test_no_profile_files_cannot_report_success(atlas): + generate(atlas) + run_stage(atlas, 1) + for path in (atlas / "4.preprocess_features/data/single_cell_profiles").glob("*.parquet"): + path.unlink() + assert "profile" in run_stage(atlas, 2, ok=False).lower() + + +def test_same_size_wrong_image_is_detected(atlas): + generate(atlas) + run_stage(atlas, 1) + next_path = next(warehouse(atlas).rglob("*_DNA.jpg")) + Image.fromarray(np.zeros((224, 224), np.uint8)).save(next_path, quality=95) + assert "Wrong crop pixels" in run_stage(atlas, 2, ok=False) + + +def test_missing_umap_is_reported_as_skipped(atlas): + generate(atlas) + run_stage(atlas, 1) + for path in (atlas / "6.profile_analysis/results/3.single_cell_embedding").glob("*.parquet"): + path.unlink() + assert "skipped" in run_stage(atlas, 2).lower() + + +def test_generator_skips_fresh_job_and_recovers_missing_crop(atlas): + generate(atlas) + path = warehouse(atlas) / "manifests/BR00150698_A673_manifest.parquet" + mtime = path.stat().st_mtime_ns + assert "Skipping" in generate(atlas) + assert path.stat().st_mtime_ns == mtime + next(warehouse(atlas).rglob("*_DNA.jpg")).unlink() + assert "Skipping" not in generate(atlas) + assert len(list(warehouse(atlas).rglob("*.jpg"))) == 12 + + +def test_overwrite_removes_crops_of_cells_that_now_fail_qc(atlas): + generate(atlas) + qc_path = atlas / "4.preprocess_features/qc_results/A673_qc_annotations.parquet" + qc = pd.read_parquet(qc_path) + qc.loc[1, "area_is_outlier"] = True + qc.to_parquet(qc_path, index=False) + generate(atlas, "--overwrite") + assert len(list(warehouse(atlas).rglob("*.jpg"))) == 6 + + +def test_changed_source_tiff_forces_regeneration(atlas): + generate(atlas) + next(atlas.glob("source images/*/Images/*.tiff")).touch() + assert "Skipping" not in generate(atlas) + + +def test_runner_end_to_end_with_existing_python(atlas): + shutil.copyfile(REPO / MODULE / "run_crop_pipeline.sh", atlas / MODULE / "run_crop_pipeline.sh") + (atlas / "utils").symlink_to(REPO / "utils", target_is_directory=True) + env = dict(os.environ, PCCMA_PYTHON=sys.executable) + result = subprocess.run(["bash", str(atlas / MODULE / "run_crop_pipeline.sh")], + cwd=atlas, env=env, capture_output=True, text=True, timeout=60) + assert result.returncode == 0, result.stdout + result.stderr + assert (warehouse(atlas) / "validation.json").is_file() + assert "No files have been synced" in result.stdout + + +def test_missing_qc_label_fails_closed(atlas): + path = atlas / "4.preprocess_features/qc_results/A673_qc_annotations.parquet" + pd.read_parquet(path).iloc[1:].to_parquet(path, index=False) + assert "Missing or invalid QC flags" in generate(atlas, ok=False) + + +def test_duplicate_positions_are_rejected(atlas): + path = atlas / "4.preprocess_features/data/converted_profiles/A673/BR00150698_A673_converted.parquet" + cells = pd.read_parquet(path) + for column in ("Metadata_Nuclei_Location_Center_X", "Metadata_Nuclei_Location_Center_Y"): + cells.loc[1, column] = cells.loc[0, column] + cells.to_parquet(path, index=False) + assert "Post-QC positions" in generate(atlas, ok=False) + + +def test_missing_job_manifest_blocks_index(atlas): + generate(atlas) + source = atlas / "4.preprocess_features/data/converted_profiles/A673/BR00150698_A673_converted.parquet" + shutil.copyfile(source, source.with_name("BR00150699_A673_converted.parquet")) + assert "Missing or stale job manifests" in run_stage(atlas, 1, ok=False) + + +def test_actual_tracked_umap_key_contract(): + from crop_warehouse import PATH_COLUMNS, POSITION_KEY, join_crop_paths + path = REPO / "6.profile_analysis/results/3.single_cell_embedding/single_cell_umap_coordinates_by_cancer_group.parquet" + table = pd.read_parquet(path) + # This checks key preservation only, not real-image availability. + position_index = table[POSITION_KEY].copy() + for column in PATH_COLUMNS: + position_index[column] = [f"key-test/{i}/{column}.jpg" for i in range(len(table))] + joined = join_crop_paths(table, position_index) + assert len(joined) == len(table) + pd.testing.assert_frame_equal(joined[POSITION_KEY], table[POSITION_KEY]) + + +def test_source_relocation_preserves_measurement(atlas): + from crop_warehouse import resolve_image_path + directory = atlas / "source images" + record = {"Image_Metadata_Plate": "BR00150698", + "Image_PathName_OrigDNA": "/unmounted/PCCMA_atlas_data/BR00150698__measurement/Images", + "Image_FileName_OrigDNA": "ch5.tiff"} + expected = directory / "BR00150698__measurement/Images/ch5.tiff" + assert resolve_image_path(record, "DNA", directory) == expected + record["Image_PathName_OrigDNA"] = "/unmounted/BR00150698__other_measurement/Images" + with pytest.raises(FileNotFoundError): + resolve_image_path(record, "DNA", directory) diff --git a/utils/tests/test_crop_warehouse.py b/utils/tests/test_crop_warehouse.py new file mode 100644 index 0000000..4165a06 --- /dev/null +++ b/utils/tests/test_crop_warehouse.py @@ -0,0 +1,111 @@ +"""Tests of crop_warehouse (the nucleocentric JPG crops of the single cells). + +The tests write small synthetic Phenix-style images to a temporary folder, like the tests of +pccma_utils.cell_images, so they run without the raw images of the atlas. +""" + +import io + +import numpy as np +import pytest +from PIL import Image + +from crop_warehouse import ( + CHANNELS, + CROP_SIZE, + JPEG_QUALITY, + composite_crops, + correct_illumination, +) +from nucleocentric_crops import ( + crop_with_padding, + get_nucleocentric_crop_box, + rescale_crop_to_8bit, +) + + +def test_crop_size_matches_morphem(): + """The warehouse crops are the same size as the MorphEm input.""" + assert CROP_SIZE == 224 + + +def test_correct_illumination_divides_and_clips(): + """Illumination correction divides by the function and clips to the 16-bit range.""" + image = np.array([[1000, 2000], [32768, 65535]], dtype=np.uint16) + illum = np.full((2, 2), 2.0, dtype=np.float32) + corrected = correct_illumination(image, illum) + assert corrected.dtype == np.float32 + assert corrected[0, 0] == 500 + assert corrected[0, 1] == 1000 + assert corrected[1, 0] == 16384 + assert corrected[1, 1] == 32767.5 # division only lowers values; the clip is a safety net + + +def test_rescale_only_saturated_at_255(): + """Only the camera-saturated pixels become 255; the others are within 0 to 254.""" + crop = np.array([[0.0, 100.0], [32767.0, 65535.0]], dtype=np.float32) + saturated = crop == 65535 + rescaled = rescale_crop_to_8bit(crop, saturated) + assert rescaled[1, 1] == 255 + assert rescaled[1, 0] == 254 # the highest unsaturated value + assert rescaled[0, 0] == 0 + assert rescaled.dtype == np.uint8 + + +def test_crop_box_centers_on_nucleus(): + """The crop is centered on the nucleus, even when it goes past the edge of the image.""" + y_min, y_max, x_min, x_max = get_nucleocentric_crop_box(center_x=10.0, center_y=10.0) + assert (x_max - x_min) == CROP_SIZE + assert (y_max - y_min) == CROP_SIZE + assert x_min < 0 # near the edge: not moved back inside + image = np.zeros((200, 200), dtype=np.uint16) + image[10 - 5 : 10 + 5, 10 - 5 : 10 + 5] = 1000 + crop, pad_fraction = crop_with_padding(image, (y_min, y_max, x_min, x_max)) + assert crop.shape == (CROP_SIZE, CROP_SIZE) + assert pad_fraction > 0 + + +def test_composite_crops_shape_and_colors(): + """The composite is an RGB image that is dark for an empty crop and bright for a full one.""" + dark = {channel: np.zeros((8, 8), dtype=np.uint8) for channel in CHANNELS} + bright = {channel: np.full((8, 8), 200, dtype=np.uint8) for channel in CHANNELS} + dark_composite = composite_crops(dark) + bright_composite = composite_crops(bright) + assert dark_composite.shape == (8, 8, 3) + assert dark_composite.max() < 10 + assert bright_composite.min() > 100 + + +def test_composite_crops_channel_color(): + """Only the DNA channel bright: the composite is blue like the DNA color of the figures.""" + crops = {channel: np.zeros((8, 8), dtype=np.uint8) for channel in CHANNELS} + crops["DNA"] = np.full((8, 8), 200, dtype=np.uint8) + composite = composite_crops(crops) + middle = composite[4, 4] + assert middle[2] > middle[0] # blue above red + assert middle[2] > middle[1] # blue above green + + +@pytest.fixture +def jpg_roundtrip(): + """Encode and decode one grayscale crop and one composite through JPEG, like the warehouse.""" + + def roundtrip(array): + image = Image.fromarray(array) + buffer = io.BytesIO() + image.save(buffer, format="jpeg", quality=JPEG_QUALITY) + buffer.seek(0) + return np.asarray(Image.open(buffer)) + + return roundtrip + + +def test_jpeg_roundtrip_keeps_pixel_values(jpg_roundtrip): + """JPEG q95 keeps the 8-bit pixel values of a microscopy crop within a few gray levels.""" + # a smooth blob in a dark background, like a fluorescence crop + y, x = np.mgrid[0:CROP_SIZE, 0:CROP_SIZE] + crop = 40 + 180 * np.exp(-(((x - 112) ** 2) + (y - 112) ** 2) / (2 * 40**2)) + crop = np.round(crop).astype(np.uint8) + decoded = jpg_roundtrip(crop) + assert decoded.shape == crop.shape + assert np.abs(decoded.astype(int) - crop.astype(int)).max() <= 3 From d5b69dd9a2b29bb3f510606b736dca4d9460a0fd Mon Sep 17 00:00:00 2001 From: d33bs Date: Fri, 13 Nov 2026 10:44:06 -0700 Subject: [PATCH 2/6] adjustments --- .../0.generate_object_crops.ipynb | 7 ++- .../1.build_crop_index.ipynb | 11 +++- 5a.object_image_crops/2.validate_joins.ipynb | 20 ++++-- 5a.object_image_crops/README.md | 63 +++++++++++++++++-- .../nbconverted/0.generate_object_crops.py | 7 ++- .../nbconverted/1.build_crop_index.py | 11 +++- .../nbconverted/2.validate_joins.py | 20 ++++-- 5a.object_image_crops/run_crop_pipeline.sh | 10 ++- utils/crop_warehouse.py | 25 ++++++++ utils/tests/test_crop_pipeline.py | 55 ++++++++++++++++ 10 files changed, 207 insertions(+), 22 deletions(-) diff --git a/5a.object_image_crops/0.generate_object_crops.ipynb b/5a.object_image_crops/0.generate_object_crops.ipynb index e365055..ff9ee15 100644 --- a/5a.object_image_crops/0.generate_object_crops.ipynb +++ b/5a.object_image_crops/0.generate_object_crops.ipynb @@ -35,7 +35,7 @@ " CHANNELS, PATH_COLUMNS, PROFILE_KEY_COLUMNS, UMAP_KEY_COLUMNS,\n", " crop_id, make_cell_crops, manifest_row, read_corrected_field,\n", " require_unique_keys, resolve_image_path, save_cell_crops, select_passing_cells,\n", - " validate_crop_files,\n", + " validate_crop_files, requested_plate, guard_plate_scope,\n", ")\n", "from path_utils import get_root_dir\n", "\n", @@ -62,6 +62,11 @@ "else:\n", " plate, cell_line, overwrite = 'BR00150698', 'A673', False\n", "\n", + "selected_plate = requested_plate()\n", + "if selected_plate and plate != selected_plate:\n", + " raise ValueError(f'Job plate {plate} is outside requested scope {selected_plate}')\n", + "guard_plate_scope(warehouse_dir, selected_plate)\n", + "\n", "# Identifiers are path components, never paths supplied by a job.\n", "for value in (plate, cell_line):\n", " if pathlib.Path(value).name != value or value in ('.', '..'):\n", diff --git a/5a.object_image_crops/1.build_crop_index.ipynb b/5a.object_image_crops/1.build_crop_index.ipynb index a12e4ff..712a528 100644 --- a/5a.object_image_crops/1.build_crop_index.ipynb +++ b/5a.object_image_crops/1.build_crop_index.ipynb @@ -26,7 +26,8 @@ "import os\n", "import pathlib\n", "import pandas as pd\n", - "from crop_warehouse import FINAL_PROFILE_KEY, POSITION_KEY, PATH_COLUMNS, require_unique_keys, validate_crop_files\n", + "from crop_warehouse import (FINAL_PROFILE_KEY, POSITION_KEY, PATH_COLUMNS, require_unique_keys,\n", + " validate_crop_files, requested_plate, guard_plate_scope)\n", "from path_utils import get_root_dir\n", "\n", "root_dir = get_root_dir()\n", @@ -36,11 +37,15 @@ "index_path = warehouse_dir / 'crops_index.parquet'\n", "manifest_dir = warehouse_dir / 'manifests'\n", "converted_dir = root_dir / '4.preprocess_features/data/converted_profiles'\n", - "converted = sorted(converted_dir.glob('*/*_converted.parquet'))\n", + "selected_plate = requested_plate()\n", + "guard_plate_scope(warehouse_dir, selected_plate)\n", + "pattern = f'*/{selected_plate}_*_converted.parquet' if selected_plate else '*/*_converted.parquet'\n", + "converted = sorted(converted_dir.glob(pattern))\n", "if not converted:\n", " raise FileNotFoundError(f'No converted profiles in {converted_dir}')\n", "expected = {path.name.replace('_converted.parquet', '_manifest.parquet') for path in converted}\n", - "manifest_paths = sorted(manifest_dir.glob('*_manifest.parquet'))\n", + "pattern = f'{selected_plate}_*_manifest.parquet' if selected_plate else '*_manifest.parquet'\n", + "manifest_paths = sorted(manifest_dir.glob(pattern))\n", "if expected != {path.name for path in manifest_paths}:\n", " raise ValueError('Missing or stale job manifests; generate every converted-profile job first')" ] diff --git a/5a.object_image_crops/2.validate_joins.ipynb b/5a.object_image_crops/2.validate_joins.ipynb index 50bd1b1..bcddbcb 100644 --- a/5a.object_image_crops/2.validate_joins.ipynb +++ b/5a.object_image_crops/2.validate_joins.ipynb @@ -29,7 +29,7 @@ "import pandas as pd\n", "from crop_warehouse import (\n", " FINAL_PROFILE_KEY, POSITION_KEY, PATH_COLUMNS, join_crop_paths, require_unique_keys,\n", - " validate_crop_files, validate_profile_join, validate_sample_pixels,\n", + " validate_crop_files, validate_profile_join, validate_sample_pixels, requested_plate, guard_plate_scope,\n", ")\n", "from path_utils import get_root_dir\n", "\n", @@ -37,13 +37,18 @@ "module_dir = root_dir / '5a.object_image_crops'\n", "warehouse_dir = pathlib.Path(os.environ.get('PCCMA_CROPS_DIR',\n", " str(module_dir / 'data/object_image_crops'))).expanduser().resolve()\n", + "selected_plate = requested_plate()\n", + "guard_plate_scope(warehouse_dir, selected_plate)\n", "report_path = warehouse_dir / 'validation.json'\n", "report_path.unlink(missing_ok=True)\n", "index_df = pd.read_parquet(warehouse_dir / 'crops_index.parquet')\n", "require_unique_keys(index_df, FINAL_PROFILE_KEY, 'Crop index')\n", "require_unique_keys(index_df, POSITION_KEY, 'Crop positions')\n", "validate_crop_files(index_df, warehouse_dir)\n", - "report = {'cells': len(index_df), 'jpg_files': len(index_df) * len(PATH_COLUMNS)}\n", + "if selected_plate and not index_df['Metadata_Plate'].eq(selected_plate).all():\n", + " raise ValueError('Index contains cells outside the requested plate scope')\n", + "report = {'cells': len(index_df), 'jpg_files': len(index_df) * len(PATH_COLUMNS),\n", + " 'plate_scope': selected_plate or 'all'}\n", "\n", "local = root_dir / '4.preprocess_features/data/single_cell_profiles'\n", "mount = pathlib.Path('~/mnt/bandicoot/PCCMA_data/Atlas_v2_profiles/single_cell_profiles').expanduser()\n", @@ -66,7 +71,8 @@ "outputs": [], "id": "code-1", "source": [ - "profile_paths = sorted(profile_dir.glob('BR*_sc_feature_selected.parquet'))\n", + "profile_pattern = f'{selected_plate}_sc_feature_selected.parquet' if selected_plate else 'BR*_sc_feature_selected.parquet'\n", + "profile_paths = sorted(profile_dir.glob(profile_pattern))\n", "if not profile_paths:\n", " raise FileNotFoundError(f'No CellProfiler single-cell profiles in {profile_dir}')\n", "profile_plates = {path.name.split('_')[0] for path in profile_paths}\n", @@ -96,7 +102,8 @@ "id": "code-2", "source": [ "morphem_dir = root_dir / '5.morphem_featurization/data/morphem_single_cell_profiles'\n", - "morphem_paths = sorted(morphem_dir.glob('BR*_morphem_sc_feature_selected.parquet'))\n", + "morphem_pattern = f'{selected_plate}_morphem_sc_feature_selected.parquet' if selected_plate else 'BR*_morphem_sc_feature_selected.parquet'\n", + "morphem_paths = sorted(morphem_dir.glob(morphem_pattern))\n", "if morphem_paths:\n", " checked = []\n", " for path in morphem_paths:\n", @@ -113,6 +120,7 @@ "\n", "umap_dir = root_dir / '6.profile_analysis/results/3.single_cell_embedding'\n", "report['umap'] = {}\n", + "report['umap_rows_outside_scope'] = {}\n", "for filename in ('single_cell_umap_coordinates_by_cancer_group.parquet', 'single_cell_umap_example_cells.parquet'):\n", " path = umap_dir / filename\n", " if not path.is_file():\n", @@ -120,6 +128,10 @@ " print(f'UMAP join skipped: {filename} unavailable')\n", " continue\n", " table = pd.read_parquet(path)\n", + " total_rows = len(table)\n", + " if selected_plate:\n", + " table = table.loc[table['Metadata_Plate'] == selected_plate]\n", + " report['umap_rows_outside_scope'][filename] = total_rows - len(table)\n", " joined = join_crop_paths(table, index_df)\n", " report['umap'][filename] = len(joined)\n", " print(f'UMAP {filename}: all {len(joined)} cells matched one-to-one')" diff --git a/5a.object_image_crops/README.md b/5a.object_image_crops/README.md index 8f64a4a..d6d1b25 100644 --- a/5a.object_image_crops/README.md +++ b/5a.object_image_crops/README.md @@ -63,12 +63,24 @@ Optional environment variables: | Variable | Purpose | | --- | --- | -| `OVERWRITE=1` | Regenerate every crop job. | +| `OVERWRITE=1` | Regenerate every selected crop job. | +| `PCCMA_PLATE` | Restrict generation, index coverage, profile checks and UMAP checks to one exact plate barcode. Unset means all plates. Use a separate output root for a plate-scoped run. | | `PCCMA_IMAGES_DIR` | Raw-image root for relocating recorded TIFF paths, preserving the exact plate-measurement folder. Defaults to `~/mnt/bandicoot/PCCMA_data/Atlas_v2_screen`. Existing recorded TIFF paths are used first. | | `PCCMA_CROPS_DIR` | Local output root, e.g. a sufficiently large local work disk. | | `PCCMA_PROFILES_DIR` | CellProfiler single-cell profiles for validation; defaults to local profiles, then the bandicoot profiles folder. | -Do a one-job pilot before a full run. After converting the notebooks, run: +To process just one plate, including index construction and validation, use a new output root: + +```bash +PCCMA_PLATE=BR00150695 PCCMA_CROPS_DIR=/local/work/new-plate-run/warehouse \ + ./5a.object_image_crops/run_crop_pipeline.sh +``` + +Other plates' inputs are ignored, not deleted or modified. The validation report records the plate +scope and how many UMAP rows lie outside it. A scoped run refuses an output directory containing +other plates' manifests/index; keep different pilot runs in different output roots. + +Do a one-job pilot before a full plate run. After converting the notebooks, run: ```bash PYTHONPATH=utils python 5a.object_image_crops/nbconverted/0.generate_object_crops.py \ @@ -78,7 +90,7 @@ PYTHONPATH=utils python 5a.object_image_crops/nbconverted/0.generate_object_crop | Notebook | Purpose | | --- | --- | | `0.generate_object_crops.ipynb` | One plate/cell-line job, reading each field once and writing six images per QC-passing cell. Includes a notebook-only preview. | -| `1.build_crop_index.ipynb` | Combine manifests, annotate wells, validate unique keys and all six paths, and publish the index atomically. Requires all converted-profile jobs; not a partial-run index builder. | +| `1.build_crop_index.ipynb` | Combine manifests, annotate wells, validate unique keys and all six paths, and publish the index atomically. Requires all converted-profile jobs within the selected plate scope (or the full atlas if no plate is selected). | | `2.validate_joins.ipynb` | Exact two-way CellProfiler profile coverage; optional MorphEm and UMAP joins; all paths; fresh pixel recomputation for up to three cells per plate. Writes a validation report. | Absent MorphEm/UMAP inputs are explicitly reported as skipped, not verified. Missing CellProfiler @@ -88,8 +100,7 @@ Pixel validation compares decoded images against a fresh JPEG roundtrip in the s codec-version differences may require validation with the original generation environment. The tracked cell-count summary lists 1,204,712 post-QC cells. Six images each means 7,228,272 JPGs. -Actual space and runtime must be measured on a real-image pilot; no full-dataset size or runtime -has been established. Check free space and file-count limits before a full run. +The one-plate measurements below are real; no full-dataset size or runtime has been established. Check free space and file-count limits before a full run. ## Join without modifying source tables @@ -142,6 +153,48 @@ The verification should report no changed/missing source files. These commands d extra destination files; the index defines the current published cell set. Do not sync while crop generation is running. Consumers prepend the destination root to the same relative paths. +## Verified one-plate run + +Completed November 13, 2026 (16:25:17 UTC), run `BR00150695-20261113T155150Z-g790ecb4`: + +- Plate `BR00150695` only: **80,493 post-QC cells**, 13 cell-line jobs and **482,958 JPGs**. +- CellProfiler and MorphEm profiles matched one-to-one; 6,500 UMAP points and seven example cells on this plate joined successfully. Other plates were excluded explicitly. +- Shared crop bounds matched the existing MorphEm metadata for every selected cell. Fresh pixel recomputation checked all six images for three cells. +- Every JPG was fully decoded and SHA256 hashed. Every archive payload was checked, followed by checksum read-back of every published artifact from bandicoot. +- The archive is 5,888,471,040 bytes (5.89 GB / 5.48 GiB). Generation, validation and safe publication took 21 minutes 47 seconds after launch. +- All 52 tests passed on Willow in the isolated run environment. Source input sizes/mtimes and the existing checkout were unchanged. + +Durable artifacts on Willow's bandicoot mount: + + /home/davebunten/mnt/bandicoot/PCCMA_data/Atlas_v2_object_crops/runs/BR00150695-20261113T155150Z-g790ecb4/ + BR00150695-object-image-crops.tar + crops_index.parquet + validation.json + completion.json + SHA256SUMS + jpg-sha256.txt.gz + preview.jpg + ... source patch/hashes, environment, membership flags and run provenance + +The tar contains `warehouse/` with the complete JPG tree, manifests, index and validation. +Relative paths in the sidecar index resolve inside that `warehouse/` directory. This plate archive +avoids copying nearly half a million individual files onto the shared filesystem. Extract only +into a new empty directory, never over existing results. + +Browsable original generated files remain on Willow: + + /home/davebunten/work/pccma-crops-runs/BR00150695-20261113T155150Z-g790ecb4/warehouse + +The original QC annotation files were unavailable. The run inherited the exact retained-object +membership of the existing published post-QC profiles and recorded run-local boolean flags; it +**did not recalculate QC** or infer original failure reasons. Input sources and prior results were +read-only. Code provenance is base revision `790ecb4` plus the preserved one-plate-scope patch, +not an unmodified checkout of that revision. + +Local review copies are gitignored under +`data/pilot_runs/BR00150695-20261113T155150Z-g790ecb4/` (preview, index, validation and completion/read-back records). +No other plate was processed. Use a new run/output directory for expansion. + ## Tests ```bash diff --git a/5a.object_image_crops/nbconverted/0.generate_object_crops.py b/5a.object_image_crops/nbconverted/0.generate_object_crops.py index 61fac34..141a466 100644 --- a/5a.object_image_crops/nbconverted/0.generate_object_crops.py +++ b/5a.object_image_crops/nbconverted/0.generate_object_crops.py @@ -27,7 +27,7 @@ CHANNELS, PATH_COLUMNS, PROFILE_KEY_COLUMNS, UMAP_KEY_COLUMNS, crop_id, make_cell_crops, manifest_row, read_corrected_field, require_unique_keys, resolve_image_path, save_cell_crops, select_passing_cells, - validate_crop_files, + validate_crop_files, requested_plate, guard_plate_scope, ) from path_utils import get_root_dir @@ -54,6 +54,11 @@ else: plate, cell_line, overwrite = 'BR00150698', 'A673', False +selected_plate = requested_plate() +if selected_plate and plate != selected_plate: + raise ValueError(f'Job plate {plate} is outside requested scope {selected_plate}') +guard_plate_scope(warehouse_dir, selected_plate) + # Identifiers are path components, never paths supplied by a job. for value in (plate, cell_line): if pathlib.Path(value).name != value or value in ('.', '..'): diff --git a/5a.object_image_crops/nbconverted/1.build_crop_index.py b/5a.object_image_crops/nbconverted/1.build_crop_index.py index 5640c7c..d0e7116 100644 --- a/5a.object_image_crops/nbconverted/1.build_crop_index.py +++ b/5a.object_image_crops/nbconverted/1.build_crop_index.py @@ -16,7 +16,8 @@ import os import pathlib import pandas as pd -from crop_warehouse import FINAL_PROFILE_KEY, POSITION_KEY, PATH_COLUMNS, require_unique_keys, validate_crop_files +from crop_warehouse import (FINAL_PROFILE_KEY, POSITION_KEY, PATH_COLUMNS, require_unique_keys, + validate_crop_files, requested_plate, guard_plate_scope) from path_utils import get_root_dir root_dir = get_root_dir() @@ -26,11 +27,15 @@ index_path = warehouse_dir / 'crops_index.parquet' manifest_dir = warehouse_dir / 'manifests' converted_dir = root_dir / '4.preprocess_features/data/converted_profiles' -converted = sorted(converted_dir.glob('*/*_converted.parquet')) +selected_plate = requested_plate() +guard_plate_scope(warehouse_dir, selected_plate) +pattern = f'*/{selected_plate}_*_converted.parquet' if selected_plate else '*/*_converted.parquet' +converted = sorted(converted_dir.glob(pattern)) if not converted: raise FileNotFoundError(f'No converted profiles in {converted_dir}') expected = {path.name.replace('_converted.parquet', '_manifest.parquet') for path in converted} -manifest_paths = sorted(manifest_dir.glob('*_manifest.parquet')) +pattern = f'{selected_plate}_*_manifest.parquet' if selected_plate else '*_manifest.parquet' +manifest_paths = sorted(manifest_dir.glob(pattern)) if expected != {path.name for path in manifest_paths}: raise ValueError('Missing or stale job manifests; generate every converted-profile job first') diff --git a/5a.object_image_crops/nbconverted/2.validate_joins.py b/5a.object_image_crops/nbconverted/2.validate_joins.py index f0ae9b6..d61d080 100644 --- a/5a.object_image_crops/nbconverted/2.validate_joins.py +++ b/5a.object_image_crops/nbconverted/2.validate_joins.py @@ -21,7 +21,7 @@ import pandas as pd from crop_warehouse import ( FINAL_PROFILE_KEY, POSITION_KEY, PATH_COLUMNS, join_crop_paths, require_unique_keys, - validate_crop_files, validate_profile_join, validate_sample_pixels, + validate_crop_files, validate_profile_join, validate_sample_pixels, requested_plate, guard_plate_scope, ) from path_utils import get_root_dir @@ -29,13 +29,18 @@ module_dir = root_dir / '5a.object_image_crops' warehouse_dir = pathlib.Path(os.environ.get('PCCMA_CROPS_DIR', str(module_dir / 'data/object_image_crops'))).expanduser().resolve() +selected_plate = requested_plate() +guard_plate_scope(warehouse_dir, selected_plate) report_path = warehouse_dir / 'validation.json' report_path.unlink(missing_ok=True) index_df = pd.read_parquet(warehouse_dir / 'crops_index.parquet') require_unique_keys(index_df, FINAL_PROFILE_KEY, 'Crop index') require_unique_keys(index_df, POSITION_KEY, 'Crop positions') validate_crop_files(index_df, warehouse_dir) -report = {'cells': len(index_df), 'jpg_files': len(index_df) * len(PATH_COLUMNS)} +if selected_plate and not index_df['Metadata_Plate'].eq(selected_plate).all(): + raise ValueError('Index contains cells outside the requested plate scope') +report = {'cells': len(index_df), 'jpg_files': len(index_df) * len(PATH_COLUMNS), + 'plate_scope': selected_plate or 'all'} local = root_dir / '4.preprocess_features/data/single_cell_profiles' mount = pathlib.Path('~/mnt/bandicoot/PCCMA_data/Atlas_v2_profiles/single_cell_profiles').expanduser() @@ -49,7 +54,8 @@ # In[ ]: -profile_paths = sorted(profile_dir.glob('BR*_sc_feature_selected.parquet')) +profile_pattern = f'{selected_plate}_sc_feature_selected.parquet' if selected_plate else 'BR*_sc_feature_selected.parquet' +profile_paths = sorted(profile_dir.glob(profile_pattern)) if not profile_paths: raise FileNotFoundError(f'No CellProfiler single-cell profiles in {profile_dir}') profile_plates = {path.name.split('_')[0] for path in profile_paths} @@ -70,7 +76,8 @@ morphem_dir = root_dir / '5.morphem_featurization/data/morphem_single_cell_profiles' -morphem_paths = sorted(morphem_dir.glob('BR*_morphem_sc_feature_selected.parquet')) +morphem_pattern = f'{selected_plate}_morphem_sc_feature_selected.parquet' if selected_plate else 'BR*_morphem_sc_feature_selected.parquet' +morphem_paths = sorted(morphem_dir.glob(morphem_pattern)) if morphem_paths: checked = [] for path in morphem_paths: @@ -87,6 +94,7 @@ umap_dir = root_dir / '6.profile_analysis/results/3.single_cell_embedding' report['umap'] = {} +report['umap_rows_outside_scope'] = {} for filename in ('single_cell_umap_coordinates_by_cancer_group.parquet', 'single_cell_umap_example_cells.parquet'): path = umap_dir / filename if not path.is_file(): @@ -94,6 +102,10 @@ print(f'UMAP join skipped: {filename} unavailable') continue table = pd.read_parquet(path) + total_rows = len(table) + if selected_plate: + table = table.loc[table['Metadata_Plate'] == selected_plate] + report['umap_rows_outside_scope'][filename] = total_rows - len(table) joined = join_crop_paths(table, index_df) report['umap'][filename] = len(joined) print(f'UMAP {filename}: all {len(joined)} cells matched one-to-one') diff --git a/5a.object_image_crops/run_crop_pipeline.sh b/5a.object_image_crops/run_crop_pipeline.sh index c876891..9281aad 100755 --- a/5a.object_image_crops/run_crop_pipeline.sh +++ b/5a.object_image_crops/run_crop_pipeline.sh @@ -20,7 +20,15 @@ run_python() { } shopt -s nullglob -converted_files=(4.preprocess_features/data/converted_profiles/*/*_converted.parquet) +if [ -n "${PCCMA_PLATE:-}" ]; then + if [[ ! "$PCCMA_PLATE" =~ ^BR[0-9]{8}$ ]]; then + printf 'ERROR: Invalid PCCMA_PLATE scope.\n' >&2 + exit 1 + fi + converted_files=(4.preprocess_features/data/converted_profiles/*/"${PCCMA_PLATE}"_*_converted.parquet) +else + converted_files=(4.preprocess_features/data/converted_profiles/*/*_converted.parquet) +fi if [ "${#converted_files[@]}" -eq 0 ]; then printf 'ERROR: No converted profiles found; run conversion and single-cell QC first.\n' >&2 exit 1 diff --git a/utils/crop_warehouse.py b/utils/crop_warehouse.py index b2b142f..131be7e 100644 --- a/utils/crop_warehouse.py +++ b/utils/crop_warehouse.py @@ -13,6 +13,8 @@ """ import io +import os +import re import pathlib import pandas as pd @@ -398,3 +400,26 @@ def validate_sample_pixels(index: pd.DataFrame, warehouse: pathlib.Path, raise ValueError(f"Wrong crop pixels: {record[column]}") checked += 1 return checked + + +def requested_plate() -> str | None: + """Return an explicit plate restriction; the unset default preserves full-atlas operation.""" + value = os.environ.get("PCCMA_PLATE", "") + if value and re.fullmatch(r"BR[0-9]{8}", value) is None: + raise ValueError(f"Invalid PCCMA_PLATE scope: {value}") + return value or None + + +def guard_plate_scope(warehouse: pathlib.Path, plate: str | None) -> None: + """Refuse to publish a single-plate index over a mixed-plate output directory.""" + if plate is None: + return + others = [p for p in (warehouse / "manifests").glob("*_manifest.parquet") + if not p.name.startswith(f"{plate}_")] + index_path = warehouse / "crops_index.parquet" + if index_path.is_file(): + existing = pd.read_parquet(index_path, columns=["Metadata_Plate"]) + if not existing["Metadata_Plate"].eq(plate).all(): + others.append(index_path) + if others: + raise ValueError("Plate scope requires a separate output directory; other plate outputs exist") diff --git a/utils/tests/test_crop_pipeline.py b/utils/tests/test_crop_pipeline.py index e0cc981..1474657 100644 --- a/utils/tests/test_crop_pipeline.py +++ b/utils/tests/test_crop_pipeline.py @@ -278,3 +278,58 @@ def test_source_relocation_preserves_measurement(atlas): record["Image_PathName_OrigDNA"] = "/unmounted/BR00150698__other_measurement/Images" with pytest.raises(FileNotFoundError): resolve_image_path(record, "DNA", directory) + + +def add_other_plate_inputs(root): + """An unprocessed second plate must not expand an explicitly plate-scoped run.""" + converted = root / "4.preprocess_features/data/converted_profiles/A673/BR00150698_A673_converted.parquet" + cells = pd.read_parquet(converted) + cells["Image_Metadata_Plate"] = "BR00150699" + cells.to_parquet(converted.with_name("BR00150699_A673_converted.parquet"), index=False) + for directory, filename in ( + ("4.preprocess_features/data/single_cell_profiles", "BR00150698_sc_feature_selected.parquet"), + ("5.morphem_featurization/data/morphem_single_cell_profiles", "BR00150698_morphem_sc_feature_selected.parquet"), + ): + path = root / directory / filename + table = pd.read_parquet(path) + table["Metadata_Plate"] = "BR00150699" + table.to_parquet(path.with_name(filename.replace("BR00150698", "BR00150699")), index=False) + for path in (root / "6.profile_analysis/results/3.single_cell_embedding").glob("*.parquet"): + table = pd.read_parquet(path) + other = table.copy() + other["Metadata_Plate"] = "BR00150699" + pd.concat([table, other], ignore_index=True).to_parquet(path, index=False) + + +def test_one_plate_runner_does_not_process_or_require_other_plates(atlas, monkeypatch): + import json + add_other_plate_inputs(atlas) + monkeypatch.setenv("PCCMA_PLATE", "BR00150698") + shutil.copyfile(REPO / MODULE / "run_crop_pipeline.sh", atlas / MODULE / "run_crop_pipeline.sh") + (atlas / "utils").symlink_to(REPO / "utils", target_is_directory=True) + env = dict(os.environ, PCCMA_PYTHON=sys.executable) + result = subprocess.run(["bash", str(atlas / MODULE / "run_crop_pipeline.sh")], + cwd=atlas, env=env, capture_output=True, text=True, timeout=60) + assert result.returncode == 0, result.stdout + result.stderr + index = pd.read_parquet(warehouse(atlas) / "crops_index.parquet") + assert set(index["Metadata_Plate"]) == {"BR00150698"} + assert not (warehouse(atlas) / "crops/BR00150699").exists() + report = json.loads((warehouse(atlas) / "validation.json").read_text()) + assert report["plate_scope"] == "BR00150698" + assert report["umap_rows_outside_scope"]["single_cell_umap_coordinates_by_cancer_group.parquet"] == 2 + + +def test_plate_scope_rejects_mixed_output_directory(atlas, monkeypatch): + generate(atlas) + manifest_dir = warehouse(atlas) / "manifests" + mixed = manifest_dir / "BR00150699_A673_manifest.parquet" + mixed.write_bytes(b"unrelated existing output") + monkeypatch.setenv("PCCMA_PLATE", "BR00150698") + assert "separate output" in generate(atlas, ok=False).lower() + assert mixed.read_bytes() == b"unrelated existing output" + + +def test_plate_scope_rejects_mismatched_job(atlas, monkeypatch): + monkeypatch.setenv("PCCMA_PLATE", "BR00150699") + assert "scope" in generate(atlas, ok=False).lower() + assert not list(warehouse(atlas).rglob("*.jpg")) From d697f01a700a747e26dd936658ac59a53265ca7b Mon Sep 17 00:00:00 2001 From: d33bs Date: Sat, 14 Nov 2026 07:45:49 -0700 Subject: [PATCH 3/6] add dashboard based on crop pilot --- .gitignore | 5 + 7.dashboard/README.md | 164 ++++++++++++ 7.dashboard/build_report.py | 246 ++++++++++++++++++ 7.dashboard/pyproject.toml | 19 ++ 7.dashboard/tests/test_browser.py | 208 +++++++++++++++ 7.dashboard/tests/test_build_report.py | 235 +++++++++++++++++ 7.dashboard/tests/test_web.mjs | 271 +++++++++++++++++++ 7.dashboard/uv.lock | 329 +++++++++++++++++++++++ 7.dashboard/web/app.js | 346 +++++++++++++++++++++++++ 7.dashboard/web/style.css | 1 + 7.dashboard/web/template.html | 55 ++++ README.md | 1 + 12 files changed, 1880 insertions(+) create mode 100644 7.dashboard/README.md create mode 100644 7.dashboard/build_report.py create mode 100644 7.dashboard/pyproject.toml create mode 100644 7.dashboard/tests/test_browser.py create mode 100644 7.dashboard/tests/test_build_report.py create mode 100644 7.dashboard/tests/test_web.mjs create mode 100644 7.dashboard/uv.lock create mode 100644 7.dashboard/web/app.js create mode 100644 7.dashboard/web/style.css create mode 100644 7.dashboard/web/template.html diff --git a/.gitignore b/.gitignore index 783901d..91634c9 100644 --- a/.gitignore +++ b/.gitignore @@ -39,6 +39,11 @@ runinfo/ 5a.object_image_crops/data/ 5a.object_image_crops/logs/ +# Generated static dashboard bundles and local previews (includes selected warehouse JPGs) +7.dashboard/dist/ +7.dashboard/previews/ +7.dashboard/.pytest_cache/ + # Ignore the crop size evaluation tables (regenerated by 0.evaluate_crop_sizes.ipynb; the figures summarize them) 5.morphem_featurization/crop_evaluation/ diff --git a/7.dashboard/README.md b/7.dashboard/README.md new file mode 100644 index 0000000..38ae84c --- /dev/null +++ b/7.dashboard/README.md @@ -0,0 +1,164 @@ +# Single-cell crop dashboard + +A static, single-page report consuming the existing analysis tables and the +post-QC image-crop warehouse. It does not recompute UMAPs, regenerate crops, +modify profiles, or need a server-side application. The browser uses native +Canvas with no JavaScript packages, CDN downloads, or analytics. + +## Data and interpretation + +The current plate is `BR00150695` (24 hours), from crop run +`BR00150695-20261113T155150Z-g790ecb4`. + +- The crop index contains 80,493 post-QC cells. QC was inherited from the + published profiles, not recalculated. +- The existing single-cell analysis contributes 6,500 sampled cells from + 13 cell lines in seven cancer groups for this plate. The other 75,252 + analysis rows are outside this report's plate scope, not missing crops. +- Each cancer group has its **own** original UMAP, fitted using that group's + sampled cells across the original plates and time points. We retain its + coordinates and show only the selected plate. This is not a new UMAP + fitted to this plate. Coordinates/distances across different groups + are not comparable, and UMAP proximity is exploratory, not a statistical test. +- The original sampling draws up to 500 cells per cell line per plate; + this viewer does not show all 80,493 warehouse cells. +- Crops are the original 224 × 224, nucleus-centered JPEG display assets: + composite plus DNA, ER, RNA, AGP, and Mito. JPEGs and per-crop display + scaling are not quantitative intensity measurements or lossless model inputs. + +The UMAP table does not retain CellProfiler object numbers. The exporter +matches its exact, unrounded plate/well/site/nucleus-X/nucleus-Y key to the +crop index, requiring unique keys on both sides and complete coverage. It +then retains the cell and nucleus object numbers from that index. It never +uses nearest-neighbor matching, rounded positions, row order, or the notebook's +older embedded PNG examples. + +## Use the page + +Choose a cancer group, hover a point to inspect its cell, and click/tap to +pin it. The inspector gives the well, field, cell/nucleus identifiers and +channel crops. Change point colors or click a legend entry to show/hide its +points. Keyboard cell navigation provides an alternative to precise hovering. +Pan/zoom and Reset view help inspect crowded regions. + +## Build a complete bundle + +Run from the repository root with Python 3.11 or 3.12 and `uv`: + +```bash +uv sync --project 7.dashboard --locked + +RUN=BR00150695-20261113T155150Z-g790ecb4 +uv run --project 7.dashboard --locked python 7.dashboard/build_report.py \ + --crop-index "5a.object_image_crops/data/pilot_runs/$RUN/crops_index.parquet" \ + --warehouse "/path/to/extracted/warehouse" \ + --plate BR00150695 \ + --run-id "$RUN" \ + --output "7.dashboard/dist/$RUN" +``` + +`--warehouse` is the directory **containing `crops/`**, not `crops/` itself. +The existing tree on Willow is: + +```text +/home/davebunten/work/pccma-crops-runs/BR00150695-20261113T155150Z-g790ecb4/warehouse +``` + +The archival copy is under the corresponding run in +`PCCMA_data/Atlas_v2_object_crops/runs/` on bandicoot; extract its `warehouse/` +tree into a new location, not over existing results. See the warehouse module +for its publication and integrity records. Source images are not bundled in +this Git checkout. + +For another coordinate table, supply `--umap /path/to/coordinates.parquet`. +Every output directory must be new; the exporter refuses to replace an +existing bundle. It stages and validates the complete output before publishing +that local directory. Only the sampled cells' six existing JPEGs are copied, +byte-for-byte, preserving index-relative paths; they are decoded to check +geometry/mode and hashed after copying. Missing, corrupt, unsafe, ambiguous, +or metadata-mismatched inputs fail the build. A 950 MB total bundle budget +provides headroom for static hosting; an oversized bundle fails instead of +silently dropping cells or channels. + +```text +7.dashboard/ + build_report.py Exact join, asset validation/copy, HTML export + web/ Editable page template, CSS and JavaScript + tests/ Exporter, interaction helper, and browser tests + pyproject.toml Small independent build/test environment + uv.lock Locked dependencies + dist// Generated bundle (gitignored) + index.html One page with embedded data, JS and CSS + .nojekyll Serve generated assets unchanged + manifest.json Input/code hashes, scope, image hashes and counts + assets/crops/... Only the selected cells' original JPEGs +``` + +The manifest records file basenames and hashes, not private input-directory +paths. The page identifies the plate, run, scope and input hashes. All data +and image paths are relative to the page, so the whole bundle can move intact. + +## Coordinate-only diagnostic preview + +If the warehouse cannot be reached, an explicit diagnostic mode builds the +real joined coordinates without any image URLs. It displays a visible warning; +it is **not a complete crop dashboard** and does not substitute synthetic cells, +contact-sheet fragments or notebook example images. + +```bash +RUN=BR00150695-20261113T155150Z-g790ecb4 +uv run --project 7.dashboard --locked python 7.dashboard/build_report.py \ + --crop-index "5a.object_image_crops/data/pilot_runs/$RUN/crops_index.parquet" \ + --run-id "$RUN" \ + --allow-missing-images \ + --output "7.dashboard/previews/$RUN-coordinates" +``` + +This option does not excuse missing/corrupt files in a supplied warehouse tree. +A complete build must be rerun into a new output directory after image access +is restored. + +## GitHub Pages and local viewing + +Open the generated `index.html` directly, or serve **only the generated bundle**: + +```bash +python3 -m http.server 8765 --bind 127.0.0.1 \ + --directory "7.dashboard/dist/$RUN" +``` + +For GitHub Pages, use the generated bundle directory as the Pages artifact +root (for example, the `path` passed to `actions/upload-pages-artifact` in +an authorized deployment workflow). Publish **all** its files, including +`assets/`, not only `index.html` or the source `web/template.html`. +Root hosting and project-prefix hosting need no path rewrite. No deployment +workflow or Pages settings are changed automatically by this module. +Do not upload the full warehouse or commit the ignored generated bundle just +to preview the source changes. Publishing the report also publishes its +selected cell images; obtain the normal dataset/publication approval first. + +## Tests + +```bash +uv run --project 7.dashboard --locked python -m pytest 7.dashboard/tests -q +node --test 7.dashboard/tests/test_web.mjs +``` + +Browser tests use Playwright; install its Chromium once: + +```bash +uv run --project 7.dashboard --locked playwright install chromium +``` + +Synthetic images in tests are labeled fixtures and verify export and UI +mechanics only. Verification on the actual plate's coordinates is separate +from real warehouse-image decoding and hover display. A coordinate-only +preview passing is not evidence that the real crops have been bundled. + +## Sources + +- [Single-cell embedding analysis](../6.profile_analysis/3.single_cell_embedding.ipynb) +- [Object crop warehouse and provenance](../5a.object_image_crops/README.md) +- [Cell Painting assay](https://doi.org/10.1038/nprot.2016.105) +- [UMAP method](https://doi.org/10.21105/joss.00861) +- [GitHub Pages publishing limits](https://docs.github.com/en/pages/getting-started-with-github-pages/github-pages-limits) diff --git a/7.dashboard/build_report.py b/7.dashboard/build_report.py new file mode 100644 index 0000000..af9790f --- /dev/null +++ b/7.dashboard/build_report.py @@ -0,0 +1,246 @@ +#!/usr/bin/env python3 +"""Export existing single-cell UMAPs and their exact crop-index matches to a static page.""" + +from pathlib import Path, PurePosixPath +from urllib.parse import quote, unquote +import argparse +import hashlib +import io +import json +import math +import re +import shutil + +import pandas as pd +from PIL import Image + +# Leave headroom below a 1 GB published-site budget; never silently ship an oversized bundle. +MAX_SITE_BYTES = 950_000_000 + +POSITION_KEY = [ + "Metadata_Plate", "Metadata_Well", "Metadata_Site", + "Metadata_Nuclei_Location_Center_X", "Metadata_Nuclei_Location_Center_Y", +] +OBJECT_KEY = POSITION_KEY[:3] + [ + "Metadata_ImageNumber", "Metadata_Nuclei_Number_Object_Number", + "Metadata_Cells_Number_Object_Number", +] +CHANNELS = ["composite", "DNA", "ER", "RNA", "AGP", "Mito"] +PATH_COLUMNS = {ch: ch if ch == "composite" else f"grayscale_{ch}" for ch in CHANNELS} + + +def require_table(frame, columns, label, *, unique=None): + """Reject absent/null fields and ambiguous keys before attempting a join.""" + missing = set(columns) - set(frame.columns) + if missing: + raise ValueError(f"{label}: missing columns: {sorted(missing)}") + if frame[columns].isna().any().any(): + raise ValueError(f"{label}: null required values") + if unique and frame.duplicated(unique).any(): + raise ValueError(f"{label}: duplicate keys") + + +def relative_crop_path(value): + """Accept only unchanged relative JPEG paths beneath the warehouse's crop tree.""" + if not isinstance(value, str): + raise ValueError("Crop path must be a string") + path = PurePosixPath(value) + if (path.is_absolute() or not path.parts or path.parts[0] != "crops" + or any(part in ("..", ".") for part in value.split("/")) + or "\\" in value or ":" in value or path.as_posix() != value + or path.suffix.lower() != ".jpg"): + raise ValueError(f"Invalid relative crop path: {value}") + return path + + +def prepare_data(umap, index, *, plate, run_id): + """Join exact nucleus positions, then retain the index's complete object identity. + + The analysis table does not retain object numbers. Plate/well/site plus the + unrounded nucleus X/Y is its available key; require uniqueness on both sides. + """ + require_table(umap, ["Metadata_Plate"], "UMAP") + require_table(index, ["Metadata_Plate"], "Crop index") + selected = umap.loc[umap.Metadata_Plate.eq(plate)].copy() + crops = index.loc[index.Metadata_Plate.eq(plate)].copy() + if selected.empty or crops.empty: + raise ValueError(f"No UMAP cells or crop-index cells for plate {plate}") + metadata = ["Metadata_cell_line", "Metadata_time_point"] + umap_required = POSITION_KEY + metadata + ["cancer_group", "tissue_site", "umap_1", "umap_2", "cluster"] + crop_required = list(dict.fromkeys(POSITION_KEY + OBJECT_KEY + metadata + + list(PATH_COLUMNS.values()) + ["Metadata_Nucleocentric_Crop_Size"])) + require_table(selected, umap_required, "UMAP", unique=POSITION_KEY) + require_table(crops, crop_required, "Crop index", unique=OBJECT_KEY) + require_table(crops, POSITION_KEY, "Crop positions", unique=POSITION_KEY) + for frame, columns in [(selected, POSITION_KEY[3:] + ["umap_1", "umap_2"]), + (crops, POSITION_KEY[3:])]: + if not all(math.isfinite(float(value)) for col in columns for value in frame[col]): + raise ValueError("Non-finite coordinates") + for frame, columns in [(selected, ["Metadata_Site", "Metadata_time_point", "cluster"]), + (crops, OBJECT_KEY[2:] + ["Metadata_time_point", "Metadata_Nucleocentric_Crop_Size"])]: + for col in columns: + if not all(float(v).is_integer() and float(v) > 0 for v in frame[col]): + raise ValueError(f"Expected positive integral values: {col}") + if crops.Metadata_Nucleocentric_Crop_Size.nunique() != 1: + raise ValueError("Mixed crop dimensions in selected plate") + for col in PATH_COLUMNS.values(): + for value in crops[col]: + relative_crop_path(value) + if crops[col].duplicated().any(): + raise ValueError(f"Reused crop paths: {col}") + joined = selected.merge(crops[crop_required], on=POSITION_KEY, how="left", + validate="one_to_one", suffixes=("", "_index"), indicator=True) + if not joined["_merge"].eq("both").all(): + raise ValueError("UMAP cells without an exact crop-index match") + for col in metadata: + if not joined[col].eq(joined[col + "_index"]).all(): + raise ValueError(f"UMAP and crop metadata disagree: {col}") + points = [] + for row in joined.to_dict("records"): + identifier = (f"{plate}_{row['Metadata_Well']}_f{int(row['Metadata_Site']):02d}" + f"_nuc{int(row['Metadata_Nuclei_Number_Object_Number']):04d}" + f"_cell{int(row['Metadata_Cells_Number_Object_Number']):04d}") + points.append({ + "id": identifier, "line": row["Metadata_cell_line"], "group": row["cancer_group"], + "tissue": row["tissue_site"], "well": row["Metadata_Well"], + "site": int(row["Metadata_Site"]), "cell": int(row["Metadata_Cells_Number_Object_Number"]), + "nucleus": int(row["Metadata_Nuclei_Number_Object_Number"]), + "time": int(row["Metadata_time_point"]), "cluster": int(row["cluster"]), + "x": row["umap_1"], "y": row["umap_2"], + "cx": row[POSITION_KEY[3]], "cy": row[POSITION_KEY[4]], + "images": {ch: "assets/" + quote(row[col], safe="/") for ch, col in PATH_COLUMNS.items()}, + }) + return { + "schema_version": 1, "plate": plate, "run_id": run_id, + "summary": {"warehouse_cells": len(crops), "umap_cells": len(points), + "excluded_umap_rows": len(umap) - len(selected), + "cell_lines": selected.Metadata_cell_line.nunique(), + "cancer_groups": selected.cancer_group.nunique(), + "crop_size": int(crops.Metadata_Nucleocentric_Crop_Size.iloc[0])}, + "sources": {"qc": "Inherited published post-QC membership; QC not recalculated."}, + "images": {"status": "bundled", "message": "Original warehouse JPEGs.", "channels": CHANNELS}, + "points": points, + } + + +def sha256(path): + """Hash a source file without retaining its local/private absolute path.""" + with Path(path).open("rb") as stream: + return hashlib.file_digest(stream, "sha256").hexdigest() + + +def build_report(*, umap_path, index_path, warehouse, output, plate, run_id, + allow_missing_images=False, web_dir=None): + """Build a new immutable static output with byte-identical, validated warehouse JPGs. + + A diagnostic coordinate-only build requires explicit opt-in and has no image + URLs. A partial or corrupt image set never silently becomes a complete report. + """ + output = Path(output) + staging = output.with_name(f".{output.name}.partial") + if output.exists() or output.is_symlink() or staging.exists(): + raise ValueError(f"Refusing to replace existing output/staging: {output}") + umap_path, index_path = Path(umap_path), Path(index_path) + payload = prepare_data(pd.read_parquet(umap_path), pd.read_parquet(index_path), + plate=plate, run_id=run_id) + for label, path in [("umap", umap_path), ("crop_index", index_path)]: + payload["sources"][label] = {"name": path.name, "sha256": sha256(path)} + warehouse = Path(warehouse) if warehouse is not None else None + available = warehouse is not None and warehouse.is_dir() + if not available and not allow_missing_images: + raise ValueError("Warehouse is unavailable; supply --warehouse with the extracted JPEG tree") + if not available: + payload["images"].update(status="unavailable", message= + "Coordinate-only preview: warehouse JPEGs are not bundled. Cell crop previews are unavailable.") + for point in payload["points"]: + point["images"] = {} + assets = [] + output.parent.mkdir(parents=True, exist_ok=True) + staging.mkdir() + try: + seen = set() + for point in payload["points"]: + for channel, url in point["images"].items(): + relative = relative_crop_path(unquote(url.removeprefix("assets/"))) + if str(relative) in seen: + raise ValueError(f"Reused image path: {relative}") + seen.add(str(relative)) + source = warehouse / relative + if (source.is_symlink() or not source.resolve().is_relative_to(warehouse.resolve()) + or not source.is_file()): + raise ValueError(f"Missing or unsafe warehouse image: {relative}") + data = source.read_bytes() + with Image.open(io.BytesIO(data)) as image: + image.load() + expected_mode = "RGB" if channel == "composite" else "L" + size = payload["summary"]["crop_size"] + if image.format != "JPEG" or image.mode != expected_mode or image.size != (size, size): + raise ValueError(f"Wrong JPEG geometry/mode: {relative}") + target = staging / "assets" / relative + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + digest = hashlib.sha256(data).hexdigest() + if sha256(target) != digest: + raise ValueError(f"Copied image checksum mismatch: {relative}") + assets.append({"path": f"assets/{relative}", "sha256": digest, "bytes": len(data)}) + payload["images"]["files"] = len(assets) + payload["images"]["bytes"] = sum(asset["bytes"] for asset in assets) + web_dir = Path(web_dir) if web_dir else Path(__file__).parent / "web" + template = (web_dir / "template.html").read_text() + # Escape data for an HTML script raw-text element, not merely for JSON. + embedded = json.dumps(payload, ensure_ascii=True, allow_nan=False, separators=(",", ":")) + embedded = embedded.replace("<", "\\u003c").replace(">", "\\u003e").replace("&", "\\u0026") + replacements = {"__REPORT_CSS__": (web_dir / "style.css").read_text(), + "__REPORT_JS__": (web_dir / "app.js").read_text(), + "__REPORT_DATA__": embedded} + if any(template.count(token) != 1 for token in replacements): + raise ValueError("Report template must contain each placeholder exactly once") + html = re.sub("|".join(replacements), lambda match: replacements[match.group()], template) + (staging / "index.html").write_text(html) + (staging / ".nojekyll").touch() + manifest = {"schema_version": 1, "plate": plate, "run_id": run_id, + "sources": payload["sources"], "summary": payload["summary"], + "images": payload["images"], "assets": assets, + "index_sha256": sha256(staging / "index.html"), + "code_sha256": {p.name: sha256(p) for p in [Path(__file__), + web_dir / "template.html", web_dir / "style.css", web_dir / "app.js"]}} + (staging / "manifest.json").write_text(json.dumps(manifest, indent=2) + "\n") + total_bytes = payload["images"]["bytes"] + (staging / "index.html").stat().st_size + (staging / "manifest.json").stat().st_size + if total_bytes > MAX_SITE_BYTES: + raise ValueError(f"Static site exceeds size budget: {total_bytes} > {MAX_SITE_BYTES} bytes") + if output.exists(): + raise ValueError(f"Output appeared during build: {output}") + staging.rename(output) + except BaseException: + shutil.rmtree(staging) + raise + return payload + + +def main(argv=None): + """Build a static report, exiting nonzero rather than emitting an incomplete bundle.""" + root = Path(__file__).resolve().parents[1] + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--umap", type=Path, default=root / "6.profile_analysis/results/3.single_cell_embedding/single_cell_umap_coordinates_by_cancer_group.parquet") + parser.add_argument("--crop-index", type=Path, required=True) + parser.add_argument("--warehouse", type=Path, help="Extracted warehouse root containing crops/ (read only)") + parser.add_argument("--plate", default="BR00150695") + parser.add_argument("--run-id", required=True, help="Crop warehouse run identifier for provenance") + parser.add_argument("--output", type=Path, required=True, help="New output directory; never overwritten") + parser.add_argument("--allow-missing-images", action="store_true", help="Explicit coordinate-only diagnostic preview, NOT a complete crop dashboard") + parser.add_argument("--web-dir", type=Path, help=argparse.SUPPRESS) + args = parser.parse_args(argv) + try: + payload = build_report(umap_path=args.umap, index_path=args.crop_index, + warehouse=args.warehouse, output=args.output, plate=args.plate, + run_id=args.run_id, allow_missing_images=args.allow_missing_images, + web_dir=args.web_dir) + except (ValueError, OSError, KeyError, TypeError) as error: + parser.exit(1, f"Report build failed: {error}\n") + print(json.dumps({"output": str(args.output.resolve()), "summary": payload["summary"], + "images": payload["images"]}, indent=2)) + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/7.dashboard/pyproject.toml b/7.dashboard/pyproject.toml new file mode 100644 index 0000000..7c32809 --- /dev/null +++ b/7.dashboard/pyproject.toml @@ -0,0 +1,19 @@ +[project] +name = "pccma-dashboard" +version = "0.1.0" +description = "Static single-cell UMAP and crop report; independent of the compute environments" +requires-python = ">=3.11,<3.13" +dependencies = [ + "pandas==2.2.3", + "pyarrow==22.0.0", + "pillow==12.3.0", +] + +[dependency-groups] +dev = ["pytest==7.4.4", "playwright==1.56.0"] + +[tool.uv] +package = false + +[tool.pytest.ini_options] +testpaths = ["tests"] diff --git a/7.dashboard/tests/test_browser.py b/7.dashboard/tests/test_browser.py new file mode 100644 index 0000000..d850f58 --- /dev/null +++ b/7.dashboard/tests/test_browser.py @@ -0,0 +1,208 @@ +"""Real Chromium interaction checks; generated images are test fixtures, not cell crops.""" + +from functools import partial +from http.server import SimpleHTTPRequestHandler, ThreadingHTTPServer +from pathlib import Path +from threading import Thread + +import pandas as pd +import pytest +from PIL import Image +from playwright.sync_api import expect, sync_playwright + +from test_build_report import builder, tables # noqa: F401 (shared pytest fixture) + + +@pytest.fixture(scope="module") +def browser(): + with sync_playwright() as playwright: + instance = playwright.chromium.launch(headless=True) + yield instance + instance.close() + + +@pytest.fixture +def origin(tmp_path): + class QuietHandler(SimpleHTTPRequestHandler): + def log_message(self, *_args): + pass + + server = ThreadingHTTPServer(("127.0.0.1", 0), partial(QuietHandler, directory=str(tmp_path))) + thread = Thread(target=server.serve_forever, daemon=True) + thread.start() + yield f"http://127.0.0.1:{server.server_port}" + server.shutdown() + server.server_close() + thread.join(timeout=5) + + +@pytest.fixture +def site(tables, tmp_path): + """Three distinctly located synthetic fixture cells in two independent groups.""" + umap, index = tables + first = umap.iloc[[0]].copy() + second = first.copy() + second["Metadata_Nuclei_Location_Center_X"] += 10 + second["umap_1"], second["umap_2"] = 3., 4. + second["Metadata_cell_line"] = "Fixture B" + third = first.copy() + third["Metadata_Nuclei_Location_Center_X"] += 20 + third["umap_1"], third["umap_2"] = 900., -700. + third["cancer_group"] = "Other fixture group" + umap = pd.concat([first, second, third], ignore_index=True) + indices = [] + warehouse = tmp_path / "warehouse" + for i, row in umap.iterrows(): + record = index.iloc[[0]].copy() + record["Metadata_Nuclei_Location_Center_X"] = row.Metadata_Nuclei_Location_Center_X + record["Metadata_cell_line"] = row.Metadata_cell_line + record["Metadata_Nuclei_Number_Object_Number"] = i + 3 + record["Metadata_Cells_Number_Object_Number"] = i + 2 + for channel, col in builder().PATH_COLUMNS.items(): + relative = f"crops/P1/fixture_{i}_{channel}.jpg" + record[col] = relative + target = warehouse / relative + target.parent.mkdir(parents=True, exist_ok=True) + Image.new("RGB" if channel == "composite" else "L", (224, 224), (i + 1) * 50).save(target, "JPEG") + indices.append(record) + umap_path, index_path = tmp_path / "umap.parquet", tmp_path / "index.parquet" + umap.to_parquet(umap_path) + pd.concat(indices).to_parquet(index_path) + output = tmp_path / "pccma" / "report" + payload = builder().build_report(umap_path=umap_path, index_path=index_path, warehouse=warehouse, + output=output, plate="P1", run_id="synthetic-test-fixture") + return output, payload + + +def pointer_target(page, index=0): + return page.evaluate("""index => { + const point = dashboard.visiblePoints[index]; + const screen = dashboard.projection.forward(point); + const rect = document.getElementById('plot').getBoundingClientRect(); + return {id:point.id, x:screen.x+rect.left, y:screen.y+rect.top}; + }""", index) + + +def test_hover_pin_channels_and_prefix_paths(browser, origin, site): + page = browser.new_page(viewport={"width": 1440, "height": 1100}) + errors, requests, failed = [], [], [] + page.on("pageerror", lambda error: errors.append(str(error))) + page.on("request", lambda request: requests.append(request.url)) + page.on("response", lambda response: failed.append(response.url) if response.status >= 400 else None) + page.goto(origin + "/pccma/report/", wait_until="load") + expect(page.locator("#error-banner")).to_be_hidden() + expect(page.locator("#image-warning")).to_be_hidden() + assert page.evaluate("dashboard.visiblePoints.length") == 2 + target = pointer_target(page) + page.mouse.move(target["x"], target["y"]) + expect(page.locator("#cell-id")).to_have_text(target["id"]) + expect(page.locator("#crop-area img")).to_have_count(6) + assert page.locator("#crop-area img").evaluate_all("images=>images.every(img=>img.complete&&img.naturalWidth===224)") + assert all("/pccma/report/assets/crops/" in url for url in requests if url.endswith(".jpg")) + page.mouse.click(target["x"], target["y"]) + expect(page.locator("#pin-status")).to_have_text("Pinned") + another = pointer_target(page, 1) + page.mouse.move(another["x"], another["y"]) + expect(page.locator("#cell-id")).to_have_text(target["id"]) + page.locator("#channel-select").select_option("DNA") + expect(page.locator("#crop-area img")).to_have_count(2) + page.locator("#unpin-cell").click() + page.locator("#next-cell").click() + expect(page.locator("#pin-status")).to_have_text("Pinned") + page.locator("#group-select").select_option("Other fixture group") + assert page.evaluate("dashboard.visiblePoints.length") == 1 + assert page.evaluate("dashboard.selectedPoint") is None + expect(page.locator("#inspector-title")).to_have_text("Point preview") + assert not errors + assert not failed + assert all(url.startswith(origin) for url in requests) + page.close() + + +def test_mobile_touch_filters_zoom_and_file_open(browser, origin, site): + context = browser.new_context(viewport={"width": 390, "height": 844}, is_mobile=True, has_touch=True) + page = context.new_page() + errors = [] + page.on("pageerror", lambda error: errors.append(str(error))) + page.goto(origin + "/pccma/report/", wait_until="load") + assert page.evaluate("document.documentElement.scrollWidth <= innerWidth") + point = pointer_target(page) + page.touchscreen.tap(point["x"], point["y"]) + expect(page.locator("#pin-status")).to_have_text("Pinned") + page.locator("#zoom-in").click() + expect(page.locator("#zoom-label")).to_have_text("130%") + page.locator("#reset-view").click() + expect(page.locator("#zoom-label")).to_have_text("100%") + # Hide all categories via actual UI; ensure the pinned cell cannot survive it. + for button in page.locator("#legend button").all(): + button.click() + expect(page.locator("#empty-state")).to_be_visible() + assert page.evaluate("dashboard.selectedPoint") is None + assert not errors + context.close() + file_page = browser.new_page() + file_page.goto((site[0] / "index.html").as_uri(), wait_until="load") + file_page.locator("#next-cell").click() + expect(file_page.locator("#crop-area img")).to_have_count(6) + assert file_page.locator("#crop-area img").evaluate_all("images=>images.every(img=>img.naturalWidth===224)") + file_page.close() + + +def test_image_404_is_visible_and_never_shows_stale_pixels(browser, origin, site): + page = browser.new_page() + page.route("**/*_DNA.jpg", lambda route: route.fulfill(status=404, body="missing test fixture")) + page.goto(origin + "/pccma/report/", wait_until="load") + page.locator("#next-cell").click() + expect(page.locator(".image-error")).to_have_count(1) + expect(page.locator(".image-error")).to_contain_text("Image could not be loaded") + assert page.locator("#crop-area img").count() == 5 + page.close() + + +def test_real_plate_coordinates_all_groups_without_fake_image_requests(browser, tmp_path, origin): + root = Path(__file__).resolve().parents[2] + index = root / "5a.object_image_crops/data/pilot_runs/BR00150695-20261113T155150Z-g790ecb4/crops_index.parquet" + if not index.exists(): + pytest.skip("Real pilot index is local, not part of a clean checkout") + output = tmp_path / "pccma" / "real" + payload = builder().build_report( + umap_path=root / "6.profile_analysis/results/3.single_cell_embedding/single_cell_umap_coordinates_by_cancer_group.parquet", + index_path=index, warehouse=None, output=output, plate="BR00150695", + run_id="BR00150695-20261113T155150Z-g790ecb4", allow_missing_images=True) + page = browser.new_page(viewport={"width": 1440, "height": 1100}) + requests, errors = [], [] + page.on("request", lambda request: requests.append(request)) + page.on("pageerror", lambda error: errors.append(str(error))) + page.goto(origin + "/pccma/real/", wait_until="load") + expect(page.locator("#image-warning")).to_be_visible() + assert payload["summary"]["umap_cells"] == 6500 + groups = page.locator("#group-select option").evaluate_all("options=>options.map(option=>option.value)") + assert len(groups) == 7 + observed = 0 + for group in groups: + page.locator("#group-select").select_option(group) + observed += page.evaluate("dashboard.visiblePoints.length") + point = pointer_target(page) + page.mouse.move(point["x"], point["y"]) + # Dense real points may choose a closer neighbor at the same screen pixel. + expect(page.locator("#cell-id")).not_to_have_text("No cell selected") + assert page.evaluate("dashboard.hoveredPoint.group") == group + # Confirm rendered colored point pixels, not just a working hit-test index. + assert page.evaluate("""() => { + const canvas=document.getElementById('plot'); + const pixels=canvas.getContext('2d').getImageData(0,0,canvas.width,canvas.height).data; + let count=0; + for(let i=0;i80 && low>50 && high-low>45) count++; + } + return count>100; + }""") + expect(page.locator("#crop-area")).to_contain_text("Crops unavailable") + assert observed == 6500 + assert not [request.url for request in requests if request.resource_type == "image"] + page.set_viewport_size({"width": 390, "height": 844}) + assert page.evaluate("document.documentElement.scrollWidth <= innerWidth") + assert not errors + page.close() diff --git a/7.dashboard/tests/test_build_report.py b/7.dashboard/tests/test_build_report.py new file mode 100644 index 0000000..8cdfe21 --- /dev/null +++ b/7.dashboard/tests/test_build_report.py @@ -0,0 +1,235 @@ +"""Tests for the static report's exact cell-to-crop join.""" + +import importlib.util +import hashlib +import json +import re +from pathlib import Path + +from PIL import Image +import pandas as pd +import pytest + +MODULE = Path(__file__).parents[1] / "build_report.py" + + +def builder(): + assert MODULE.is_file(), "The static dashboard exporter has not been implemented" + spec = importlib.util.spec_from_file_location("build_report", MODULE) + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + return module + + +@pytest.fixture +def tables(): + umap = pd.DataFrame([ + {"Metadata_Plate": "P1", "Metadata_Well": "C03", "Metadata_Site": 1, + "Metadata_Nuclei_Location_Center_X": 12.1234567890123, + "Metadata_Nuclei_Location_Center_Y": 24.5, "Metadata_cell_line": "DAOY", + "Metadata_time_point": 24, "cancer_group": "Medulloblastoma", + "tissue_site": "Central nervous system", "umap_1": 1.25, "umap_2": -2.5, + "cluster": 2}, + {"Metadata_Plate": "P2", "Metadata_Well": "C03", "Metadata_Site": 1, + "Metadata_Nuclei_Location_Center_X": 90., + "Metadata_Nuclei_Location_Center_Y": 90., "Metadata_cell_line": "OTHER", + "Metadata_time_point": 48, "cancer_group": "Other", "tissue_site": "Other", + "umap_1": 999., "umap_2": 999., "cluster": 1}, + ]) + index = umap.iloc[[0]].drop(columns=["umap_1", "umap_2", "cluster", "cancer_group", "tissue_site"]).copy() + index["Metadata_ImageNumber"] = 7 + index["Metadata_Nuclei_Number_Object_Number"] = 3 + index["Metadata_Cells_Number_Object_Number"] = 2 + index["Metadata_Nucleocentric_Crop_Size"] = 224 + for channel in ["DNA", "ER", "RNA", "AGP", "Mito", "composite"]: + column = channel if channel == "composite" else f"grayscale_{channel}" + index[column] = f"crops/P1/DAOY/C03/f01/P1_C03_f01_nuc0003_cell0002_{channel}.jpg" + return umap, index + + +def test_exact_join_scopes_plate_and_preserves_coordinates(tables): + umap, index = tables + report = builder().prepare_data(umap, index, plate="P1", run_id="pilot") + assert report["summary"]["umap_cells"] == 1 + assert report["summary"]["excluded_umap_rows"] == 1 + point = report["points"][0] + assert point["cx"] == 12.1234567890123 + assert point["id"] == "P1_C03_f01_nuc0003_cell0002" + assert (point["x"], point["y"], point["line"], point["cluster"]) == (1.25, -2.5, "DAOY", 2) + assert point["images"]["DNA"] == "assets/" + index.iloc[0].grayscale_DNA + + +@pytest.mark.parametrize("problem", [ + "missing_column", "null_key", "duplicate_index", "duplicate_umap", "missing_match", + "rounded_coordinate", "nonfinite", "line_mismatch", "time_mismatch", "empty_plate", + "absolute_path", "traversal", "url_path", "backslash", "duplicate_object", +]) +def test_invalid_join_inputs_fail_closed(tables, problem): + umap, index = tables + if problem == "missing_column": + umap = umap.drop(columns="cancer_group") + elif problem == "null_key": + index.loc[0, "Metadata_Well"] = None + elif problem == "duplicate_index": + index = pd.concat([index, index], ignore_index=True) + elif problem == "duplicate_umap": + umap = pd.concat([umap, umap.iloc[[0]]], ignore_index=True) + elif problem == "missing_match": + index.loc[0, "Metadata_Well"] = "C04" + elif problem == "rounded_coordinate": + index.loc[0, "Metadata_Nuclei_Location_Center_X"] = 12.123456789 + elif problem == "nonfinite": + umap.loc[0, "umap_1"] = float("inf") + elif problem == "line_mismatch": + index.loc[0, "Metadata_cell_line"] = "WRONG" + elif problem == "time_mismatch": + index.loc[0, "Metadata_time_point"] = 48 + elif problem == "empty_plate": + umap = umap.iloc[[1]] + elif problem == "duplicate_object": + second = index.copy() + second["Metadata_Nuclei_Location_Center_X"] = 91. + index = pd.concat([index, second], ignore_index=True) + else: + index.loc[0, "composite"] = { + "absolute_path": "/etc/passwd", "traversal": "crops/../../private.jpg", + "url_path": "https://other.example/crop.jpg", "backslash": "crops\\\\private.jpg", + }[problem] + with pytest.raises(ValueError): + builder().prepare_data(umap, index, plate="P1", run_id="pilot") + + +@pytest.fixture +def build_inputs(tables, tmp_path): + umap, index = tables + umap_path, index_path = tmp_path / "umap.parquet", tmp_path / "index.parquet" + umap.to_parquet(umap_path) + index.to_parquet(index_path) + warehouse = tmp_path / "warehouse" + for col in ["composite"] + [f"grayscale_{ch}" for ch in ["DNA", "ER", "RNA", "AGP", "Mito"]]: + path = warehouse / index.iloc[0][col] + path.parent.mkdir(parents=True, exist_ok=True) + Image.new("RGB" if col == "composite" else "L", (224, 224), 80).save(path, "JPEG") + web_dir = tmp_path / "web" + web_dir.mkdir() + (web_dir / "template.html").write_text( + '' + '' + '') + (web_dir / "style.css").write_text("body {color: white}") + (web_dir / "app.js").write_text("console.log('fixture only');") + return {"umap_path": umap_path, "index_path": index_path, "warehouse": warehouse, + "output": tmp_path / "site", "plate": "P1", "run_id": "pilot", "web_dir": web_dir} + + +def test_export_bundles_original_bytes_and_records_provenance(build_inputs): + payload = builder().build_report(**build_inputs) + site = build_inputs["output"] + assert (site / ".nojekyll").is_file() + assert payload["images"]["status"] == "bundled" + assert payload["images"]["files"] == 6 + html = (site / "index.html").read_text() + embedded = json.loads(re.search(r'id="report-data">(.*?)', html, re.S)[1]) + assert embedded == payload + assert str(build_inputs["warehouse"]) not in html + manifest = json.loads((site / "manifest.json").read_text()) + assert len(manifest["assets"]) == 6 + for entry in manifest["assets"]: + copied = (site / entry["path"]).read_bytes() + original = (build_inputs["warehouse"] / entry["path"].removeprefix("assets/")).read_bytes() + assert copied == original + assert hashlib.sha256(copied).hexdigest() == entry["sha256"] + assert payload["sources"]["umap"]["sha256"] == hashlib.sha256(build_inputs["umap_path"].read_bytes()).hexdigest() + + +@pytest.mark.parametrize("problem", ["missing", "corrupt", "wrong_size", "wrong_mode", "symlink"]) +def test_incomplete_or_invalid_warehouse_leaves_no_published_output(build_inputs, problem): + index = pd.read_parquet(build_inputs["index_path"]) + path = build_inputs["warehouse"] / index.iloc[0].composite + if problem == "missing": + path.unlink() + elif problem == "corrupt": + path.write_bytes(b"not a jpeg") + elif problem == "wrong_size": + Image.new("RGB", (160, 160)).save(path, "JPEG") + elif problem == "wrong_mode": + Image.new("L", (224, 224)).save(path, "JPEG") + elif problem == "symlink": + outside = build_inputs["output"].parent / "outside.jpg" + outside.write_bytes(path.read_bytes()) + path.unlink() + path.symlink_to(outside) + with pytest.raises((ValueError, OSError)): + builder().build_report(**build_inputs) + assert not build_inputs["output"].exists() + assert not build_inputs["output"].with_name(".site.partial").exists() + + +def test_unavailable_warehouse_requires_explicit_diagnostic_opt_in(build_inputs): + build_inputs["warehouse"] = None + with pytest.raises(ValueError, match="Warehouse is unavailable"): + builder().build_report(**build_inputs) + payload = builder().build_report(**build_inputs, allow_missing_images=True) + assert payload["images"]["status"] == "unavailable" + assert payload["images"]["files"] == 0 + assert all(point["images"] == {} for point in payload["points"]) + assert not (build_inputs["output"] / "assets").exists() + + +def test_diagnostic_opt_in_does_not_hide_partial_warehouse(build_inputs): + index = pd.read_parquet(build_inputs["index_path"]) + (build_inputs["warehouse"] / index.iloc[0].composite).unlink() + with pytest.raises(ValueError, match="Missing or unsafe"): + builder().build_report(**build_inputs, allow_missing_images=True) + + +def test_existing_output_is_never_overwritten(build_inputs): + build_inputs["output"].mkdir() + sentinel = build_inputs["output"] / "keep.txt" + sentinel.write_text("keep me") + with pytest.raises(ValueError, match="Refusing to replace"): + builder().build_report(**build_inputs) + assert sentinel.read_text() == "keep me" + + +def test_script_text_in_metadata_cannot_escape_json_element(build_inputs): + text = ' __REPORT_JS__ & < >' + for name in ["umap_path", "index_path"]: + frame = pd.read_parquet(build_inputs[name]) + frame.loc[0, "Metadata_cell_line"] = text + frame.to_parquet(build_inputs[name]) + payload = builder().build_report(**build_inputs) + html = (build_inputs["output"] / "index.html").read_text() + assert text not in html + assert 'window.injected=true' not in html + embedded = json.loads(re.search(r'id="report-data">(.*?)', html, re.S)[1]) + assert embedded["points"][0]["line"] == text + assert embedded == payload + + +def test_cli_builds_from_absolute_inputs_and_reports_missing_assets(build_inputs): + import subprocess + import sys + + command = [sys.executable, str(MODULE), "--umap", str(build_inputs["umap_path"]), + "--crop-index", str(build_inputs["index_path"]), "--plate", "P1", + "--run-id", "pilot", "--output", str(build_inputs["output"]), + "--allow-missing-images", "--web-dir", str(build_inputs["web_dir"])] + result = subprocess.run(command, cwd=build_inputs["output"].parent, capture_output=True, text=True, timeout=30) + assert result.returncode == 0, result.stderr + assert (build_inputs["output"] / "index.html").exists() + assert json.loads(result.stdout)["images"]["status"] == "unavailable" + failed = subprocess.run(command, capture_output=True, text=True, timeout=30) + assert failed.returncode != 0 + assert "Refusing to replace" in failed.stderr + assert "Traceback" not in failed.stderr + + +def test_oversized_static_site_fails_before_publication(build_inputs, monkeypatch): + module = builder() + monkeypatch.setattr(module, "MAX_SITE_BYTES", 100, raising=False) + with pytest.raises(ValueError, match="size budget"): + module.build_report(**build_inputs) + assert not build_inputs["output"].exists() + + diff --git a/7.dashboard/tests/test_web.mjs b/7.dashboard/tests/test_web.mjs new file mode 100644 index 0000000..eaf891e --- /dev/null +++ b/7.dashboard/tests/test_web.mjs @@ -0,0 +1,271 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { createRequire } from 'node:module'; +import { existsSync, readFileSync } from 'node:fs'; +const require = createRequire(import.meta.url); +const appPath = new URL('../web/app.js', import.meta.url); +const app = existsSync(appPath) ? require(appPath.pathname) : {}; +const points = [ + { id: 'a', group: 'Brain', line: 'DAOY', cluster: 0, well: 'C03', x: 0, y: 0 }, + { id: 'b', group: 'Brain', line: 'ONS', cluster: 1, well: 'C04', x: 10, y: 20 }, + { id: 'c', group: 'Lung', line: 'A549', cluster: 0, well: 'D03', x: 1000, y: -500 }, +]; +test('bounds stay within each independently embedded group and handle empty or constant axes', () => { + assert.equal(typeof app.groupBounds, 'function'); + assert.deepEqual(app.groupBounds(points, 'Brain'), { minX: 0, maxX: 10, minY: 0, maxY: 20 }); + assert.deepEqual(app.groupBounds(points, 'Lung'), { minX: 999.5, maxX: 1000.5, minY: -500.5, maxY: -499.5 }); + assert.equal(app.groupBounds(points, 'missing'), null); +}); +test('projection preserves geometry and inverts zoomed panned coordinates', () => { + assert.equal(typeof app.createProjection, 'function'); + const bounds = app.groupBounds(points, 'Brain'); + const project = app.createProjection(bounds, 800, 600, { zoom: 2.5, panX: 37, panY: -19 }); + for (const point of points.slice(0, 2)) { + const screen = project.forward(point); + const original = project.inverse(screen); + assert.ok(Math.abs(original.x - point.x) < 1e-10); + assert.ok(Math.abs(original.y - point.y) < 1e-10); + } + const center = app.createProjection(bounds, 800, 600).forward({ x: 5, y: 10 }); + assert.deepEqual(center, { x: 400, y: 300 }); +}); +test('nearest point uses screen-space radius and returns no hit outside it', () => { + assert.equal(typeof app.nearestPoint, 'function'); + const projection = app.createProjection(app.groupBounds(points, 'Brain'), 800, 600); + const target = projection.forward(points[1]); + assert.equal(app.nearestPoint(points.slice(0, 2), { x: target.x + 3, y: target.y }, projection, 9), points[1]); + assert.equal(app.nearestPoint(points.slice(0, 2), { x: 0, y: 0 }, projection, 9), null); + assert.equal(app.nearestPoint([], target, projection, 9), null); +}); +test('selection, toggles and keyboard traversal never retain a hidden or other-group cell', () => { + assert.equal(typeof app.createState, 'function'); + assert.equal(typeof app.reduceState, 'function'); + let state = app.createState(points); + assert.equal(state.group, 'Brain'); + state = app.reduceState(state, { type: 'pin', id: 'a' }, points); + assert.equal(state.selectedId, 'a'); + state = app.reduceState(state, { type: 'toggle', value: 'DAOY' }, points); + assert.equal(state.selectedId, null); + assert.ok(state.hidden.has('DAOY')); + state = app.reduceState(state, { type: 'step', direction: 1 }, points); + assert.equal(state.selectedId, 'b'); + state = app.reduceState(state, { type: 'color', value: 'well' }, points); + assert.equal(state.hidden.size, 0); + assert.equal(state.selectedId, 'b'); + state = app.reduceState(state, { type: 'step', direction: 1 }, points); + assert.equal(state.selectedId, 'a'); + state = app.reduceState(state, { type: 'step', direction: -1 }, points); + assert.equal(state.selectedId, 'b'); + state = app.reduceState(state, { type: 'group', value: 'Lung' }, points); + assert.equal(state.selectedId, null); + state = app.reduceState(state, { type: 'pin', id: 'a' }, points); + assert.equal(state.selectedId, null); + state = app.reduceState(state, { type: 'pin', id: 'c' }, points); + state = app.reduceState(state, { type: 'unpin' }, points); + assert.equal(state.selectedId, null); + state = app.reduceState(state, { type: 'toggle', value: 'D03' }, points); + state = app.reduceState(state, { type: 'step', direction: 1 }, points); + assert.equal(state.selectedId, null); + assert.equal(app.createState([]).group, ''); +}); +test('image slots clear stale pixels immediately and ignore late completions', () => { + assert.equal(typeof app.createImageSlot, 'function'); + const requested = []; + const document = { createElement: tag => { + const element = { tagName: tag, textContent: '', alt: '' }; + Object.defineProperty(element, 'src', { set(value) { requested.push(element); element.url = value; } }); + return element; + }}; + const container = { children: [], replaceChildren(...children) { this.children = children; } }; + const update = app.createImageSlot(document, container); + update('assets/crops/a.jpg', 'DNA for a'); + const first = requested[0]; + assert.match(container.children[0].textContent, /Loading/); + first.onload(); + assert.equal(container.children[0], first); + update('assets/crops/b.jpg', 'DNA for b'); + assert.notEqual(container.children[0], first); + first.onload(); + assert.notEqual(container.children[0], first); + requested[1].onerror(); + assert.match(container.children[0].textContent, /Image could not be loaded/); + update(null, 'DNA for c'); + assert.equal(requested.length, 2); + assert.match(container.children[0].textContent, /unavailable/i); + update('https://example.invalid/bad.jpg', 'external'); + update('assets/crops/../../bad.jpg', 'traversal'); + assert.equal(requested.length, 2); +}); +test('static template inlines exactly one of each build placeholder without external dependencies', () => { + const templatePath = new URL('../web/template.html', import.meta.url); + assert.ok(existsSync(templatePath), 'template.html must exist'); + const template = readFileSync(templatePath, 'utf8'); + for (const token of ['__REPORT_CSS__', '__REPORT_DATA__', '__REPORT_JS__']) { + assert.equal(template.split(token).length - 1, 1, token); + } + assert.match(template, / + + + diff --git a/README.md b/README.md index 88a9f66..41654de 100644 --- a/README.md +++ b/README.md @@ -97,6 +97,7 @@ The module numbers follow the order in which we run them. | [4.preprocess_features](./4.preprocess_features/) | Convert the CellProfiler outputs to single-cell parquet files with CytoTable, remove poor quality single cells with coSMicQC, and process the profiles with pycytominer into single-cell (normalized and feature-selected) and bulk (aggregated, normalized, and feature-selected) profiles, with a QC report per cell line and plate. | | [5.morphem_featurization](./5.morphem_featurization/) | Extract nucleocentric deep learning features with MorphEm using the nuclei from CellProfiler, and process them into single-cell and bulk profiles. | | [5a.object_image_crops](./5a.object_image_crops/) | Write the nucleocentric crop of every single cell that passed QC to a standalone image-crop warehouse (JPGs plus a manifest), joinable with the single-cell profiles and the UMAP tables. | +| [7.dashboard](./7.dashboard/) | Build a static single-page UMAP explorer with exact single-cell crop previews, ready for GitHub Pages. | | [cell_lines](./cell_lines/) | Build the consolidated cell line metadata table and create the descriptive figures of the cell lines. | | [environments](./environments/) | Conda environment files and a script to create the environments on an HPC cluster. | | [utils](./utils/) | Shared functions for creating LoadData CSVs, running CellProfiler in parallel, loading the single cells that passed QC, extracting MorphEm features, and writing the image-crop warehouse. The uv environments install it as a package in editable mode (`pccma-atlas-utils`), so notebooks import it without changing `sys.path`. | From 27582de2be582b9b42d903afa5970b0c18168a5c Mon Sep 17 00:00:00 2001 From: d33bs Date: Mon, 16 Nov 2026 16:01:35 -0700 Subject: [PATCH 4/6] dashboard edits --- 7.dashboard/README.md | 139 +++++++++++- 7.dashboard/build_report.py | 133 +++++++++++- 7.dashboard/pyproject.toml | 1 + 7.dashboard/tests/test_browser.py | 55 ++++- 7.dashboard/tests/test_build_report.py | 144 +++++++++++++ 7.dashboard/tests/test_channel_mix.py | 121 +++++++++++ 7.dashboard/tests/test_real_bundle.py | 285 +++++++++++++++++++++++++ 7.dashboard/tests/test_web.mjs | 158 +++++++++++++- 7.dashboard/uv.lock | 24 +++ 7.dashboard/web/app.js | 175 ++++++++++++++- 7.dashboard/web/style.css | 24 +++ 7.dashboard/web/template.html | 17 +- 12 files changed, 1233 insertions(+), 43 deletions(-) create mode 100644 7.dashboard/tests/test_channel_mix.py create mode 100644 7.dashboard/tests/test_real_bundle.py diff --git a/7.dashboard/README.md b/7.dashboard/README.md index 38ae84c..397e830 100644 --- a/7.dashboard/README.md +++ b/7.dashboard/README.md @@ -35,11 +35,51 @@ older embedded PNG examples. ## Use the page -Choose a cancer group, hover a point to inspect its cell, and click/tap to -pin it. The inspector gives the well, field, cell/nucleus identifiers and -channel crops. Change point colors or click a legend entry to show/hide its -points. Keyboard cell navigation provides an alternative to precise hovering. -Pan/zoom and Reset view help inspect crowded regions. +The header shows the plate ID and its timepoint(s) in hours; the provenance +panel at the bottom repeats it alongside the other source metadata. Choose a +cancer group and hover a point to preview its crop beside the pointer, kept +inside the browser window. The five channel checkboxes above the plot select +any combination for **both** the hover preview and pinned image. Every selection, +including all five, is tinted and additively mixed from the original grayscale +JPEGs in the browser; it does not switch to a precomputed composite. Color swatches +show the fixed display mapping. Unchecking everything shows a clear placeholder. +The inspector also shows the selected channels' individual grayscale crops. +Pin one cell, then hover another to compare without replacing the pinned cell. +The selection persists while switching groups or cells; no embedding is refitted. +Click/tap to pin a cell in the detailed inspector. The inspector gives the +well, field, cell/nucleus identifiers and channel crops. Change point colors +or click a legend entry to show/hide its points. Keyboard cell navigation +provides an alternative to precise hovering. Pan/zoom and Reset view help +inspect crowded regions. + +## Complete local pilot + +The complete report, including the real extracted images, is available locally at: + +```text +7.dashboard/dist/BR00150695-pages-pilot-v4/index.html +``` + +This is the full crop-enabled report, not the earlier coordinate-only preview. +It includes 39,000 original JPEGs: six images for each of the 6,500 plotted cells. +All selected files were copied read-only from the existing Willow warehouse and +checked against its original `jpg-sha256.txt.gz`, not just hashes generated by +the report exporter. The local and Willow crop-index files also have matching +SHA-256 hashes. No crops or UMAP coordinates were regenerated. + +The selected source cache is under +`7.dashboard/previews/BR00150695-20261113T155150Z-g790ecb4-warehouse/`. +It contains the `crops/` tree, `selected-paths.txt`, the original warehouse hash +list, and `transfer-verification.json`. This cache is sufficient as the +`--warehouse` argument when rebuilding the same plate's report into a new output. +The cache and generated report are gitignored local data, not included in a +fresh checkout or automatically published. + +Real-image browser evidence is under +`7.dashboard/previews/BR00150695-pages-pilot-v4-evidence/`: desktop/mobile/hover screenshots +and `browser-verification.json`. Verification covers native mouse hover and +pinning across all 13 cell lines and seven groups, all five grayscale channel +switches, mobile touch selection, project-prefix serving, and direct file opening. ## Build a complete bundle @@ -90,7 +130,8 @@ silently dropping cells or channels. dist// Generated bundle (gitignored) index.html One page with embedded data, JS and CSS .nojekyll Serve generated assets unchanged - manifest.json Input/code hashes, scope, image hashes and counts + manifest.json Input/code hashes, scope, image/catalog hashes and counts + data/pilot.duckdb Pilot-only cell metadata and JPEG asset catalog assets/crops/... Only the selected cells' original JPEGs ``` @@ -98,6 +139,57 @@ The manifest records file basenames and hashes, not private input-directory paths. The page identifies the plate, run, scope and input hashes. All data and image paths are relative to the page, so the whole bundle can move intact. +## Pilot DuckDB catalog + +Every complete build includes `data/pilot.duckdb`; the provenance panel offers a +download link. It catalogs **only the 6,500 plotted pilot cells**, not all 80,493 +warehouse cells. The current catalog is 10,760,192 bytes and contains: + +- `cells` — 6,500 rows: cell identity, plate/run, line/group/tissue, well/site, + time point in hours, object identifiers, UMAP coordinates and nucleus centers. + Coordinates retain double precision. +- `image_assets` — 39,000 rows, keyed by `(cell_id, channel)`: original JPEG + paths, byte sizes and SHA-256 hashes for five grayscale channels plus the saved + composite. `path` is relative to the **bundle root**, not the `data/` directory. +- `report_metadata` — 10 JSON-valued provenance entries, including source + basenames/checksums, scope and summaries. No private input directory paths. + +JPEGs remain separate byte-identical static assets, not database blobs. This +lets the viewer load only the current cells' images instead of downloading a +whole image database. The dashboard does not use DuckDB-Wasm or query the catalog +at runtime; the catalog is a downloadable queryable index of the same data. +The exporter closes/checkpoints the database, reopens it read-only, and compares +all persisted rows and foreign-key coverage. Diagnostic builds omit the catalog. +Its bytes count toward the same 950 MB bundle limit. + +Example query, run from the repository root against the current local pilot: + +```bash +uv run --project 7.dashboard --locked python - <<'PY' +import duckdb + +with duckdb.connect( + "7.dashboard/dist/BR00150695-pages-pilot-v4/data/pilot.duckdb", + read_only=True, +) as connection: + print(connection.execute(""" + SELECT + c.cell_line, + c.time_point, + a.channel, + a.path + FROM cells c + JOIN image_assets a USING (cell_id) + WHERE a.channel = 'DNA' + ORDER BY c.cell_id + LIMIT 3 + """).fetchall()) +PY +``` + +After publication, resolve an `image_assets.path` against the URL of the report +directory (the directory containing `index.html`), not against the catalog URL. + ## Coordinate-only diagnostic preview If the warehouse cannot be reached, an explicit diagnostic mode builds the @@ -131,7 +223,20 @@ For GitHub Pages, use the generated bundle directory as the Pages artifact root (for example, the `path` passed to `actions/upload-pages-artifact` in an authorized deployment workflow). Publish **all** its files, including `assets/`, not only `index.html` or the source `web/template.html`. -Root hosting and project-prefix hosting need no path rewrite. No deployment +Root hosting and project-prefix hosting need no path rewrite. The current +complete pilot directory is 422,547,980 bytes (including JPEGs, catalog, HTML and +manifest), within the exporter budget. Keep `data/` as well as `assets/` intact. + +A portable ZIP of this directory can be created outside the site root: + +```bash +BUNDLE=7.dashboard/dist/BR00150695-pages-pilot-v4 +python3 -m zipfile -c "$BUNDLE.zip" "$BUNDLE" +python3 -m zipfile -t "$BUNDLE.zip" +``` + +Unzip it, then use the extracted directory **containing `index.html`** as the +Pages artifact root. Do not upload the ZIP itself as a site asset. No deployment workflow or Pages settings are changed automatically by this module. Do not upload the full warehouse or commit the ignored generated bundle just to preview the source changes. Publishing the report also publishes its @@ -155,6 +260,26 @@ mechanics only. Verification on the actual plate's coordinates is separate from real warehouse-image decoding and hover display. A coordinate-only preview passing is not evidence that the real crops have been bundled. +To enable the additional real-bundle tests, provide the complete local +bundle and retain the original warehouse hash list in the source cache above: + +```bash +PCCMA_DASHBOARD_BUNDLE="$PWD/7.dashboard/dist/BR00150695-pages-pilot-v4" \ +PCCMA_DASHBOARD_EVIDENCE="$PWD/7.dashboard/previews/BR00150695-pages-pilot-v4-evidence" \ +uv run --project 7.dashboard --locked python -m pytest 7.dashboard/tests -q +``` + +These tests check every bundled image against both its bundle manifest and the +original warehouse hashes, then exercise actual image display in Chromium. +The fixture suite checks all 32 channel subsets against independently computed +pixels. Real-bundle tests check a two-channel mix in both the pinned and hover +images, native interactions across all 13 lines, mobile/file opening, root and +project-prefix URLs, and the catalog download hash. +Without `PCCMA_DASHBOARD_BUNDLE`, the real-bundle tests explicitly skip; the +fixture tests still run. `PCCMA_DASHBOARD_EVIDENCE` is optional and controls where +fresh screenshots and the browser verification record are written. Tests do +not modify or deploy the report bundle. + ## Sources - [Single-cell embedding analysis](../6.profile_analysis/3.single_cell_embedding.ipynb) diff --git a/7.dashboard/build_report.py b/7.dashboard/build_report.py index af9790f..d0417d2 100644 --- a/7.dashboard/build_report.py +++ b/7.dashboard/build_report.py @@ -11,6 +11,7 @@ import re import shutil +import duckdb import pandas as pd from PIL import Image @@ -104,6 +105,7 @@ def prepare_data(umap, index, *, plate, run_id): "id": identifier, "line": row["Metadata_cell_line"], "group": row["cancer_group"], "tissue": row["tissue_site"], "well": row["Metadata_Well"], "site": int(row["Metadata_Site"]), "cell": int(row["Metadata_Cells_Number_Object_Number"]), + "image": int(row["Metadata_ImageNumber"]), "nucleus": int(row["Metadata_Nuclei_Number_Object_Number"]), "time": int(row["Metadata_time_point"]), "cluster": int(row["cluster"]), "x": row["umap_1"], "y": row["umap_2"], @@ -116,7 +118,8 @@ def prepare_data(umap, index, *, plate, run_id): "excluded_umap_rows": len(umap) - len(selected), "cell_lines": selected.Metadata_cell_line.nunique(), "cancer_groups": selected.cancer_group.nunique(), - "crop_size": int(crops.Metadata_Nucleocentric_Crop_Size.iloc[0])}, + "crop_size": int(crops.Metadata_Nucleocentric_Crop_Size.iloc[0]), + "timepoints": sorted({int(value) for value in selected.Metadata_time_point})}, "sources": {"qc": "Inherited published post-QC membership; QC not recalculated."}, "images": {"status": "bundled", "message": "Original warehouse JPEGs.", "channels": CHANNELS}, "points": points, @@ -129,6 +132,123 @@ def sha256(path): return hashlib.file_digest(stream, "sha256").hexdigest() +def build_catalog(bundle, payload, assets): + """Write a self-contained native DuckDB catalog for exactly the plotted cells. + + JPEGs stay separate; image_assets.path is an unescaped POSIX filesystem path + relative to the bundle root (NOT relative to data/). report_metadata values + are JSON, with source basenames/checksums but no input directory paths. + Diagnostic coordinate-only reports deliberately do not call this function. + """ + points = payload["points"] + if (payload["images"]["status"] != "bundled" or not points + or len(points) != payload["summary"]["umap_cells"]): + raise ValueError("Catalog requires a complete plotted-cell bundle") + by_path = {asset["path"]: asset for asset in assets} + if len(by_path) != len(assets) or len(assets) != len(points) * len(CHANNELS): + raise ValueError("Catalog asset count or uniqueness mismatch") + cell_columns = ["cell_id", "plate", "run_id", "cell_line", "cancer_group", "tissue_site", + "well", "site", "image_number", "cell_number", "nucleus_number", + "time_point", "cluster", "umap_1", "umap_2", "center_x", "center_y"] + cells, images = [], [] + for point in points: + if set(point["images"]) != set(CHANNELS): + raise ValueError("Catalog cell is missing expected channels") + cells.append((point["id"], payload["plate"], payload["run_id"], point["line"], + point["group"], point["tissue"], point["well"], point["site"], + point["image"], point["cell"], point["nucleus"], point["time"], + point["cluster"], point["x"], point["y"], point["cx"], point["cy"])) + for channel in CHANNELS: + path = unquote(point["images"][channel]) + relative_crop_path(path.removeprefix("assets/")) + asset = by_path.get(path) + if (not path.startswith("assets/") or asset is None + or not isinstance(asset["bytes"], int) or asset["bytes"] <= 0 + or not re.fullmatch(r"[0-9a-f]{64}", asset["sha256"])): + raise ValueError("Catalog asset path, size or checksum mismatch") + images.append((point["id"], channel, path, asset["bytes"], asset["sha256"])) + if {row[2] for row in images} != set(by_path): + raise ValueError("Catalog includes assets outside the plotted cells") + metadata = { + "schema_version": 1, "scope": "plotted_pilot_cells_only", + "plate": payload["plate"], "run_id": payload["run_id"], + "summary": payload["summary"], "sources": payload["sources"], + "channels": CHANNELS, "images": payload["images"], + "path_base": "bundle_root", "duckdb_version": duckdb.__version__, + } + metadata_rows = [(key, json.dumps(value, sort_keys=True, allow_nan=False)) + for key, value in metadata.items()] + path = Path(bundle) / "data" / "pilot.duckdb" + path.parent.mkdir() + # Explicit schemas/constraints, not inferred float32 or blob-backed images. + with duckdb.connect(str(path)) as connection: + connection.execute(""" + CREATE TABLE cells ( + cell_id VARCHAR PRIMARY KEY, plate VARCHAR NOT NULL, run_id VARCHAR NOT NULL, + cell_line VARCHAR NOT NULL, cancer_group VARCHAR NOT NULL, tissue_site VARCHAR NOT NULL, + well VARCHAR NOT NULL, site BIGINT NOT NULL CHECK (site > 0), + image_number BIGINT NOT NULL CHECK (image_number > 0), + cell_number BIGINT NOT NULL CHECK (cell_number > 0), + nucleus_number BIGINT NOT NULL CHECK (nucleus_number > 0), + time_point BIGINT NOT NULL CHECK (time_point > 0), + cluster BIGINT NOT NULL CHECK (cluster > 0), + umap_1 DOUBLE NOT NULL CHECK (isfinite(umap_1)), + umap_2 DOUBLE NOT NULL CHECK (isfinite(umap_2)), + center_x DOUBLE NOT NULL CHECK (isfinite(center_x)), + center_y DOUBLE NOT NULL CHECK (isfinite(center_y)) + ) + """).fetchall() + connection.execute(""" + CREATE TABLE image_assets ( + cell_id VARCHAR NOT NULL REFERENCES cells(cell_id), + channel VARCHAR NOT NULL CHECK (channel IN ('composite', 'DNA', 'ER', 'RNA', 'AGP', 'Mito')), + path VARCHAR NOT NULL UNIQUE, bytes BIGINT NOT NULL CHECK (bytes > 0), + sha256 VARCHAR NOT NULL CHECK (regexp_full_match(sha256, '[0-9a-f]{64}')), + PRIMARY KEY (cell_id, channel) + ) + """).fetchall() + connection.execute("CREATE TABLE report_metadata (key VARCHAR PRIMARY KEY, value JSON NOT NULL)").fetchall() + for name, columns, rows in [ + ("cells", cell_columns, cells), + ("image_assets", ["cell_id", "channel", "path", "bytes", "sha256"], images), + ("report_metadata", ["key", "value"], metadata_rows), + ]: + connection.register("catalog_input", pd.DataFrame(rows, columns=columns)) + connection.execute(f"INSERT INTO {name} SELECT * FROM catalog_input").fetchall() + connection.unregister("catalog_input") + connection.execute("CHECKPOINT").fetchall() + # Reopen the persisted artifact read-only, comparing full values as well as + # counts and FK coverage. A successful INSERT alone is not verification. + with duckdb.connect(str(path), read_only=True) as connection: + counts = {name: connection.execute(f"SELECT count(*) FROM {name}").fetchall()[0][0] + for name in ("cells", "image_assets", "report_metadata")} + if counts != {"cells": len(cells), "image_assets": len(images), "report_metadata": len(metadata_rows)}: + raise ValueError("Catalog read-back row count mismatch") + if connection.execute("SELECT * FROM cells ORDER BY cell_id").fetchall() != sorted(cells): + raise ValueError("Catalog read-back cell values differ") + if connection.execute("SELECT * FROM image_assets ORDER BY cell_id, channel").fetchall() != sorted(images): + raise ValueError("Catalog read-back image values differ") + actual_metadata = {key: json.loads(value) for key, value in + connection.execute("SELECT * FROM report_metadata").fetchall()} + if actual_metadata != metadata: + raise ValueError("Catalog read-back provenance differs") + orphans = connection.execute(""" + SELECT count(*) FROM image_assets a LEFT JOIN cells c USING (cell_id) + WHERE c.cell_id IS NULL + """).fetchall()[0][0] + incomplete = connection.execute(""" + SELECT c.cell_id FROM cells c LEFT JOIN image_assets a USING (cell_id) + GROUP BY c.cell_id HAVING count(a.channel) <> ? + """, [len(CHANNELS)]).fetchall() + if orphans or incomplete: + raise ValueError("Catalog read-back referential integrity mismatch") + if Path(str(path) + ".wal").exists(): + raise ValueError("Catalog is not self-contained: unexpected write-ahead log") + return {"status": "bundled", "path": path.relative_to(bundle).as_posix(), + "bytes": path.stat().st_size, "sha256": sha256(path), "tables": counts, + "schema_version": 1, "path_base": "bundle_root"} + + def build_report(*, umap_path, index_path, warehouse, output, plate, run_id, allow_missing_images=False, web_dir=None): """Build a new immutable static output with byte-identical, validated warehouse JPGs. @@ -185,6 +305,9 @@ def build_report(*, umap_path, index_path, warehouse, output, plate, run_id, assets.append({"path": f"assets/{relative}", "sha256": digest, "bytes": len(data)}) payload["images"]["files"] = len(assets) payload["images"]["bytes"] = sum(asset["bytes"] for asset in assets) + payload["catalog"] = (build_catalog(staging, payload, assets) if available else { + "status": "omitted", "reason": "Coordinate-only diagnostic; no complete image-asset catalog." + }) web_dir = Path(web_dir) if web_dir else Path(__file__).parent / "web" template = (web_dir / "template.html").read_text() # Escape data for an HTML script raw-text element, not merely for JSON. @@ -200,12 +323,12 @@ def build_report(*, umap_path, index_path, warehouse, output, plate, run_id, (staging / ".nojekyll").touch() manifest = {"schema_version": 1, "plate": plate, "run_id": run_id, "sources": payload["sources"], "summary": payload["summary"], - "images": payload["images"], "assets": assets, + "images": payload["images"], "catalog": payload["catalog"], "assets": assets, "index_sha256": sha256(staging / "index.html"), "code_sha256": {p.name: sha256(p) for p in [Path(__file__), web_dir / "template.html", web_dir / "style.css", web_dir / "app.js"]}} (staging / "manifest.json").write_text(json.dumps(manifest, indent=2) + "\n") - total_bytes = payload["images"]["bytes"] + (staging / "index.html").stat().st_size + (staging / "manifest.json").stat().st_size + total_bytes = sum(path.stat().st_size for path in staging.rglob("*") if path.is_file()) if total_bytes > MAX_SITE_BYTES: raise ValueError(f"Static site exceeds size budget: {total_bytes} > {MAX_SITE_BYTES} bytes") if output.exists(): @@ -235,10 +358,10 @@ def main(argv=None): warehouse=args.warehouse, output=args.output, plate=args.plate, run_id=args.run_id, allow_missing_images=args.allow_missing_images, web_dir=args.web_dir) - except (ValueError, OSError, KeyError, TypeError) as error: + except (ValueError, OSError, KeyError, TypeError, duckdb.Error) as error: parser.exit(1, f"Report build failed: {error}\n") print(json.dumps({"output": str(args.output.resolve()), "summary": payload["summary"], - "images": payload["images"]}, indent=2)) + "images": payload["images"], "catalog": payload["catalog"]}, indent=2)) return 0 diff --git a/7.dashboard/pyproject.toml b/7.dashboard/pyproject.toml index 7c32809..a6e9d79 100644 --- a/7.dashboard/pyproject.toml +++ b/7.dashboard/pyproject.toml @@ -4,6 +4,7 @@ version = "0.1.0" description = "Static single-cell UMAP and crop report; independent of the compute environments" requires-python = ">=3.11,<3.13" dependencies = [ + "duckdb==1.4.5", "pandas==2.2.3", "pyarrow==22.0.0", "pillow==12.3.0", diff --git a/7.dashboard/tests/test_browser.py b/7.dashboard/tests/test_browser.py index d850f58..fa20eca 100644 --- a/7.dashboard/tests/test_browser.py +++ b/7.dashboard/tests/test_browser.py @@ -96,7 +96,7 @@ def test_hover_pin_channels_and_prefix_paths(browser, origin, site): target = pointer_target(page) page.mouse.move(target["x"], target["y"]) expect(page.locator("#cell-id")).to_have_text(target["id"]) - expect(page.locator("#crop-area img")).to_have_count(6) + expect(page.locator("#crop-area img")).to_have_count(5) assert page.locator("#crop-area img").evaluate_all("images=>images.every(img=>img.complete&&img.naturalWidth===224)") assert all("/pccma/report/assets/crops/" in url for url in requests if url.endswith(".jpg")) page.mouse.click(target["x"], target["y"]) @@ -104,8 +104,32 @@ def test_hover_pin_channels_and_prefix_paths(browser, origin, site): another = pointer_target(page, 1) page.mouse.move(another["x"], another["y"]) expect(page.locator("#cell-id")).to_have_text(target["id"]) - page.locator("#channel-select").select_option("DNA") - expect(page.locator("#crop-area img")).to_have_count(2) + for channel in ["ER", "RNA", "AGP", "Mito"]: + page.locator(f"#channel-toggle-{channel}").uncheck() + expect(page.locator("#crop-area img")).to_have_count(1) # only the DNA thumbnail remains + mix_canvas = page.locator("#crop-area canvas") + page.wait_for_function("document.querySelectorAll('#crop-area canvas').length===1") + # The single-channel mix is still tinted and drawn for real, not a blank canvas. + assert mix_canvas.evaluate("""canvas => { + const ctx = canvas.getContext('2d'); + const pixels = ctx.getImageData(0, 0, canvas.width, canvas.height).data; + for (let i = 0; i < pixels.length; i += 4) if (pixels[i + 3] > 0 && pixels[i] > 0) return true; + return false; + }"""), "the DNA-only mix canvas must actually paint tinted pixels" + for channel in ["ER", "RNA"]: + page.locator(f"#channel-toggle-{channel}").check() + expect(page.locator("#crop-area img")).to_have_count(3) # DNA + ER + RNA thumbnails, live mix stays a canvas + page.wait_for_function("document.querySelectorAll('#crop-area canvas').length===1") + page.locator("#channel-toggle-DNA").uncheck() + page.locator("#channel-toggle-ER").uncheck() + page.locator("#channel-toggle-RNA").uncheck() + expect(page.locator("#crop-area")).to_contain_text("Select at least one channel") + page.locator("#channel-toggle-DNA").check() + page.locator("#channel-toggle-ER").check() + page.locator("#channel-toggle-RNA").check() + page.locator("#channel-toggle-AGP").check() + page.locator("#channel-toggle-Mito").check() + expect(page.locator("#crop-area img")).to_have_count(5) # live five-channel mix + all 5 thumbnails page.locator("#unpin-cell").click() page.locator("#next-cell").click() expect(page.locator("#pin-status")).to_have_text("Pinned") @@ -143,7 +167,7 @@ def test_mobile_touch_filters_zoom_and_file_open(browser, origin, site): file_page = browser.new_page() file_page.goto((site[0] / "index.html").as_uri(), wait_until="load") file_page.locator("#next-cell").click() - expect(file_page.locator("#crop-area img")).to_have_count(6) + expect(file_page.locator("#crop-area img")).to_have_count(5) assert file_page.locator("#crop-area img").evaluate_all("images=>images.every(img=>img.naturalWidth===224)") file_page.close() @@ -153,9 +177,26 @@ def test_image_404_is_visible_and_never_shows_stale_pixels(browser, origin, site page.route("**/*_DNA.jpg", lambda route: route.fulfill(status=404, body="missing test fixture")) page.goto(origin + "/pccma/report/", wait_until="load") page.locator("#next-cell").click() - expect(page.locator(".image-error")).to_have_count(1) - expect(page.locator(".image-error")).to_contain_text("Image could not be loaded") - assert page.locator("#crop-area img").count() == 5 + expect(page.locator(".image-error")).to_have_count(2) + expect(page.locator(".image-error").first).to_contain_text("Image could not be loaded") + assert page.locator("#crop-area img").count() == 4 + page.close() + + +@pytest.mark.parametrize("viewport", [{"width": 1280, "height": 577}, {"width": 900, "height": 700}]) +def test_hover_crop_is_fully_visible_without_scrolling(browser, origin, site, viewport): + page = browser.new_page(viewport=viewport) + page.goto(origin + "/pccma/report/", wait_until="load") + target = pointer_target(page, 1) # The upper fixture point remains in view. + page.mouse.move(target["x"], target["y"]) + expect(page.locator("#cell-id")).to_have_text(target["id"]) + page.wait_for_function("document.querySelectorAll('#crop-area img').length===5") + # A decoded image below the fold does not satisfy a visible hover preview. + assert page.locator("#hover-preview canvas").evaluate_all("""images => images.some(image => { + const rect=image.getBoundingClientRect(); + return image.width===224 && rect.width>=100 && rect.height>=100 && + rect.left>=0 && rect.top>=0 && rect.right<=innerWidth && rect.bottom<=innerHeight; + })"""), "Hover must display a complete crop inside the current viewport" page.close() diff --git a/7.dashboard/tests/test_build_report.py b/7.dashboard/tests/test_build_report.py index 8cdfe21..9e11a3f 100644 --- a/7.dashboard/tests/test_build_report.py +++ b/7.dashboard/tests/test_build_report.py @@ -5,7 +5,9 @@ import json import re from pathlib import Path +from urllib.parse import unquote +import duckdb from PIL import Image import pandas as pd import pytest @@ -52,6 +54,7 @@ def test_exact_join_scopes_plate_and_preserves_coordinates(tables): report = builder().prepare_data(umap, index, plate="P1", run_id="pilot") assert report["summary"]["umap_cells"] == 1 assert report["summary"]["excluded_umap_rows"] == 1 + assert report["summary"]["timepoints"] == [24] point = report["points"][0] assert point["cx"] == 12.1234567890123 assert point["id"] == "P1_C03_f01_nuc0003_cell0002" @@ -172,6 +175,11 @@ def test_unavailable_warehouse_requires_explicit_diagnostic_opt_in(build_inputs) payload = builder().build_report(**build_inputs, allow_missing_images=True) assert payload["images"]["status"] == "unavailable" assert payload["images"]["files"] == 0 + assert payload["catalog"]["status"] == "omitted" + assert "diagnostic" in payload["catalog"]["reason"] + manifest = json.loads((build_inputs["output"] / "manifest.json").read_text()) + assert manifest["catalog"] == payload["catalog"] + assert not (build_inputs["output"] / "data").exists() assert all(point["images"] == {} for point in payload["points"]) assert not (build_inputs["output"] / "assets").exists() @@ -233,3 +241,139 @@ def test_oversized_static_site_fails_before_publication(build_inputs, monkeypatc assert not build_inputs["output"].exists() +def test_native_catalog_contains_only_plotted_cells_and_complete_asset_links(build_inputs): + module = builder() + # A warehouse row with no plotted UMAP point must not be packaged, nor + # should its deliberately absent JPEGs be needed to build the pilot. + index = pd.read_parquet(build_inputs["index_path"]) + unplotted = index.copy() + unplotted["Metadata_Nuclei_Location_Center_X"] = 900.0 + unplotted["Metadata_Nuclei_Number_Object_Number"] = 9 + unplotted["Metadata_Cells_Number_Object_Number"] = 8 + for column in module.PATH_COLUMNS.values(): + unplotted[column] = unplotted[column].str.replace("nuc0003_cell0002", "nuc0009_cell0008") + pd.concat([index, unplotted], ignore_index=True).to_parquet(build_inputs["index_path"]) + payload = module.build_report(**build_inputs) + site = build_inputs["output"] + catalog = site / "data/pilot.duckdb" + manifest = json.loads((site / "manifest.json").read_text()) + entry = manifest["catalog"] + assert entry == payload["catalog"] + assert entry["path"] == "data/pilot.duckdb" + assert entry["bytes"] == catalog.stat().st_size > 0 + assert entry["sha256"] == hashlib.sha256(catalog.read_bytes()).hexdigest() + assert entry["tables"] == {"cells": 1, "image_assets": 6, "report_metadata": 10} + assert entry["path_base"] == "bundle_root" + assert not catalog.with_suffix(".duckdb.wal").exists() + assert str(build_inputs["warehouse"]).encode() not in catalog.read_bytes() + assert str(build_inputs["umap_path"].parent).encode() not in catalog.read_bytes() + with duckdb.connect(str(catalog), read_only=True) as connection: + assert connection.execute("SHOW TABLES").fetchall() == [ + ("cells",), ("image_assets",), ("report_metadata",)] + columns = dict(connection.execute("SELECT column_name, data_type FROM information_schema.columns WHERE table_name = 'cells'").fetchall()) + assert columns == { + "cell_id": "VARCHAR", "plate": "VARCHAR", "run_id": "VARCHAR", "cell_line": "VARCHAR", + "cancer_group": "VARCHAR", "tissue_site": "VARCHAR", "well": "VARCHAR", "site": "BIGINT", + "image_number": "BIGINT", "cell_number": "BIGINT", "nucleus_number": "BIGINT", + "time_point": "BIGINT", "cluster": "BIGINT", "umap_1": "DOUBLE", "umap_2": "DOUBLE", + "center_x": "DOUBLE", "center_y": "DOUBLE", + } + assert connection.execute("SELECT * FROM cells").fetchall() == [( + "P1_C03_f01_nuc0003_cell0002", "P1", "pilot", "DAOY", "Medulloblastoma", + "Central nervous system", "C03", 1, 7, 2, 3, 24, 2, + 1.25, -2.5, 12.1234567890123, 24.5)] + rows = connection.execute("SELECT cell_id, channel, path, bytes, sha256 FROM image_assets").fetchall() + assert len(rows) == 6 + assert {row[1] for row in rows} == set(module.CHANNELS) + for cell_id, channel, path, size, digest in rows: + assert cell_id == payload["points"][0]["id"] + assert path == unquote(payload["points"][0]["images"][channel]) + data = (site / path).read_bytes() + assert len(data) == size + assert hashlib.sha256(data).hexdigest() == digest + assert connection.execute("SELECT count(*) FROM image_assets ANTI JOIN cells USING (cell_id)").fetchall() == [(0,)] + metadata = {key: json.loads(value) for key, value in connection.execute("SELECT * FROM report_metadata").fetchall()} + assert metadata["scope"] == "plotted_pilot_cells_only" + assert metadata["summary"] == payload["summary"] + assert metadata["summary"]["warehouse_cells"] == 2 + assert metadata["summary"]["umap_cells"] == 1 + assert metadata["sources"] == payload["sources"] + assert metadata["path_base"] == "bundle_root" + assert metadata["duckdb_version"] == duckdb.__version__ == "1.4.5" + assert not connection.execute("SELECT 1 FROM information_schema.columns WHERE data_type = 'BLOB'").fetchall() + with pytest.raises(duckdb.InvalidInputException, match="read-only"): + connection.execute("DELETE FROM report_metadata").fetchall() + + +def test_catalog_paths_are_bundle_relative_not_url_escaped(build_inputs): + index = pd.read_parquet(build_inputs["index_path"]) + for column in builder().PATH_COLUMNS.values(): + old = build_inputs["warehouse"] / index.loc[0, column] + index.loc[0, column] = index.loc[0, column].replace("DAOY/", "DAOY #µ%/") + new = build_inputs["warehouse"] / index.loc[0, column] + new.parent.mkdir(parents=True, exist_ok=True) + old.rename(new) + index.to_parquet(build_inputs["index_path"]) + payload = builder().build_report(**build_inputs) + assert "%20%23%C2%B5%25" in payload["points"][0]["images"]["DNA"] + with duckdb.connect(str(build_inputs["output"] / payload["catalog"]["path"]), read_only=True) as connection: + paths = connection.execute("SELECT path FROM image_assets").fetchall() + assert all("DAOY #µ%/" in path for (path,) in paths) + assert all((build_inputs["output"] / path).is_file() for (path,) in paths) + + +@pytest.mark.parametrize("statement", [ + "INSERT INTO image_assets SELECT 'missing-cell', channel, 'assets/crops/other.jpg', bytes, sha256 FROM image_assets LIMIT 1", + "INSERT INTO image_assets SELECT * FROM image_assets LIMIT 1", + "UPDATE cells SET umap_1 = 'NaN'::DOUBLE", + "UPDATE image_assets SET sha256 = 'not-a-sha256'", +]) +def test_catalog_native_constraints_are_enforced(build_inputs, statement): + payload = builder().build_report(**build_inputs) + with duckdb.connect(str(build_inputs["output"] / payload["catalog"]["path"])) as connection: + with pytest.raises(duckdb.ConstraintException): + connection.execute(statement).fetchall() + + +@pytest.mark.parametrize("corruption", [ + "UPDATE cells SET umap_1 = 42.0", + "DELETE FROM image_assets WHERE channel = 'DNA'", + "UPDATE image_assets SET bytes = bytes + 1 WHERE channel = 'DNA'", + "UPDATE report_metadata SET value = '\"wrong\"' WHERE key = 'scope'", +]) +def test_catalog_readonly_readback_rejects_persisted_corruption(build_inputs, monkeypatch, corruption): + module = builder() + native_connect = duckdb.connect + reads = [] + + def connect(database, **kwargs): + if kwargs.get("read_only"): + reads.append(database) + with native_connect(database) as connection: + connection.execute(corruption).fetchall() + return native_connect(database, **kwargs) + + monkeypatch.setattr(module.duckdb, "connect", connect) + with pytest.raises(ValueError, match="Catalog read-back"): + module.build_report(**build_inputs) + assert len(reads) == 1 + assert not build_inputs["output"].exists() + assert not build_inputs["output"].with_name(".site.partial").exists() + + +def test_catalog_bytes_count_toward_entire_site_budget(build_inputs, monkeypatch): + module = builder() + payload = module.build_report(**build_inputs) + site = build_inputs["output"] + measured_bytes = sum(path.stat().st_size for path in site.rglob("*") if path.is_file()) + noncatalog_bytes = measured_bytes - payload["catalog"]["bytes"] + assert measured_bytes < module.MAX_SITE_BYTES + # This permits every HTML/JPEG/manifest byte, but not the DuckDB file. + monkeypatch.setattr(module, "MAX_SITE_BYTES", noncatalog_bytes) + build_inputs["output"] = site.with_name("too-large") + with pytest.raises(ValueError, match="size budget"): + module.build_report(**build_inputs) + assert not build_inputs["output"].exists() + assert not site.with_name(".too-large.partial").exists() + + diff --git a/7.dashboard/tests/test_channel_mix.py b/7.dashboard/tests/test_channel_mix.py new file mode 100644 index 0000000..d766b90 --- /dev/null +++ b/7.dashboard/tests/test_channel_mix.py @@ -0,0 +1,121 @@ +"""Pixel-level browser checks of every grayscale-channel combination. + +Only the small synthetic fixture is used here; real pilot coverage is separate. +""" + +from itertools import combinations +import re +from urllib.parse import unquote + +from PIL import Image +from playwright.sync_api import expect + +from test_browser import browser, origin, pointer_target, site # noqa: F401 +from test_build_report import tables # noqa: F401 + + +COLORS = { + "DNA": (77, 124, 255), "ER": (58, 214, 176), "RNA": (255, 209, 102), + "AGP": (255, 95, 162), "Mito": (255, 107, 77), +} + + +def expected_pixel(bundle, point, chosen): + """Independent additive-color oracle using the exact decoded grayscale JPEGs.""" + values = [] + for channel in chosen: + with Image.open(bundle / unquote(point["images"][channel])) as image: + values.append((image.getpixel((112, 112)), COLORS[channel])) + return [min(255, sum(round(value * color[component] / 255) for value, color in values)) + for component in range(3)] + [255] + + +def wait_mix(page, selector, point, chosen): + label = " + ".join(chosen) + " crop · " + point["id"] + page.wait_for_function("""({selector,label}) => { + const canvas=document.querySelector(selector); + return canvas && canvas.getAttribute('aria-label')===label; + }""", arg={"selector": selector, "label": label}, timeout=5000) + return page.locator(selector).evaluate("""canvas => Array.from( + canvas.getContext('2d').getImageData(112,112,1,1).data) + """) + + +def test_all_32_selections_mix_correct_pixels_for_hover_and_pin(browser, origin, site): + bundle, payload = site + page = browser.new_page(viewport={"width": 1600, "height": 1400}) + errors, composite_requests = [], [] + page.on("pageerror", lambda error: errors.append(str(error))) + page.on("request", lambda request: composite_requests.append(request.url) + if request.url.endswith("_composite.jpg") else None) + page.goto(origin + "/pccma/report/", wait_until="load") + # Users can set the shared selection BEFORE hovering/pinning anything. + expect(page.locator("#channel-toggle-DNA")).to_be_enabled() + expect(page.locator("#plate-label")).to_contain_text("Timepoint 24 h") + first = pointer_target(page, 0) + page.mouse.click(first["x"], first["y"]) + expect(page.locator("#cell-id")).to_have_text(first["id"]) + points = {point["id"]: point for point in payload["points"]} + pinned = points[first["id"]] + checked = [] + for count in range(6): + for selection in combinations(COLORS, count): + chosen = list(selection) + for channel in COLORS: + page.locator(f"#channel-toggle-{channel}").set_checked(channel in chosen) + second = pointer_target(page, 1) + page.mouse.move(second["x"], second["y"]) + hovered = points[second["id"]] + expect(page.locator("#hover-preview")).to_be_visible() + expect(page.locator("#cell-id")).to_have_text(pinned["id"]) + expect(page.locator("#pin-status")).to_have_text("Pinned") + if chosen: + for selector, point in [("#crop-area canvas", pinned), + ("#hover-preview canvas", hovered)]: + actual = wait_mix(page, selector, point, chosen) + expected = expected_pixel(bundle, point, chosen) + # Each canvas multiply/add can round by a byte; tolerate at + # most one per layer, not arbitrary visual similarity. + assert all(abs(a - b) <= len(chosen) for a, b in zip(actual, expected)), ( + chosen, selector, actual, expected) + expect(page.locator("#crop-area img")).to_have_count(len(chosen)) + else: + expect(page.locator("#crop-area canvas")).to_have_count(0) + expect(page.locator("#hover-preview canvas")).to_have_count(0) + expect(page.locator("#crop-area")).to_contain_text("Select at least one channel") + expect(page.locator("#hover-preview")).to_contain_text("Select at least one channel") + checked.append(selection) + assert len(checked) == 32 + assert not composite_requests, "Even all-five mixing must work from grayscale alone" + page.mouse.move(0, 0) + expect(page.locator("#hover-preview")).to_be_hidden() + expect(page.locator("#cell-id")).to_have_text(pinned["id"]) + assert not errors + page.close() + + +def test_grayscale_mix_on_direct_file_open_and_mobile(browser, origin, site): + bundle, _payload = site + page = browser.new_page() + errors = [] + page.on("pageerror", lambda error: errors.append(str(error))) + page.goto((bundle / "index.html").as_uri(), wait_until="load") + page.locator("#next-cell").click() + expect(page.locator("#crop-area canvas")).to_have_count(1) + for channel in ["ER", "RNA", "AGP"]: + page.locator(f"#channel-toggle-{channel}").uncheck() + expect(page.locator("#crop-area canvas")).to_have_attribute("aria-label", re.compile(r"DNA \+ Mito crop")) + # file:// canvases may be tainted; rendering/screenshot, not pixel readback, + # is the contract for the downloadable report. + assert page.locator("#crop-area canvas").evaluate("c=>c.width===224 && c.height===224") + assert not errors + page.close() + context = browser.new_context(viewport={"width": 390, "height": 844}, is_mobile=True, has_touch=True) + mobile = context.new_page() + mobile.goto(origin + "/pccma/report/", wait_until="load") + mobile.locator("#channel-toggle-Mito").uncheck() + mobile.locator("#next-cell").click() + expect(mobile.locator("#crop-area canvas")).to_have_count(1) + expect(mobile.locator("#crop-area img")).to_have_count(4) + assert mobile.evaluate("document.documentElement.scrollWidth<=innerWidth") + context.close() diff --git a/7.dashboard/tests/test_real_bundle.py b/7.dashboard/tests/test_real_bundle.py new file mode 100644 index 0000000..9736dd0 --- /dev/null +++ b/7.dashboard/tests/test_real_bundle.py @@ -0,0 +1,285 @@ +"""Opt-in verification of the real pilot bundle, never synthetic fixture images. + +Set PCCMA_DASHBOARD_BUNDLE to a complete build directory. These tests read the +original warehouse hash list from the local pilot cache, but never require SSH +or modify the bundle. Optional screenshots/evidence go to PCCMA_DASHBOARD_EVIDENCE. +""" + +import gzip +import hashlib +import json +import os +from pathlib import Path +from urllib.parse import unquote, urljoin + +import pytest +from playwright.sync_api import expect + +from test_browser import browser, origin # noqa: F401 (shared pytest fixtures) + + +@pytest.fixture(scope="module") +def real_pilot(): + configured = os.environ.get("PCCMA_DASHBOARD_BUNDLE") + if not configured: + pytest.skip("Set PCCMA_DASHBOARD_BUNDLE to opt into real warehouse-image verification") + bundle = Path(configured).expanduser().resolve() + html = (bundle / "index.html").read_text() + payload = json.loads(html.split('", 1)[0]) + manifest = json.loads((bundle / "manifest.json").read_text()) + assert payload["images"]["status"] == "bundled", "A diagnostic preview is not a real crop bundle" + assert payload["plate"] == "BR00150695" + assert payload["run_id"] == "BR00150695-20261113T155150Z-g790ecb4" + assert payload["summary"]["umap_cells"] == len(payload["points"]) == 6500 + assert payload["images"]["files"] == len(manifest["assets"]) == 39000 + return bundle, payload, manifest + + +def test_real_pilot_all_assets_match_original_warehouse_hashes(real_pilot): + bundle, payload, manifest = real_pilot + root = Path(__file__).resolve().parents[2] + hashes = root / "7.dashboard/previews" / (payload["run_id"] + "-warehouse") / "jpg-sha256.txt.gz" + assert hashes.is_file(), "Real source hashes are required, not only self-generated bundle hashes" + assets = {asset["path"]: asset for asset in manifest["assets"]} + referenced = {unquote(path) for point in payload["points"] for path in point["images"].values()} + assert len(assets) == len(referenced) == 39000 + assert set(assets) == referenced + original = {} + with gzip.open(hashes, "rt") as stream: + for line in stream: + digest, relative = line.rstrip("\n").split(" ", 1) + if "assets/" + relative in referenced: + assert relative not in original + original[relative] = digest + assert len(original) == len(assets) + assert hashlib.sha256((bundle / "index.html").read_bytes()).hexdigest() == manifest["index_sha256"] + for relative, asset in assets.items(): + path = bundle / relative + assert not path.is_symlink() and path.is_file() + assert path.stat().st_size == asset["bytes"] + with path.open("rb") as stream: + actual = hashlib.file_digest(stream, "sha256").hexdigest() + assert actual == asset["sha256"] == original[relative.removeprefix("assets/")] + + +def isolated_target(page, line): + """Choose a well-separated real point so pointer rounding cannot hit a neighbor.""" + return page.evaluate("""line => { + const points=dashboard.visiblePoints; + const projected=points.map(point=>({point,...dashboard.projection.forward(point)})); + let best=null, bestDistance=-1; + for(const candidate of projected.filter(item=>item.point.line===line)){ + let minimum=Infinity; + for(const other of projected){ + if(other.point.id===candidate.point.id) continue; + minimum=Math.min(minimum,(candidate.x-other.x)**2+(candidate.y-other.y)**2); + } + if(minimum>bestDistance){best=candidate;bestDistance=minimum;} + } + const rect=document.getElementById('plot').getBoundingClientRect(); + return {id:best.point.id,x:best.x+rect.left,y:best.y+rect.top}; + }""", line) + + +def test_real_pilot_native_hover_all_lines_channels_mobile_and_file_open(real_pilot, browser, origin, tmp_path): + bundle, payload, _manifest = real_pilot + link = tmp_path / "pccma" / "report" + link.parent.mkdir() + link.symlink_to(bundle, target_is_directory=True) + page = browser.new_page(viewport={"width": 1600, "height": 1200}) + errors, failed, requested = [], [], [] + page.on("pageerror", lambda error: errors.append(str(error))) + page.on("response", lambda response: failed.append(response.url) if response.status >= 400 else None) + page.on("request", lambda request: requested.append(request.url)) + page.goto(origin + "/pccma/report/", wait_until="load") + expect(page.locator("#error-banner")).to_be_hidden() + expect(page.locator("#image-warning")).to_be_hidden() + points_by_id = {point["id"]: point for point in payload["points"]} + representatives = sorted({(point["group"], point["line"]) for point in payload["points"]}) + checked = [] + for group, line in representatives: + page.locator("#group-select").select_option(group) + for channel in ["DNA", "ER", "RNA", "AGP", "Mito"]: + box = page.locator(f"#channel-toggle-{channel}") + if box.is_enabled() and not box.is_checked(): + box.check() + target = isolated_target(page, line) + page.mouse.move(target["x"], target["y"]) + expect(page.locator("#cell-id")).to_have_text(target["id"]) + expect(page.locator("#inspector-title")).to_have_text(line) + expect(page.locator("#crop-area img")).to_have_count(5) + assert page.locator("#crop-area img").evaluate_all("images=>images.every(img=>img.complete&&img.naturalWidth===224&&img.naturalHeight===224)") + assert page.locator(".image-error").count() == 0 + sources = page.locator("#crop-area img").evaluate_all("images=>images.map(img=>img.src)") + assert set(sources) == {urljoin(origin + "/pccma/report/", path) for channel, path in points_by_id[target["id"]]["images"].items() if channel != "composite"} + page.mouse.click(target["x"], target["y"]) + expect(page.locator("#pin-status")).to_have_text("Pinned") + for channel in ["DNA", "ER", "RNA", "AGP", "Mito"]: + for other in ["DNA", "ER", "RNA", "AGP", "Mito"]: + box = page.locator(f"#channel-toggle-{other}") + if other == channel and not box.is_checked(): + box.check() + elif other != channel and box.is_checked(): + box.uncheck() + # A single channel is still a live canvas mix (tinted), not the five-channel composite. + expect(page.locator("#crop-area canvas")).to_have_count(1) + expect(page.locator("#crop-area img")).to_have_count(1) + expected = points_by_id[target["id"]]["images"] + assert page.locator("#crop-area img").evaluate_all("images=>images.map(img=>img.src)") == [ + urljoin(origin + "/pccma/report/", expected[channel]), + ] + for channel in ["DNA", "ER", "RNA", "AGP", "Mito"]: + box = page.locator(f"#channel-toggle-{channel}") + if not box.is_checked(): + box.check() + expect(page.locator("#crop-area canvas")).to_have_count(1) + expect(page.locator("#crop-area img")).to_have_count(5) + checked.append({"group": group, "line": line, "cell_id": target["id"], "channels": 6}) + assert len(checked) == 13 + assert len({item["group"] for item in checked}) == 7 + assert not errors and not failed + assert all(url.startswith(origin) for url in requested) + evidence = os.environ.get("PCCMA_DASHBOARD_EVIDENCE") + if evidence: + directory = Path(evidence) + directory.mkdir(parents=True, exist_ok=True) + page.screenshot(path=str(directory / "desktop.png"), full_page=True) + # Touch selection with real, decoded images at mobile width. + context = browser.new_context(viewport={"width": 390, "height": 844}, is_mobile=True, has_touch=True) + mobile = context.new_page() + mobile.goto(origin + "/pccma/report/", wait_until="load") + first_line = mobile.evaluate("dashboard.visiblePoints[0].line") + target = isolated_target(mobile, first_line) + mobile.touchscreen.tap(target["x"], target["y"]) + expect(mobile.locator("#pin-status")).to_have_text("Pinned") + expect(mobile.locator("#crop-area img")).to_have_count(5) + assert mobile.evaluate("document.documentElement.scrollWidth<=innerWidth") + if evidence: + mobile.screenshot(path=str(Path(evidence) / "mobile.png"), full_page=True) + context.close() + direct = browser.new_page() + direct.goto((bundle / "index.html").as_uri(), wait_until="load") + direct.locator("#next-cell").click() + expect(direct.locator("#crop-area img")).to_have_count(5) + assert direct.locator("#crop-area img").evaluate_all("images=>images.every(img=>img.naturalWidth===224)") + direct.close() + if evidence: + (Path(evidence) / "browser-verification.json").write_text(json.dumps({ + "plate": payload["plate"], "run_id": payload["run_id"], "status": "passed", + "checked_real_cells": checked, "groups_checked": 7, "lines_checked": len(checked), + "channels_per_cell": 6, "native_mouse_hover": True, "click_to_pin": True, + "channel_switches_checked": ["DNA", "ER", "RNA", "AGP", "Mito"], + "mobile_touch": True, "direct_file_open": True, "project_prefix": "/pccma/report/", + "page_errors": errors, "http_errors": failed, + }, indent=2) + "\n") + page.close() + + +def test_real_pilot_hover_crop_is_visible_in_laptop_window(real_pilot, browser, origin, tmp_path): + bundle, _payload, _manifest = real_pilot + link = tmp_path / "pccma" / "hover" + link.parent.mkdir() + link.symlink_to(bundle, target_is_directory=True) + page = browser.new_page(viewport={"width": 1280, "height": 577}) + page.goto(origin + "/pccma/hover/", wait_until="load") + targets = page.evaluate("""() => { + const rect=document.getElementById('plot').getBoundingClientRect(); + const found=[]; + for(const point of dashboard.visiblePoints){ + const at=dashboard.projection.forward(point); + const x=at.x+rect.left, y=at.y+rect.top; + if(x>rect.left+20 && xrect.top+20 && y { + const rect=image.getBoundingClientRect(); + return image.width===224 && rect.width>=100 && rect.height>=100 && + rect.top>=0 && rect.left>=0 && rect.bottom<=innerHeight && rect.right<=innerWidth; + }""") + expected = page.evaluate("dashboard.hoveredPoint.id") + assert expected in preview.locator("canvas").get_attribute("aria-label") + assert preview.evaluate("node=>getComputedStyle(node).pointerEvents") == "none" + evidence = os.environ.get("PCCMA_DASHBOARD_EVIDENCE") + if evidence: + Path(evidence).mkdir(parents=True, exist_ok=True) + page.screenshot(path=str(Path(evidence) / "hover-laptop.png")) + page.mouse.click(target["x"], target["y"]) + expect(page.locator("#pin-status")).to_have_text("Pinned") + expect(page.locator("#cell-id")).to_have_text(target["id"]) + # Hovering the pinned cell itself shows nothing new; the floating preview stays hidden. + expect(preview).to_be_hidden() + # Hovering a *different* cell while pinned still floats it for comparison, and the + # pinned inspector below is undisturbed. + page.mouse.move(other["x"], other["y"]) + expect(preview).to_be_visible() + expected_other = page.evaluate("dashboard.hoveredPoint.id") + expect(preview.locator("canvas")).to_have_count(1) + assert expected_other in preview.locator("canvas").get_attribute("aria-label") + assert expected_other != expected + expect(page.locator("#pin-status")).to_have_text("Pinned") + page.close() + + +@pytest.mark.parametrize("prefix", ["", "/pccma/report"]) +def test_real_pilot_mixes_grayscale_for_hover_and_pin_and_serves_catalog( + real_pilot, browser, origin, tmp_path, prefix): + from test_channel_mix import expected_pixel, wait_mix + + bundle, payload, manifest = real_pilot + if prefix: + link = tmp_path / prefix.lstrip("/") + link.parent.mkdir(parents=True) + link.symlink_to(bundle, target_is_directory=True) + else: + for path in bundle.iterdir(): + (tmp_path / path.name).symlink_to(path, target_is_directory=path.is_dir()) + page = browser.new_page(viewport={"width": 1600, "height": 1400}) + errors, requests = [], [] + page.on("pageerror", lambda error: errors.append(str(error))) + page.on("request", lambda request: requests.append(request.url)) + page.goto(origin + prefix + "/", wait_until="load") + lines = page.evaluate("[...new Set(dashboard.visiblePoints.map(p=>p.line))]") + target = isolated_target(page, lines[0]) + other = isolated_target(page, lines[1]) + points = {point["id"]: point for point in payload["points"]} + page.mouse.click(target["x"], target["y"]) + for channel in ["ER", "RNA", "AGP"]: + page.locator(f"#channel-toggle-{channel}").uncheck() + page.mouse.move(other["x"], other["y"]) + chosen = ["DNA", "Mito"] + for selector, point in [("#crop-area canvas", points[target["id"]]), + ("#hover-preview canvas", points[other["id"]])]: + actual = wait_mix(page, selector, point, chosen) + expected = expected_pixel(bundle, point, chosen) + assert all(abs(a-b) <= len(chosen) for a, b in zip(actual, expected)), ( + selector, actual, expected) + expect(page.locator("#cell-id")).to_have_text(target["id"]) + expect(page.locator("#pin-status")).to_have_text("Pinned") + assert not any(url.endswith("composite.jpg") for url in requests) + assert not any(url.endswith(".duckdb") for url in requests), "Viewer must not download a database to render images" + page.locator("details.provenance summary").click() + expect(page.locator("#catalog-download")).to_be_visible() + catalog = manifest["catalog"] + response = page.request.get(origin + prefix + "/" + catalog["path"], timeout=20000) + assert response.status == 200 + assert len(response.body()) == catalog["bytes"] + assert hashlib.sha256(response.body()).hexdigest() == catalog["sha256"] + if os.environ.get("PCCMA_DASHBOARD_EVIDENCE") and prefix: + directory = Path(os.environ["PCCMA_DASHBOARD_EVIDENCE"]) + directory.mkdir(parents=True, exist_ok=True) + page.locator("details.provenance summary").click() + page.mouse.move(other["x"], other["y"]) + expect(page.locator("#hover-preview canvas")).to_have_count(1) + page.screenshot(path=str(directory / "live-mix-comparison.png"), full_page=True) + assert not errors + page.close() + diff --git a/7.dashboard/tests/test_web.mjs b/7.dashboard/tests/test_web.mjs index eaf891e..9185703 100644 --- a/7.dashboard/tests/test_web.mjs +++ b/7.dashboard/tests/test_web.mjs @@ -96,6 +96,61 @@ test('image slots clear stale pixels immediately and ignore late completions', ( update('assets/crops/../../bad.jpg', 'traversal'); assert.equal(requested.length, 2); }); +test('channel mix slot mixes grayscale layers, rejects incomplete selections and ignores stale loads', async () => { + assert.equal(typeof app.createChannelMixSlot, 'function'); + const requested = []; + function makeElement(tag) { + const element = { tagName: tag, textContent: '', attrs: {} }; + element.setAttribute = (key, value) => { element.attrs[key] = String(value); }; + element.getAttribute = key => element.attrs[key]; + if (tag === 'img') Object.defineProperty(element, 'src', { set(value) { requested.push(element); element.url = value; } }); + if (tag === 'canvas') element.getContext = () => new Proxy({}, { get: (t, k) => t[k] || (() => {}), set: (t, k, v) => { t[k] = v; return true; } }); + return element; + } + const document = { createElement: makeElement }; + const container = { children: [], replaceChildren(...children) { this.children = children; } }; + const update = app.createChannelMixSlot(document, container); + // No channels selected: a clear placeholder, no network request at all. + update({ type: 'none' }, 'nothing'); + assert.match(container.children[0].textContent, /select at least one channel/i); + assert.equal(requested.length, 0); + // A subset: live-mixed on a canvas once every selected channel has loaded. + update({ type: 'mix', layers: [ + { path: 'assets/crops/a.DNA.jpg', color: '#4d7cff' }, + { path: 'assets/crops/a.ER.jpg', color: '#3ad6b0' }, + ] }, 'DNA + ER mix'); + assert.equal(requested.length, 2); + assert.match(container.children[0].textContent, /Loading/); + requested[0].onload(); + requested[1].onload(); + await Promise.resolve(); await Promise.resolve(); + assert.equal(container.children[0].tagName, 'canvas'); + assert.equal(container.children[0].getAttribute('role'), 'img'); + assert.equal(container.children[0].getAttribute('aria-label'), 'DNA + ER mix'); + // A failed selected channel is explicit, never silently omitted from the mix. + update({ type: 'mix', layers: [ + { path: 'assets/crops/a.DNA.jpg', color: '#4d7cff' }, + { path: 'assets/crops/a.ER.jpg', color: '#3ad6b0' }, + ] }, 'partial mix'); + requested[2].onload(); + requested[3].onerror(); + await Promise.resolve(); await Promise.resolve(); + assert.match(container.children[0].textContent, /every selected channel/); + // Every selected channel fails: a clear error, not a blank canvas. + update({ type: 'mix', layers: [{ path: 'assets/crops/a.DNA.jpg', color: '#4d7cff' }] }, 'all missing'); + requested[4].onerror(); + await Promise.resolve(); await Promise.resolve(); + assert.match(container.children[0].textContent, /could not be loaded/i); + // Unsafe paths never reach the network, even inside a mix. + update({ type: 'mix', layers: [{ path: 'https://example.invalid/x.jpg', color: '#fff' }] }, 'unsafe'); + assert.equal(requested.length, 5); + assert.match(container.children[0].textContent, /unavailable/i); + update({ type: 'mix', layers: [{ path: 'assets/crops/old.DNA.jpg', color: '#4d7cff' }] }, 'old cell'); + update({ type: 'none' }, 'new selection'); + requested[5].onload(); + await Promise.resolve(); await Promise.resolve(); + assert.match(container.children[0].textContent, /Select at least one/); +}); test('static template inlines exactly one of each build placeholder without external dependencies', () => { const templatePath = new URL('../web/template.html', import.meta.url); assert.ok(existsSync(templatePath), 'template.html must exist'); @@ -131,16 +186,30 @@ function fixture(report) { const html = readFileSync(new URL('../web/template.html', import.meta.url), 'utf8'); const elements = new Map([...html.matchAll(/id="([^"]+)"/g)].map(([, id]) => [id, new Element(id === 'plot' ? 'canvas' : 'div')])); elements.get('report-data').textContent = typeof report === 'string' ? report : JSON.stringify(report); - elements.get('channel-select').value = 'all'; + for (const channel of ['DNA', 'ER', 'RNA', 'AGP', 'Mito']) elements.get('channel-toggle-' + channel).checked = true; elements.get('image-warning').hidden = true; elements.get('error-banner').hidden = true; - const document = { getElementById: id => elements.get(id), createElement: tag => new Element(tag) }; + const document = { + getElementById: id => elements.get(id), createElement: tag => new Element(tag), + createElementNS: (namespace, tag) => { const node = new Element(tag); node.namespaceURI = namespace; return node; }, + }; const window = { devicePixelRatio: 2, addEventListener() {} }; return { elements, document, window, imageRequests }; } +// Sets the final checked state of every channel checkbox, firing one 'change' +// event — mirrors a user settling on a selection after a few clicks. +function setChannels(f, names) { + let last = null; + for (const channel of ['DNA', 'ER', 'RNA', 'AGP', 'Mito']) { + const box = f.elements.get('channel-toggle-' + channel); + box.checked = names.includes(channel); + last = box; + } + last.emit('change'); +} const reportFixture = { schema_version: 1, plate: 'BR00150695', run_id: 'test-run', - summary: { warehouse_cells: 3, umap_cells: 3, excluded_umap_rows: 0, cell_lines: 3, cancer_groups: 2, crop_size: 224 }, + summary: { warehouse_cells: 3, umap_cells: 3, excluded_umap_rows: 0, cell_lines: 3, cancer_groups: 2, crop_size: 224, timepoints: [24] }, sources: { umap: { name: 'umap.parquet', sha256: '123' }, crop_index: { name: 'crops_index.parquet', sha256: '456' }, qc: 'Inherited QC.' }, images: { status: 'unavailable', message: 'Warehouse unavailable.', channels: ['composite', 'DNA', 'ER', 'RNA', 'AGP', 'Mito'] }, points: points.map(point => ({ ...point, tissue: 'test tissue', site: 1, cell: 2, nucleus: 3, time: 24, cx: 1.25, cy: 2.5, images: {} })), @@ -177,6 +246,76 @@ test('mounted dashboard initializes the first group, genuine pointer hover/pin a f.elements.get('unpin-cell').emit('click'); assert.equal(api.selectedPoint, null); }); +test('plate header and provenance mention the plate timepoint', () => { + const f = fixture(reportFixture); + app.mountDashboard(f.document, f.window); + assert.match(f.elements.get('plate-label').textContent, /Timepoint 24 h/); + const provenance = f.elements.get('provenance-metadata'); + const labels = provenance.children.filter((_, i) => i % 2 === 0).map(node => node.textContent); + const values = provenance.children.filter((_, i) => i % 2 === 1).map(node => node.textContent); + assert.equal(values[labels.indexOf('Timepoint(s)')], '24 h'); + const multi = fixture({ ...reportFixture, summary: { ...reportFixture.summary, timepoints: [24, 48] } }); + app.mountDashboard(multi.document, multi.window); + assert.match(multi.elements.get('plate-label').textContent, /Timepoints 24, 48 h/); +}); +test('the channel checkboxes drive both hover and pinned mixes', () => { + const bundled = structuredClone(reportFixture); + bundled.images.status = 'bundled'; + bundled.points[0].images = Object.fromEntries(['composite', 'DNA', 'ER', 'RNA', 'AGP', 'Mito'].map(channel => [channel, 'assets/crops/a.' + channel + '.jpg'])); + const f = fixture(bundled); + const api = app.mountDashboard(f.document, f.window); + const target = api.projection.forward(points[0]); + const canvas = f.elements.get('plot'); + canvas.emit('pointermove', { clientX: target.x, clientY: target.y, pointerType: 'mouse' }); + assert.equal(api.hoveredPoint.id, 'a'); + assert.equal(f.elements.get('hover-preview').hidden, false); + assert.equal(f.imageRequests.at(-1).url, 'assets/crops/a.Mito.jpg'); + setChannels(f, ['DNA']); + assert.equal(f.imageRequests.at(-1).url, 'assets/crops/a.DNA.jpg'); + assert.match(f.elements.get('hover-preview-title').textContent, /DNA/); + assert.equal(f.elements.get('crop-area').children.length, 2, 'the pinned/hover crop grid follows the same channel choice'); +}); +test('hovering a different cell still floats a comparison preview while one is pinned', () => { + const bundled = structuredClone(reportFixture); + bundled.images.status = 'bundled'; + for (const [id, point] of [['a', bundled.points[0]], ['b', bundled.points[1]]]) { + point.images = Object.fromEntries(['composite', 'DNA', 'ER', 'RNA', 'AGP', 'Mito'].map(channel => [channel, `assets/crops/${id}.${channel}.jpg`])); + } + const f = fixture(bundled); + const api = app.mountDashboard(f.document, f.window); + const canvas = f.elements.get('plot'); + const atA = api.projection.forward(points[0]); + canvas.emit('pointerdown', { clientX: atA.x, clientY: atA.y, pointerId: 1, button: 0 }); + canvas.emit('pointerup', { clientX: atA.x, clientY: atA.y, pointerId: 1 }); + assert.equal(api.selectedPoint.id, 'a'); + // Hovering the pinned cell itself adds nothing new; the floating preview stays hidden. + canvas.emit('pointermove', { clientX: atA.x, clientY: atA.y, pointerType: 'mouse' }); + assert.equal(f.elements.get('hover-preview').hidden, true); + // Hovering a different cell while pinned still floats its crop for comparison. + const atB = api.projection.forward(points[1]); + canvas.emit('pointermove', { clientX: atB.x, clientY: atB.y, pointerType: 'mouse' }); + assert.equal(f.elements.get('hover-preview').hidden, false); + assert.equal(f.imageRequests.at(-1).url, 'assets/crops/b.Mito.jpg'); + // The pinned inspector below still shows the pinned cell, not the hovered one. + assert.equal(f.elements.get('cell-id').textContent, 'a'); +}); +test('any subset including all five mixes live; empty selection has a clear placeholder', () => { + const bundled = structuredClone(reportFixture); + bundled.images.status = 'bundled'; + bundled.points[0].images = Object.fromEntries(['composite', 'DNA', 'ER', 'RNA', 'AGP', 'Mito'].map(channel => [channel, 'assets/crops/a.' + channel + '.jpg'])); + const f = fixture(bundled); + const api = app.mountDashboard(f.document, f.window); + api.hoverPoint('a'); + assert.equal(f.elements.get('crop-area').children[0].children[0].textContent, 'Live mix · DNA + ER + RNA + AGP + Mito'); + assert.equal(f.elements.get('crop-area').children.length, 6, 'main mix figure + all 5 channel thumbnails'); + setChannels(f, ['DNA', 'Mito']); + assert.equal(f.elements.get('crop-area').children[0].children[0].textContent, 'Live mix · DNA + Mito'); + assert.equal(f.elements.get('crop-area').children.length, 3, 'main mix figure + only the 2 picked channel thumbnails'); + assert.deepEqual(f.elements.get('crop-area').children.slice(1).map(fig => fig.children[0].textContent), ['DNA', 'Mito']); + setChannels(f, []); + assert.equal(f.elements.get('crop-area').children[0].children[0].textContent, 'No channels selected'); + assert.equal(f.elements.get('crop-area').children.length, 1, 'only the main placeholder figure, no channel thumbnails'); +}); test('mounted dashboard has readable malformed and empty payload states', () => { assert.equal(typeof app.mountDashboard, 'function'); const bad = fixture('{broken'); @@ -201,15 +340,14 @@ test('bundled report requests only real per-cell paths, renders composite plus a api.hoverPoint('a'); assert.equal(f.elements.get('inspector-title').textContent, malicious); assert.equal(f.elements.get('crop-area').children.length, 6); - assert.equal(f.imageRequests.length, 6); - assert.ok(f.imageRequests.every(image => image.url.startsWith('assets/crops/a.'))); - f.elements.get('channel-select').value = 'DNA'; - f.elements.get('channel-select').emit('change'); + assert.equal(f.imageRequests.length, 10); + assert.ok(f.imageRequests.every(image => image.url.startsWith('assets/crops/a.') && !image.url.endsWith('composite.jpg'))); + setChannels(f, ['DNA']); assert.equal(f.elements.get('crop-area').children.length, 2); - assert.equal(f.imageRequests.length, 8); - assert.equal(f.imageRequests[7].url, 'assets/crops/a.DNA.jpg'); + assert.equal(f.imageRequests.length, 11, 'decoded mix layers are shared across selections'); + assert.equal(f.imageRequests[10].url, 'assets/crops/a.DNA.jpg'); api.hoverPoint('b'); - assert.equal(f.imageRequests.length, 8, 'missing channel paths must not create requests'); + assert.equal(f.imageRequests.length, 11, 'missing channel paths must not create requests'); assert.match(f.elements.get('crop-area').children[0].children[1].children[0].textContent, /unavailable/i); }); test('wheel zoom anchors the cursor, drag pans without pinning, reset restores geometry, and keyboard selects', () => { diff --git a/7.dashboard/uv.lock b/7.dashboard/uv.lock index 8716c9d..657b55b 100644 --- a/7.dashboard/uv.lock +++ b/7.dashboard/uv.lock @@ -15,6 +15,28 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/d1/d6/3965ed04c63042e047cb6a3e6ed1a63a35087b6a609aa3a15ed8ac56c221/colorama-0.4.6-py2.py3-none-any.whl", hash = "sha256:4f1d9991f5acc0ca119f9d443620b77f9d6b33703e51011c16baf57afb285fc6", size = 25335, upload-time = "2022-10-25T02:36:20.889Z" }, ] +[[package]] +name = "duckdb" +version = "1.4.5" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/45/05/9e32eb606684bbfd739a757acfa887705930b84e5a598da6bb85c48eb35f/duckdb-1.4.5.tar.gz", hash = "sha256:783779bde612172b06c250b5f34f7fc29471833545f2894aadedbffbbcc49013", size = 18424446, upload-time = "2026-06-17T10:46:36.409Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/64/c5/0364355e4a25a1f2cb70a5a04d8caad7ee7e9b6b67b4a524b3fa53b3bfdc/duckdb-1.4.5-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:46eb53cd9ecec2972044a988be4a2e60d58cd185349d4a27f4944b8824d137af", size = 28924380, upload-time = "2026-06-17T10:44:51.456Z" }, + { url = "https://files.pythonhosted.org/packages/92/a3/7d74d0e3ee5a4396495c22551f9422543bb7ee324d24394adeae73b9ccf5/duckdb-1.4.5-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:14ee4000e879ce1f9a1a6dc08936cca5bfe0990b81e1b5a0466a746070bf1033", size = 15364409, upload-time = "2026-06-17T10:44:54.4Z" }, + { url = "https://files.pythonhosted.org/packages/81/ff/dfe91b05ac76b63f54e72a3b336f7c6800bb3f973fedf9466209053104c7/duckdb-1.4.5-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:58df29096a43c1ad29f0a323babe0de1c2e15b0921f7642a35b0e9b2e05a766a", size = 13681675, upload-time = "2026-06-17T10:44:57.22Z" }, + { url = "https://files.pythonhosted.org/packages/ce/5a/710056b19860f43bcdb6c4ad574fa012ac8488880d42cbf76c1b0690f0ba/duckdb-1.4.5-cp311-cp311-manylinux_2_26_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:326429624e488faecafcee8c1d02668bf424b144f1ac6ef8706028c439c3f5ab", size = 18448570, upload-time = "2026-06-17T10:45:00.186Z" }, + { url = "https://files.pythonhosted.org/packages/f3/b1/b9acfa09c7ed5e793f528886f9b7e207698d5cf1988b6e6a68a5bbcaffb4/duckdb-1.4.5-cp311-cp311-manylinux_2_26_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:45b6ac74a17a80d19e9da4b224115aac1ed691dcb56e271a88ee665c9e05c57a", size = 20448938, upload-time = "2026-06-17T10:45:03.33Z" }, + { url = "https://files.pythonhosted.org/packages/5c/7d/05cb1adf33606877865bccebcb517e26a2090e4d89e5b0fe804d31222256/duckdb-1.4.5-cp311-cp311-win_amd64.whl", hash = "sha256:00690b6aabd731144697a08bba16e35c748a3f06cefcc166ee8597159fc6bf6c", size = 12267440, upload-time = "2026-06-17T10:45:06.238Z" }, + { url = "https://files.pythonhosted.org/packages/9c/ec/e9d71c5213ede2a6c47e7c9f37044301e3e9b4be3a44c9f9d5b2ac2d15e8/duckdb-1.4.5-cp311-cp311-win_arm64.whl", hash = "sha256:00f0c430da0eff57d46a1c0fbc0d605ce66508fac0bc5c485067a19d8d4f0a2b", size = 13029594, upload-time = "2026-06-17T10:45:09.649Z" }, + { url = "https://files.pythonhosted.org/packages/8f/ac/b30b1ddf2a4948e520c99eeb868de3d5299c2ffdfb94ca8cac2203f092c9/duckdb-1.4.5-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:09823cdf26dd0aa99a4c23a47f2b0a29c285a68db7e075f8603b678d8a3ddeb6", size = 28967421, upload-time = "2026-06-17T10:45:13.277Z" }, + { url = "https://files.pythonhosted.org/packages/13/fe/06fcf75bb9b22221b6f2fbb0c5327670e36974d05d84c8e5a73a87676477/duckdb-1.4.5-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:c08999ed92ac66caecfc3945dd7184fdc145570e56ec5af6ec4dd84f1e1bab8c", size = 15388216, upload-time = "2026-06-17T10:45:16.374Z" }, + { url = "https://files.pythonhosted.org/packages/a8/f7/cb0c5e2ed724de27fdb945ff5101c48216afe1aacc1294462658bfa7676e/duckdb-1.4.5-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:07328a3e3a52221bd13c7dfc2f072be4fae84d42a5ef272d6fd497cda43e375f", size = 13705300, upload-time = "2026-06-17T10:45:19.184Z" }, + { url = "https://files.pythonhosted.org/packages/5b/a2/dbc65b784ee731e246fe5b3066b61aa0afe01dbf4927d3f2db97ced45d6f/duckdb-1.4.5-cp312-cp312-manylinux_2_26_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:0c72b1dcf27a71ef5f3dc14b92b9ed9274c5584bb0e88590b78907cbb8e254f3", size = 18476603, upload-time = "2026-06-17T10:45:22.906Z" }, + { url = "https://files.pythonhosted.org/packages/84/ef/f6fbb91cab7209acaffa1d861f54d67d55254d5c20d73191867a2f91d613/duckdb-1.4.5-cp312-cp312-manylinux_2_26_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:aa294d028c149ca21110e366eaffcb4fc9ab11d7d203d50f7bc49a07ab34b960", size = 20483899, upload-time = "2026-06-17T10:45:26.431Z" }, + { url = "https://files.pythonhosted.org/packages/ed/c0/cf35aeb21f9c94ec1fc409d21f746109959272356ee6a8b0479113f9eadc/duckdb-1.4.5-cp312-cp312-win_amd64.whl", hash = "sha256:6b8d992d957c89e83d697756f6c5b5aea910d6bf16e2666da4c508f891932ae2", size = 12279480, upload-time = "2026-06-17T10:45:29.201Z" }, + { url = "https://files.pythonhosted.org/packages/9c/c5/aef86244585028c344703d0bb7d23c0b7cc4d8f606e1e58fa8d43c61de6b/duckdb-1.4.5-cp312-cp312-win_arm64.whl", hash = "sha256:47d2a6cbf7ccb8723d716150a3aa6c22647177876278aa781bf843d649011e72", size = 13036352, upload-time = "2026-06-17T10:45:31.894Z" }, +] + [[package]] name = "greenlet" version = "3.5.6" @@ -157,6 +179,7 @@ name = "pccma-dashboard" version = "0.1.0" source = { virtual = "." } dependencies = [ + { name = "duckdb" }, { name = "pandas" }, { name = "pillow" }, { name = "pyarrow" }, @@ -170,6 +193,7 @@ dev = [ [package.metadata] requires-dist = [ + { name = "duckdb", specifier = "==1.4.5" }, { name = "pandas", specifier = "==2.2.3" }, { name = "pillow", specifier = "==12.3.0" }, { name = "pyarrow", specifier = "==22.0.0" }, diff --git a/7.dashboard/web/app.js b/7.dashboard/web/app.js index cda754c..9c3e8c0 100644 --- a/7.dashboard/web/app.js +++ b/7.dashboard/web/app.js @@ -1,6 +1,9 @@ /* PCCMA static dashboard. No network or library dependencies. */ (function () { 'use strict'; + const CHANNELS = ['DNA', 'ER', 'RNA', 'AGP', 'Mito']; + // Fixed pseudo-colors for exploration, not quantitative intensity measurements. + const CHANNEL_TINT = { DNA: '#4d7cff', ER: '#3ad6b0', RNA: '#ffd166', AGP: '#ff5fa2', Mito: '#ff6b4d' }; function category(point, colorBy) { return String(point[colorBy] ?? 'Unknown'); } @@ -89,6 +92,87 @@ image.src = path; }; } + function isSafeCropPath(path) { + return typeof path === 'string' && /^assets\/crops\/[A-Za-z0-9_./-]+\.jpg$/.test(path) && !path.split('/').includes('..'); + } + function loadImageElement(document, path) { + return new Promise(resolve => { + const image = document.createElement('img'); + image.decoding = 'async'; + image.onload = () => resolve(image); + image.onerror = () => resolve(null); + image.src = path; + }); + } + // Tint and add grayscale JPEGs without pixel readback, so downloaded reports + // also work via file://. All selections use the same display-only colors. + function createChannelMixSlot(document, container, loadImage = path => loadImageElement(document, path)) { + let revision = 0; + return function update(descriptor, description) { + const current = ++revision; + const status = document.createElement('p'); + status.className = 'image-status'; + if (!descriptor || descriptor.type === 'none') { + status.textContent = 'Select at least one channel to preview.'; + container.replaceChildren(status); + return; + } + const layers = descriptor.layers ?? []; + if (!layers.length || layers.some(layer => !isSafeCropPath(layer.path))) { + status.textContent = 'Image unavailable for this cell.'; + status.className = 'image-status image-error'; + container.replaceChildren(status); + return; + } + status.textContent = 'Loading image…'; + container.replaceChildren(status); + Promise.all(layers.map(layer => loadImage(layer.path))).then(images => { + if (revision !== current) return; + const loaded = images.map((image, index) => image && { image, color: layers[index].color }).filter(Boolean); + if (loaded.length !== layers.length) { + status.textContent = 'Image could not be loaded for every selected channel. ' + description; + status.className = 'image-status image-error'; + container.replaceChildren(status); + return; + } + const size = loaded[0].image.naturalWidth || 224; + const mix = document.createElement('canvas'); + mix.width = size; mix.height = size; + const ctx = mix.getContext('2d'); + if (!ctx) { + status.textContent = 'Channel mixing is unavailable in this browser.'; + status.className = 'image-status image-error'; + container.replaceChildren(status); + return; + } + { + ctx.fillStyle = '#000'; ctx.fillRect(0, 0, size, size); + for (const { image, color } of loaded) { + // Multiply tints the grayscale pixels without losing intensity, + // then "lighter" (additive) stacks each tinted channel together. + const layer = document.createElement('canvas'); + layer.width = size; layer.height = size; + const layerCtx = layer.getContext('2d'); + if (!layerCtx) { + status.textContent = 'Channel mixing is unavailable in this browser.'; + status.className = 'image-status image-error'; + container.replaceChildren(status); + return; + } + layerCtx.drawImage(image, 0, 0, size, size); + layerCtx.globalCompositeOperation = 'multiply'; + layerCtx.fillStyle = color; + layerCtx.fillRect(0, 0, size, size); + ctx.globalCompositeOperation = 'lighter'; + ctx.drawImage(layer, 0, 0); + } + } + mix.setAttribute('role', 'img'); + mix.setAttribute('aria-label', description); + container.replaceChildren(mix); + }); + }; + } function mountDashboard(document, window) { const $ = id => document.getElementById(id); const element = (tag, text, className) => { @@ -118,8 +202,9 @@ const byId = new Map(points.map(point => [point.id, point])); const groups = [...new Set(points.map(point => point.group))]; const number = value => Number.isFinite(value) ? value.toLocaleString('en-US') : 'Not recorded'; - const channels = ['DNA', 'ER', 'RNA', 'AGP', 'Mito']; + const channels = CHANNELS; const bundled = data.images?.status === 'bundled'; + $('catalog-download').hidden = data.catalog?.path !== 'data/pilot.duckdb'; const palette = ['#73b9d7', '#eba16d', '#9dc88c', '#c6a0d8', '#e3859d', '#6ec8ba', '#d5c575', '#95a1e1', '#d7ad91', '#88b7a2', '#c2b6e8', '#d7a8bf', '#8cc8d1', '#b6c079']; let state = createState(points), visible = [], projection; let view = { zoom: 1, panX: 0, panY: 0 }; @@ -129,7 +214,11 @@ // after viewport changes; the small point clouds do not need GPU backing. const ctx = canvas.getContext('2d', { willReadFrequently: true }); if (!ctx) return fail(new Error('Canvas rendering is not supported by this browser.')); - $('plate-label').textContent = 'Plate ' + (data.plate ?? 'not recorded') + ' · exact crop-key joins · published post-QC cells'; + const timepoints = Array.isArray(data.summary?.timepoints) ? data.summary.timepoints : []; + const timepointLabel = timepoints.length === 1 ? `Timepoint ${timepoints[0]} h` + : timepoints.length > 1 ? `Timepoints ${timepoints.join(', ')} h` : null; + $('plate-label').textContent = 'Plate ' + (data.plate ?? 'not recorded') + ' · exact crop-key joins · published post-QC cells' + + (timepointLabel ? ' · ' + timepointLabel : ''); const summaries = [[points.length, 'plotted cells'], [new Set(points.map(point => point.line)).size, 'cell lines'], [groups.length, 'cancer groups'], [data.summary?.warehouse_cells, 'warehouse cells']]; for (const [count, label] of summaries) { const item = element('div', undefined, 'summary-item'); @@ -153,6 +242,7 @@ for (const [key, value] of [ ['Plate', data.plate], ['Extraction run', data.run_id], ['Warehouse cells', number(data.summary?.warehouse_cells)], ['Displayed cells', number(points.length)], ['Excluded UMAP rows', number(data.summary?.excluded_umap_rows)], + ['Timepoint(s)', timepoints.length ? timepoints.join(', ') + ' h' : null], ['UMAP source', data.sources?.umap?.name], ['UMAP SHA-256', data.sources?.umap?.sha256], ['Crop index', data.sources?.crop_index?.name], ['Crop-index SHA-256', data.sources?.crop_index?.sha256], ['QC membership', data.sources?.qc], ['Images', data.images?.status], ['Image details', data.images?.message], @@ -211,18 +301,70 @@ $('zoom-in').disabled = view.zoom >= 20; $('zoom-out').disabled = view.zoom <= 0.5; } + const hoverPreview = $('hover-preview'); + const channelCheckbox = name => $('channel-toggle-' + name); + function selectedChannels() { return channels.filter(name => channelCheckbox(name).checked); } + // Bound decoded-image memory while reusing layers between hover and pin. + const imageCache = new Map(); + function loadChannelImage(path) { + if (imageCache.has(path)) return imageCache.get(path); + const pending = loadImageElement(document, path).then(image => { + if (!image && imageCache.get(path) === pending) imageCache.delete(path); + return image; + }); + imageCache.set(path, pending); + if (imageCache.size > 50) imageCache.delete(imageCache.keys().next().value); + return pending; + } + function mixDescriptor(point, chosen) { + if (!chosen.length) return { type: 'none' }; + return { type: 'mix', layers: chosen.map(name => ({ path: point.images?.[name], color: CHANNEL_TINT[name] })) }; + } + function channelLabel(chosen) { + return chosen.length ? chosen.join(' + ') : 'No channel selected'; + } + const updateHoverImage = createChannelMixSlot(document, $('hover-preview-image'), loadChannelImage); + let hoverPreviewKey = null; + function hideHoverPreview() { + hoverPreview.hidden = true; + hoverPreviewKey = null; + } + function updateHoverContent(point) { + const chosen = selectedChannels(); + const key = point.id + ':' + chosen.join(','); + if (key === hoverPreviewKey) return; + hoverPreviewKey = key; + const label = channelLabel(chosen); + $('hover-preview-title').textContent = point.line + ' · ' + point.well + ' / ' + point.site + ' · ' + label; + updateHoverImage(mixDescriptor(point, chosen), label + ' crop · ' + point.id); + } + function showHoverPreview(point, event) { + if (!point || !bundled || point.id === state.selectedId) { hideHoverPreview(); return; } + updateHoverContent(point); + hoverPreview.hidden = false; + const rect = hoverPreview.getBoundingClientRect(); + const margin = 8, gap = 14; + const left = event.clientX + gap + rect.width <= window.innerWidth - margin + ? event.clientX + gap : event.clientX - rect.width - gap; + const top = event.clientY + gap + rect.height <= window.innerHeight - margin + ? event.clientY + gap : event.clientY - rect.height - gap; + hoverPreview.style.left = Math.max(margin, Math.min(left, window.innerWidth - rect.width - margin)) + 'px'; + hoverPreview.style.top = Math.max(margin, Math.min(top, window.innerHeight - rect.height - margin)) + 'px'; + } function renderInspector(force = false) { + if (!state.hoveredId || state.hoveredId === state.selectedId) hideHoverPreview(); const point = byId.get(state.selectedId ?? state.hoveredId); - const key = (point?.id ?? '') + ':' + $('channel-select').value + ':' + Boolean(state.selectedId); + const chosen = selectedChannels(); + const key = (point?.id ?? '') + ':' + chosen.join(',') + ':' + Boolean(state.selectedId); if (!force && key === lastInspectorKey) return; lastInspectorKey = key; $('pin-status').textContent = state.selectedId ? 'Pinned' : 'Unpinned'; $('pin-status').className = state.selectedId ? 'badge pinned' : 'badge'; $('unpin-cell').disabled = !state.selectedId; $('previous-cell').disabled = !visible.length; $('next-cell').disabled = !visible.length; - $('channel-select').disabled = !bundled || !point; + for (const name of channels) channelCheckbox(name).disabled = !bundled; $('inspector-title').textContent = point ? point.line ?? 'Cell preview' : 'Point preview'; - $('inspector-hint').textContent = state.selectedId ? 'Pinned cell. Unpin to resume hover previews; use Previous / Next to browse visible cells.' : 'Hover a point to inspect its extracted cell crop. Click or tap to keep it here.'; + $('inspector-hint').textContent = state.selectedId ? 'Pinned cell. Hover another point to compare it in the floating preview; use Previous / Next to browse visible cells.' : 'Hover a point to inspect its extracted cell crop. Click or tap to keep it here.'; $('cell-id').textContent = point?.id ?? 'No cell selected'; $('cell-metadata').replaceChildren(); $('crop-area').replaceChildren(); @@ -240,10 +382,15 @@ $('crop-area').append(element('p', 'Crops unavailable. This diagnostic report contains cell coordinates and metadata only; no real images have been loaded.', 'crop-placeholder')); return; } - const chosen = $('channel-select').value; - for (const channel of ['composite', ...(chosen === 'all' ? channels : channels.filter(channel => channel === chosen))]) { - const figure = element('figure', undefined, 'crop-figure' + (channel === 'composite' ? ' composite' : '')); - const caption = element('figcaption', channel === 'composite' ? 'Composite · five-channel overlay' : channel); + const label = channelLabel(chosen); + const mainFigure = element('figure', undefined, 'crop-figure composite'); + const mainCaption = element('figcaption', chosen.length ? 'Live mix · ' + label : 'No channels selected'); + const mainFrame = element('div', undefined, 'image-frame'); + mainFigure.append(mainCaption, mainFrame); $('crop-area').append(mainFigure); + createChannelMixSlot(document, mainFrame, loadChannelImage)(mixDescriptor(point, chosen), label + ' crop · ' + point.id); + for (const channel of chosen) { + const figure = element('figure', undefined, 'crop-figure'); + const caption = element('figcaption', channel); const frame = element('div', undefined, 'image-frame'); figure.append(caption, frame); $('crop-area').append(figure); createImageSlot(document, frame)(point.images?.[channel], channel + ' crop · ' + point.id); @@ -284,7 +431,12 @@ function reset() { view = { zoom: 1, panX: 0, panY: 0 }; draw(); } groupSelect.addEventListener('change', () => { reset(); dispatch({ type: 'group', value: groupSelect.value }); }); $('color-select').addEventListener('change', () => dispatch({ type: 'color', value: $('color-select').value })); - $('channel-select').addEventListener('change', () => renderInspector(true)); + for (const name of channels) { + channelCheckbox(name).addEventListener('change', () => { + renderInspector(true); + if (hoverPreviewKey !== null) updateHoverContent(byId.get(state.hoveredId)); + }); + } $('previous-cell').addEventListener('click', () => dispatch({ type: 'step', direction: -1 })); $('next-cell').addEventListener('click', () => dispatch({ type: 'step', direction: 1 })); $('unpin-cell').addEventListener('click', () => dispatch({ type: 'unpin' })); @@ -307,6 +459,7 @@ const point = nearestPoint(visible, at, projection, 10); if ((point?.id ?? null) !== state.hoveredId) dispatch({ type: 'hover', id: point?.id }); canvas.style.cursor = point ? 'pointer' : 'crosshair'; + showHoverPreview(point, event); } }); canvas.addEventListener('pointerup', event => { @@ -340,7 +493,7 @@ refreshFilters(); resize(); return api; } - const helpers = { category, filterPoints, groupBounds, createProjection, nearestPoint, createState, reduceState, createImageSlot, mountDashboard }; + const helpers = { category, filterPoints, groupBounds, createProjection, nearestPoint, createState, reduceState, createImageSlot, createChannelMixSlot, mountDashboard, CHANNELS, CHANNEL_TINT }; if (typeof module !== 'undefined' && module.exports) module.exports = helpers; if (typeof document !== 'undefined' && typeof window !== 'undefined') mountDashboard(document, window); })(); diff --git a/7.dashboard/web/style.css b/7.dashboard/web/style.css index 6697f66..fb8db6d 100644 --- a/7.dashboard/web/style.css +++ b/7.dashboard/web/style.css @@ -1 +1,25 @@ :root{color-scheme:dark;--bg:#101419;--panel:#171d24;--plot:#11171e;--border:#303b48;--text:#e5ebf1;--muted:#a0aebd;--accent:#78c6bc;--warning:#f2cb88;font-family:ui-sans-serif,system-ui,-apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif;font-size:14px;line-height:1.5}*{box-sizing:border-box}body{margin:0;background:var(--bg);color:var(--text)}[hidden]{display:none!important}button,select{font:inherit}button,select{color:var(--text);background:#1d2630;border:1px solid #475566;border-radius:5px;min-height:36px}button{padding:6px 11px;cursor:pointer}button:hover{background:#2a3845;border-color:#a0aebd}button:disabled{opacity:.45;cursor:default}button:focus-visible,select:focus-visible,summary:focus-visible,a:focus-visible,canvas:focus-visible{outline:3px solid var(--accent);outline-offset:3px}a{color:inherit}h1,h2,h3,p{margin:0}h1{font-size:clamp(23px,2.3vw,33px);font-weight:650;letter-spacing:-.035em;line-height:1.25}h1 a{text-decoration:none}h1 a span{font-size:.65em;color:var(--muted);vertical-align:middle}h1 a:hover{color:var(--accent)}h2{font-size:17px;font-weight:600}h3{font-size:13px;font-weight:600}.page-header{max-width:1700px;margin:auto;display:flex;align-items:center;justify-content:space-between;gap:24px;padding:30px 30px 23px}.eyebrow{color:var(--accent);font-size:10px;letter-spacing:.13em;text-transform:uppercase;font-weight:650;margin-bottom:8px}.subtitle{font-size:12px;color:var(--muted);margin-top:8px}.summary{display:flex;gap:28px}.summary-item{display:flex;flex-direction:column}.summary-value{font-size:24px;line-height:1.15;font-variant-numeric:tabular-nums;font-weight:600;letter-spacing:-.035em}.summary-label{font-size:11px;color:var(--muted);margin-top:5px}main{max-width:1700px;margin:auto;padding:0 30px}.banner{padding:14px 18px;border:1px solid;border-radius:6px;margin-bottom:18px;font-size:13px}.warning{color:#ffe0ac;background:#30271c;border-color:#85683e}.error{color:#ffd0cf;background:#361e24;border-color:#925362}.workspace{display:grid;grid-template-columns:minmax(0,1fr) 360px;gap:18px;align-items:start}.plot-panel,.inspector{border:1px solid var(--border);border-radius:8px;background:var(--panel);overflow:hidden}.toolbar{display:flex;align-items:end;gap:14px;padding:17px 19px;border-bottom:1px solid var(--border);flex-wrap:wrap}label{display:flex;flex-direction:column;gap:5px;font-size:11px;color:var(--muted);font-weight:550;letter-spacing:.015em}select{padding:6px 30px 6px 10px;max-width:100%;font-size:13px;font-weight:400;letter-spacing:normal}.toolbar label:first-child{flex:1;min-width:160px}.zoom-controls{display:flex;align-items:center;gap:5px;margin-left:auto}.zoom-controls button{min-width:36px}.zoom-controls output{width:43px;text-align:center;font-size:11px;color:var(--muted);font-variant-numeric:tabular-nums}.zoom-controls #reset-view{font-size:11px;margin-left:4px}.plot-heading{display:flex;justify-content:space-between;align-items:center;gap:10px;padding:15px 20px 0}.plot-heading p{font-size:11px;color:var(--muted);font-variant-numeric:tabular-nums}.plot-wrap{position:relative;height:clamp(440px,62vh,760px);background:var(--plot);margin:12px 12px 0;border:1px solid #283440;border-radius:4px;overflow:hidden}canvas{display:block;width:100%;height:100%;touch-action:none;cursor:crosshair}.axis-label{position:absolute;color:#8191a3;font-size:10px;letter-spacing:.08em;pointer-events:none}.axis-x{bottom:10px;left:50%;transform:translateX(-50%)}.axis-y{top:50%;left:10px;writing-mode:vertical-rl;transform:rotate(180deg)}.plot-annotation{position:absolute;right:13px;bottom:10px;font-size:10px;color:#8191a3;pointer-events:none}.empty-state{position:absolute;inset:0;display:grid;place-content:center;text-align:center;padding:30px;color:var(--muted);pointer-events:none}.plot-footer{padding:11px 20px 15px;color:var(--muted);font-size:11px}.microcopy{font-size:11px;color:var(--muted);line-height:1.6}.plot-footer .microcopy{margin-top:3px}.legend-heading{padding:12px 20px 7px;border-top:1px solid var(--border);display:flex;align-items:center;justify-content:space-between;gap:12px}.legend-heading span{font-size:10px;color:var(--muted)}.legend{display:flex;flex-wrap:wrap;gap:7px;padding:0 19px 17px;max-height:200px;overflow:auto}.legend button{font-size:11px;display:flex;align-items:center;gap:7px;min-height:30px;padding:4px 8px;background:transparent}.legend button[aria-pressed=false]{opacity:.45;text-decoration:line-through}.swatch{width:8px;height:8px;border-radius:50%;flex:none}.legend-count{color:var(--muted);font-variant-numeric:tabular-nums}.inspector{padding:19px;position:sticky;top:16px}.inspector-heading{display:flex;justify-content:space-between;align-items:center;gap:12px}.inspector-heading .eyebrow{margin-bottom:4px}.badge{padding:3px 8px;border:1px solid var(--border);border-radius:20px;font-size:10px;color:var(--muted)}.badge.pinned{color:var(--accent);border-color:#4c8179}.inspector-hint{font-size:11px;color:var(--muted);margin:14px 0}.cell-navigation{display:flex;gap:6px;margin-bottom:15px}.cell-navigation button{font-size:11px;min-height:32px;padding:5px 8px}.cell-navigation button:last-child{margin-left:auto}.cell-id{font-family:ui-monospace,SFMono-Regular,Consolas,monospace;font-size:10px;overflow-wrap:anywhere;background:#11171e;border:1px solid #283440;padding:9px;border-radius:4px}.metadata{display:grid;grid-template-columns:auto 1fr;gap:5px 13px;font-size:11px;margin:14px 0;min-height:90px}.metadata dt{color:var(--muted)}.metadata dd{margin:0;text-align:right;overflow-wrap:anywhere}.crop-area{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:8px}.crop-placeholder{grid-column:1/-1;min-height:224px;display:grid;place-content:center;padding:20px;text-align:center;font-size:12px;color:var(--muted);border:1px dashed var(--border);border-radius:4px}.crop-figure{margin:0;min-width:0}.crop-figure.composite{grid-column:1/-1}.crop-figure figcaption{display:flex;align-items:center;justify-content:space-between;margin-bottom:5px;color:var(--muted);font-size:10px}.image-frame{aspect-ratio:1;background:#090d11;border:1px solid #283440;display:grid;place-items:center;overflow:hidden;border-radius:3px}.image-frame img{display:block;width:100%;height:100%;object-fit:contain}.composite .image-frame{width:min(100%,280px);margin:0 auto}.image-status{font-size:10px;line-height:1.4;text-align:center;padding:7px;color:var(--muted);overflow-wrap:anywhere}.image-error{color:#ffb7b0}.channel-controls{margin-top:13px}.channel-controls label{flex-direction:row;justify-content:space-between;align-items:center}.channel-controls select{font-size:11px;max-width:170px}.crop-note{margin-top:12px;font-size:10px}.provenance{margin-top:20px;border-top:1px solid var(--border);font-size:12px;color:var(--muted)}.provenance summary{padding:14px 0;cursor:pointer;color:var(--text);font-size:12px}.provenance-body{max-width:1000px;line-height:1.7;padding-bottom:14px}.provenance-body p{margin-bottom:10px}.provenance-metadata{display:grid;grid-template-columns:120px 1fr;gap:7px 15px;font-size:11px}.provenance-metadata dd{margin:0;overflow-wrap:anywhere;font-family:ui-monospace,SFMono-Regular,Consolas,monospace}.page-footer{max-width:1700px;margin:auto;padding:10px 30px 24px;font-size:10px;color:#8797a8}.skip-link{position:absolute;top:-100px;left:20px;padding:10px;z-index:10;background:var(--panel)}.skip-link:focus{top:10px}@media(min-width:1500px){.workspace{grid-template-columns:minmax(0,1fr) 400px}}@media(max-width:1080px){.workspace{grid-template-columns:minmax(0,1fr) 310px}.toolbar{gap:9px}.zoom-controls{margin-left:0}.summary{gap:17px}.summary-value{font-size:21px}.inspector{padding:15px}.crop-area{grid-template-columns:repeat(2,minmax(0,1fr))}}@media(max-width:800px){.page-header{align-items:start;flex-direction:column;gap:20px;padding:24px 17px 20px}.summary{width:100%;justify-content:space-between;gap:12px}.summary-label{font-size:10px}.workspace{grid-template-columns:1fr}.inspector{position:static;padding:18px}.crop-area{grid-template-columns:repeat(5,minmax(0,1fr))}.composite .image-frame{width:min(100%,280px)}main{padding:0 14px}.plot-wrap{height:480px}.plot-heading{align-items:start}.plot-heading p{text-align:right}.legend-heading{align-items:start}.page-footer{padding:15px}.provenance-metadata{grid-template-columns:95px 1fr}}@media(max-width:480px){.toolbar{padding:14px;gap:11px}.toolbar label:first-child{min-width:150px}.plot-wrap{height:420px;margin:10px 8px 0}.plot-heading{padding:14px 14px 0}.plot-heading h2{font-size:15px}.plot-heading p{font-size:10px}.plot-footer{padding:11px 14px 14px}.plot-annotation{display:none}.crop-area{grid-template-columns:repeat(3,minmax(0,1fr))}.legend-heading{padding-left:14px;padding-right:14px}.legend{padding-left:13px;padding-right:13px}.summary{flex-wrap:wrap}.summary-value{font-size:21px}.legend-heading span{max-width:115px}.channel-controls select{max-width:160px}} + +/* Keep the hover crop visible even when the detailed inspector is below the fold. */ +.hover-preview{position:fixed;z-index:30;pointer-events:none;width:210px;max-width:calc(100vw - 16px);padding:10px;background:#171d24;border:1px solid #78c6bc;border-radius:7px;box-shadow:0 8px 28px #0008} +.hover-preview-title{font-size:12px;font-weight:600;overflow-wrap:anywhere;margin-bottom:8px} +.hover-preview-frame{width:100%;aspect-ratio:1;background:#080b0f;display:grid;place-items:center;overflow:hidden} +.hover-preview-frame img{display:block;width:100%;height:100%;object-fit:contain} +.hover-preview-frame .image-status{padding:8px;font-size:12px;text-align:left} +.hover-preview-hint{font-size:11px;line-height:1.4;color:var(--muted);margin-top:8px} + +/* The shared mixer remains reachable before selecting or pinning a cell. */ +.channel-controls{margin:0 0 16px;border:1px solid var(--border);border-radius:6px;padding:8px 14px 12px} +.channel-controls legend{font-size:12px;color:var(--muted);padding:0 6px} +.channel-controls #channel-help{margin-top:8px} +.channel-toggles{display:flex;flex-wrap:wrap;gap:10px} +.channel-controls .channel-toggle{display:flex;flex-direction:row;justify-content:flex-start;align-items:center;gap:5px;font-size:12px;cursor:pointer;min-height:28px} +.channel-toggle input{margin:0;cursor:pointer} +.channel-toggle input:disabled,.channel-toggle input:disabled+.swatch{cursor:default;opacity:.5} +.channel-toggle .swatch{width:9px;height:9px;border-radius:50%;flex:none} +.swatch[data-channel="DNA"]{background:#4d7cff} +.swatch[data-channel="ER"]{background:#3ad6b0} +.swatch[data-channel="RNA"]{background:#ffd166} +.swatch[data-channel="AGP"]{background:#ff5fa2} +.swatch[data-channel="Mito"]{background:#ff6b4d} +.crop-figure.composite canvas,.hover-preview-frame canvas{display:block;width:100%;height:100%} diff --git a/7.dashboard/web/template.html b/7.dashboard/web/template.html index b384e7c..d39e7b4 100644 --- a/7.dashboard/web/template.html +++ b/7.dashboard/web/template.html @@ -16,6 +16,13 @@
+
Image channels · hover & pinned cell
+ + + + + +

Choose any combination. Both images mix the selected grayscale channels live using these colors.

@@ -41,14 +48,18 @@

No cell selected

Select a cell to view its images.

-
-

224 × 224 px crops · JPEG quality 95 visual derivatives, not quantitative intensity measurements.

+

224 × 224 px crops · JPEG quality 95 visual derivatives, not quantitative intensity measurements. Live mixes use fixed display colors; the original warehouse composite is retained in the downloadable assets.

-
Data provenance & interpretation

This is a single-plate subset of the existing all-timepoint UMAP, not an embedding refit on the selected plate. Original UMAP coordinates were computed independently within each cancer group across nine plates. Distances across cancer-group UMAPs are not comparable.

The published sampling selected 500 cells per cell line per plate after QC. Only exact crop-key matches for this plate are displayed; no other-plate or background points are included.

+
Data provenance & interpretation

This is a single-plate subset of the existing all-timepoint UMAP, not an embedding refit on the selected plate. Original UMAP coordinates were computed independently within each cancer group across nine plates. Distances across cancer-group UMAPs are not comparable.

The published sampling selected 500 cells per cell line per plate after QC. Only exact crop-key matches for this plate are displayed; no other-plate or background points are included.

+ From 93625296770ba1410d8d1a1b3111aa34a8d1194d Mon Sep 17 00:00:00 2001 From: d33bs Date: Mon, 16 Nov 2026 21:54:26 -0700 Subject: [PATCH 5/6] add github pages deploy for pilot dashboard --- .github/workflows/dashboard-pages.yml | 119 +++++ 7.dashboard/DEPLOYMENT.md | 190 ++++++++ 7.dashboard/README.md | 16 +- 7.dashboard/pages.py | 542 +++++++++++++++++++++ 7.dashboard/pilot-provenance.json | 75 +++ 7.dashboard/pilot-source.json | 20 + 7.dashboard/tests/test_pages.py | 674 ++++++++++++++++++++++++++ 7.dashboard/tests/test_real_bundle.py | 11 +- 8 files changed, 1643 insertions(+), 4 deletions(-) create mode 100644 .github/workflows/dashboard-pages.yml create mode 100644 7.dashboard/DEPLOYMENT.md create mode 100644 7.dashboard/pages.py create mode 100644 7.dashboard/pilot-provenance.json create mode 100644 7.dashboard/pilot-source.json create mode 100644 7.dashboard/tests/test_pages.py diff --git a/.github/workflows/dashboard-pages.yml b/.github/workflows/dashboard-pages.yml new file mode 100644 index 0000000..2b24f31 --- /dev/null +++ b/.github/workflows/dashboard-pages.yml @@ -0,0 +1,119 @@ +name: Dashboard Pages + +"on": + pull_request: + branches: [main] + paths: + - "7.dashboard/**" + - ".github/workflows/dashboard-pages.yml" + push: + branches: [main] + paths: + - "7.dashboard/**" + - ".github/workflows/dashboard-pages.yml" + workflow_dispatch: + +permissions: + contents: read + +concurrency: + group: dashboard-pages-${{ github.ref }} + cancel-in-progress: false + +jobs: + test: + name: Dashboard tests + runs-on: ubuntu-24.04 + timeout-minutes: 15 + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + - uses: astral-sh/setup-uv@68559e99cc807c1eb7e9238fd43a15bba460eec2 # v10.3.3 + with: + version: "0.11.19" + python-version: "3.12" + enable-cache: false + - uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0 + with: + node-version: "24" + package-manager-cache: false + - name: Install locked dependencies and Chromium + run: | + uv sync --project 7.dashboard --locked + uv run --project 7.dashboard --locked playwright install --with-deps chromium + - name: Test exporter, input packaging and browser channel mixing + run: | + uv run --project 7.dashboard --locked python -m pytest 7.dashboard/tests -q + node --test 7.dashboard/tests/test_web.mjs + + build: + name: Build verified pilot + needs: test + runs-on: ubuntu-24.04 + timeout-minutes: 20 + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + - uses: astral-sh/setup-uv@68559e99cc807c1eb7e9238fd43a15bba460eec2 # v10.3.3 + with: + version: "0.11.19" + python-version: "3.12" + enable-cache: false + - name: Install locked dependencies and Chromium + run: | + uv sync --project 7.dashboard --locked + uv run --project 7.dashboard --locked playwright install --with-deps chromium + - name: Download and verify pinned public pilot inputs + run: | + uv run --project 7.dashboard --locked python 7.dashboard/pages.py stage \ + --config 7.dashboard/pilot-source.json \ + --output "$RUNNER_TEMP/pccma-pilot-inputs" + - name: Build from checked-out code and immutable inputs + run: | + uv run --project 7.dashboard --locked python 7.dashboard/pages.py build \ + --config 7.dashboard/pilot-source.json \ + --inputs "$RUNNER_TEMP/pccma-pilot-inputs" \ + --output 7.dashboard/dist/pages + - name: Verify every original image and real pilot browser interactions + env: + PCCMA_DASHBOARD_BUNDLE: ${{ github.workspace }}/7.dashboard/dist/pages + PCCMA_DASHBOARD_SOURCE_HASHES: ${{ runner.temp }}/pccma-pilot-inputs/warehouse/jpg-sha256.txt.gz + run: | + uv run --project 7.dashboard --locked python -m pytest \ + 7.dashboard/tests/test_real_bundle.py -q + - name: Upload complete Pages site + if: >- + github.repository == 'WayScience/pccma' && + github.ref == 'refs/heads/main' && + github.event_name != 'pull_request' + uses: actions/upload-pages-artifact@fc324d3547104276b827a68afc52ff2a11cc49c9 # v5.0.0 + with: + path: 7.dashboard/dist/pages + include-hidden-files: true + retention-days: 1 + + deploy: + name: Deploy dashboard + if: >- + github.repository == 'WayScience/pccma' && + github.ref == 'refs/heads/main' && + github.event_name != 'pull_request' + needs: build + runs-on: ubuntu-24.04 + timeout-minutes: 10 + permissions: + pages: write + id-token: write + environment: + name: github-pages + url: ${{ steps.deployment.outputs.page_url }} + steps: + - name: Check Pages configuration + uses: actions/configure-pages@45bfe0192ca1faeb007ade9deae92b16b8254a0d # v6.0.0 + with: + enablement: false + - name: Deploy tested site + id: deployment + uses: actions/deploy-pages@368f82528645a54fb793d4d04e342629a3f51346 # v5.0.1 diff --git a/7.dashboard/DEPLOYMENT.md b/7.dashboard/DEPLOYMENT.md new file mode 100644 index 0000000..911e7a1 --- /dev/null +++ b/7.dashboard/DEPLOYMENT.md @@ -0,0 +1,190 @@ +# Deploy the pilot dashboard on merge + +## What happens automatically + +`.github/workflows/dashboard-pages.yml` runs when dashboard or workflow files +change in a pull request to `main`, when those changes land on `main`, and on +manual dispatch. + +1. Run the exporter, input-packaging and browser fixture tests plus JavaScript + tests with the locked dashboard environment. +2. Download the public pilot-input archive pinned by URL, exact byte count and + SHA-256 in `pilot-source.json`. Reject missing, changed, unsafe or incomplete + inputs; do not fall back to synthetic images or a coordinate-only report. +3. Build a fresh report from the checked-out Python, HTML, JavaScript and CSS. + The input archive contains public report-input tables and original JPEGs, + **not a prebuilt page**. + Changes to channel controls therefore reach the deployed site on the next + merge without republishing the image data. +4. Check every bundled JPEG against the original warehouse hashes and test the + real pilot in Chromium, including hover/pin channel mixing, root and project + URLs, mobile/file viewing, and the DuckDB catalog download. +5. On `WayScience/pccma`'s `main` only, upload the complete generated directory + and deploy it to the `github-pages` environment. Pull requests build and test + the same pilot but cannot publish it. A failed test/build blocks deployment. + +The workflow uses no SSH access to Willow/bandicoot, local crop cache, PAT or +custom repository secrets. Its default permission is `contents: read`; only the +separate deployment job receives `pages: write` and `id-token: write`. Action +revisions are pinned to verified commit SHAs. No generated image tree, database +or archive should be committed to Git. + +## One-time maintainer setup before merging + +### 1. Publish the immutable input asset + +Publishing the input archive makes the selected cell images public. Obtain the +normal dataset/publication approval before this step. + +The prepared upload file (415,035,598 bytes) is: + +```text +7.dashboard/dist/pilot-inputs.tar.gz +``` + +Public Parquet inputs retain all original rows and exact report-required values, +but omit unused source-directory columns and table attributes that could disclose +private HPC paths. `pilot-provenance.json` records the original and public input +hashes and omitted columns. Original JPEGs and the compressed JPEG hash list are +unchanged. The original private input files are not modified. + +This is a **different artifact** from the earlier `BR00150695-pages-pilot-v4.zip`. +The ZIP is a rendered report for manual viewing; CI needs the public input +archive so it can build the latest application code. + +Upload `pilot-inputs.tar.gz` to a **published, non-draft GitHub Release** with tag +`dashboard-pilot-BR00150695-v1` in `WayScience/pccma`. Keep the filename unchanged. +The release's tag is a data-snapshot identifier, not an application version. +From the repository root, an authenticated maintainer can do this with: + +```bash +gh release create dashboard-pilot-BR00150695-v1 \ + 7.dashboard/dist/pilot-inputs.tar.gz \ + --repo WayScience/pccma \ + --target main \ + --title "Dashboard pilot inputs: BR00150695" \ + --notes "Immutable public report tables, original warehouse hashes and selected JPEGs for the 24-hour BR00150695 pilot." +``` + +Alternatively, create the release and upload the asset in GitHub's Releases UI. +Do not upload the rendered-report ZIP under the input archive's name. Do not +replace this asset with different bytes; a checksum mismatch intentionally +fails CI. For new data, publish a new snapshot tag and update the reviewed URL, +SHA-256, size and scope in `pilot-source.json` together. + +Check the published asset before merging by downloading, validating and staging +it into a new local directory: + +```bash +uv run --project 7.dashboard --locked python 7.dashboard/pages.py stage \ + --config 7.dashboard/pilot-source.json \ + --output 7.dashboard/previews/release-input-check +``` + +The upload is a one-time operation. Subsequent UI/code merges reuse this pinned +public data asset; there is no dependency on expiring Actions artifacts. + +### 2. Enable GitHub Pages using Actions + +In `WayScience/pccma`, open: + +```text +Settings → Pages → Build and deployment → Source → GitHub Actions +``` + +Do not choose deployment from a branch or select the repository root as a +Jekyll source. This application is generated from a separate build directory. +The workflow checks that Pages is configured; it does not silently create or +reconfigure the public site. + +Actions were enabled for the repository when this workflow was prepared. If an +organization policy changes, allow the pinned `actions/*` and +`astral-sh/setup-uv` actions. Do not add a personal-access-token secret or broaden +all jobs' token permissions. + +### 3. Check environment deployment rules + +Under `Settings → Environments`, create or inspect `github-pages`. +For branch restriction, use **Selected branches and tags → branch `main`**. +Do not select "protected branches only" unless `main` is actually protected. +Leave required reviewers off for fully automatic deployment; if reviewers are +required, a merge builds the site but publication waits for approval. + +### 4. Review, push and merge the code changes + +Include the workflow, `7.dashboard/pages.py`, `pilot-source.json`, +`pilot-provenance.json`, packaging tests, source-hash test update and +documentation in the change. Keep `dist/` and +`previews/` ignored. Upload the public data asset before relying on the PR build +check: the real-data job deliberately fails if the asset is absent. + +Wait for both `Dashboard tests` and `Build verified pilot` to pass on the PR. +These can be made required checks in branch protection. A merge that changes +the dashboard then runs the same checks and deploys automatically. Unrelated +changes outside the workflow's path filters do not republish the site. + +The expected default project-site URL after a successful deployment is: + +```text +https://wayscience.github.io/pccma/ +``` + +The workflow's deployment environment reports the authoritative URL, including +any custom domain configured later. After the first merge, inspect that exact +run's successful deployment and open the hosted page to verify real image +loading and hover/pin comparison. Local checks cannot prove a hosted deployment. + +If the first run failed because setup was incomplete, finish the setup and +rerun the failed workflow. Once the workflow is on `main`, a manual rebuild is: + +```bash +gh workflow run dashboard-pages.yml --repo WayScience/pccma --ref main +``` + +## Reproduce the build without publishing + +Use an empty output directory for each stage/build; neither command overwrites +an existing successful result. + +To use the prepared local archive without downloading it (the same checksum +and safety checks still apply): + +```bash +uv run --project 7.dashboard --locked python 7.dashboard/pages.py stage \ + --config 7.dashboard/pilot-source.json \ + --archive 7.dashboard/dist/pilot-inputs.tar.gz \ + --output 7.dashboard/previews/pages-inputs + +uv run --project 7.dashboard --locked python 7.dashboard/pages.py build \ + --config 7.dashboard/pilot-source.json \ + --inputs 7.dashboard/previews/pages-inputs \ + --output 7.dashboard/dist/pages-rehearsal + +PCCMA_DASHBOARD_BUNDLE="$PWD/7.dashboard/dist/pages-rehearsal" \ +PCCMA_DASHBOARD_SOURCE_HASHES="$PWD/7.dashboard/previews/pages-inputs/warehouse/jpg-sha256.txt.gz" \ +uv run --project 7.dashboard --locked python -m pytest \ + 7.dashboard/tests/test_real_bundle.py -q +``` + +For a new snapshot, regenerate the archive from read-only original inputs using +`pages.py package`, then review its printed descriptor before updating the +configuration. Do not pin a checksum guessed from a filename or an archive that +was not actually produced and verified. +## Verification performed before handoff + +A clean Linux x86_64 container (Python 3.12, Node 24, locked uv environment) +completed the source/fixture suite: **137 passed**, plus **19 JavaScript tests**. +Six fixture-stage tests skipped as designed: five real-data tests awaited the +build, and one optional test required an existing private cache. + +The same container then staged the actual pinned public archive, built the +6,500-cell/39,000-JPEG pilot without local cache access, and passed all **five +real-bundle tests** using the staged original hash list. A GNU tar Pages artifact +was created and read back: **452,751,360 bytes / 39,004 files**, with image/catalog +hashes, HTML hash, `.nojekyll` and no-link checks passing. `actionlint` and +`zizmor` also passed for the workflow. + +The rehearsal used `--archive` for local acquisition; HTTPS acquisition has +fixture coverage, but the public release URL cannot be exercised until a +maintainer uploads the asset. No release, repository setting, commit, push or +hosted deployment was performed as part of this preparation. diff --git a/7.dashboard/README.md b/7.dashboard/README.md index 397e830..d06ae40 100644 --- a/7.dashboard/README.md +++ b/7.dashboard/README.md @@ -236,8 +236,20 @@ python3 -m zipfile -t "$BUNDLE.zip" ``` Unzip it, then use the extracted directory **containing `index.html`** as the -Pages artifact root. Do not upload the ZIP itself as a site asset. No deployment -workflow or Pages settings are changed automatically by this module. +Pages artifact root for a manual deployment. Do not upload the ZIP itself as a +site asset. + +For automatic deployment on merge, use +[the one-time setup and deployment guide](DEPLOYMENT.md). The +`Dashboard Pages` workflow tests pull requests and rebuilds/deploys changes to +`main` from the immutable public input archive pinned in `pilot-source.json`. +It consumes public report-input tables and original JPEGs, not a stale prebuilt +report, and does not +need a local warehouse cache or SSH credentials. A maintainer must first upload +`dist/pilot-inputs.tar.gz` to the documented GitHub Release and set +**Settings → Pages → Source → GitHub Actions**. Neither the public upload nor +repository settings are changed by running the local exporter. + Do not upload the full warehouse or commit the ignored generated bundle just to preview the source changes. Publishing the report also publishes its selected cell images; obtain the normal dataset/publication approval first. diff --git a/7.dashboard/pages.py b/7.dashboard/pages.py new file mode 100644 index 0000000..2bcf654 --- /dev/null +++ b/7.dashboard/pages.py @@ -0,0 +1,542 @@ +#!/usr/bin/env python3 +"""Package immutable pilot inputs, stage a pinned archive, and build current Pages code. + +Only report-needed Parquet columns, the original compressed JPEG hash list, and +selected original JPEGs travel in the input archive. Public tables keep all rows +and unrounded values, but omit unused private source paths. HTML, JavaScript and +DuckDB are built from this checkout. Commands never replace existing outputs. +""" + +import argparse +import ctypes +import gzip +import hashlib +import http.client +import json +import os +from pathlib import Path +import re +import shutil +import sys +import tarfile +import tempfile +from urllib.error import URLError +from urllib.parse import unquote, urlsplit +from urllib.request import HTTPRedirectHandler, Request, build_opener + +import pandas as pd + +import build_report as report + +INPUTS = { + "umap": "inputs/single_cell_umap_coordinates_by_cancer_group.parquet", + "crop_index": "inputs/crops_index.parquet", + "warehouse": "warehouse", + "source_hashes": "warehouse/jpg-sha256.txt.gz", +} +REQUIRED_FILES = frozenset(INPUTS[key] for key in ("umap", "crop_index", "source_hashes")) +MAX_EXPANDED_BYTES = 950_000_000 +MAX_MEMBERS = 60_000 +CHUNK = 1024 * 1024 +DOWNLOAD_TIMEOUT = 30 +DOWNLOAD_RETRIES = 2 + + +def _identifier(value, label): + if not isinstance(value, str) or not re.fullmatch(r"[A-Za-z0-9][A-Za-z0-9_.-]{0,255}", value): + raise ValueError(f"Invalid {label}") + return value + + +def _https_url(value): + if not isinstance(value, str) or any(ord(c) <= 32 for c in value): + raise ValueError("Archive URL must be HTTPS") + parsed = urlsplit(value) + if (parsed.scheme != "https" or not parsed.hostname or parsed.username is not None + or parsed.password is not None or parsed.fragment or "\\" in value): + raise ValueError("Archive URL must be HTTPS without credentials or fragment") + # Accessing port also rejects malformed/out-of-range port specifications. + parsed.port + return value + + +def _keys(value, keys, label): + if not isinstance(value, dict) or set(value) != set(keys): + raise ValueError(f"Invalid {label} keys; expected {sorted(keys)}") + + +def load_config(path): + """Validate the exact version-one schema, including local-archive workflows.""" + def unique_object(pairs): + result = {} + for key, value in pairs: + if key in result: + raise ValueError(f"Duplicate config key: {key}") + result[key] = value + return result + + config = json.loads(Path(path).read_text(), object_pairs_hook=unique_object) + _keys(config, {"schema_version", "plate", "run_id", "archive", "inputs", "expected"}, "config") + if type(config["schema_version"]) is not int or config["schema_version"] != 1: + raise ValueError("Unsupported schema_version") + _identifier(config["plate"], "plate") + _identifier(config["run_id"], "run_id") + _keys(config["archive"], {"url", "sha256", "bytes"}, "archive") + archive = config["archive"] + _https_url(archive["url"]) + if not isinstance(archive["sha256"], str) or not re.fullmatch(r"[0-9a-f]{64}", archive["sha256"]): + raise ValueError("Archive sha256 must be 64 lowercase hex digits") + if type(archive["bytes"]) is not int or not 0 < archive["bytes"] <= MAX_EXPANDED_BYTES: + raise ValueError("Invalid archive bytes budget") + if config["inputs"] != INPUTS: + raise ValueError("Input paths must match the immutable pilot archive layout") + _keys(config["expected"], {"cells", "assets"}, "expected") + expected = config["expected"] + if (any(type(expected[k]) is not int or expected[k] <= 0 for k in expected) + or expected["assets"] != expected["cells"] * len(report.CHANNELS) + or expected["assets"] + len(REQUIRED_FILES) > MAX_MEMBERS): + raise ValueError("Expected counts must describe six unique assets per cell within member budget") + return config + + +def _no_symlinks(path): + """Reject symlink ancestors too, including a dangling output symlink.""" + path = Path(os.path.abspath(path)) + for candidate in (path, *path.parents): + if candidate.is_symlink(): + raise ValueError(f"Unsafe symlink path: {candidate}") + return path + + +def _regular(path, root=None): + path = _no_symlinks(path) + if root is not None and not path.is_relative_to(Path(root).resolve()): + raise ValueError("Input file escapes its root") + if not path.is_file(): + raise ValueError(f"Missing regular input file: {path.name}") + return path + + +def _new_output(output): + output = _no_symlinks(output) + if output.exists(): + raise ValueError(f"Refusing to replace existing output: {output}") + output.parent.mkdir(parents=True, exist_ok=True) + _no_symlinks(output) + return output + + +def _publish_directory(source, output): + """Atomically rename with no-replace semantics; never fall back to overwrite. + + macOS renamex_np(RENAME_EXCL) and Linux renameat2(RENAME_NOREPLACE) + protect even against an empty directory appearing after the initial check. + """ + _new_output(output) + libc = ctypes.CDLL(None, use_errno=True) + if sys.platform == "darwin": + rename = libc.renamex_np + rename.argtypes = [ctypes.c_char_p, ctypes.c_char_p, ctypes.c_uint] + args = [os.fsencode(source), os.fsencode(output), 0x4] + elif sys.platform.startswith("linux") and hasattr(libc, "renameat2"): + rename = libc.renameat2 + rename.argtypes = [ctypes.c_int, ctypes.c_char_p, ctypes.c_int, ctypes.c_char_p, ctypes.c_uint] + args = [-100, os.fsencode(source), -100, os.fsencode(output), 1] + else: + raise OSError("Atomic no-replace directory publication requires macOS or Linux rename support") + rename.restype = ctypes.c_int + if rename(*args): + error = ctypes.get_errno() + raise OSError(error, os.strerror(error), str(output)) + + +def _member_name(name): + if (not isinstance(name, str) or not name or name.startswith("/") + or "\\" in name or ":" in name or any(ord(c) < 32 or ord(c) == 127 for c in name) + or any(part in ("", ".", "..") for part in name.split("/"))): + raise ValueError(f"Unsafe archive member: {name!r}") + if name in REQUIRED_FILES: + return name + if name.startswith("warehouse/crops/"): + report.relative_crop_path(name.removeprefix("warehouse/")) + return name + raise ValueError(f"Unexpected archive member: {name}") + + +def _selection(umap, crop_index, warehouse, *, plate, run_id): + payload = report.prepare_data(pd.read_parquet(umap), pd.read_parquet(crop_index), + plate=plate, run_id=run_id) + selected = {} + for point in payload["points"]: + if set(point["images"]) != set(report.CHANNELS): + raise ValueError("Incomplete selected channels") + for url in point["images"].values(): + relative = report.relative_crop_path(unquote(url.removeprefix("assets/"))) + if len(relative.parts) < 3 or relative.parts[1] != plate: + raise ValueError("Selected JPEG is outside configured plate scope") + name = _member_name(f"warehouse/{relative}") + if name in selected: + raise ValueError("Reused selected JPEG path") + selected[name] = _regular(Path(warehouse) / relative, warehouse) + return payload, selected + + +def _source_hashes(path, selected): + """Read the ORIGINAL list, retaining only selected entries; reject gzip bombs.""" + needed = {name.removeprefix("warehouse/") for name in selected} + hashes = {} + total = 0 + with gzip.open(_regular(path), "rb") as stream: + while True: + line = stream.readline(16_385) + if not line: + break + total += len(line) + if len(line) > 16_384 or total > MAX_EXPANDED_BYTES: + raise ValueError("Original source hash list exceeds expanded budget") + match = re.fullmatch(rb"([0-9a-fA-F]{64}) [ *]([^\r\n]+)\n?", line) + if not match: + raise ValueError("Malformed original JPEG hash list") + relative = match[2].decode("utf-8") + report.relative_crop_path(relative) + if relative in needed: + if relative in hashes: + raise ValueError(f"Duplicate original JPEG hash: {relative}") + hashes[relative] = match[1].decode("ascii").lower() + if set(hashes) != needed: + raise ValueError("Selected JPEG missing from original source hash list") + return {f"warehouse/{name}": digest for name, digest in hashes.items()} + + +def _verify_jpegs(selected, source_hashes): + hashes = _source_hashes(source_hashes, selected) + for name, path in selected.items(): + if report.sha256(path) != hashes[name]: + raise ValueError(f"Original JPEG hash mismatch: {name}") + return hashes + + +def _read_exact(stream: gzip.GzipFile, count: int) -> bytes: + value = stream.read(count) + if len(value) != count: + raise ValueError("Truncated gzip/tar archive") + return value + + +def _read_archive(path, *, root=None, expected=None): + """Read raw USTAR headers, never extractall or implicit PAX/GNU extensions. + + Reading headers ourselves prevents tarfile's transparent extension handling + from allocating an unbounded PAX/longname payload before size/type checks. + The complete gzip stream (including trailer/CRC) is consumed and checked. + """ + members = {} + expanded = 0 + with gzip.GzipFile(filename=path, mode="rb") as stream: + while True: + header = _read_exact(stream, 512) + if header == bytes(512): + if _read_exact(stream, 512) != bytes(512): + raise ValueError("Invalid tar end marker") + tail_size = 1024 + while tail := stream.read(CHUNK): + tail_size += len(tail) + # Streaming tar writers can pad one additional record when + # their final two zero blocks straddle a record boundary. + if tail_size > 2 * tarfile.RECORDSIZE or any(tail): + raise ValueError("Unexpected trailing tar/gzip content") + break + info = tarfile.TarInfo.frombuf(header, "utf-8", "strict") + name = _member_name(info.name) + if not info.isreg() or info.type not in (tarfile.REGTYPE, tarfile.AREGTYPE): + raise ValueError("Archive accepts regular files only (no links, directories or extensions)") + if name in members: + raise ValueError(f"Duplicate archive member: {name}") + if len(members) >= MAX_MEMBERS: + raise ValueError("Archive exceeds member count budget") + expanded += info.size + if info.size <= 0 or expanded > MAX_EXPANDED_BYTES: + raise ValueError("Archive exceeds expanded bytes budget or has empty member") + if expected is not None and name not in expected: + raise ValueError(f"Unexpected read-back member: {name}") + digest = hashlib.sha256() + target = None + try: + if root is not None: + destination = Path(root) / name + destination.parent.mkdir(parents=True, exist_ok=True) + target = destination.open("xb") + remaining = info.size + while remaining: + data = _read_exact(stream, min(CHUNK, remaining)) + digest.update(data) + if target is not None: + target.write(data) + remaining -= len(data) + if target is not None: + target.flush() + padding = _read_exact(stream, (-info.size) % 512) + if any(padding): + raise ValueError("Nonzero tar member padding") + finally: + if target is not None: + target.close() + metadata = {"bytes": info.size, "sha256": digest.hexdigest()} + if expected is not None and metadata != expected[name]: + raise ValueError(f"Archive source-byte read-back mismatch: {name}") + members[name] = metadata + if not REQUIRED_FILES.issubset(members): + raise ValueError("Archive lacks required original input members") + if expected is not None and set(members) != set(expected): + raise ValueError("Archive read-back member set mismatch") + return members + + +def _public_parquet(path, columns, work): + """Drop unused columns/attrs that could disclose private source filesystem paths.""" + frame = pd.read_parquet(path) + omitted = sorted(set(frame.columns) - set(columns)) + if not omitted and not frame.attrs: + return path, omitted + public = frame.loc[:, columns].copy() + public.attrs.clear() + target = work / path.name + public.to_parquet(target, index=False) + return target, omitted + + +def package(*, umap, crop_index, warehouse, source_hashes, plate, run_id, output): + """Package public build inputs, verifying original images and unchanged report values.""" + _identifier(plate, "plate") + _identifier(run_id, "run_id") + output = _new_output(output) + sources = {INPUTS["umap"]: _regular(umap), INPUTS["crop_index"]: _regular(crop_index), + INPUTS["source_hashes"]: _regular(source_hashes)} + for name, path in sources.items(): + if path.name != Path(name).name: + raise ValueError(f"Original input basename must be {Path(name).name}; got {path.name}") + original = {name: {"bytes": path.stat().st_size, "sha256": report.sha256(path)} + for name, path in sources.items()} + payload, selected = _selection(umap, crop_index, warehouse, plate=plate, run_id=run_id) + hashes = _verify_jpegs(selected, source_hashes) + sources.update(selected) + metadata = dict(original) + metadata.update({name: {"bytes": path.stat().st_size, "sha256": hashes[name]} + for name, path in selected.items()}) + work = Path(tempfile.mkdtemp(prefix=f".{output.name}.partial-", dir=output.parent)) + partial = work / "inputs.tar.gz" + omitted = {} + try: + for name, expected in original.items(): + if report.sha256(sources[name]) != expected["sha256"]: + raise ValueError(f"Source changed during packaging: {name}") + # These are the exact report-required columns, retaining all rows and + # unrounded values but never unused absolute TIFF source directories. + common = report.POSITION_KEY + ["Metadata_cell_line", "Metadata_time_point"] + columns = { + "umap": common + ["cancer_group", "tissue_site", "umap_1", "umap_2", "cluster"], + "crop_index": list(dict.fromkeys(common + report.OBJECT_KEY + + list(report.PATH_COLUMNS.values()) + ["Metadata_Nucleocentric_Crop_Size"])), + } + archive_sources = dict(sources) + for key, required in columns.items(): + name = INPUTS[key] + archive_sources[name], omitted[key] = _public_parquet(sources[name], required, work) + path = archive_sources[name] + metadata[name] = {"bytes": path.stat().st_size, "sha256": report.sha256(path)} + checked = report.prepare_data(pd.read_parquet(archive_sources[INPUTS["umap"]]), + pd.read_parquet(archive_sources[INPUTS["crop_index"]]), + plate=plate, run_id=run_id) + if checked != payload: + raise ValueError("Public input projection changed report values or scope") + if len(sources) > MAX_MEMBERS or sum(m["bytes"] for m in metadata.values()) > MAX_EXPANDED_BYTES: + raise ValueError("Selected inputs exceed archive size/member budget") + with partial.open("xb") as raw: + with gzip.GzipFile(filename="", mode="wb", fileobj=raw, mtime=0) as zipped: + with tarfile.open(fileobj=zipped, mode="w|", format=tarfile.USTAR_FORMAT, + encoding="utf-8", errors="strict") as archive: + for name, path in sorted(archive_sources.items()): + info = tarfile.TarInfo(name) + info.size = metadata[name]["bytes"] + info.mode = 0o644 + info.mtime = info.uid = info.gid = 0 + info.uname = info.gname = "" + with path.open("rb") as stream: + archive.addfile(info, stream) + raw.flush() + os.fsync(raw.fileno()) + archive_sha = report.sha256(partial) + archive_bytes = partial.stat().st_size + if archive_bytes > MAX_EXPANDED_BYTES: + raise ValueError("Compressed archive exceeds size budget") + _read_archive(partial, expected=metadata) + for name, path in sources.items(): + expected = original[name] if name in original else metadata[name] + if report.sha256(path) != expected["sha256"]: + raise ValueError(f"Source changed during packaging: {name}") + if report.sha256(partial) != archive_sha: + raise ValueError("Full archive checksum read-back mismatch") + _no_symlinks(output) + os.link(partial, output) + finally: + shutil.rmtree(work) + return {"schema_version": 1, "plate": plate, "run_id": run_id, + "archive": {"sha256": archive_sha, "bytes": archive_bytes}, + "inputs": dict(INPUTS), "expected": {"cells": len(payload["points"]), "assets": len(selected)}, + "members": len(metadata), "expanded_bytes": sum(m["bytes"] for m in metadata.values()), + "summary": payload["summary"], "sources": original, + "archived_sources": {name: metadata[name] for name in original}, "omitted_columns": omitted} + + +class _HTTPSRedirects(HTTPRedirectHandler): + def redirect_request(self, req, fp, code, msg, headers, newurl): + _https_url(newurl) + return super().redirect_request(req, fp, code, msg, headers, newurl) + + +def _copy_pinned(stream, target, pin): + digest = hashlib.sha256() + count = 0 + with target.open("xb") as output: + while data := stream.read(min(CHUNK, pin["bytes"] - count + 1)): + count += len(data) + if count > pin["bytes"]: + raise ValueError("Archive exceeds pinned bytes budget") + digest.update(data) + output.write(data) + if count != pin["bytes"]: + raise ValueError("Archive bytes differ from pinned size") + if digest.hexdigest() != pin["sha256"]: + raise ValueError("Archive sha256 checksum mismatch") + + +def _acquire_archive(config, target, local): + pin = config["archive"] + if local is not None: + with _regular(local).open("rb") as source: + _copy_pinned(source, target, pin) + return + opener = build_opener(_HTTPSRedirects()) + for attempt in range(DOWNLOAD_RETRIES + 1): + try: + request = Request(pin["url"], headers={"Accept-Encoding": "identity", "User-Agent": "pccma-pages/1"}) + with opener.open(request, timeout=DOWNLOAD_TIMEOUT) as response: + _https_url(response.geturl()) + _copy_pinned(response, target, pin) + return + except (OSError, URLError, http.client.HTTPException): + target.unlink(missing_ok=True) + if attempt == DOWNLOAD_RETRIES: + raise + + +def stage(*, config, output, archive=None): + """Download/copy a pinned archive, hash before extraction, publish a new root.""" + config = load_config(config) + output = _new_output(output) + work = Path(tempfile.mkdtemp(prefix=f".{output.name}.partial-", dir=output.parent)) + try: + packed = work / "download.tar.gz" + _acquire_archive(config, packed, archive) + extracted = work / "extracted" + extracted.mkdir() + members = _read_archive(packed, root=extracted) + if len(members) - len(REQUIRED_FILES) != config["expected"]["assets"]: + raise ValueError("Extracted asset count differs from expected count") + _publish_directory(extracted, output) + finally: + shutil.rmtree(work) + return {"output": str(output), "archive": config["archive"], "members": len(members), + "expanded_bytes": sum(m["bytes"] for m in members.values())} + + +def _input_tree(root): + root = _no_symlinks(root) + if not root.is_dir(): + raise ValueError("Extracted inputs root is missing") + files = set() + expanded = 0 + for directory, dirs, names in os.walk(root, followlinks=False): + for name in dirs: + _no_symlinks(Path(directory) / name) + for name in names: + path = _regular(Path(directory) / name, root) + files.add(_member_name(path.relative_to(root).as_posix())) + expanded += path.stat().st_size + if len(files) > MAX_MEMBERS or expanded > MAX_EXPANDED_BYTES: + raise ValueError("Extracted inputs exceed size/member budget") + if not REQUIRED_FILES.issubset(files): + raise ValueError("Extracted inputs lack required original input members") + return root, files + + +def build(*, config, inputs, output): + """Check exact selected scope and original hashes, then build current web code.""" + config = load_config(config) + output = _new_output(output) + root, files = _input_tree(inputs) + umap, crop_index = root / INPUTS["umap"], root / INPUTS["crop_index"] + source_hashes = root / INPUTS["source_hashes"] + original = {name: report.sha256(root / name) for name in REQUIRED_FILES} + payload, selected = _selection(umap, crop_index, root / INPUTS["warehouse"], + plate=config["plate"], run_id=config["run_id"]) + counts = {"cells": len(payload["points"]), "assets": len(selected)} + if counts != config["expected"]: + raise ValueError(f"Prepared counts differ from expected counts: {counts} != {config['expected']}") + if files != REQUIRED_FILES | set(selected): + raise ValueError("Extracted JPEG member set differs from selected plotted pilot scope") + hashes = _verify_jpegs(selected, source_hashes) + work = Path(tempfile.mkdtemp(prefix=f".{output.name}.partial-", dir=output.parent)) + try: + site = work / "site" + built = report.build_report(umap_path=umap, index_path=crop_index, + warehouse=root / INPUTS["warehouse"], output=site, + plate=config["plate"], run_id=config["run_id"]) + if built["points"] != payload["points"] or built["summary"] != payload["summary"]: + raise ValueError("Prepared scope changed during report build") + manifest = json.loads((site / "manifest.json").read_text()) + copied = {"warehouse/" + a["path"].removeprefix("assets/"): a["sha256"] for a in manifest["assets"]} + if copied != hashes or built["images"]["files"] != counts["assets"]: + raise ValueError("Built JPEGs differ from original source hashes") + for name, digest in original.items(): + if report.sha256(root / name) != digest: + raise ValueError("Original inputs changed during build") + for label in ("umap", "crop_index"): + if built["sources"][label]["sha256"] != original[INPUTS[label]]: + raise ValueError("Original input source hash was not preserved") + _publish_directory(site, output) + finally: + shutil.rmtree(work) + return {"output": str(output), "plate": config["plate"], "run_id": config["run_id"], + "summary": built["summary"], "images": built["images"], "catalog": built["catalog"]} + + +def main(argv=None): + parser = argparse.ArgumentParser(description=__doc__) + commands = parser.add_subparsers(dest="command", required=True) + packing = commands.add_parser("package", help="Package only original plotted pilot inputs") + for option in ("umap", "crop-index", "warehouse", "source-hashes", "output"): + packing.add_argument(f"--{option}", type=Path, required=True) + for option in ("plate", "run-id"): + packing.add_argument(f"--{option}", required=True) + staging = commands.add_parser("stage", help="Verify a pinned archive before safe extraction") + staging.add_argument("--config", type=Path, required=True) + staging.add_argument("--output", type=Path, required=True) + staging.add_argument("--archive", type=Path, help="Local archive; bypass network, never checksums") + building = commands.add_parser("build", help="Build current report code from staged original inputs") + building.add_argument("--config", type=Path, required=True) + building.add_argument("--inputs", type=Path, required=True) + building.add_argument("--output", type=Path, required=True) + arguments = vars(parser.parse_args(argv)) + command = arguments.pop("command") + try: + result = {"package": package, "stage": stage, "build": build}[command](**arguments) + except (ValueError, OSError, EOFError, tarfile.TarError, KeyError, TypeError, + http.client.HTTPException, report.duckdb.Error) as error: + parser.exit(1, f"Pages {command} failed: {error}\n") + print(json.dumps(result, indent=2, sort_keys=True, allow_nan=False)) + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/7.dashboard/pilot-provenance.json b/7.dashboard/pilot-provenance.json new file mode 100644 index 0000000..1a7019b --- /dev/null +++ b/7.dashboard/pilot-provenance.json @@ -0,0 +1,75 @@ +{ + "schema_version": 1, + "plate": "BR00150695", + "run_id": "BR00150695-20261113T155150Z-g790ecb4", + "original_sources": { + "inputs/crops_index.parquet": { + "bytes": 7171328, + "sha256": "945cf7b64cb86f3d5b2d70402fb244813d3e89ac97dd00cd3371bd1a818b6c11" + }, + "inputs/single_cell_umap_coordinates_by_cancer_group.parquet": { + "bytes": 2808145, + "sha256": "ffc1d53501cf3b4551840dd4c919d58360c2c3219e97a53c6379d7ccfaf92c2d" + }, + "warehouse/jpg-sha256.txt.gz": { + "bytes": 23624030, + "sha256": "4ebdb9cd027e3e0af4b83c2fc6f56ec0b8491c4f895037fc33f87fc456e478ad" + } + }, + "public_sources": { + "inputs/crops_index.parquet": { + "bytes": 6603597, + "sha256": "0d437a8c56b759e42a2611481f90faec98aaa3068a6ca0aba4ebe44f6d431403" + }, + "inputs/single_cell_umap_coordinates_by_cancer_group.parquet": { + "bytes": 2808145, + "sha256": "ffc1d53501cf3b4551840dd4c919d58360c2c3219e97a53c6379d7ccfaf92c2d" + }, + "warehouse/jpg-sha256.txt.gz": { + "bytes": 23624030, + "sha256": "4ebdb9cd027e3e0af4b83c2fc6f56ec0b8491c4f895037fc33f87fc456e478ad" + } + }, + "omitted_columns": { + "crop_index": [ + "Image_FileName_OrigAGP", + "Image_FileName_OrigDNA", + "Image_FileName_OrigER", + "Image_FileName_OrigMito", + "Image_FileName_OrigRNA", + "Image_Metadata_Plate", + "Image_Metadata_Site", + "Image_Metadata_Well", + "Image_PathName_OrigAGP", + "Image_PathName_OrigDNA", + "Image_PathName_OrigER", + "Image_PathName_OrigMito", + "Image_PathName_OrigRNA", + "Metadata_Crop_Format", + "Metadata_Crop_Generator", + "Metadata_Crop_Rescaling", + "Metadata_JPEG_Quality", + "Metadata_JPEG_Subsampling", + "Metadata_Nucleocentric_Crop_Maximum_X", + "Metadata_Nucleocentric_Crop_Maximum_Y", + "Metadata_Nucleocentric_Crop_Minimum_X", + "Metadata_Nucleocentric_Crop_Minimum_Y", + "Metadata_Nucleocentric_Pad_Fraction", + "Metadata_NumPy_Version", + "Metadata_Pillow_Version" + ], + "umap": [] + }, + "summary": { + "cancer_groups": 7, + "cell_lines": 13, + "crop_size": 224, + "excluded_umap_rows": 75252, + "timepoints": [ + 24 + ], + "umap_cells": 6500, + "warehouse_cells": 80493 + }, + "note": "Public tables retain all original rows and exact report-needed values. Unused columns and table attrs are omitted to avoid publishing private source directories. Source JPEGs and original compressed JPEG hashes are byte-identical. Original source hashes document the input projections; public input hashes describe the actual archive tables." +} diff --git a/7.dashboard/pilot-source.json b/7.dashboard/pilot-source.json new file mode 100644 index 0000000..6f8b55d --- /dev/null +++ b/7.dashboard/pilot-source.json @@ -0,0 +1,20 @@ +{ + "schema_version": 1, + "plate": "BR00150695", + "run_id": "BR00150695-20261113T155150Z-g790ecb4", + "archive": { + "bytes": 415035598, + "sha256": "d83004f32ea67010f1528c44aaf699741d9d01308040abc4e941a29e76c763ad", + "url": "https://github.com/WayScience/pccma/releases/download/dashboard-pilot-BR00150695-v1/pilot-inputs.tar.gz" + }, + "inputs": { + "crop_index": "inputs/crops_index.parquet", + "source_hashes": "warehouse/jpg-sha256.txt.gz", + "umap": "inputs/single_cell_umap_coordinates_by_cancer_group.parquet", + "warehouse": "warehouse" + }, + "expected": { + "assets": 39000, + "cells": 6500 + } +} diff --git a/7.dashboard/tests/test_pages.py b/7.dashboard/tests/test_pages.py new file mode 100644 index 0000000..10b6b05 --- /dev/null +++ b/7.dashboard/tests/test_pages.py @@ -0,0 +1,674 @@ +"""Fixture-only CLI and hostile-input checks for immutable Pages pilot inputs.""" + +import gzip +import hashlib +import importlib.util +import io +import json +import os +from pathlib import Path +import shutil +import subprocess +import sys +import tarfile +from urllib.error import URLError + +import duckdb +import pandas as pd +from PIL import Image +import pytest + +DASHBOARD = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(DASHBOARD)) +SPEC = importlib.util.spec_from_file_location("pilot_pages", DASHBOARD / "pages.py") +assert SPEC is not None and SPEC.loader is not None +pages = importlib.util.module_from_spec(SPEC) +SPEC.loader.exec_module(pages) +PLATE = "BR00150695" +RUN = "fixture-original-run" + + +def digest(path): + return hashlib.sha256(path.read_bytes()).hexdigest() + + +@pytest.fixture +def pilot(tmp_path): + source = tmp_path / "original inputs" + source.mkdir() + warehouse = source / "warehouse" + base = { + "Metadata_Plate": PLATE, "Metadata_Well": "C03", "Metadata_Site": 1, + "Metadata_Nuclei_Location_Center_X": 12.1234567890123, + "Metadata_Nuclei_Location_Center_Y": 24.5, "Metadata_cell_line": "DAOY", + "Metadata_time_point": 24, + } + umap = pd.DataFrame([ + dict(base, cancer_group="Medulloblastoma", tissue_site="CNS", umap_1=1.25, umap_2=-2.5, cluster=2), + dict(base, Metadata_Plate="OTHER", cancer_group="Other", tissue_site="Other", umap_1=99., umap_2=99., cluster=1), + ]) + row = dict(base, Metadata_ImageNumber=7, Metadata_Nuclei_Number_Object_Number=3, + Metadata_Cells_Number_Object_Number=2, Metadata_Nucleocentric_Crop_Size=16) + for channel, column in pages.report.PATH_COLUMNS.items(): + row[column] = f"crops/{PLATE}/DAOY/C03/f01/{PLATE}_C03_f01_nuc0003_cell0002_{channel}.jpg" + image = warehouse / row[column] + image.parent.mkdir(parents=True, exist_ok=True) + Image.new("RGB" if channel == "composite" else "L", (16, 16), 80).save(image, "JPEG") + # Full index includes an unplotted cell whose absent JPEGs must not be needed. + unplotted = dict(row, Metadata_Nuclei_Location_Center_X=900., + Metadata_Nuclei_Number_Object_Number=9, Metadata_Cells_Number_Object_Number=8) + for column in pages.report.PATH_COLUMNS.values(): + unplotted[column] = row[column].replace("nuc0003_cell0002", "nuc0009_cell0008") + index = pd.DataFrame([row, unplotted]) + umap_path = source / Path(pages.INPUTS["umap"]).name + index_path = source / Path(pages.INPUTS["crop_index"]).name + umap.to_parquet(umap_path) + index.to_parquet(index_path) + hashes = warehouse / "jpg-sha256.txt.gz" + lines = [f"{digest(warehouse / row[column])} {row[column]}\n" + for column in pages.report.PATH_COLUMNS.values()] + # Preserve unrelated original hashes verbatim, not a rewritten subset list. + lines.append("0" * 64 + " crops/OTHER/not-packaged.jpg\n") + hashes.write_bytes(gzip.compress("".join(lines).encode(), mtime=12345)) + # Old generated results are irrelevant and must never enter the archive. + (warehouse / "old-index.html").write_text("do not publish") + (warehouse / "old.duckdb").write_bytes(b"not an input") + return {"umap": umap_path, "crop_index": index_path, "warehouse": warehouse, + "source_hashes": hashes, "plate": PLATE, "run_id": RUN, "output": tmp_path / "pilot-inputs.tar.gz"} + + +def make_config(tmp_path, archive, *, expected=None): + config = { + "schema_version": 1, "plate": PLATE, "run_id": RUN, + "archive": {"url": "https://example.invalid/pilot-inputs.tar.gz", "sha256": digest(archive), + "bytes": archive.stat().st_size}, + "inputs": dict(pages.INPUTS), "expected": expected or {"cells": 1, "assets": 6}, + } + path = tmp_path / "pages-config.json" + path.write_text(json.dumps(config)) + return path + + +@pytest.fixture +def packed(pilot, tmp_path): + descriptor = pages.package(**pilot) + config = make_config(tmp_path, pilot["output"]) + return pilot, descriptor, config + + +@pytest.fixture +def staged(packed, tmp_path): + pilot, descriptor, config = packed + root = tmp_path / "extracted" + pages.stage(config=config, output=root, archive=pilot["output"]) + return pilot, descriptor, config, root + + +def run_cli(module, arguments, cwd): + result = subprocess.run([sys.executable, str(module), *map(str, arguments)], cwd=cwd, + env={k: v for k, v in os.environ.items() if k != "PYTHONPATH"}, + capture_output=True, text=True, timeout=90) + assert result.returncode == 0, result.stderr + assert not result.stderr + return json.loads(result.stdout) + + +def test_real_cli_package_stage_build_uses_current_web_and_original_sources(pilot, tmp_path): + descriptor = run_cli(DASHBOARD / "pages.py", ["package", *sum( + (["--" + key.replace("_", "-"), value] for key, value in pilot.items()), [])], tmp_path) + assert descriptor["expected"] == {"cells": 1, "assets": 6} + assert descriptor["members"] == 9 + assert descriptor["archive"] == {"sha256": digest(pilot["output"]), "bytes": pilot["output"].stat().st_size} + assert descriptor["inputs"] == pages.INPUTS + assert descriptor["summary"]["excluded_umap_rows"] == 1 + assert descriptor["summary"]["warehouse_cells"] == 2 + config = make_config(tmp_path, pilot["output"]) + extracted = tmp_path / "staged inputs" + stage_metadata = run_cli(DASHBOARD / "pages.py", ["stage", "--config", config, + "--archive", pilot["output"], "--output", extracted], tmp_path) + assert stage_metadata["members"] == 9 + for key in ("umap", "crop_index", "source_hashes"): + assert (extracted / pages.INPUTS[key]).read_bytes() == pilot[key].read_bytes() + # Build from a fresh copy of current source; modify web AFTER packaging. + # No writes to the repository's web files or real distribution directories. + checkout = tmp_path / "current checkout" + checkout.mkdir() + for name in ("pages.py", "build_report.py"): + shutil.copyfile(DASHBOARD / name, checkout / name) + shutil.copytree(DASHBOARD / "web", checkout / "web") + marker = "/* latest-source-after-input-packaging */" + with (checkout / "web/app.js").open("a") as stream: + stream.write("\n" + marker + "\n") + site = tmp_path / "new site" + result = run_cli(checkout / "pages.py", ["build", "--config", config, + "--inputs", extracted, "--output", site], tmp_path) + assert marker in (site / "index.html").read_text() + assert result["summary"] == descriptor["summary"] + assert result["images"]["files"] == 6 + assert result["catalog"]["status"] == "bundled" + manifest = json.loads((site / "manifest.json").read_text()) + assert manifest["code_sha256"]["app.js"] == digest(checkout / "web/app.js") + for label in ("umap", "crop_index"): + assert manifest["sources"][label] == {"name": pilot[label].name, "sha256": digest(pilot[label])} + for asset in manifest["assets"]: + original = pilot["warehouse"] / asset["path"].removeprefix("assets/") + assert (site / asset["path"]).read_bytes() == original.read_bytes() + assert asset["sha256"] == digest(original) + assert (site / ".nojekyll").is_file() + with duckdb.connect(str(site / "data/pilot.duckdb"), read_only=True) as connection: + assert connection.execute("SELECT count(*) FROM cells").fetchall() == [(1,)] + assert connection.execute("SELECT count(*) FROM image_assets").fetchall() == [(6,)] + assert connection.execute("SELECT DISTINCT plate, run_id FROM cells").fetchall() == [(PLATE, RUN)] + summary_row = connection.execute("SELECT value FROM report_metadata WHERE key='summary'").fetchone() + assert summary_row is not None + summary = json.loads(summary_row[0]) + assert summary == descriptor["summary"] + assert str(pilot["warehouse"]) not in (site / "index.html").read_text() + + +@pytest.mark.parametrize("private_field", ["columns", "attrs", "both"]) +def test_public_snapshot_omits_unused_private_paths_without_changing_report(pilot, tmp_path, private_field): + private = "/private/scratch/example-person@example.invalid/source-images" + original = {} + for key in ("umap", "crop_index"): + frame = pd.read_parquet(pilot[key]) + if private_field in ("columns", "both"): + frame["Unused_Source_Path"] = private + if private_field in ("attrs", "both"): + frame.attrs["source_directory"] = private + frame.to_parquet(pilot[key]) + original[key] = digest(pilot[key]) + descriptor = pages.package(**pilot) + config = make_config(tmp_path, pilot["output"]) + extracted = tmp_path / "public-inputs" + pages.stage(config=config, output=extracted, archive=pilot["output"]) + for key in ("umap", "crop_index"): + public_path = extracted / pages.INPUTS[key] + public = pd.read_parquet(public_path) + assert "Unused_Source_Path" not in public.columns + assert not public.attrs + assert private.encode() not in public_path.read_bytes() + assert digest(pilot[key]) == original[key], "Original files must remain untouched" + assert descriptor["sources"][pages.INPUTS[key]]["sha256"] == original[key] + assert descriptor["archived_sources"][pages.INPUTS[key]]["sha256"] == digest(public_path) + assert len(public) == len(pd.read_parquet(pilot[key])) + site = tmp_path / "site" + result = pages.build(config=config, inputs=extracted, output=site) + assert result["summary"] == descriptor["summary"] + assert result["images"]["files"] == 6 + assert private not in (site / "index.html").read_text() + + +def test_archive_is_deterministic_sorted_regular_only_and_byte_verified(packed, tmp_path): + pilot, descriptor, _ = packed + second = tmp_path / "second.tar.gz" + again = pages.package(**dict(pilot, output=second)) + assert second.read_bytes() == pilot["output"].read_bytes() + assert again == descriptor + with tarfile.open(second, "r:gz") as archive: + members = archive.getmembers() + names = [m.name for m in members] + assert names == sorted(names) + assert len(names) == len(set(names)) == 9 + assert set(names) == pages.REQUIRED_FILES | { + "warehouse/" + str(p.relative_to(pilot["warehouse"])) for p in pilot["warehouse"].rglob("*.jpg")} + for member in members: + assert member.isreg() + assert member.mtime == member.uid == member.gid == 0 + assert member.uname == member.gname == "" + assert member.mode == 0o644 + assert archive.extractfile(member).read() == ( + pilot[{pages.INPUTS["umap"]: "umap", pages.INPUTS["crop_index"]: "crop_index", + pages.INPUTS["source_hashes"]: "source_hashes"}[member.name]].read_bytes() + if member.name in pages.REQUIRED_FILES else + (pilot["warehouse"] / member.name.removeprefix("warehouse/")).read_bytes()) + # gzip must omit timestamp and filename, so moving output cannot change bytes. + header = second.read_bytes()[:10] + assert header[3] & 8 == 0 + assert header[4:8] == bytes(4) + + +@pytest.mark.parametrize("problem", ["checksum", "short", "long", "gzip_crc", "gzip_truncated"]) +def test_stage_rejects_tampered_pins_or_gzip_and_cleans_partial(packed, tmp_path, problem): + pilot, _, config_path = packed + config = json.loads(config_path.read_text()) + archive = pilot["output"] + data = archive.read_bytes() + if problem == "checksum": + config["archive"]["sha256"] = "0" * 64 + elif problem == "short": + config["archive"]["bytes"] += 1 + elif problem == "long": + config["archive"]["bytes"] -= 1 + else: + archive.write_bytes(data[:-8] + bytes([data[-8] ^ 1]) + data[-7:] + if problem == "gzip_crc" else data[:-5]) + config["archive"].update(sha256=digest(archive), bytes=archive.stat().st_size) + config_path.write_text(json.dumps(config)) + output = tmp_path / "no-stage" + with pytest.raises((ValueError, OSError, EOFError)): + pages.stage(config=config_path, output=output, archive=archive) + assert not output.exists() + assert not list(tmp_path.glob(".no-stage.partial-*")) + + +def hostile_archive(tmp_path, members): + archive = tmp_path / "hostile.tar.gz" + # Raw headers allow declaring enormous files without allocating their data. + with gzip.open(archive, "wb") as stream: + for info, body in members: + stream.write(info.tobuf(format=tarfile.USTAR_FORMAT)) + stream.write(body) + stream.write(bytes((-len(body)) % 512)) + stream.write(bytes(1024)) + return archive + + +def member(name, body=b"x", *, kind=tarfile.REGTYPE, size=None): + info = tarfile.TarInfo(name) + info.type = kind + info.size = len(body) if size is None else size + info.linkname = "../../escape" + return info, body + + +@pytest.mark.parametrize("name", [ + "/absolute.jpg", "../escape.jpg", "warehouse/crops/../escape.jpg", "warehouse/./crops/file.jpg", + "warehouse//crops/file.jpg", "warehouse/crops/x\\escape.jpg", "warehouse/crops/C:escape.jpg", + "warehouse/crops/file.jpg/", "index.html", "warehouse/pilot.duckdb", "inputs/other.parquet", + "warehouse/crops/not-jpeg.png", "warehouse/crops/with\nnewline.jpg", +]) +def test_stage_rejects_unsafe_or_unapproved_member_names(tmp_path, name): + archive = hostile_archive(tmp_path, [member(name)]) + config = make_config(tmp_path, archive) + with pytest.raises(ValueError, match="Unsafe|Unexpected|Invalid relative"): + pages.stage(config=config, output=tmp_path / "bad", archive=archive) + assert not (tmp_path / "bad").exists() + assert not (tmp_path / "escape.jpg").exists() + assert not list(tmp_path.glob(".bad.partial-*")) + + +@pytest.mark.parametrize("kind", [tarfile.SYMTYPE, tarfile.LNKTYPE, tarfile.DIRTYPE, + tarfile.CHRTYPE, tarfile.BLKTYPE, tarfile.FIFOTYPE, + tarfile.XHDTYPE, tarfile.GNUTYPE_LONGNAME, tarfile.GNUTYPE_SPARSE]) +def test_stage_rejects_links_directories_devices_and_extended_headers(tmp_path, kind): + archive = hostile_archive(tmp_path, [member("warehouse/crops/unsafe.jpg", kind=kind)]) + config = make_config(tmp_path, archive) + with pytest.raises(ValueError, match="regular files only"): + pages.stage(config=config, output=tmp_path / "bad", archive=archive) + assert not (tmp_path / "bad").exists() + + +@pytest.mark.parametrize("problem", ["duplicate", "oversized", "missing_inputs", "truncated", "empty"]) +def test_stage_bounds_members_and_requires_complete_input_layout(tmp_path, problem): + name = "warehouse/crops/a.jpg" + members = [member(name)] + if problem == "duplicate": + members *= 2 + elif problem == "oversized": + members = [member(name, body=b"", size=pages.MAX_EXPANDED_BYTES + 1)] + elif problem == "truncated": + members = [member(name, body=b"", size=100_000)] + elif problem == "empty": + members = [member(name, body=b"")] + archive = hostile_archive(tmp_path, members) + config = make_config(tmp_path, archive) + with pytest.raises((ValueError, OSError, EOFError)): + pages.stage(config=config, output=tmp_path / "bad", archive=archive) + assert not (tmp_path / "bad").exists() + assert not list(tmp_path.glob(".bad.partial-*")) + + +def test_stage_bounds_aggregate_size_and_member_count(packed, tmp_path, monkeypatch): + pilot, _, config = packed + # Keep configured six assets valid while reducing read-time member budget. + original_load = pages.load_config + validated = original_load(config) + monkeypatch.setattr(pages, "load_config", lambda _: validated) + monkeypatch.setattr(pages, "MAX_MEMBERS", 2) + with pytest.raises(ValueError, match="member count budget"): + pages.stage(config=config, output=tmp_path / "bad-count", archive=pilot["output"]) + monkeypatch.setattr(pages, "MAX_MEMBERS", 60_000) + monkeypatch.setattr(pages, "MAX_EXPANDED_BYTES", 1000) + with pytest.raises(ValueError, match="expanded bytes budget"): + pages.stage(config=config, output=tmp_path / "bad-size", archive=pilot["output"]) + assert not (tmp_path / "bad-count").exists() + assert not (tmp_path / "bad-size").exists() + + +@pytest.mark.parametrize("problem", ["missing", "hash_mismatch", "hash_missing", "hash_duplicate", "symlink", "parent_symlink"]) +def test_package_rejects_missing_unsafe_or_untrusted_original_jpegs(pilot, problem, tmp_path): + image = next(pilot["warehouse"].rglob("*.jpg")) + relative = image.relative_to(pilot["warehouse"]).as_posix() + hashes = gzip.decompress(pilot["source_hashes"].read_bytes()).decode() + if problem == "missing": + image.unlink() + elif problem == "hash_mismatch": + Image.new("L", (16, 16), 23).save(image, "JPEG") + elif problem == "hash_missing": + pilot["source_hashes"].write_bytes(gzip.compress("".join( + line + "\n" for line in hashes.splitlines() if not line.endswith(relative)).encode())) + elif problem == "hash_duplicate": + pilot["source_hashes"].write_bytes(gzip.compress((hashes + f"{digest(image)} {relative}\n").encode())) + elif problem == "symlink": + outside = tmp_path / "outside.jpg" + outside.write_bytes(image.read_bytes()) + image.unlink() + image.symlink_to(outside) + else: + parent = image.parent + moved = parent.with_name("real-images") + parent.rename(moved) + parent.symlink_to(moved, target_is_directory=True) + with pytest.raises(ValueError, match="Missing|hash|symlink"): + pages.package(**pilot) + assert not pilot["output"].exists() + assert not list(tmp_path.glob(".pilot-inputs.tar.gz.partial-*")) + + +def test_package_enforces_original_basenames(pilot): + wrong = pilot["umap"].with_name("renamed.parquet") + shutil.copyfile(pilot["umap"], wrong) + with pytest.raises(ValueError, match="Original input basename"): + pages.package(**dict(pilot, umap=wrong)) + + +@pytest.mark.parametrize("problem", ["wrong_expected", "wrong_plate", "missing", "hash_mismatch", "extra_image", "symlink"]) +def test_build_fails_before_publication_for_count_scope_or_hash_problems(staged, tmp_path, problem): + _, _, config_path, root = staged + config = json.loads(config_path.read_text()) + image = next((root / "warehouse/crops").rglob("*.jpg")) + if problem == "wrong_expected": + config["expected"] = {"cells": 2, "assets": 12} + elif problem == "wrong_plate": + config["plate"] = "WRONG" + elif problem == "missing": + image.unlink() + elif problem == "hash_mismatch": + image.write_bytes(image.read_bytes() + b"changed") + elif problem == "extra_image": + (image.parent / "extra.jpg").write_bytes(image.read_bytes()) + else: + outside = tmp_path / "outside.jpg" + outside.write_bytes(image.read_bytes()) + image.unlink() + image.symlink_to(outside) + config_path.write_text(json.dumps(config)) + output = tmp_path / "bad-site" + with pytest.raises(ValueError): + pages.build(config=config_path, inputs=root, output=output) + assert not output.exists() + assert not list(tmp_path.glob(".bad-site.partial-*")) + + +@pytest.mark.parametrize("command", ["package", "stage", "build"]) +@pytest.mark.parametrize("existing", ["file", "directory", "dangling_symlink", "parent_symlink"]) +def test_all_commands_refuse_existing_or_symlink_outputs(staged, tmp_path, command, existing): + pilot, _, config, root = staged + output = tmp_path / "keep" + if existing == "file": + output.write_text("untouched") + elif existing == "directory": + output.mkdir() + (output / "sentinel").write_text("untouched") + elif existing == "dangling_symlink": + output.symlink_to(tmp_path / "missing-target") + else: + real_parent = tmp_path / "real-parent" + real_parent.mkdir() + output.symlink_to(real_parent, target_is_directory=True) + output = output / "new-output" + with pytest.raises(ValueError, match="Refusing|symlink"): + if command == "package": + pages.package(**dict(pilot, output=output)) + elif command == "stage": + pages.stage(config=config, output=output, archive=pilot["output"]) + else: + pages.build(config=config, inputs=root, output=output) + if existing == "file": + assert output.read_text() == "untouched" + elif existing == "directory": + assert (output / "sentinel").read_text() == "untouched" + + +@pytest.mark.parametrize("mutation", ["schema", "unknown", "bool_size", "http", "file_url", "credentials", + "wrong_path", "zero_cells", "not_six", "bad_sha", "fragment"]) +def test_exact_config_schema_rejects_unsupported_inputs(packed, mutation): + _, _, path = packed + config = json.loads(path.read_text()) + if mutation == "schema": + config["schema_version"] = True + elif mutation == "unknown": + config["private_cache"] = "/not/allowed" + elif mutation == "bool_size": + config["archive"]["bytes"] = True + elif mutation == "http": + config["archive"]["url"] = "http://example.invalid/input.tar.gz" + elif mutation == "file_url": + config["archive"]["url"] = "file:///input.tar.gz" + elif mutation == "credentials": + config["archive"]["url"] = "https://user:secret@example.invalid/input.tar.gz" + elif mutation == "wrong_path": + config["inputs"]["umap"] = "../umap.parquet" + elif mutation == "zero_cells": + config["expected"] = {"cells": 0, "assets": 0} + elif mutation == "not_six": + config["expected"]["assets"] = 5 + elif mutation == "bad_sha": + config["archive"]["sha256"] = "a" * 63 + else: + config["archive"]["url"] += "#fragment" + path.write_text(json.dumps(config)) + with pytest.raises(ValueError): + pages.load_config(path) + + +def test_duplicate_json_keys_are_rejected(packed): + _, _, path = packed + path.write_text(path.read_text().replace('"schema_version": 1', '"schema_version": 1, "schema_version": 1')) + with pytest.raises(ValueError, match="Duplicate config key"): + pages.load_config(path) + + +def test_streamed_network_download_retries_twice_and_checks_redirects(packed, tmp_path, monkeypatch): + pilot, _, config = packed + calls = [] + reads = [] + + class Response(io.BytesIO): + def geturl(self): + return "https://release-assets.example.invalid/immutable-inputs.tar.gz" + + def read(self, size=-1): + reads.append(size) + return super().read(size) + + class Opener: + def open(self, request, *, timeout): + calls.append((request.full_url, timeout, request.get_header("Accept-encoding"))) + if len(calls) < 3: + raise URLError("fixture transient failure") + return Response(pilot["output"].read_bytes()) + + monkeypatch.setattr(pages, "build_opener", lambda handler: Opener()) + result = pages.stage(config=config, output=tmp_path / "network-stage") + assert result["members"] == 9 + assert len(calls) == 3 + assert all(call == ("https://example.invalid/pilot-inputs.tar.gz", 30, "identity") for call in calls) + assert reads and all(0 < size <= pages.CHUNK for size in reads) + with pytest.raises(ValueError, match="HTTPS"): + pages._HTTPSRedirects().redirect_request(None, None, 302, "", {}, "http://unsafe.example/input") + + +def test_failed_network_exhausts_retries_and_cleans_staging(packed, tmp_path, monkeypatch): + _, _, config = packed + calls = [] + + class Opener: + def open(self, *args, **kwargs): + calls.append(1) + raise URLError("fixture offline") + + monkeypatch.setattr(pages, "build_opener", lambda _: Opener()) + with pytest.raises(URLError): + pages.stage(config=config, output=tmp_path / "offline") + assert len(calls) == 3 + assert not (tmp_path / "offline").exists() + assert not list(tmp_path.glob(".offline.partial-*")) + + +def test_cli_errors_are_nonzero_and_do_not_emit_success_json(packed, tmp_path): + pilot, _, config = packed + value = json.loads(config.read_text()) + value["archive"]["sha256"] = "0" * 64 + config.write_text(json.dumps(value)) + result = subprocess.run([sys.executable, str(DASHBOARD / "pages.py"), "stage", "--config", str(config), + "--archive", str(pilot["output"]), "--output", str(tmp_path / "bad")], + capture_output=True, text=True, timeout=30) + assert result.returncode == 1 + assert "sha256 checksum mismatch" in result.stderr + assert "Traceback" not in result.stderr + assert result.stdout == "" + + +def test_archive_source_byte_readback_precedes_publication(pilot, monkeypatch, tmp_path): + real_readback = pages._read_archive + + def corrupt(path, **kwargs): + expected = dict(kwargs["expected"]) + name = next(iter(expected)) + expected[name] = dict(expected[name], sha256="0" * 64) + return real_readback(path, expected=expected) + + monkeypatch.setattr(pages, "_read_archive", corrupt) + with pytest.raises(ValueError, match="source-byte read-back mismatch"): + pages.package(**pilot) + assert not pilot["output"].exists() + assert not list(tmp_path.glob(".pilot-inputs.tar.gz.partial-*")) + + +def test_atomic_directory_publish_cannot_replace_empty_directory(tmp_path, monkeypatch): + source = tmp_path / "partial" + source.mkdir() + (source / "sentinel").write_text("new") + output = tmp_path / "existing" + output.mkdir() + # Bypass the preliminary existence check to exercise the OS no-replace + # primitive itself, as if another writer won the publication race. + monkeypatch.setattr(pages, "_new_output", lambda value: Path(value)) + with pytest.raises(OSError): + pages._publish_directory(source, output) + assert not list(output.iterdir()) + assert (source / "sentinel").read_text() == "new" + + +@pytest.mark.parametrize("size", [6657, 7169, 16897]) +def test_valid_streaming_tar_record_boundary_padding_is_accepted(tmp_path, size): + path = tmp_path / "record-boundary.tar.gz" + with path.open("wb") as raw: + with gzip.GzipFile(filename="", mode="wb", fileobj=raw, mtime=0) as stream: + with tarfile.open(fileobj=stream, mode="w|", format=tarfile.USTAR_FORMAT) as archive: + for index, name in enumerate(sorted(pages.REQUIRED_FILES)): + data = b"x" * (size if index == 0 else 1) + info = tarfile.TarInfo(name) + info.size = len(data) + archive.addfile(info, io.BytesIO(data)) + assert set(pages._read_archive(path)) == pages.REQUIRED_FILES + + +@pytest.mark.parametrize("problem", ["negative_size", "header_checksum", "trailing_data", "concatenated_gzip"]) +def test_stage_checks_raw_headers_and_complete_gzip_stream(tmp_path, problem): + info, body = member("warehouse/crops/a.jpg") + if problem == "negative_size": + info.size = -1 + body = b"" + header = bytearray(info.tobuf(format=tarfile.GNU_FORMAT)) + if problem == "header_checksum": + header[0] ^= 1 + uncompressed = bytes(header) + body + bytes((-len(body)) % 512) + bytes(1024) + if problem == "trailing_data": + uncompressed += b"not part of the tar" + compressed = gzip.compress(uncompressed) + if problem == "concatenated_gzip": + compressed += gzip.compress(b"hidden second stream") + archive = tmp_path / "invalid-header.tar.gz" + archive.write_bytes(compressed) + config = make_config(tmp_path, archive) + with pytest.raises((ValueError, OSError, tarfile.TarError)): + pages.stage(config=config, output=tmp_path / "bad", archive=archive) + assert not (tmp_path / "bad").exists() + assert not list(tmp_path.glob(".bad.partial-*")) + + +def test_stage_checksum_is_verified_before_extraction(packed, tmp_path, monkeypatch): + pilot, _, path = packed + config = json.loads(path.read_text()) + config["archive"]["sha256"] = "0" * 64 + path.write_text(json.dumps(config)) + + def must_not_extract(*args, **kwargs): + pytest.fail("Extraction started before archive checksum validation") + + monkeypatch.setattr(pages, "_read_archive", must_not_extract) + with pytest.raises(ValueError, match="sha256 checksum mismatch"): + pages.stage(config=path, output=tmp_path / "bad", archive=pilot["output"]) + assert not (tmp_path / "bad").exists() + + +def test_package_detects_original_input_mutation_before_publish(pilot, monkeypatch): + selection = pages._selection + + def mutate_after_read(*args, **kwargs): + result = selection(*args, **kwargs) + with pilot["umap"].open("ab") as stream: + stream.write(b"source mutation after selecting original rows") + return result + + monkeypatch.setattr(pages, "_selection", mutate_after_read) + with pytest.raises(ValueError, match="Source changed during packaging"): + pages.package(**pilot) + assert not pilot["output"].exists() + + +def test_package_atomic_publish_loses_race_without_overwrite(pilot, monkeypatch): + link = os.link + + def racing_link(source, target): + Path(target).write_bytes(b"concurrent writer wins") + link(source, target) + + monkeypatch.setattr(pages.os, "link", racing_link) + with pytest.raises(FileExistsError): + pages.package(**pilot) + assert pilot["output"].read_bytes() == b"concurrent writer wins" + + +def test_download_retries_after_partial_stream_without_reusing_bytes(packed, tmp_path, monkeypatch): + pilot, _, config = packed + attempts = [] + archive_bytes = pilot["output"].read_bytes() + + class Response(io.BytesIO): + def __init__(self, fail): + super().__init__(archive_bytes) + self.fail = fail + + def geturl(self): + return "https://example.invalid/pilot-inputs.tar.gz" + + def read(self, size=-1): + if self.fail and self.tell(): + raise TimeoutError("fixture midstream timeout") + return super().read(min(size, 17)) + + class Opener: + def open(self, *args, **kwargs): + attempts.append(1) + return Response(fail=len(attempts) < 3) + + monkeypatch.setattr(pages, "build_opener", lambda _: Opener()) + output = tmp_path / "retried-stage" + result = pages.stage(config=config, output=output) + assert len(attempts) == 3 + assert result["members"] == 9 + assert (output / pages.INPUTS["umap"]).read_bytes() == pilot["umap"].read_bytes() diff --git a/7.dashboard/tests/test_real_bundle.py b/7.dashboard/tests/test_real_bundle.py index 9736dd0..ed4b94b 100644 --- a/7.dashboard/tests/test_real_bundle.py +++ b/7.dashboard/tests/test_real_bundle.py @@ -38,7 +38,9 @@ def real_pilot(): def test_real_pilot_all_assets_match_original_warehouse_hashes(real_pilot): bundle, payload, manifest = real_pilot root = Path(__file__).resolve().parents[2] - hashes = root / "7.dashboard/previews" / (payload["run_id"] + "-warehouse") / "jpg-sha256.txt.gz" + configured_hashes = os.environ.get("PCCMA_DASHBOARD_SOURCE_HASHES") + hashes = (Path(configured_hashes).expanduser().resolve() if configured_hashes else + root / "7.dashboard/previews" / (payload["run_id"] + "-warehouse") / "jpg-sha256.txt.gz") assert hashes.is_file(), "Real source hashes are required, not only self-generated bundle hashes" assets = {asset["path"]: asset for asset in manifest["assets"]} referenced = {unquote(path) for point in payload["points"] for path in point["images"].values()} @@ -255,6 +257,7 @@ def test_real_pilot_mixes_grayscale_for_hover_and_pin_and_serves_catalog( for channel in ["ER", "RNA", "AGP"]: page.locator(f"#channel-toggle-{channel}").uncheck() page.mouse.move(other["x"], other["y"]) + expect(page.locator("#hover-preview")).to_be_visible() chosen = ["DNA", "Mito"] for selector, point in [("#crop-area canvas", points[target["id"]]), ("#hover-preview canvas", points[other["id"]])]: @@ -277,9 +280,13 @@ def test_real_pilot_mixes_grayscale_for_hover_and_pin_and_serves_catalog( directory = Path(os.environ["PCCMA_DASHBOARD_EVIDENCE"]) directory.mkdir(parents=True, exist_ok=True) page.locator("details.provenance summary").click() + page.evaluate("window.scrollTo(0, 0)") + other = isolated_target(page, lines[1]) + page.mouse.move(0, 0) page.mouse.move(other["x"], other["y"]) + expect(page.locator("#hover-preview")).to_be_visible() expect(page.locator("#hover-preview canvas")).to_have_count(1) - page.screenshot(path=str(directory / "live-mix-comparison.png"), full_page=True) + page.screenshot(path=str(directory / "live-mix-comparison.png"), full_page=False) assert not errors page.close() From 4c2bcce8d5b5c40041a865fc1ea8040909bcfe3f Mon Sep 17 00:00:00 2001 From: d33bs Date: Tue, 17 Nov 2026 08:09:08 -0700 Subject: [PATCH 6/6] tests --- 7.dashboard/tests/test_browser.py | 9 +++++++-- 7.dashboard/tests/test_real_bundle.py | 2 ++ 2 files changed, 9 insertions(+), 2 deletions(-) diff --git a/7.dashboard/tests/test_browser.py b/7.dashboard/tests/test_browser.py index fa20eca..7c77181 100644 --- a/7.dashboard/tests/test_browser.py +++ b/7.dashboard/tests/test_browser.py @@ -143,14 +143,19 @@ def test_hover_pin_channels_and_prefix_paths(browser, origin, site): page.close() -def test_mobile_touch_filters_zoom_and_file_open(browser, origin, site): - context = browser.new_context(viewport={"width": 390, "height": 844}, is_mobile=True, has_touch=True) +@pytest.mark.parametrize("height", [600, 844]) +def test_mobile_touch_filters_zoom_and_file_open(browser, origin, site, height): + context = browser.new_context(viewport={"width": 390, "height": height}, is_mobile=True, has_touch=True) page = context.new_page() errors = [] page.on("pageerror", lambda error: errors.append(str(error))) page.goto(origin + "/pccma/report/", wait_until="load") assert page.evaluate("document.documentElement.scrollWidth <= innerWidth") + # Native coordinate taps do not auto-scroll like locator.tap(). Header/font + # differences can put the lower fixture point below the mobile viewport. + page.locator("#plot").scroll_into_view_if_needed() point = pointer_target(page) + assert page.evaluate("p => p.x > 0 && p.x < innerWidth && p.y > 0 && p.y < innerHeight", point) page.touchscreen.tap(point["x"], point["y"]) expect(page.locator("#pin-status")).to_have_text("Pinned") page.locator("#zoom-in").click() diff --git a/7.dashboard/tests/test_real_bundle.py b/7.dashboard/tests/test_real_bundle.py index ed4b94b..6bddc84 100644 --- a/7.dashboard/tests/test_real_bundle.py +++ b/7.dashboard/tests/test_real_bundle.py @@ -151,7 +151,9 @@ def test_real_pilot_native_hover_all_lines_channels_mobile_and_file_open(real_pi mobile = context.new_page() mobile.goto(origin + "/pccma/report/", wait_until="load") first_line = mobile.evaluate("dashboard.visiblePoints[0].line") + mobile.locator("#plot").scroll_into_view_if_needed() target = isolated_target(mobile, first_line) + assert mobile.evaluate("p => p.x > 0 && p.x < innerWidth && p.y > 0 && p.y < innerHeight", target) mobile.touchscreen.tap(target["x"], target["y"]) expect(mobile.locator("#pin-status")).to_have_text("Pinned") expect(mobile.locator("#crop-area img")).to_have_count(5)