Tools for analysis of RAW data coming from the IceCube Upgrade cameras deployed during the 25-26 season.
New to the data? Start with the step-by-step tutorial at the end of this page.
| File | Version | Last Updated |
|---|---|---|
ICUCamera.py |
v1.0.0 | 2026-01-15 |
ICUC_report.py |
v1.0.3 | 2026-01-15 |
This is different from ICUCamera package for people at SouthPole.
Check the dependency list below, and if you have any restrictions to use modules other than os, numpy, matplotlib, please check the link above.
This project requires the following Python packages:
- Python >= 3.8
- numpy
- matplotlib
- opencv-python
- astropy
- os
- sys
- glob
- gzip
- struct
- argparse
- tarfile
- pathlib
- scipy
- pandas
python ICUC_report --input [full/path/of/your/rawfile.raw] --outputdir [directory/path/to/store/pdfs/]
If you have multiple .raw files in a directory, and want to generate report files for all of them, checkout pdf_generate_loop.sh script.
This is a script which includes functions processing the images from IceCube Upgrade Camera System (a.k.a. Fixed Focus Camera, SKKU Camera, South Korea Camera, etc.,)
As we develope better processing methods, this script will be updated.
Specific use of the modules are explaind in example.ipynb
Here you can find out how to use each function in ICUCamera.py.
Whenever you add new functions in ICUCamera.py, it is strongly recommended to add a blocks in this notebook
This is a folder with example .raw file and intermediate image files generated in the example.ipynb.
Let's keep this directory as light as possible.
If you'd like to use data other than that, please use other directory, or make /data/ directory inside this repo.
since /data/ is a part of the .gitignore, it won't be uploaded in the github.
As real data is transfered via JADE, it is sent out as a .tar.gz file which contains a .raw file and a .semfile.
These scripts explains how to unzip and extract the .raw file only.
From a downloaded archive to an image you can analyze: unpack, decode, look up the device, load its lens mask and put every image on one brightness scale. Every snippet below was run on real data.
- Unpack the
.tar.gzfiles that JADE delivers. - Read the device, camera and time out of each file name.
- Decode the
.rawfile into an array of counts. - Look the device up: depth, OMKey, production ID.
- Load its lens mask.
- Bring every image onto the same brightness scale (long vs short captures).
You need Python 3 with numpy, scipy and pandas. The decoder uses only the standard library plus numpy.
Paths. The first lines of the script set four paths. Replace the
/path/to/...placeholders with your own. The calibration folder/data/ana/Calibration/upgrade-camerais shared.
import gzip, re, glob, json, os, tarfile, zlib, sqlite3
import numpy as np, pandas as pd
from scipy import ndimage as ndi
# ---- paths (edit these) -------------------------------------------------
OUT = '/path/to/UpgradeCameraImageAnalysis/dailyReportRunner/output' # <MMDD>/*.raw
CAL = '/data/ana/Calibration/upgrade-camera' # masks, master.json, comm_modules.xlsx
REPO = '/path/to/UpgradeCamera' # UpgradeCameraImageAnalysis + upgrade_commissioning_scripts
MODES = '/path/to/image_modes.csv'Images arrive through JADE as .tar.gz files. Each holds one .raw image and one .sem file. Only the .raw file is needed. The function below extracts it and leaves the archive alone, unlike the project's tar_unzip.py, which deletes the archive after extracting.
# ---- 1. unpack a JADE archive (.tar.gz holds one .raw and one .sem) ------------
def extract_raw(tar_path, out_dir):
with tarfile.open(tar_path, 'r:gz') as tar:
raw = [m for m in tar.getmembers() if m.name.endswith('.raw')]
assert len(raw) == 1
out = os.path.join(out_dir, os.path.basename(raw[0].name))
with tar.extractfile(raw[0]) as fi, open(out, 'wb') as fo: fo.write(fi.read())
return outA name looks like Camera-Run_IIB_string88_mDOM_port5111_cam1_illum1_gain0_exposure3700ms_20260117-00-10-14.raw. Possible trailing parts such as _trial0_new are ignored. The fields are:
| Part | Meaning |
|---|---|
IIB |
Run type, the configuration the camera was run in |
string88, mDOM, port5111 |
String number, module type, and the DOMNet port that identifies the device on that string |
cam1 |
On an mDOM, camera 1 is the bottom camera. Cameras 2 and 3 are the side cameras, angled at 45 degrees |
illum1 |
LED that was on. 1 is the bottom LED, 4 the top one, and 0 means no LED |
exposure3700ms |
Exposure time. The analysis here uses cam 1, illum 1, 3700 ms |
20260117-00-10-14 |
Time stamp, year month day then hour minute second |
The function image_table() reads these fields into a table, one row per image, sorted by device and time. It also attaches each image's capture mode and brightness factor, which step 6 explains.
# ---- 3. image table from file names --------------------------------------
PAT = re.compile(r'string(\d+)_(\w+?)_port(\d+)_cam(\d+)_illum(\d+)_gain0_exposure(\d+)ms_(\d{8}-\d\d-\d\d-\d\d)')
def image_table(illum=1, exposure=3700):
modes = pd.read_csv(MODES).drop_duplicates('image').set_index('image')
rows = []
for f in glob.glob(f'{OUT}/*/*illum{illum}_gain0_exposure{exposure}ms*.raw'):
n = os.path.basename(f); m = PAT.search(n)
if not m or 'LOG' in n: continue
s, dev, p, cam, ill, exp, ts = m.groups()
fac, mode = 1.0, 'unknown'
if n in modes.index:
r = modes.loc[n]; mode = r.mode_status
if pd.notna(r.correction_factor): fac = float(r.correction_factor)
else: mode = f'unknown ({mode})'
rows.append(dict(string=int(s), device=dev, port=int(p), cam=int(cam), file=f, mode=mode, factor=fac,
time=pd.to_datetime(ts, format='%Y%m%d-%H-%M-%S')))
return pd.DataFrame(rows).sort_values(['string','device','port','cam','time'])The file has three parts:
- A 12-byte common header, not compressed.
- A gzip stream containing a 40-byte image header, then the pixels.
- Pixels stored as 16-bit words that hold 12-bit values, so shift right by 4.
The image is 1312 columns wide and 993 rows tall (979 for a smaller window). It is a Bayer mosaic, so averaging each 2 by 2 cell gives a clean half-resolution image of 496 by 656 pixels. Then subtract the sensor pedestal of 240 counts.
# ---- 2. decode a .raw file ------------------------------------------------
PED = 240 # sensor pedestal in counts
def decode(path):
buf = open(path, 'rb').read()
data = gzip.decompress(buf[12:]) # first 12 bytes (common header) are NOT compressed
px = (np.frombuffer(data[40:], '<u2') >> 4).astype(np.float32) # 40-byte image header; 16-bit words hold 12-bit pixels
rows = int(round(px.size / 1312)) # 993 or 979 rows, 1312 columns
a = np.pad(px, (0, 1312*rows - px.size)).reshape(rows, 1312)[:rows//2*2]
half = (a[0::2,0::2] + a[0::2,1::2] + a[1::2,0::2] + a[1::2,1::2]) / 4 # average each 2x2 Bayer cell -> half resolution
half = np.clip(half - PED, 0, None)
out = np.zeros((496, 656), np.float32); out[:min(496, half.shape[0])] = half[:496]
return out # counts above pedestal, shape (496, 656)
def smooth(im): return ndi.uniform_filter(im, 5)The 40-byte header holds the camera ID, capture mode, exposure, gain and heater state. header_info(filename) in ICUCamera.py prints them. To view an image, plot np.log10(im + 1), which keeps both the dim lens and the bright harness visible.
Several files describe the system. None alone maps a string and port to a mask, so the lookup uses two of them.
| Source | What it holds | Used for |
|---|---|---|
master.json |
One record per image (IMAGE_METADATA: file name, date, run type, LED on and off times, capture start and finish, string, port, OMKey) and one per configuration (CONFIG_FILES, keyed by CONFIG_ID: depth, quad, wire pair, address, host) |
Image metadata, capture times |
master.sqlite |
The same records in tables images and configs. Each value is zlib-compressed JSON. This is an older snapshot |
Querying without loading 55 MB of JSON |
comm_modules (.xlsx or .csv) |
The layout. Each row is one position on a wire pair, with the device type on each string, depth, OMKey and port number | Port to OMKey and depth |
string_NN_geometry.json |
For each string, every device with its position (equal to the OMKey), production_id and coordinates. Found in upgrade_commissioning_scripts/geometry/ |
OMKey to production ID |
mask_npy/D###-v1_cam-1_....npy |
One lens mask per device and camera, named by production ID | Step 5 |
The chain is: port number, then OMKey and depth from the layout table, then production ID from the geometry file, then the mask file whose name starts with that ID.
# ---- 4. device lookup: depth, OMKey, production id, mask ------------------------
def device_info(string, port, comm_csv):
cm = pd.read_csv(comm_csv) # layout table (one row per position on a wire pair)
row = cm[(cm.PortNumber == port) & (cm[str(string)] == 'mDOM')].iloc[0]
omkey, depth = int(row.OMKey), float(row.Depth)
geo = json.load(open(f'{REPO}/upgrade_commissioning_scripts/geometry/string_{string}_geometry.json'))
dev = [d for g in geo if g['id'] == string for d in g['devices'] if d['position'] == omkey and d['type'] == 'mdom'][0]
return dict(omkey=omkey, depth=depth, production_id=dev['production_id']) # e.g. 'mDOM_D154'
def load_masks(production_id, erode=4):
d = production_id.split('_')[-1] # 'D154'
f = sorted(glob.glob(f'{CAL}/mask_npy/{d}-*.npy'))[-1] # newest mask for this device
m = np.load(f)[:992, :1312] # True = open lens, False = harness
raw = m.reshape(496, 2, 656, 2).all((1, 3)) # half resolution
return raw, ndi.binary_erosion(raw, iterations=erode) # eroded copy drops the bright harness rimAn older
database.jsonmapped a string and port straight to a production ID. It no longer exists, so use the layout table and geometry files as above. Depths differ slightly between sources (2181 m in the layout table, 2178 m in the configuration for the same device), so pick one source and stay with it.
To see what was logged about an image, load master.json. It also lists images from other cameras and LEDs, so filter first.
import json, pandas as pd
M = json.load(open('/data/ana/Calibration/upgrade-camera/master.json'))
df = pd.DataFrame(M['IMAGE_METADATA'])
rows = df[(df.STRING == 88) & (df.PORT == 5111) & (df.CAMERA == 1) & (df.ILLUMINATION == 1)]
cfg = M['CONFIG_FILES'][rows.iloc[0].CONFIG_ID]['CONFIG_LST'][0] # depth, quad, address, host, ...
# The sqlite version stores each record as zlib-compressed JSON:
import sqlite3, zlib
con = sqlite3.connect('file:/data/ana/Calibration/upgrade-camera/master.sqlite?mode=ro', uri=True)
fn, cid, blob = con.execute('select filename, config_id, value from images limit 1').fetchone()
record = json.loads(zlib.decompress(blob))The mask is a 993 by 1312 array where True means open lens and False means harness. A device can have more than one mask file, so take the newest. Crop to 992 by 1312, then reduce to half resolution to match the decoded images. A pixel counts as open only if all four of its source pixels are open.
The function load_masks() in step 4 also returns an eroded copy. The bright rim of the harness would otherwise leak into any measurement made inside the lens, so the open area is trimmed inward by 4 half-resolution pixels.
Nominal captures last about 7.4 s (long). Some are cut short at about 5.4 s and come out dimmer. A short image has to be multiplied by 2.198 before it is compared with a long one. That factor comes from a measured ratio of 0.456 ± 0.007.
- The mode of each image is listed in
image_modes.csv(mode_statusandcorrection_factor). Master metadata also logs capture start and finish, but for many images these read "Unknown". - If the mode is unknown the table uses a factor of 1 and the mode is marked
unknown. An unknown mode leaves the image uncorrected. If it was really a short capture, it stays about 2.2 times too dim next to the long ones. - One way to infer a mode is to compare the image with the median of the device's known long images. A ratio of 0.38 to 0.55 means short, and 0.85 to 1.2 means long.
The table is built by image_table() in step 2. The final image is the median of the last three images with a known mode, each smoothed and multiplied by its own factor. Using the median keeps one odd frame from dominating.
# ---- 5. final image on the long-capture scale ----------------------------------
def final_image(g, k=3):
tail = g.iloc[-k:]
known = tail[~tail['mode'].str.startswith('unknown')]
use = known if len(known) else tail.iloc[-1:] # fall back to the last image, factor 1
return np.median([smooth(decode(r.file)) * r.factor for r in use.itertuples()], axis=0)Click to expand
import gzip, re, glob, json, os, tarfile, zlib, sqlite3
import numpy as np, pandas as pd
from scipy import ndimage as ndi
# ---- paths (edit these) -------------------------------------------------
OUT = '/path/to/UpgradeCameraImageAnalysis/dailyReportRunner/output' # <MMDD>/*.raw
CAL = '/data/ana/Calibration/upgrade-camera' # masks, master.json, comm_modules.xlsx
REPO = '/path/to/UpgradeCamera' # UpgradeCameraImageAnalysis + upgrade_commissioning_scripts
MODES = '/path/to/image_modes.csv'
# ---- 1. unpack a JADE archive (.tar.gz holds one .raw and one .sem) ------------
def extract_raw(tar_path, out_dir):
with tarfile.open(tar_path, 'r:gz') as tar:
raw = [m for m in tar.getmembers() if m.name.endswith('.raw')]
assert len(raw) == 1
out = os.path.join(out_dir, os.path.basename(raw[0].name))
with tar.extractfile(raw[0]) as fi, open(out, 'wb') as fo: fo.write(fi.read())
return out
# ---- 2. decode a .raw file ------------------------------------------------
PED = 240 # sensor pedestal in counts
def decode(path):
buf = open(path, 'rb').read()
data = gzip.decompress(buf[12:]) # first 12 bytes (common header) are NOT compressed
px = (np.frombuffer(data[40:], '<u2') >> 4).astype(np.float32) # 40-byte image header; 16-bit words hold 12-bit pixels
rows = int(round(px.size / 1312)) # 993 or 979 rows, 1312 columns
a = np.pad(px, (0, 1312*rows - px.size)).reshape(rows, 1312)[:rows//2*2]
half = (a[0::2,0::2] + a[0::2,1::2] + a[1::2,0::2] + a[1::2,1::2]) / 4 # average each 2x2 Bayer cell -> half resolution
half = np.clip(half - PED, 0, None)
out = np.zeros((496, 656), np.float32); out[:min(496, half.shape[0])] = half[:496]
return out # counts above pedestal, shape (496, 656)
def smooth(im): return ndi.uniform_filter(im, 5)
# ---- 3. image table from file names --------------------------------------
PAT = re.compile(r'string(\d+)_(\w+?)_port(\d+)_cam(\d+)_illum(\d+)_gain0_exposure(\d+)ms_(\d{8}-\d\d-\d\d-\d\d)')
def image_table(illum=1, exposure=3700):
modes = pd.read_csv(MODES).drop_duplicates('image').set_index('image')
rows = []
for f in glob.glob(f'{OUT}/*/*illum{illum}_gain0_exposure{exposure}ms*.raw'):
n = os.path.basename(f); m = PAT.search(n)
if not m or 'LOG' in n: continue
s, dev, p, cam, ill, exp, ts = m.groups()
fac, mode = 1.0, 'unknown'
if n in modes.index:
r = modes.loc[n]; mode = r.mode_status
if pd.notna(r.correction_factor): fac = float(r.correction_factor)
else: mode = f'unknown ({mode})'
rows.append(dict(string=int(s), device=dev, port=int(p), cam=int(cam), file=f, mode=mode, factor=fac,
time=pd.to_datetime(ts, format='%Y%m%d-%H-%M-%S')))
return pd.DataFrame(rows).sort_values(['string','device','port','cam','time'])
# ---- 4. device lookup: depth, OMKey, production id, mask ------------------------
def device_info(string, port, comm_csv):
cm = pd.read_csv(comm_csv) # layout table (one row per position on a wire pair)
row = cm[(cm.PortNumber == port) & (cm[str(string)] == 'mDOM')].iloc[0]
omkey, depth = int(row.OMKey), float(row.Depth)
geo = json.load(open(f'{REPO}/upgrade_commissioning_scripts/geometry/string_{string}_geometry.json'))
dev = [d for g in geo if g['id'] == string for d in g['devices'] if d['position'] == omkey and d['type'] == 'mdom'][0]
return dict(omkey=omkey, depth=depth, production_id=dev['production_id']) # e.g. 'mDOM_D154'
def load_masks(production_id, erode=4):
d = production_id.split('_')[-1] # 'D154'
f = sorted(glob.glob(f'{CAL}/mask_npy/{d}-*.npy'))[-1] # newest mask for this device
m = np.load(f)[:992, :1312] # True = open lens, False = harness
raw = m.reshape(496, 2, 656, 2).all((1, 3)) # half resolution
return raw, ndi.binary_erosion(raw, iterations=erode) # eroded copy drops the bright harness rim
# ---- 5. final image on the long-capture scale ----------------------------------
def final_image(g, k=3):
tail = g.iloc[-k:]
known = tail[~tail['mode'].str.startswith('unknown')]
use = known if len(known) else tail.iloc[-1:] # fall back to the last image, factor 1
return np.median([smooth(decode(r.file)) * r.factor for r in use.itertuples()], axis=0)Code here was run against the images and calibration files available in December 2026. File layout can change, so check the paths first.