Back to home page

EIC code displayed by LXR

 
 

    


Warning, /firebird/CLAUDE.md is written in an unsupported language. File is not indexed.

0001 # CLAUDE.md
0002 
0003 This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
0004 
0005 ## Project Overview
0006 
0007 **Firebird** is a web-based event display framework for particle physics experiments, 
0008 specifically designed for the Electron-Ion Collider (EIC). 
0009 It visualizes detector geometries, particle trajectories, and physics processes using modern web technologies. 
0010 Firebird serves research, debugging/QC, and educational purposes.
0011 
0012 **Live deployment:** https://seeeic.org (Firebird Event Display application)
0013 **Documentation:** https://eic.github.io/firebird/ (VitePress documentation site)
0014 
0015 ## Repository Structure
0016 
0017 This is a **monorepo** containing three interdependent components:
0018 
0019 - **firebird-ng/** - Angular 20 frontend (TypeScript, Three.js, RxJS)
0020 - **pyrobird/** - Python Flask backend (file server, ROOT conversion)
0021 - **dd4hep-plugin/** - C++ Geant4/DD4Hep plugin (trajectory extraction during simulation)
0022 
0023 The documentation source lives in:
0024 - **docs/** - VitePress documentation site (deployed to GitHub Pages)
0025 - **firebird-ng/src/assets/doc** - Documentation embedded in the Angular application
0026 
0027 ## Common Development Commands
0028 
0029 ### Frontend (firebird-ng)
0030 
0031 ```bash
0032 cd firebird-ng
0033 
0034 # Development server with hot reload
0035 ng serve                       # http://localhost:4200
0036 
0037 # Testing
0038 npm test                       # Interactive tests (Karma)
0039 npm run test:headless          # CI mode (headless Chrome)
0040 ng test --include='**/my-component.spec.ts'  # Run single test file
0041 
0042 # Building
0043 npm run build                 # Production build
0044 npm run build:ghpages         # GitHub Pages deployment
0045 npm run build:watch           # Watch mode for development
0046 
0047 # Generate components (Angular CLI)
0048 ng generate component component-name
0049 ng generate service service-name
0050 ```
0051 
0052 ### Backend (pyrobird)
0053 
0054 ```bash
0055 cd pyrobird
0056 
0057 # Development installation with all optional features
0058 python -m pip install --editable .[dev,batch,xrootd]
0059 
0060 # Start development server
0061 pyrobird serve                                    # Serves files from CWD
0062 pyrobird serve --work-path=/path/to/data         # Restrict to specific directory
0063 gunicorn --bind 0.0.0.0:5454 pyrobird.server:flask_app --log-level debug
0064 
0065 # Testing (requires dev dependencies)
0066 pytest ./tests/unit_tests                        # Run unit tests
0067 pytest ./tests/integration_tests                 # Run integration tests
0068 pytest -x --pdb                                  # Stop on first error, debug
0069 pytest ./tests/unit_tests/test_cli.py            # Run single test file
0070 pytest ./tests/unit_tests/test_cli.py::test_name # Run specific test
0071 
0072 # CLI utilities
0073 pyrobird convert input.root output.json          # Convert ROOT to Firebird DEX
0074 pyrobird merge file1.json file2.json -o out.json # Merge DEX files
0075 pyrobird geo geometry.root                       # Extract geometry
0076 ```
0077 
0078 ### DD4Hep Plugin (dd4hep-plugin)
0079 
0080 ```bash
0081 cd dd4hep-plugin
0082 mkdir build && cd build
0083 cmake ..
0084 make && make install        # Installs to ./prefix/lib
0085 
0086 # Make library discoverable
0087 cd ..
0088 export LD_LIBRARY_PATH="$(pwd)/prefix/lib:$LD_LIBRARY_PATH"
0089 
0090 # Run simulation with plugin
0091 ddsim --steeringFile=firebird_steering.py \
0092       --compactFile=detector.xml \
0093       -N=100 \
0094       --outputFile=sim.edm4hep.root \
0095       --inputFiles=input.hepmc
0096 ```
0097 
0098 ### Full Build (all components)
0099 
0100 ```bash
0101 # Root level orchestration
0102 python build.py all              # Build frontend and copy to pyrobird
0103 python build.py --dry-run all    # Test build without changes
0104 
0105 # build all with changing version (source files will be changed)
0106 python build.py all --version=v2025.12.1
0107 ```
0108 
0109 ## High-Level Architecture
0110 
0111 Firebird is made so that running frontend alone is sufficient for most use cases.
0112 Backend serves for:
0113 - some file conversions (e.g. working with xrootd, editing events, etc.)
0114 - serving firebird locally for users
0115 - using pip install for deployment
0116 
0117 
0118 ### Frontend Architecture (firebird-ng)
0119 
0120 The Angular application uses a **service-oriented architecture** with clear separation of concerns:
0121 
0122 #### Core Services Layer
0123 
0124 - **three.service.ts** (3700+ lines) - Central Three.js orchestration
0125   - Scene setup (cameras, lights, rendering loop)
0126   - Raycasting for object selection
0127   - BVH (Bounding Volume Hierarchy) acceleration for performance
0128   - Clipping planes and measurement tools
0129   - Frame callbacks for animations
0130 
0131 - **event-display.service.ts** - High-level event visualization
0132   - Data loading (geometry, events, ROOT files)
0133   - Time animation and event cycling
0134   - Painter orchestration
0135   - Animation manager integration
0136 
0137 - **geometry.service.ts** - Detector geometry management
0138   - Load and process ROOT geometry files
0139   - Geometry optimization and post-processing
0140 
0141 - **data-model.service.ts** - Event data management
0142   - Load Firebird DEX format events
0143   - Load EDM4eic ROOT files
0144   - Event registry and navigation
0145 
0146 #### Data Model Layer
0147 
0148 The **event group factory pattern** enables extensibility:
0149 
0150 - `EventGroup` - Abstract base class for all event components
0151 - `BoxHitGroup` - Tracker hits (3D boxes with energy/time)
0152 - `PointTrajectoryGroup` - Particle trajectories (polylines)
0153 - Component registry with `registerComponentFactory()` for custom types
0154 
0155 To add a new component type:
0156 1. Extend `EventGroup` and implement `toDexObject()`
0157 2. Create a factory implementing `EventGroupFactory`
0158 3. Register the factory at initialization
0159 
0160 #### Painter System
0161 
0162 Painters render event data to Three.js objects using **time-aware rendering**:
0163 
0164 - `data-model-painter.ts` - Main orchestrator (filters by time range)
0165 - `trajectory.painter.ts` - Particle tracks with smooth splines
0166 - `box-hit.painter.ts` - Individual tracker hits
0167 - `step-track.painter.ts` - Geant4 step-by-step trajectories
0168 
0169 The system uses Angular signals for reactive time updates that automatically propagate through the painter hierarchy.
0170 
0171 ### Backend Architecture (pyrobird)
0172 
0173 Flask server with three main API endpoints:
0174 
0175 - `GET /api/v1/download` - Secure file downloads with access control
0176 - `GET /api/v1/convert/edm4eic/<event>` - Convert EDM4eic events to JSON
0177 - `GET /assets/config.jsonc` - Serve dynamic configuration
0178 
0179 **Security model** (restrictive by default):
0180 - `--work-path` restricts downloads to specific directory (default: CWD)
0181 - `--allow-any-file` disables path restrictions (DANGEROUS in production)
0182 - `--disable-files` disables all downloads
0183 - Path traversal prevention built-in
0184 
0185 ### DD4Hep Plugin Architecture
0186 
0187 Three Geant4 actions for trajectory extraction:
0188 
0189 1. **FirebirdTrajectoryWriterEventAction** (PRIMARY USE CASE)
0190    - Saves trajectories at end of event (same as Geant4 event display)
0191    - Extensive filtering: momentum, vertex position, step cuts, particle type
0192    - Configured via Python steering files
0193 
0194 2. **FirebirdTrajectoryWriterSteppingAction** (CUSTOMIZATION)
0195    - Captures data step-by-step as simulation runs
0196    - Users modify C++ code for custom physics data extraction
0197    - Access to detailed internal Geant4 information
0198 
0199 3. **TextDumpingSteppingAction** (SIMPLE TEXT OUTPUT)
0200    - Easy-to-parse text format for custom analysis
0201    - Example for plugin extension
0202 
0203 ## Firebird Data Exchange Format (DEX)
0204 
0205 Standardized JSON format for event data interoperability:
0206 
0207 ```json
0208 {
0209   "type": "firebird-dex-json",
0210   "version": "0.04",
0211   "origin": {
0212     "source": "filename.root",
0213     "by": "Pyrobird"
0214   },
0215   "events": [
0216     {
0217       "id": "event_0",
0218       "groups": [
0219         {
0220           "name": "BarrelHits",
0221           "type": "BoxTrackerHit",
0222           "hits": [{"pos": [x,y,z], "dim": [dx,dy,dz], "t": [t,dt], "ed": [e,de]}]
0223         },
0224         {
0225           "name": "CentralTracks",
0226           "type": "TrackerLinePointTrajectory",
0227           "lines": [{"points": [[x,y,z,t,dx,dy,dz,dt], ...], "params": [...]}]
0228         }
0229       ]
0230     }
0231   ]
0232 }
0233 ```
0234 
0235 **Key types:**
0236 - `BoxTrackerHit` - 3D box hits with energy/time information
0237 - `TrackerLinePointTrajectory` - Polyline trajectories with metadata
0238 - Extensible via factory pattern for custom component types
0239 
0240 ## Important Architectural Patterns
0241 
0242 ### 1. Factory Pattern for Event Components
0243 
0244 Component factories enable DEX deserialization without modifying core code. Register new types with `registerComponentFactory()` in appropriate initialization code (typically in the component's own file or a central registry).
0245 
0246 ### 2. Time-Aware Rendering
0247 
0248 The painter system filters data by time range using Angular signals:
0249 - `EventTime` signal propagates through painter hierarchy
0250 - Components show/hide based on time range
0251 - Tween.js enables smooth animations
0252 
0253 ### 3. BVH Acceleration
0254 
0255 `three-mesh-bvh` provides fast raycasting for object selection:
0256 - Lazy BVH computation on demand
0257 - Frustum culling for performance
0258 - Critical for large detector geometries
0259 
0260 ### 4. Service Singletons
0261 
0262 Angular services are singletons managing global state:
0263 - Scene management (three.service)
0264 - Event data (data-model.service)
0265 - Configuration (config.service)
0266 - URL parameters (url.service)
0267 
0268 ### 5. Security by Configuration (pyrobird)
0269 
0270 Restrictive defaults prevent unauthorized file access:
0271 - Explicit opt-in for dangerous features
0272 - Path traversal prevention
0273 - CORS disabled by default
0274 
0275 ## Testing Infrastructure
0276 
0277 ### Frontend Testing
0278 - **Framework:** Karma + Jasmine
0279 - **CI:** GitHub Actions on every push/PR (Node.js 22, headless Chrome)
0280 - Run tests: `npm test` or `npm run test:headless`
0281 
0282 ### Backend Testing
0283 - **Framework:** pytest
0284 - **CI:** GitHub Actions (Python 3.9-3.12)
0285 - Run tests: `pytest ./tests/unit_tests`
0286 - Debug: `pytest -x --pdb`
0287 
0288 ## Code Standards
0289 
0290 ### Python (pyrobird)
0291 - **Style:** PEP8 required
0292 - **Docstrings:** NumPy style format
0293 - **Type hints:** Use throughout
0294 - **Exceptions:** Use specific exceptions, not generic ones
0295 - **Dependencies:** Add to `pyproject.toml` with justification
0296 
0297 ### TypeScript (firebird-ng)
0298 - **Type safety:** Strict TypeScript compilation
0299 - **Components:** Standalone Angular components (Angular 20)
0300 - **Reactive programming:** RxJS and Angular signals
0301 - **Bundle size:** 2MB warning, 5MB error limits
0302 
0303 ## CI/CD and Deployment
0304 
0305 ### GitHub Actions Workflows
0306 
0307 - **frontend.yaml** - Build and test Angular app (CI only, no deployment)
0308 - **docs.yaml** - Build and deploy VitePress documentation to GitHub Pages
0309 - **pyrobird.yaml** - Test Python package on multiple Python versions
0310 - **integration-tests.yml** - Run full integration test suite
0311 
0312 ### Deployment Architecture
0313 
0314 The Firebird project uses a split deployment model:
0315 
0316 1. **Firebird Event Display Application** - Hosted on https://seeeic.org (separate server)
0317 2. **VitePress Documentation** - Deployed to https://eic.github.io/firebird/ via GitHub Pages
0318 
0319 ### GitHub Pages Deployment (Documentation)
0320 
0321 The `docs.yaml` workflow handles documentation deployment:
0322 1. Triggered on push to `main` branch (when `docs/` changes) or manually via `workflow_dispatch`
0323 2. Builds VitePress documentation from `docs/` directory
0324 3. Deploys to https://eic.github.io/firebird/
0325 
0326 To build documentation locally:
0327 ```bash
0328 cd docs
0329 npm install
0330 npm run build      # Build for production
0331 npm run dev        # Development server with hot reload
0332 ```
0333 
0334 ## Working with ROOT Files
0335 
0336 Firebird supports ROOT geometry and event files through pyrobird:
0337 
0338 ```bash
0339 # Extract geometry from ROOT file
0340 pyrobird geo detector.root
0341 
0342 # Convert EDM4eic events to DEX format
0343 pyrobird convert simulation.edm4hep.root output.json
0344 
0345 # Server can convert events on-the-fly
0346 # GET /api/v1/convert/edm4eic/5?filename=path/to/file.edm4eic.root
0347 ```
0348 
0349 ## Key Configuration Files
0350 
0351 - `firebird-ng/angular.json` - Angular build configuration, bundle size limits
0352 - `firebird-ng/package.json` - Dependencies, npm scripts
0353 - `firebird-ng/tsconfig.json` - TypeScript compiler settings (strict mode)
0354 - `pyrobird/pyproject.toml` - Python packaging, dependencies, metadata
0355 - `dd4hep-plugin/CMakeLists.txt` - C++ build system, DD4Hep/Geant4 integration
0356 - `.github/workflows/` - CI/CD pipeline definitions
0357 - `firebird-ng/src/assets/config.jsonc` - Runtime configuration (geometry, server URLs)
0358 
0359 ## Performance Considerations
0360 
0361 1. **BVH acceleration** - Enable for large geometries (automatic in three.service)
0362 2. **Bundle size limits** - Keep production builds under 2MB (warning at 2MB, error at 5MB)
0363 3. **Lazy loading** - Use Angular route-based code splitting
0364 4. **Geometry merging** - Merge similar geometry for reduced draw calls
0365 5. **Time-based filtering** - Painters only render objects in current time range
0366 6. **Web Workers** - Event loading happens in worker thread (event-loader.worker.ts)
0367 
0368 ## Common Development Scenarios
0369 
0370 ### Adding a New Event Component Type
0371 
0372 1. Create class extending `EventGroup` in `firebird-ng/src/app/model/`
0373 2. Implement `toDexObject()` for serialization
0374 3. Create factory class implementing `EventGroupFactory`
0375 4. Register factory in appropriate initialization code
0376 5. Create painter in `firebird-ng/src/app/painters/` to render component
0377 6. Update pyrobird conversion if needed
0378 
0379 ### Modifying DD4Hep Trajectory Filtering
0380 
0381 1. Edit steering file (e.g., `dd4hep-plugin/firebird_steering.py`)
0382 2. Adjust parameters: `MomentumMin`, `VertexZMin/Max`, `StepCut`, `SaveParticles` (PDG codes)
0383 3. Rebuild if modifying C++ code: `cd dd4hep-plugin/build && make && make install`
0384 
0385 ### Adding a New Backend Endpoint
0386 
0387 1. Add route to `pyrobird/server/__init__.py`
0388 2. Implement handler function
0389 3. Add tests in `pyrobird/tests/unit_tests/`
0390 4. Consider security implications (file access, CORS)
0391 5. Update API documentation in README
0392 
0393 ### Debugging Visualization Issues
0394 
0395 1. Check browser console for Three.js errors
0396 2. Use Performance Stats component (toggle in UI)
0397 3. Verify DEX format with sample files
0398 4. Check painter configuration in scene tree
0399 5. Use raycasting component to inspect object properties
0400 6. Enable verbose logging: `ng serve --verbose`
0401 
0402 ## Important Notes
0403 
0404 - **Bundle optimization:** Angular build enforces size limits. Use `ng build --stats-json` to analyze.
0405 - **ROOT file compatibility:** pyrobird uses Uproot (pure Python). Some complex ROOT types may require conversion.
0406 - **XRootD support:** Install with `pip install pyrobird[xrootd]` for remote file access.
0407 - **Docker for DD4Hep:** EIC provides `eicweb/eic_xl:nightly` with full HENP stack.
0408 - **Git LFS:** This repository may use Git LFS for large binary files.
0409 - **Documentation:** User-facing documentation is in `docs/` (VitePress site) and also in `firebird-ng/src/assets/doc/` (embedded in app), including tutorials.