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
6 changes: 3 additions & 3 deletions src/content/docs/architecture/data-flow.md
Original file line number Diff line number Diff line change
Expand Up @@ -106,9 +106,9 @@ POST /jobs/batch
Used for Geant4 simulations. Runs entirely in the browser — no backend required.

1. The Pyodide converter generates `geometry.gdml` and `run.mac`.
2. These files are passed to the **Geant4 Wasm Worker**.
3. Geant4 executes the simulation in WebAssembly.
4. Output files are parsed by `Geant4ResultsFileParser`.
2. `Geant4LocalWorkerSimulationService` splits the total primary count across up to `MAX_LOCAL_GEANT4_WORKERS` (currently `3`) parallel **Geant4 Wasm Workers** and injects unique `/random/setSeeds` pairs into each worker's `run.mac` (`Geant4MacroHelpers.ts`).
3. Each worker executes its portion of the simulation in an isolated WebAssembly instance and reports task progress independently.
4. Once all workers finish, partial scorer output files are summed cell-by-cell (`mergeGeant4ResultFiles`) and parsed by `Geant4ResultsFileParser`.
5. Results are rendered directly — no server round-trip.

:::note
Expand Down
131 changes: 70 additions & 61 deletions src/content/docs/frontend/geant4-wasm.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,25 +8,30 @@ YAPTIDE supports running **Geant4 simulations entirely in the browser** using a
## Architecture

```
┌───────────────────────────────────────────────────┐
│ Browser │
│ │
│ ┌──────────┐ ┌────────────┐ ┌────────────┐ │
│ │ Editor │ → │ Pyodide │ → │ Geant4 │ │
│ │ JSON │ │ Converter │ │ Wasm Worker│ │
│ │ │ │ │ │ │ │
│ │ │ │ .gdml + │ │ Executes │ │
│ │ │ │ .mac files │ │ simulation │ │
│ └──────────┘ └────────────┘ └─────┬──────┘ │
│ │ │
│ ┌─────▼──────┐ │
│ │ Results │ │
│ │ Parser │ │
│ │ │ │
│ │ JSRoot │ │
│ │ Plots │ │
│ └────────────┘ │
└───────────────────────────────────────────────────┘
┌────────────────────────────────────────────────────────────────────────────┐
│ Browser │
│ │
│ ┌──────────┐ ┌────────────┐ ┌──────────────────┐ │
│ │ Editor │ → │ Pyodide │ → │ Macro Splitter │ │
│ │ JSON │ │ Converter │ │ (primaries + │ │
│ │ │ │ .gdml + │ │ unique RNG │ │
│ │ │ │ .mac files │ │ seeds per task) │ │
│ └──────────┘ └────────────┘ └────────┬─────────┘ │
│ │ │
│ ┌────────────────────┼────────────────────┐ │
│ ▼ ▼ ▼ │
│ ┌─────────────┐ ┌─────────────┐ ┌─────────────┐ │
│ │ Geant4 Wasm │ │ Geant4 Wasm │ ... │ Geant4 Wasm │ │
│ │ Worker 1 │ │ Worker 2 │ │ Worker K │ │
│ └──────┬──────┘ └──────┬──────┘ └──────┬──────┘ │
│ └────────────────────┼────────────────────┘ │
│ ▼ │
│ ┌───────────────────┐ │
│ │ Scorer File Merger│ │
│ │ & Results Parser │ │
│ │ → JSRoot Plots │ │
│ └───────────────────┘ │
└────────────────────────────────────────────────────────────────────────────┘
```

## Execution Flow
Expand All @@ -38,69 +43,71 @@ The Pyodide converter generates Geant4-native input files from the editor JSON:
- **`geometry.gdml`** — GDML XML describing the simulation geometry (solids, volumes, placements)
- **`run.mac`** — Geant4 macro with particle source commands (`/gps/...`), scoring mesh definitions (`/score/...`), and run commands (`/run/beamOn`)

### 2. Geant4 Wasm Worker
### 2. Multi-Worker Partitioning and RNG Seeding

`Geant4Worker/` contains the Web Worker that loads and runs the Geant4 Wasm binary:
Each Geant4 Wasm module is compiled single-threaded (without Emscripten pthreads). To utilize multiple CPU cores in the browser, `Geant4LocalWorkerSimulationService` splits a single simulation (`jobId`) across a pool of independent Web Workers (`workers: Record<JobId, Geant4Worker[]>`):

```typescript
// Simplified worker flow
self.onmessage = async (event) => {
const { gdml, macro } = event.data;

// Load Geant4 Wasm
const geant4 = await loadGeant4Wasm();

// Write input files to the virtual filesystem
geant4.FS.writeFile('/geometry.gdml', gdml);
geant4.FS.writeFile('/run.mac', macro);
1. **Worker count (`determineWorkerCount`)**: Defaults to `Math.max(1, Math.min(navigator.hardwareConcurrency - 1, MAX_LOCAL_GEANT4_WORKERS))`, reserving one core for UI responsiveness and capping concurrency at `MAX_LOCAL_GEANT4_WORKERS` (currently `3`) to stay within browser memory limits. Users can adjust the count via the **Number of tasks** field in `RunSimulationForm.tsx` (still clamped to `MAX_LOCAL_GEANT4_WORKERS`).
2. **Primary particle distribution (`distributePrimaries` in `services/Geant4MacroHelpers.ts`)**: Splits the total `/run/beamOn` primary count evenly across the workers, assigning any remainder particles to the first workers. Workers that would receive `0` primaries (when primaries < worker count) are not spawned.
3. **Independent RNG streams (`prepareWorkerMacro` in `services/Geant4MacroHelpers.ts`)**: Generates a unique pair of positive 32-bit cryptographic seeds via `crypto.getRandomValues()` (`generateRandomSeeds`) and injects `/random/setSeeds <seed1> <seed2>` immediately before the rewritten `/run/beamOn <workerPrimaries>` command in each worker's `run.mac`. Without distinct seeds, every worker would replay identical Monte Carlo histories.

// Execute
geant4.run(['/run.mac']);
### 3. Geant4 Wasm Workers

// Read output files from the virtual filesystem
const outputFiles = readOutputFiles(geant4.FS);
`Geant4Worker/` wraps the Web Worker (`geant4Worker.worker.ts`) that loads and executes the Geant4 Wasm binary in an isolated memory space:

// Post results back to main thread
self.postMessage({ type: 'results', data: outputFiles });
```typescript
// Simplified per-worker flow
self.onmessage = async (event) => {
// 1. Load Geant4 Wasm module (createWasmModule)
// 2. Load datasets (full preloaded packages or lazy on-demand files)
// 3. Write geometry.gdml and this worker's tailored run.mac to MEMFS
// 4. Execute Geant4GDMRun(geometryDefinition, macroFile)
// 5. Return requested scorer dump files via READ_FILE messages
};
```

### 3. Dataset Download
Each worker runs independently with its own Wasm linear memory and virtual filesystem (Shared-Nothing model). Cancelling a job (`cancelJob`) cancels all workers belonging to that `jobId`.

Geant4 requires physics **datasets** (cross-section tables, etc.) to run simulations. These are downloaded on first use:
### 4. Dataset Loading

1. The UI detects that Geant4 datasets are needed
2. `Geant4DatasetContextProvider` triggers the download
3. Datasets are downloaded from a CDN and cached in the browser's IndexedDB
4. Subsequent runs skip the download
Geant4 requires physics **datasets** (cross-section tables, etc.) to run simulations. Two loading modes are supported:

- **Partial (Lazy, default in multi-worker runs)**: Registers dataset paths with Emscripten's `FS_createLazyFile` using JSON manifests (`S3_JSON_FILES`) so only the files touched by the active simulation are fetched on demand.
- **Full (Preloaded)**: Downloads all dataset archives via `Geant4DatasetContextProvider` and caches them in the browser's IndexedDB (`EM_PRELOAD_CACHE`) for offline/cached reuse.

:::caution
The dataset download can be several hundred MB. Users are informed of the progress and can cancel.
Full dataset downloads total roughly 1.8 GB and are cached in IndexedDB. Because each Web Worker has its own Emscripten virtual filesystem (MEMFS), loading full datasets into multiple workers simultaneously increases memory usage significantly; lazy/partial datasets are much lighter for multi-worker runs.
:::

### 4. Progress Reporting
### 5. Progress Reporting and State Aggregation

The Wasm worker reports progress back to the main thread:
Each Wasm worker reports its own simulated primary count back to the main thread via `Geant4SetProgressFunction` and `postMessage`:

```typescript
// In the worker
geant4.onProgress = (simulated, total) => {
self.postMessage({
type: 'progress',
data: { simulatedPrimaries: simulated, requestedPrimaries: total }
const progressCallback = (progress: number) => {
workerPostMessage({
type: Geant4WorkerMessageType.PROGRESS,
data: progress
});
};
```

The `Geant4LocalWorkerSimulationService` translates these into the same status format as the remote service, so the UI renders progress bars identically.
`Geant4LocalWorkerSimulationService` aggregates the worker pool for each `jobId`:

- **`getJobTasksStatus(jobId)`** returns one `{ requestedPrimaries, simulatedPrimaries }` entry per worker, matching the multi-task format consumed by `taskTotals()` in the UI.
- **`getJobCombinedState(jobId)`** derives the overall job status across all workers (`FAILED` if any failed, `CANCELED` if any was canceled, `RUNNING` while any worker is still running, `COMPLETED` only once all workers finish).
- **`getJobStartTime` / `getJobEndTime`** report the earliest worker start timestamp and the latest worker completion timestamp.

### 5. Result Parsing
### 6. Result Merging and Parsing

Output files from the Geant4 run are parsed by `Geant4ResultsFileParser`:
Once every worker in a job reaches `COMPLETED`, `hydrateResults(jobId)` aggregates and parses the outputs:

- Reads scorer output files from the Wasm virtual filesystem
- Converts them into the standard `Estimator` → `Page` structure
- Results are passed directly to JSRoot for rendering
1. Finds all output filenames declared via `/score/dumpQuantityToFile` in `run.mac`.
2. Fetches each output file from every worker (`fetchResultsFile`).
3. Merges the partial scorer files with **`mergeGeant4ResultFiles`** (`services/Geant4MacroHelpers.ts`), which preserves the 3-line Geant4 header and sums `total(value)`, `total(val^2)`, and `entry` cell-by-cell across all workers for each mesh coordinate `(iX, iY, iZ)`.
4. Passes the merged files into **`Geant4ResultsFileParser`**, which normalizes summed `total(value)` columns by the job's total `numPrimaries[jobId]` and builds the standard `Estimator` → `Page` structures for JSRoot rendering.
5. Calls `markSafeForTermination()` on every worker in the job to release Wasm memory.

## Demo Mode

Expand Down Expand Up @@ -131,8 +138,10 @@ The macro generator creates:

### Limitations

- **Performance**: WebAssembly runs single-threaded and is slower than native Geant4. Complex simulations with many primaries may take several minutes.
- **Memory**: Large geometries or high-resolution scoring meshes may exhaust browser memory (typically ~2–4 GB limit).
- **Performance**: Each Geant4 Wasm module is single-threaded and slower than native Geant4. Parallelizing primaries across multiple Web Workers provides near-linear speedup for large primary counts, though each worker repeats `/run/initialize` (physics table construction), adding a fixed startup overhead.
- **Memory and worker cap**: Web Workers do not share memory (Shared-Nothing model). Each worker allocates its own Emscripten Wasm heap (currently fixed at `-s TOTAL_MEMORY=512MB` in the upstream `geant-web-application` build, without `ALLOW_MEMORY_GROWTH`) plus its own MEMFS virtual filesystem. Spawning too many concurrent workers can exceed the browser tab's memory/contiguous `ArrayBuffer` allocation limits (`RangeError: Array buffer allocation failed`). Concurrency is therefore capped at `MAX_LOCAL_GEANT4_WORKERS = 3`.
- *Scaling further*: Rebuilding the Wasm binary with a smaller initial heap and dynamic growth (e.g., `-s INITIAL_MEMORY=64MB -s ALLOW_MEMORY_GROWTH=1 -s MAXIMUM_MEMORY=512MB`) or compiling multithreaded Geant4 with Emscripten pthreads (`SharedArrayBuffer` + COOP/COEP headers) would allow raising this cap to use all host CPU cores.
- **Additive merging assumption**: `mergeGeant4ResultFiles` combines worker outputs by summing `total(value)`, `total(val^2)`, and `entry` per bin before dividing by total primaries. This is exact for additive primitive scorers (dose, energy deposit, fluence), whereas ratio/weighted quantities (such as dose-averaged LET) would require weighted merging if added in the future.
- **Physics models**: The Wasm build may not include all Geant4 physics lists. Check the specific build for available models.

## Webpack Configuration
Expand All @@ -159,7 +168,7 @@ config.resolve.fallback = {
Check the browser console for network errors. The CDN URL must be accessible. Verify IndexedDB storage quota isn't exhausted.

**Simulation crashes:**
Check the browser console for Wasm memory errors. Reduce the number of primaries or simplify the geometry. The Wasm runtime has a hard memory limit.
Check the browser console for Wasm memory errors (such as `RangeError: Array buffer allocation failed`). Reduce **Number of tasks** (worker count), switch to **Partial (Lazy)** datasets, reduce the number of primaries, or simplify the geometry. Each Wasm worker has a hard memory limit and occupies its own linear memory buffer.

**Slow performance:**
Geant4 Wasm is single-threaded. For large simulations, use the remote backend with SHIELD-HIT12A or FLUKA instead.
Increase **Number of tasks** (up to `MAX_LOCAL_GEANT4_WORKERS`) to parallelize primaries across browser Web Workers. For very large simulations, use the remote backend with SHIELD-HIT12A or FLUKA instead.
36 changes: 15 additions & 21 deletions src/content/docs/frontend/simulation-services.md
Original file line number Diff line number Diff line change
Expand Up @@ -90,7 +90,7 @@ Batch submissions require Keycloak authentication (PLGrid credentials).

## Local Simulation Service (Geant4 Wasm)

`services/Geant4LocalWorkerSimulationService.ts` runs Geant4 simulations entirely in the browser.
`services/Geant4LocalWorkerSimulationService.ts` runs Geant4 simulations entirely in the browser across a pool of parallel Web Workers.

### Execution Flow

Expand All @@ -102,36 +102,30 @@ Batch submissions require Keycloak authentication (PLGrid credentials).
→ geometry.gdml + run.mac
│
▼
3. Geant4 Wasm Worker
→ Executes simulation
→ Produces output files
3. Macro Partitioning (Geant4MacroHelpers.ts)
→ Determines worker count (min(cores - 1, MAX_LOCAL_GEANT4_WORKERS))
→ Splits /run/beamOn primaries across K workers
→ Injects unique /random/setSeeds per worker
│
▼
4. Geant4ResultsFileParser
→ Parses output into estimators/pages
4. Geant4 Wasm Workers (1..K in parallel)
→ Each worker executes its portion in isolated Wasm memory
→ Produces partial scorer output files
│
▼
5. UI renders results (JSRoot)
5. Merge & Parse (Geant4MacroHelpers.ts → Geant4ResultsFileParser)
→ Sums total(value), total(val^2), entry across all workers
→ Normalizes by total primaries into estimators/pages
│
▼
6. UI renders results (JSRoot) and terminates workers
```

No server communication occurs. This path works in **demo mode**.

### Progress Tracking

The Geant4 Wasm worker reports progress via `postMessage`:

```typescript
// In the Wasm worker
self.postMessage({
type: 'progress',
data: {
simulatedPrimaries: 5000,
requestedPrimaries: 10000
}
});
```

The service updates the UI's progress bars using the same interface as the remote service.
Each Geant4 Wasm worker reports its simulated primaries via `postMessage`. `Geant4LocalWorkerSimulationService` exposes one entry per worker in `jobTasksStatus` (`{ requestedPrimaries, simulatedPrimaries }`) and derives the overall `jobState` across the worker pool (`getJobCombinedState`). The UI aggregates these entries via `taskTotals()`, rendering progress bars identically to multi-task remote jobs.

## Result Format

Expand Down