Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
119 changes: 119 additions & 0 deletions .github/workflows/dashboard-pages.yml
Original file line number Diff line number Diff line change
@@ -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
9 changes: 9 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,15 @@ 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/

# 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/

Expand Down
250 changes: 250 additions & 0 deletions 5a.object_image_crops/0.generate_object_crops.ipynb
Original file line number Diff line number Diff line change
@@ -0,0 +1,250 @@
{
"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, requested_plate, guard_plate_scope,\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",
"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",
" 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
}
Loading