IDC Lung-PET-CT-Dx: Lung Cancer CT, PET (355 patients): sample notebook

A worked notebook for IDC Lung-PET-CT-Dx: Lung Cancer CT, PET (355 patients), with 6 code cells and the output each one printed. On Scigantic it opens in a hosted JupyterLab with the dataset already mounted, so nothing is downloaded first.

Provider
NCI Imaging Data Commons; Lung-PET-CT-Dx contributors; tables and sample by Scigantic
License
Per series (series.parquet license_short_name): CC BY 4.0 2,606. Cite the source DOI(s) and the IDC.
Size
9 parquet tables plus 394 sample DICOM files (47 MB)
Stored at
Amazon S3, s3://scigantic-idc-open/lung_pet_ct_dx (us-east-1)
Access
Free and public. No account with the data provider is needed.
DOI
10.7937/tcia.2020.nnc2-0461

The notebook

Lung-PET-CT-Dx on the Imaging Data Commons: 355 patients, 2,606 series, 124.65 GB

Lung Cancer imaging of the lung from the NCI Imaging Data Commons (IDC). Series by modality: CT 1,162, SR 1,091, SEG 220, PT 133.

This mount is the collection's index plus a real sample, not the collection: series.parquet (one row per DICOM series, with the public S3 location of each), studies.parquet, patients.parquet, the IDC clinical tables, and sample/ folders holding one CT series (CC BY 4.0); one PT series (CC BY 4.0); one SEG series (CC BY 4.0). Anything else is one anonymous S3 read away. README.md and BUILD_REPORT.json at the mount root say exactly how this was built (idc-index, IDC v25).

The code below reads all of it with the scigantic-nci package (pip install "scigantic-nci[dicom]", already installed in this image): from scigantic_nci import idc, then calls such as idc.series("lung_pet_ct_dx"), idc.read_sample and idc.pull_series. Run anywhere else, the same calls read s3://scigantic-idc-open/lung_pet_ct_dx/ anonymously.

import os, json
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import pydicom
from scigantic_nci import idc, NciError
plt.rcParams['figure.dpi'] = 72  # keeps the saved figures small enough for the notebook preview
try:
    from matplotlib_inline.backend_inline import set_matplotlib_formats
    set_matplotlib_formats('jpeg')  # slide renders are photographic; JPEG is a fifth the size of PNG here
except ImportError:
    pass

C = 'lung_pet_ct_dx'
# scigantic_nci reads the mounted archive when its BUILD_REPORT.json names this collection, else s3://scigantic-idc-open/<collection>/ anonymously.
M = os.environ.get('SCIGANTIC_MOUNT_PATH', '/mnt/archive')
on_mount = os.path.exists(f'{M}/BUILD_REPORT.json') and json.load(open(f'{M}/BUILD_REPORT.json')).get('collection_id') == C
print('reading', C, 'from', M if on_mount else f's3://scigantic-idc-open/{C}/')

report = idc.report(C)
series = idc.series(C)  # one row per DICOM series, with its public S3 location
patients = idc.patients(C)
studies = idc.studies(C)
print(report['collection_name'], '| IDC', report['idc_data_version'], '| built', report['built_at'][:10])
print(f"{len(patients):,} patients, {len(studies):,} studies, {len(series):,} series, {series.series_size_MB.sum()/1024:,.1f} GB in the IDC buckets\n")
by_mod = series.groupby('Modality').agg(series=('SeriesInstanceUID', 'count'), patients=('PatientID', 'nunique'), GB=('series_size_MB', lambda s: round(s.sum() / 1024, 2))).sort_values('series', ascending=False)
print(by_mod.to_string())
fig, ax = plt.subplots(figsize=(7, 3))
by_mod['patients'].plot.bar(ax=ax, color='#4a6fa5'); ax.set_ylabel('patients'); ax.set_title(f"{report['collection_name']}: patients per modality"); plt.tight_layout()

Output:

reading lung_pet_ct_dx from /mnt/archive
Lung-PET-CT-Dx | IDC v25 | built 2026-11-17
355 patients, 436 studies, 2,606 series, 124.6 GB in the IDC buckets

          series  patients      GB
Modality                          
CT          1162       355  120.45
SR          1091       354    0.05
SEG          220       151    0.39
PT           133       133    3.76

1. Studies and patients

A study is one imaging visit (all series acquired together); a patient may have several. studies.parquet collapses the series table to one row per study with the modalities present, patients.parquet to one row per patient.

print('Studies per patient:'); print(patients.n_studies.describe()[['min', '50%', 'max']].to_string())
print('\nModality combinations per study (top 8):'); print(studies.modalities.value_counts().head(8).to_string())
sex = patients.PatientSex.replace('', np.nan).dropna()
if len(sex): print('\nPatientSex:', sex.value_counts().to_dict())
ages = pd.to_numeric(series.PatientAge.dropna().astype(str).str.extract(r'(\d+)')[0], errors='coerce')
if ages.notna().sum() > 10: print(f'PatientAge at imaging: median {ages.median():.0f} y (IQR {ages.quantile(.25):.0f}-{ages.quantile(.75):.0f}) on {ages.notna().sum():,} series')
if 'BodyPartExamined' in series: print('\nBodyPartExamined:', series.BodyPartExamined.dropna().value_counts().head(6).to_dict())
print('\nLicenses (per series):', series.license_short_name.value_counts().to_dict())

Output:

Studies per patient:
min    1.0
50%    1.0
max    7.0

Modality combinations per study (top 8):
modalities
CT, SR             183
CT, SEG, SR        101
CT, PT, SR          82
CT, PT, SEG, SR     48
CT                  16
CT, SEG              3
PT                   3

...

2. Open the sample CT series

sample/CT_1.3.6.1.4.1.14519.5.2.1.6655.2359.268264887799643615596734596273/ is the complete series of patient Lung_Dx-B0022 (30 instances, 15.8 MB, CC BY 4.0), copied byte-for-byte from s3://idc-open-data/5866ad55-7c19-414e-8161-03faf89797a9/*. One .dcm per slice; idc.read_sample sorts them on ImagePositionPatient[2] (InstanceNumber as a fallback) and stacks them, applying RescaleSlope/RescaleIntercept so values are Hounsfield units. The pydicom datasets are in vol.datasets.

try:
    vol = idc.read_sample(C, 'CT')  # Volume: instances sorted by ImagePositionPatient z then InstanceNumber, CT in Hounsfield units
except NciError as e:  # compressed transfer syntax with no decoder plugin in this image
    print(e, 'Skipping the render.')
    vol = None
if vol is not None:
    n = len(vol.datasets)
    if vol.array is not None and n >= 3:
        lo, hi = -160, 240  # soft-tissue window in Hounsfield units
        picks = [(vol.array[i], f'slice {i + 1}/{n}') for i in (n // 4, n // 2, 3 * n // 4)]
    else:  # 2D modalities or a series that mixes image sizes (scouts, crops): show instances one by one
        imgs = vol.images if vol.ragged else list(vol.array)
        picks = [(img, f'{d.get("SeriesDescription", "")} {img.shape[1]}x{img.shape[0]}') for img, d in zip(imgs[:3], vol.datasets[:3])]
        flat = np.concatenate([p[0].ravel() for p in picks]); lo, hi = np.percentile(flat, 1), np.percentile(flat, 99)
    shapes = sorted({im.shape for im in vol.images}) if vol.ragged else [vol.array.shape[1:]]
    d0 = vol.datasets[0]
    print(f'{vol.modality} {n} instances, image shapes {shapes} | spacing {d0.get("PixelSpacing") or d0.get("ImagerPixelSpacing")} mm, slice thickness {d0.get("SliceThickness")} mm | {d0.get("Manufacturer")} {d0.get("ManufacturerModelName")} | {d0.get("SeriesDescription")}')
    fig, axes = plt.subplots(1, len(picks), figsize=(3.6 * len(picks), 3.8))
    for ax, (img, label) in zip(np.atleast_1d(axes), picks):
        ax.imshow(img if img.ndim == 2 else np.clip((img - lo) / max(hi - lo, 1e-6), 0, 1), cmap='gray', vmin=lo, vmax=hi); ax.set_title(label, fontsize=9); ax.axis('off')  # RGB (ultrasound) is scaled to 0-1
    plt.suptitle(f"Lung-PET-CT-Dx: sample CT series, patient Lung_Dx-B0022"); plt.tight_layout()

Output:

CT 30 instances, image shapes [(512, 512)] | spacing [0.734375, 0.734375] mm, slice thickness 10 mm | SIEMENS Sensation 10 | ThoraxRoutine  10.0  B40f

3. The sample segmentation

sample/SEG_1.2.276.0.7230010.3.1.3.17436516.2367242.1720643428.673380/ is a DICOM SEG series of patient Lung_Dx-A0068 (0.1 MB, CC BY 4.0): a stack of binary frames, one per segment and source slice, with SegmentSequence naming each segment and ReferencedSeriesSequence pointing at the image series it was drawn on. A few collections label ordinary image instances (one label map per slice) as SEG; the cell handles both. idc.sample_files lists the files; on the mount they are read in place, and elsewhere the same series is pulled from IDC with idc.pull_series. The source image series can be pulled from IDC the same way as any other row of series.parquet.

# scigantic_nci has no SEG reader, and read_sample decodes one frame per instance, which pydicom cannot do for some 1-bit SEG objects,
# so the SEG files are read whole with pydicom: in place on the mount (sample_files gives paths relative to the archive root), else pulled from IDC.
seg_sample = idc.samples(C).query("modality == 'SEG'").iloc[0]
if on_mount:
    seg_files = [os.path.join(M, f) for f in idc.sample_files(C, 'SEG')]
else:
    seg_files = idc.pull_series(series[series.SeriesInstanceUID == seg_sample.SeriesInstanceUID].iloc[0], '/tmp/idc_pull/' + seg_sample.SeriesInstanceUID)
seg_ds = [pydicom.dcmread(f) for f in seg_files]
seg = seg_ds[0]
if 'SegmentSequence' in seg:  # a DICOM Segmentation object
    print(seg.Modality, seg.get('SeriesDescription'), '|', int(seg.get('NumberOfFrames', 1)), 'frames of', seg.Rows, 'x', seg.Columns, '|', seg.get('ContentCreatorName'))
    print('segments:', [(int(x.SegmentNumber), str(x.SegmentLabel), str(x.get('SegmentAlgorithmType'))) for x in seg.SegmentSequence][:8])
    mask = seg.pixel_array
else:  # labelled SEG but stored as ordinary images: one label map per slice
    seg_ds.sort(key=lambda d: (float(d.ImagePositionPatient[2]) if 'ImagePositionPatient' in d else 0.0, int(d.get('InstanceNumber', 0))))
    print(seg.Modality, seg.get('SeriesDescription'), '|', len(seg_ds), seg.SOPClassUID.name, 'instances of', seg.Rows, 'x', seg.Columns, '(label maps, not a Segmentation object)')
    mask = np.stack([d.pixel_array for d in seg_ds])
    values, counts = np.unique(mask, return_counts=True)
    mask = mask != values[counts.argmax()]  # label maps carry a nonzero background value; everything else is labelled
ref = seg.ReferencedSeriesSequence[0].SeriesInstanceUID if 'ReferencedSeriesSequence' in seg else None
src = series[series.SeriesInstanceUID == ref]
if len(src):
    r = src.iloc[0]
    print(f'drawn on the {r.Modality} series of patient {r.PatientID}: {int(r.instanceCount)} instances, {r.series_size_MB:.1f} MB, {r.license_short_name}, {r.series_aws_url}')
mask = (mask[None] if mask.ndim == 2 else mask) > 0
i = int(mask.reshape(mask.shape[0], -1).sum(1).argmax())  # the frame with the most labelled pixels
print(f'{int(mask.sum()):,} labelled pixels over {mask.shape[0]} frames; densest frame {i + 1}')
fig, ax = plt.subplots(figsize=(3.8, 3.8)); ax.imshow(mask[i], cmap='gray'); ax.axis('off'); ax.set_title(f"Lung-PET-CT-Dx: sample SEG, frame {i + 1}", fontsize=9); plt.tight_layout()

Output:

SEG AIMI lung and nodule AI segmentation | 3 frames of 512 x 512 | BAMFHealth^AI
segments: [(1, 'Lung', 'AUTOMATIC')]
drawn on the CT series of patient Lung_Dx-A0068: 3 instances, 1.6 MB, CC BY 4.0, s3://idc-open-data/ab339dad-9a0b-4798-b0d9-51c94bb6ac8f/*
14,810 labelled pixels over 3 frames; densest frame 1

4. Clinical tables

IDC ships 3 clinical table(s) for this collection (bamf_aimi_annotations_lung_ct_qa_results, bamf_aimi_annotations_lung_fdg_pet_ct_qa_results, lung_pet_ct_dx_clinical; idc.clinical_tables lists them), keyed by dicom_patient_id = PatientID. clinical/dictionary.parquet (idc.clinical_dictionary) carries the human-readable label and the coded values for every column; coded columns store the code.

clin = idc.clinical(C, 'bamf_aimi_annotations_lung_ct_qa_results')
dictionary = idc.clinical_dictionary(C)
print(clin.shape, 'rows x cols in', 'bamf_aimi_annotations_lung_ct_qa_results')
print(dictionary[dictionary.short_table_name == 'bamf_aimi_annotations_lung_ct_qa_results'][['column', 'column_label']].head(15).to_string(index=False))
joined = patients.merge(clin, left_on='PatientID', right_on='dicom_patient_id', how='left')
print(f'\n{joined.dicom_patient_id.notna().sum()} of {len(patients)} imaged patients have a clinical row')

Output:

(477, 15) rows x cols in bamf_aimi_annotations_lung_ct_qa_results
                     column                    column_label
           dicom_patient_id idc_provenance_dicom_patient_id
               source_batch     idc_provenance_source_batch
                   reviewer                        Reviewer
                 validation                      Validation
                 collection                      Collection
                  patientid                       PatientID
                  studydate                       StudyDate
           studydate_suffix                StudyDate_suffix
           studyinstanceuid                StudyInstanceUID
          seriesinstanceuid               SeriesInstanceUID
             aisegmentation                  AISegmentation
                likertscore                     LikertScore
commentsaboutaisegmentation     CommentsAboutAISegmentation
...

5. Pull any series from IDC on demand

The collection is 124.65 GB in s3://idc-open-data (and idc-open-data-cr for CC BY-NC series); it is not on this mount. Every row of series.parquet has aws_bucket and crdc_series_uuid; the objects under that prefix are the series' instances. idc.pull_series(row, dest) takes such a row and downloads the instances anonymously, so this needs no credentials. Check series_size_MB before pulling: a pod has a few GB of local disk.

cand = idc.series(C, modality='CT', max_size_mb=20).sort_values('series_size_MB')  # filters pushed down to parquet
row = cand.iloc[len(cand) // 2] if len(cand) else series.sort_values('series_size_MB').iloc[0]
print(row.PatientID, row.Modality, int(row.instanceCount), 'instances,', round(idc.series_size(row), 1), 'MB ->', row.series_aws_url)
print('IDC viewer:', idc.viewer_url(row))
files = idc.pull_series(row, '/tmp/idc_pull')  # anonymous read of s3://<aws_bucket>/<crdc_series_uuid>/, returns the local paths
d = pydicom.dcmread(files[0], stop_before_pixels=True)
print(len(files), 'files downloaded;', d.Modality, d.get('SeriesDescription'), d.get('Rows'), 'x', d.get('Columns'))

Output:

Lung_Dx-A0142 CT 20 instances, 10.5 MB -> s3://idc-open-data/33ab920f-c53d-4fc3-b65c-4435d41c4e40/*
IDC viewer: https://viewer.imaging.datacommons.cancer.gov/viewer/1.3.6.1.4.1.14519.5.2.1.6655.2359.110766248667294166794519718535?seriesInstanceUID=1.3.6.1.4.1.14519.5.2.1.6655.2359.241779235461555360878581665082
20 files downloaded; CT ThoraxRoutine  10.0  B40f 512 x 512

Try this in the AI assistant

The chat panel is prefilled with the first of these.

Licenses are per series (license_short_name in series.parquet). Cite the collection DOI(s) in README.md and the IDC papers (Fedorov et al. 2021, 2023) when you publish.

Run it

Open this notebook to run it, see the dataset page for the full description, or browse the full catalog.