1
0
forked from alberto/dask
Files
dask/example_notebook.ipynb
2026-11-06 18:07:46 -06:00

667 lines
23 KiB
Plaintext
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
{
"cells": [
{
"cell_type": "markdown",
"id": "c0",
"metadata": {},
"source": [
"# EEG cohort from SeaweedFS (S3)\n",
"\n",
"The EDF files are in the bucket `processed`, folder `eeg-edf/` (copied from the NFS with rclone).\n",
"All functions that read the files run **on the Dask workers**: only they can reach the S3 service and have the keys (secret `seaweed-s3`).\n"
]
},
{
"cell_type": "code",
"execution_count": 21,
"id": "c1",
"metadata": {},
"outputs": [],
"source": [
"import os\n",
"import pandas as pd\n",
"from dask.distributed import Client"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "c2",
"metadata": {},
"outputs": [
{
"name": "stderr",
"output_type": "stream",
"text": [
"2026-10-30 02:39:05,032 - distributed.client - ERROR - Failed to reconnect to scheduler after 30.00 seconds, closing client\n"
]
}
],
"source": [
"client = Client(os.environ[\"DASK_SCHEDULER\"], direct_to_workers=False)\n",
"\n",
"S3_ENDPOINT = \"http://seaweedfs-s3.seaweedfs:8333\" # in-cluster address of the S3 gateway\n",
"BASES = [ # bucket/folder, without \"s3://\"\n",
" \"processed/eeg-edf-2025\",\n",
" \"processed/eeg-edf-2026\",\n",
"] # bucket/folder, without \"s3://\"\n",
"\n",
"def s3():\n",
" \"\"\"S3 connection, created on the worker. The keys come from the worker's\n",
" environment (AWS_ACCESS_KEY_ID / AWS_SECRET_ACCESS_KEY from the secret seaweed-s3).\"\"\"\n",
" import s3fs\n",
" return s3fs.S3FileSystem(\n",
" client_kwargs={\"endpoint_url\": S3_ENDPOINT},\n",
" config_kwargs={\"s3\": {\"addressing_style\": \"path\"}},\n",
" )"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "c3",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"400 files\n"
]
},
{
"data": {
"text/html": [
"<div>\n",
"<style scoped>\n",
" .dataframe tbody tr th:only-of-type {\n",
" vertical-align: middle;\n",
" }\n",
"\n",
" .dataframe tbody tr th {\n",
" vertical-align: top;\n",
" }\n",
"\n",
" .dataframe thead th {\n",
" text-align: right;\n",
" }\n",
"</style>\n",
"<table border=\"1\" class=\"dataframe\">\n",
" <thead>\n",
" <tr style=\"text-align: right;\">\n",
" <th></th>\n",
" <th>path</th>\n",
" </tr>\n",
" </thead>\n",
" <tbody>\n",
" <tr>\n",
" <th>0</th>\n",
" <td>processed/eeg-edf/eeg_001/eeg_001.edf</td>\n",
" </tr>\n",
" <tr>\n",
" <th>1</th>\n",
" <td>processed/eeg-edf/eeg_002/eeg_002.edf</td>\n",
" </tr>\n",
" <tr>\n",
" <th>2</th>\n",
" <td>processed/eeg-edf/eeg_003/eeg_003.edf</td>\n",
" </tr>\n",
" <tr>\n",
" <th>3</th>\n",
" <td>processed/eeg-edf/eeg_004/eeg_004.edf</td>\n",
" </tr>\n",
" <tr>\n",
" <th>4</th>\n",
" <td>processed/eeg-edf/eeg_005/eeg_005.edf</td>\n",
" </tr>\n",
" </tbody>\n",
"</table>\n",
"</div>"
],
"text/plain": [
" path\n",
"0 processed/eeg-edf/eeg_001/eeg_001.edf\n",
"1 processed/eeg-edf/eeg_002/eeg_002.edf\n",
"2 processed/eeg-edf/eeg_003/eeg_003.edf\n",
"3 processed/eeg-edf/eeg_004/eeg_004.edf\n",
"4 processed/eeg-edf/eeg_005/eeg_005.edf"
]
},
"execution_count": 25,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"def list_files(bases):\n",
" fs = s3()\n",
" files = []\n",
" for base in bases:\n",
" files += fs.glob(f\"{base}/eeg_*/*.edf\")\n",
" return sorted(files)\n",
"\n",
"files = client.submit(list_files, BASES).result()\n",
"info = pd.DataFrame(files, columns=[\"path\"])\n",
"print(f\"{len(files)} files\")\n",
"info.head()"
]
},
{
"cell_type": "code",
"execution_count": 33,
"id": "c4",
"metadata": {},
"outputs": [
{
"data": {
"text/html": [
"<div>\n",
"<style scoped>\n",
" .dataframe tbody tr th:only-of-type {\n",
" vertical-align: middle;\n",
" }\n",
"\n",
" .dataframe tbody tr th {\n",
" vertical-align: top;\n",
" }\n",
"\n",
" .dataframe thead th {\n",
" text-align: right;\n",
" }\n",
"</style>\n",
"<table border=\"1\" class=\"dataframe\">\n",
" <thead>\n",
" <tr style=\"text-align: right;\">\n",
" <th></th>\n",
" <th>path</th>\n",
" <th>age</th>\n",
" </tr>\n",
" </thead>\n",
" <tbody>\n",
" <tr>\n",
" <th>10</th>\n",
" <td>processed/eeg-edf/eeg_011/eeg_011.edf</td>\n",
" <td>42.776181</td>\n",
" </tr>\n",
" <tr>\n",
" <th>11</th>\n",
" <td>processed/eeg-edf/eeg_012/eeg_012.edf</td>\n",
" <td>45.174538</td>\n",
" </tr>\n",
" <tr>\n",
" <th>12</th>\n",
" <td>processed/eeg-edf/eeg_013/eeg_013.edf</td>\n",
" <td>46.324435</td>\n",
" </tr>\n",
" <tr>\n",
" <th>31</th>\n",
" <td>processed/eeg-edf/eeg_032/eeg_032.edf</td>\n",
" <td>38.965092</td>\n",
" </tr>\n",
" <tr>\n",
" <th>45</th>\n",
" <td>processed/eeg-edf/eeg_046/eeg_046.edf</td>\n",
" <td>40.772074</td>\n",
" </tr>\n",
" <tr>\n",
" <th>...</th>\n",
" <td>...</td>\n",
" <td>...</td>\n",
" </tr>\n",
" <tr>\n",
" <th>370</th>\n",
" <td>processed/eeg-edf/eeg_371/eeg_371.edf</td>\n",
" <td>23.622177</td>\n",
" </tr>\n",
" <tr>\n",
" <th>371</th>\n",
" <td>processed/eeg-edf/eeg_372/eeg_372.edf</td>\n",
" <td>14.521561</td>\n",
" </tr>\n",
" <tr>\n",
" <th>393</th>\n",
" <td>processed/eeg-edf/eeg_394/eeg_394.edf</td>\n",
" <td>13.207392</td>\n",
" </tr>\n",
" <tr>\n",
" <th>395</th>\n",
" <td>processed/eeg-edf/eeg_396/eeg_396.edf</td>\n",
" <td>6.702259</td>\n",
" </tr>\n",
" <tr>\n",
" <th>398</th>\n",
" <td>processed/eeg-edf/eeg_399/eeg_399.edf</td>\n",
" <td>14.061602</td>\n",
" </tr>\n",
" </tbody>\n",
"</table>\n",
"<p>69 rows × 2 columns</p>\n",
"</div>"
],
"text/plain": [
" path age\n",
"10 processed/eeg-edf/eeg_011/eeg_011.edf 42.776181\n",
"11 processed/eeg-edf/eeg_012/eeg_012.edf 45.174538\n",
"12 processed/eeg-edf/eeg_013/eeg_013.edf 46.324435\n",
"31 processed/eeg-edf/eeg_032/eeg_032.edf 38.965092\n",
"45 processed/eeg-edf/eeg_046/eeg_046.edf 40.772074\n",
".. ... ...\n",
"370 processed/eeg-edf/eeg_371/eeg_371.edf 23.622177\n",
"371 processed/eeg-edf/eeg_372/eeg_372.edf 14.521561\n",
"393 processed/eeg-edf/eeg_394/eeg_394.edf 13.207392\n",
"395 processed/eeg-edf/eeg_396/eeg_396.edf 6.702259\n",
"398 processed/eeg-edf/eeg_399/eeg_399.edf 14.061602\n",
"\n",
"[69 rows x 2 columns]"
]
},
"execution_count": 33,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"def get_dates(path):\n",
" \"\"\"Download one EDF file to a temporary file on the worker, read the header\n",
" (birthday and measurement date), and delete the file.\n",
" MNE needs a local file, so the file is downloaded once and both dates are read from it.\"\"\"\n",
" import tempfile, mne\n",
" with tempfile.NamedTemporaryFile(suffix=\".edf\") as tmp:\n",
" s3().get(path, tmp.name)\n",
" raw = mne.io.read_raw_edf(tmp.name, preload=False, verbose=False)\n",
" subject = raw.info.get(\"subject_info\") or {}\n",
" return subject.get(\"birthday\"), raw.info.get(\"meas_date\")\n",
"\n",
"dates = client.gather(client.map(get_dates, files, priority=-10))\n",
"birthdates, meas_dates = zip(*dates)\n",
"\n",
"age = pd.to_datetime(list(meas_dates)).tz_localize(None) - pd.to_datetime(list(birthdates))\n",
"info[\"age\"] = age.days / 30.4375 # age in months\n",
"\n",
"cohort = info[info[\"age\"].between(6, 48)]\n",
"cohort"
]
},
{
"cell_type": "code",
"execution_count": 32,
"id": "c5",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"120 files, 3.9 GB in 72 s → 56 MB/s, 1.67 files/s\n",
"Share of task time: {'t_download': 0.09, 't_load': 0.01, 't_compute': 0.9}\n"
]
},
{
"data": {
"text/html": [
"<div>\n",
"<style scoped>\n",
" .dataframe tbody tr th:only-of-type {\n",
" vertical-align: middle;\n",
" }\n",
"\n",
" .dataframe tbody tr th {\n",
" vertical-align: top;\n",
" }\n",
"\n",
" .dataframe thead th {\n",
" text-align: right;\n",
" }\n",
"</style>\n",
"<table border=\"1\" class=\"dataframe\">\n",
" <thead>\n",
" <tr style=\"text-align: right;\">\n",
" <th></th>\n",
" <th>size_mb</th>\n",
" <th>minutes</th>\n",
" <th>t_download</th>\n",
" <th>t_load</th>\n",
" <th>t_compute</th>\n",
" </tr>\n",
" </thead>\n",
" <tbody>\n",
" <tr>\n",
" <th>count</th>\n",
" <td>120.000000</td>\n",
" <td>120.000000</td>\n",
" <td>120.000000</td>\n",
" <td>120.000000</td>\n",
" <td>120.000000</td>\n",
" </tr>\n",
" <tr>\n",
" <th>mean</th>\n",
" <td>33.270833</td>\n",
" <td>31.031044</td>\n",
" <td>1.771728</td>\n",
" <td>0.218511</td>\n",
" <td>17.470543</td>\n",
" </tr>\n",
" <tr>\n",
" <th>std</th>\n",
" <td>5.261671</td>\n",
" <td>4.906919</td>\n",
" <td>1.639108</td>\n",
" <td>0.067583</td>\n",
" <td>2.863214</td>\n",
" </tr>\n",
" <tr>\n",
" <th>min</th>\n",
" <td>16.873072</td>\n",
" <td>15.666600</td>\n",
" <td>0.378095</td>\n",
" <td>0.090979</td>\n",
" <td>9.242718</td>\n",
" </tr>\n",
" <tr>\n",
" <th>25%</th>\n",
" <td>32.299602</td>\n",
" <td>30.116600</td>\n",
" <td>0.680634</td>\n",
" <td>0.174837</td>\n",
" <td>16.137114</td>\n",
" </tr>\n",
" <tr>\n",
" <th>50%</th>\n",
" <td>32.603041</td>\n",
" <td>30.391600</td>\n",
" <td>0.913733</td>\n",
" <td>0.204039</td>\n",
" <td>16.924555</td>\n",
" </tr>\n",
" <tr>\n",
" <th>75%</th>\n",
" <td>33.329296</td>\n",
" <td>31.108267</td>\n",
" <td>2.662091</td>\n",
" <td>0.238240</td>\n",
" <td>17.766862</td>\n",
" </tr>\n",
" <tr>\n",
" <th>max</th>\n",
" <td>65.760560</td>\n",
" <td>61.316600</td>\n",
" <td>7.616306</td>\n",
" <td>0.576866</td>\n",
" <td>31.160814</td>\n",
" </tr>\n",
" </tbody>\n",
"</table>\n",
"</div>"
],
"text/plain": [
" size_mb minutes t_download t_load t_compute\n",
"count 120.000000 120.000000 120.000000 120.000000 120.000000\n",
"mean 33.270833 31.031044 1.771728 0.218511 17.470543\n",
"std 5.261671 4.906919 1.639108 0.067583 2.863214\n",
"min 16.873072 15.666600 0.378095 0.090979 9.242718\n",
"25% 32.299602 30.116600 0.680634 0.174837 16.137114\n",
"50% 32.603041 30.391600 0.913733 0.204039 16.924555\n",
"75% 33.329296 31.108267 2.662091 0.238240 17.766862\n",
"max 65.760560 61.316600 7.616306 0.576866 31.160814"
]
},
"execution_count": 32,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"import time\n",
"\n",
"N_FILES = 120 # number of files for the test (all: len(files))\n",
"REPEAT = 1 # repeat the computation to make tasks longer (2, 3, …)\n",
"\n",
"BANDS = {\"delta\": (1, 4), \"theta\": (4, 8), \"alpha\": (8, 13), \"beta\": (13, 30), \"gamma\": (30, 40)}\n",
"\n",
"def _process(path):\n",
" \"\"\"Download the whole EDF file, load all of it, and compute:\n",
" - a broadband filter and a Welch power spectrum,\n",
" - for each band: band-pass filter + Hilbert envelope (CPU-heavy).\n",
" Returns a small result and the time of each step.\"\"\"\n",
" import os, time, tempfile, mne, numpy as np\n",
" t0 = time.perf_counter()\n",
" with tempfile.NamedTemporaryFile(suffix=\".edf\") as tmp:\n",
" s3().get(path, tmp.name) # network: whole file\n",
" size_mb = os.path.getsize(tmp.name) / 1e6\n",
" t1 = time.perf_counter()\n",
" raw = mne.io.read_raw_edf(tmp.name, preload=True, verbose=False) # whole file in memory\n",
" t2 = time.perf_counter()\n",
"\n",
" sf = raw.info[\"sfreq\"]\n",
" out = {}\n",
" for _ in range(REPEAT):\n",
" # 1) broadband filter + Welch spectrum\n",
" broad = raw.copy().filter(1.0, 40.0, verbose=False)\n",
" n_fft = min(int(sf * 4), broad.n_times)\n",
" psd = broad.compute_psd(method=\"welch\", fmin=1, fmax=40,\n",
" n_fft=n_fft, n_per_seg=n_fft, n_overlap=n_fft // 2,\n",
" reject_by_annotation=False, verbose=False)\n",
" p, f = psd.get_data(return_freqs=True)\n",
" for b, (lo, hi) in BANDS.items():\n",
" out[f\"psd_{b}\"] = float(p[:, (f >= lo) & (f < hi)].mean())\n",
" del broad\n",
"\n",
" # 2) band envelopes: filter the whole signal in each band, then Hilbert\n",
" for b, (lo, hi) in BANDS.items():\n",
" band = raw.copy().filter(lo, hi, verbose=False)\n",
" band.apply_hilbert(envelope=True, verbose=False)\n",
" out[f\"env_{b}\"] = float(band.get_data().mean())\n",
" del band\n",
" t3 = time.perf_counter()\n",
"\n",
" return {\"path\": path, \"size_mb\": size_mb, \"minutes\": raw.times[-1] / 60, \"sfreq\": sf,\n",
" \"t_download\": t1 - t0, \"t_load\": t2 - t1, \"t_compute\": t3 - t2, **out}\n",
"\n",
"def process(path):\n",
" try:\n",
" return _process(path)\n",
" except Exception as e:\n",
" return {\"path\": path, \"error\": repr(e)}\n",
"\n",
"sample = files[:N_FILES]\n",
"start = time.perf_counter()\n",
"results = client.gather(client.map(process, sample, priority=-10, pure=False))\n",
"wall = time.perf_counter() - start\n",
"\n",
"res = pd.DataFrame(results)\n",
"if \"error\" in res:\n",
" print(res[res[\"error\"].notna()][[\"path\", \"error\"]])\n",
" res = res[res[\"error\"].isna()]\n",
"\n",
"total_mb = res[\"size_mb\"].sum()\n",
"busy = res[[\"t_download\", \"t_load\", \"t_compute\"]].sum()\n",
"print(f\"{len(res)} files, {total_mb/1024:.1f} GB in {wall:.0f} s \"\n",
" f\"→ {total_mb/wall:.0f} MB/s, {len(res)/wall:.2f} files/s\")\n",
"print(\"Share of task time:\", (busy / busy.sum()).round(2).to_dict())\n",
"res.describe()[[\"size_mb\", \"minutes\", \"t_download\", \"t_load\", \"t_compute\"]]"
]
},
{
"cell_type": "code",
"execution_count": 20,
"id": "b9d6f476",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"READ: 120 files, 3.8 GB in 9 s → 452 MB/s total (431 MiB/s)\n",
"per task: median 14 MB/s, min 6, max 41\n"
]
},
{
"data": {
"text/html": [
"<div>\n",
"<style scoped>\n",
" .dataframe tbody tr th:only-of-type {\n",
" vertical-align: middle;\n",
" }\n",
"\n",
" .dataframe tbody tr th {\n",
" vertical-align: top;\n",
" }\n",
"\n",
" .dataframe thead th {\n",
" text-align: right;\n",
" }\n",
"</style>\n",
"<table border=\"1\" class=\"dataframe\">\n",
" <thead>\n",
" <tr style=\"text-align: right;\">\n",
" <th></th>\n",
" <th>mb</th>\n",
" <th>seconds</th>\n",
" <th>mb_s</th>\n",
" </tr>\n",
" </thead>\n",
" <tbody>\n",
" <tr>\n",
" <th>count</th>\n",
" <td>120.000000</td>\n",
" <td>120.000000</td>\n",
" <td>120.000000</td>\n",
" </tr>\n",
" <tr>\n",
" <th>mean</th>\n",
" <td>32.766451</td>\n",
" <td>2.501361</td>\n",
" <td>15.222508</td>\n",
" </tr>\n",
" <tr>\n",
" <th>std</th>\n",
" <td>4.365266</td>\n",
" <td>0.935034</td>\n",
" <td>6.600385</td>\n",
" </tr>\n",
" <tr>\n",
" <th>min</th>\n",
" <td>16.578072</td>\n",
" <td>0.557785</td>\n",
" <td>6.384499</td>\n",
" </tr>\n",
" <tr>\n",
" <th>25%</th>\n",
" <td>32.242019</td>\n",
" <td>1.850727</td>\n",
" <td>10.478099</td>\n",
" </tr>\n",
" <tr>\n",
" <th>50%</th>\n",
" <td>32.649662</td>\n",
" <td>2.408755</td>\n",
" <td>13.657625</td>\n",
" </tr>\n",
" <tr>\n",
" <th>75%</th>\n",
" <td>33.620235</td>\n",
" <td>3.082557</td>\n",
" <td>17.772913</td>\n",
" </tr>\n",
" <tr>\n",
" <th>max</th>\n",
" <td>53.696960</td>\n",
" <td>4.781475</td>\n",
" <td>41.132171</td>\n",
" </tr>\n",
" </tbody>\n",
"</table>\n",
"</div>"
],
"text/plain": [
" mb seconds mb_s\n",
"count 120.000000 120.000000 120.000000\n",
"mean 32.766451 2.501361 15.222508\n",
"std 4.365266 0.935034 6.600385\n",
"min 16.578072 0.557785 6.384499\n",
"25% 32.242019 1.850727 10.478099\n",
"50% 32.649662 2.408755 13.657625\n",
"75% 33.620235 3.082557 17.772913\n",
"max 53.696960 4.781475 41.132171"
]
},
"execution_count": 20,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"import time\n",
"\n",
"N_FILES = 120 # files to read (use different ones than the CPU test, to avoid cache)\n",
"OFFSET = 120 # start position in `files`\n",
"CHUNK_MB = 8 # read size per request\n",
"ENDPOINT = S3_ENDPOINT # or \"http://seaweedfs-s3-local.seaweedfs:8333\" to compare\n",
"\n",
"def _read_whole(path, endpoint=ENDPOINT, chunk_mb=CHUNK_MB):\n",
" \"\"\"Read the whole object from S3 in chunks, without saving it.\n",
" Only a CRC32 is computed, so the task is limited by I/O, not CPU.\"\"\"\n",
" import time, zlib, s3fs\n",
" fs = s3fs.S3FileSystem(client_kwargs={\"endpoint_url\": endpoint},\n",
" config_kwargs={\"s3\": {\"addressing_style\": \"path\"}})\n",
" chunk = chunk_mb * 1024 * 1024\n",
" t0 = time.perf_counter()\n",
" n, crc = 0, 0\n",
" with fs.open(path, \"rb\", block_size=chunk, cache_type=\"none\") as f:\n",
" while True:\n",
" b = f.read(chunk)\n",
" if not b:\n",
" break\n",
" n += len(b)\n",
" crc = zlib.crc32(b, crc)\n",
" dt = time.perf_counter() - t0\n",
" return {\"path\": path, \"mb\": n / 1e6, \"seconds\": dt, \"mb_s\": n / 1e6 / dt, \"crc\": crc}\n",
"\n",
"def read_whole(path):\n",
" try:\n",
" return _read_whole(path)\n",
" except Exception as e:\n",
" return {\"path\": path, \"error\": repr(e)}\n",
"\n",
"sample = files[OFFSET:OFFSET + N_FILES]\n",
"start = time.perf_counter()\n",
"results = client.gather(client.map(read_whole, sample, priority=-10, pure=False))\n",
"wall = time.perf_counter() - start\n",
"\n",
"io = pd.DataFrame(results)\n",
"if \"error\" in io:\n",
" print(io[io[\"error\"].notna()][[\"path\", \"error\"]])\n",
" io = io[io[\"error\"].isna()]\n",
"\n",
"total = io[\"mb\"].sum()\n",
"print(f\"READ: {len(io)} files, {total/1024:.1f} GB in {wall:.0f} s \"\n",
" f\"→ {total/wall:.0f} MB/s total ({total/wall/1.048576:.0f} MiB/s)\")\n",
"print(f\"per task: median {io['mb_s'].median():.0f} MB/s, min {io['mb_s'].min():.0f}, max {io['mb_s'].max():.0f}\")\n",
"io.describe()[[\"mb\", \"seconds\", \"mb_s\"]]"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "base",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.14.7"
}
},
"nbformat": 4,
"nbformat_minor": 5
}