Skip to content

Latest commit

Β 

History

History
440 lines (323 loc) Β· 16.1 KB

File metadata and controls

440 lines (323 loc) Β· 16.1 KB

AGENTS.md

This file provides guidance to AI agents (Claude Code, Gemini, Codex) when working with code in this repository.

For user-facing overview and usage, see README.md.

Repository Overview

This repository contains computational fluid dynamics simulations for drop impact studies using the Basilisk C framework. The project focuses on axisymmetric two-phase flow simulations with adaptive mesh refinement.

Recent Update (2025): The codebase has been refactored for improved maintainability, modularity, and HPC compatibility. See Modular Structure below.

Basilisk (Required)

First-time install (or reinstall):

curl -sL https://raw.githubusercontent.com/comphy-lab/basilisk-C/main/reset_install_basilisk-ref-locked.sh | bash -s -- --ref=v2026-01-13 --hard

Subsequent runs (reuses existing basilisk/ if same ref):

curl -sL https://raw.githubusercontent.com/comphy-lab/basilisk-C/main/reset_install_basilisk-ref-locked.sh | bash -s -- --ref=v2026-01-13

Note: Replace v2026-01-13 with the latest release tag.

Purpose

This document outlines the coding standards, project structure, and best practices for computational fluid dynamics simulations using the Basilisk framework. Following these standards ensures code readability, maintainability, and reproducibility across the CoMPhy Lab's research projects.

Modular Structure (2025 Restructuring)

The code has been completely reorganized with case-based folder management and root-level execution:

Directory Structure

Drop-Impact/
β”œβ”€β”€ .github/                # Docs pipeline and issue templates
β”œβ”€β”€ .project_config         # Basilisk environment setup
β”œβ”€β”€ AGENTS.md               # This file (authoritative guidance)
β”œβ”€β”€ CLAUDE.md               # Local pointer to AGENTS.md (not tracked)
β”œβ”€β”€ basilisk/               # Basilisk framework (local-only; ignored)
β”‚
β”œβ”€β”€ src-local/              # Modular header files
β”‚   β”œβ”€β”€ params.h            # Parameter structures and parsing with CaseNo
β”‚   β”œβ”€β”€ geometry.h          # Drop geometry and initialization
β”‚   β”œβ”€β”€ diagnostics.h       # Statistics and output handling
β”‚   └── parse_params.sh     # Shell parameter parsing library
β”‚
β”œβ”€β”€ postProcess/            # Analysis and visualization tools
β”‚   β”œβ”€β”€ getData-generic.c   # Field extraction on structured grids
β”‚   β”œβ”€β”€ getFacet.c          # Interface geometry extraction
β”‚   β”œβ”€β”€ getFootPrint.c      # Footprint height analysis
β”‚   β”œβ”€β”€ getFootPrint.py     # Multi-cutoff footprint time-series
β”‚   β”œβ”€β”€ plotFootPrint.py    # Publication-quality footprint plots
β”‚   └── Video-generic.py    # Frame-by-frame visualization
β”‚
β”œβ”€β”€ runSimulation.sh        # Single case runner (from root)
β”œβ”€β”€ runParameterSweep.sh    # Parameter sweep runner (from root)
β”œβ”€β”€ runPostProcess-Ncases.sh  # Post-process cases
β”œβ”€β”€ runSweepHamilton.sbatch # Cluster batch script (Hamilton)
β”œβ”€β”€ runSweepSnellius.sbatch # Cluster batch script (Snellius)
β”œβ”€β”€ default.params          # Single-case configuration (edit this)
β”œβ”€β”€ sweep.params            # Sweep configuration (edit this)
β”‚
└── simulationCases/
    β”œβ”€β”€ dropImpact.c        # Main simulation (refactored with docs)
    β”œβ”€β”€ dropImpact_legacy.c # Original version (archived)
    β”œβ”€β”€ runSnellius_legacy.sbatch  # Legacy batch script
    └── 1000/               # Case folders created by scripts
        β”œβ”€β”€ dropImpact      # Compiled executable
        β”œβ”€β”€ dropImpact.c    # Source copy
        β”œβ”€β”€ case.params     # Parameter copy
        β”œβ”€β”€ log             # Time series data
        β”œβ”€β”€ restart         # Restart checkpoint
        └── intermediate/   # Snapshot files

Key Improvements

  1. Case-Based Organization (CaseNo system):

    • Each simulation runs in simulationCases/<CaseNo>/ folder
    • CaseNo is a 4-digit number (1000-9999) set in parameter files
    • Auto-incrementing CaseNo for parameter sweeps
    • Restart-aware (continues from checkpoint if folder exists)
  2. Root-Level Execution:

    • All scripts run from project root
    • Edit default.params or sweep.params at root
    • Output folders automatically created in simulationCases/
  3. Parameter Management (src-local/params.h):

    • Added CaseNo field for folder naming
    • Centralized configuration structure
    • Parameter file support (key=value format)
    • Input validation with clear error messages
    • Command-line and file-based modes
  4. Modular Code (src-local/geometry.h, diagnostics.h):

    • Separated concerns (geometry, statistics, I/O)
    • Reusable components
    • Fixed file I/O performance bug (no repeated open/close)
    • Extensible for additional features
  5. Shell-Based Workflows:

    • Pure shell scripting (no Python dependencies)
    • Parameter sweep support (sequential execution)
    • Comprehensive error handling
  6. Documentation:

    • Literate programming style (markdown in code)
    • Self-documenting parameter files
    • Complete documentation in AGENTS.md
    • Correct Reynolds number formula: Re = √We/Oh

Quick Start

# From project root directory

# Single simulation
vim default.params      # Set CaseNo=1000, We, Oh, etc.
./runSimulation.sh

# Parameter sweep
vim sweep.params        # Set CASE_START, CASE_END, sweep variables
./runParameterSweep.sh

Code Style

  • Indentation: 2 spaces (no tabs).
  • Line Length: Maximum 80 characters per line.
  • Comments: Use Markdown in comments starting with /**; avoid bare * in comments.
  • Spacing: Include spaces after commas and around operators (+, -).
  • File Organization:
    • Place core functionality in .h headers
    • Implement tests in .c files
  • Naming Conventions:
    • Use snake_case for variables and parameters
    • Use camelCase for functions and methods
  • Error Handling: Return meaningful values and provide descriptive stderr messages.

Build & Test Commands

Serial (Single-Core) Compilation

Standard Compilation:

qcc -autolink file.c -o executable -lm

Compilation with Custom Headers:

qcc -I$PWD/src-local -autolink file.c -o executable -lm

MPI Parallel Compilation

macOS (Darwin):

CC99='mpicc -std=c99' qcc -I$PWD/src-local -Wall -O2 -D_MPI=1 -disable-dimensions file.c -o executable -lm

Linux:

CC99='mpicc -std=c99 -D_GNU_SOURCE=1' qcc -I$PWD/src-local -Wall -O2 -D_MPI=1 -disable-dimensions file.c -o executable -lm

Execution with MPI:

mpirun -np 4 ./executable params.file  # 4 cores (default)
mpirun -np 8 ./executable params.file  # 8 cores

MPI Requirements

To use MPI parallel execution, you must have MPI tools installed:

  • macOS: brew install open-mpi
  • Linux: sudo apt-get install libopenmpi-dev (Ubuntu/Debian) or sudo yum install openmpi-devel (RHEL/CentOS)

The scripts will automatically verify that mpicc and mpirun are available when --mpi flag is used.

Best Practices

  • Keep simulations modular and reusable
  • Document physical assumptions and numerical methods
  • Perform mesh refinement studies to ensure solution convergence
  • Include visualization scripts in the postProcess directory

Basilisk Framework

Basilisk is a computational fluid dynamics solver that uses:

  • qcc: A custom C preprocessor/compiler that extends C with grid abstractions
  • Adaptive mesh refinement: Quad/octree-based grids with automatic refinement
  • Two-phase flow: Volume-of-Fluid (VOF) method with surface tension
  • Navier-Stokes: Centered formulation for incompressible flows

Key framework files are located in basilisk/src/.

Project Configuration

The .project_config file sets up the Basilisk environment (typically created locally by the install script above and ignored by git):

export BASILISK=/path/to/basilisk/src
export PATH=$PATH:$BASILISK

This must be sourced before running simulations to access the qcc compiler. The runner scripts will error if .project_config is missing.

Building and Running Simulations

Workflow

Run simulations from the project root directory:

# Edit parameter file
vim default.params          # Set CaseNo, We, Oh, etc.

# Run single simulation (serial)
./runSimulation.sh

# Run single simulation (MPI parallel, 4 cores)
./runSimulation.sh --mpi

# Run with custom number of cores (8 cores)
./runSimulation.sh --mpi --cores 8

# Compile only (check for errors)
./runSimulation.sh --compile-only

# Compile with MPI (no execution)
./runSimulation.sh --mpi --compile-only

# Debug mode
./runSimulation.sh --debug

# Debug mode with MPI
./runSimulation.sh --mpi --debug

# Parameter sweep (serial)
vim sweep.params           # Set CASE_START, CASE_END, sweep variables
./runParameterSweep.sh

# Parameter sweep (MPI parallel, 4 cores per case)
./runParameterSweep.sh --mpi

# Parameter sweep with custom cores (8 cores per case)
./runParameterSweep.sh --mpi --cores 8

Execution Modes

Serial (Default):

  • Single-core execution
  • No special requirements
  • Backward compatible with all existing workflows

MPI Parallel (--mpi flag):

  • Multi-core execution using MPI
  • Requires OpenMPI or MPICH installed
  • Significant speedup for large simulations
  • Default: 4 cores (configurable with --cores N)

Parameter File Mode (Current)

The single-case runner expects a parameter file. Use the default or pass a custom file path:

./runSimulation.sh default.params
./runSimulation.sh my_case.params

Compilation Details

Serial Compilation:

qcc -I../../src-local -O2 -Wall -disable-dimensions <file>.c -o <executable> -lm

MPI Parallel Compilation (macOS):

CC99='mpicc -std=c99' qcc -I../../src-local -Wall -O2 -D_MPI=1 -disable-dimensions <file>.c -o <executable> -lm

MPI Parallel Compilation (Linux):

CC99='mpicc -std=c99 -D_GNU_SOURCE=1' qcc -I../../src-local -Wall -O2 -D_MPI=1 -disable-dimensions <file>.c -o <executable> -lm

Key flags:

  • -I../../src-local: Include local header directory (relative to case folder)
  • -O2: Optimization level 2
  • -Wall: All warnings
  • -disable-dimensions: Disable dimensional analysis (Basilisk feature)
  • -D_MPI=1: Enable MPI parallelization (MPI builds only)
  • CC99='mpicc ...': Use MPI C compiler (MPI builds only)
  • -lm: Link math library

Simulation Parameters

The dropImpact.c simulation requires 6 command-line arguments:

./dropImpact <MAXlevel> <tmax> <We> <Ohd> <Ohs> <Ldomain>

Parameters:

  • MAXlevel: Maximum adaptive mesh refinement level (e.g., 10)
  • tmax: Maximum simulation time (e.g., 4e0)
  • We: Weber number - ratio of inertial to surface tension forces (e.g., 1e1)
  • Ohd: Ohnesorge number for drop phase - viscous/surface tension ratio (e.g., 1e-3)
  • Ohs: Ohnesorge number for surrounding phase (e.g., 1e-5)
  • Ldomain: Domain size in drop radii (e.g., 8e0)

Default values are set in default.params (single runs) and sweep.params (sweeps).

Simulation Code Structure

Key Components in dropImpact.c

  1. Includes: Basilisk modules for axisymmetric flow, Navier-Stokes, two-phase flow, and surface tension

    #include "axi.h"
    #include "navier-stokes/centered.h"
    #include "two-phase.h"
    #include "tension.h"
  2. Error Tolerances: Control adaptive mesh refinement

    #define fErr (1e-3)    // VOF error tolerance
    #define KErr (1e-6)    // Curvature error tolerance
    #define VelErr (1e-2)  // Velocity error tolerance
  3. Physical Parameters:

    • Rho21: Density ratio (1e-3 for air-water)
    • Xdist: Initial drop position (1.02 radii from axis)
  4. Boundary Conditions:

    • Left (axis): No-slip, no fluid
    • Right/Top: Neumann for velocity, Dirichlet for pressure (open boundaries)
  5. Event System: Basilisk uses events for temporal control

    • init(t=0): Initial conditions with refinement
    • adapt(i++): Called every timestep for mesh adaptation
    • writingFiles(t+=tsnap): Save snapshots every 0.01 time units
    • logWriting(i++): Write kinetic energy to log every timestep

Output Files

Each simulation run produces:

  • log: Time series of iteration, timestep, time, and kinetic energy
  • restart: Full simulation state for restarts
  • intermediate/snapshot-X.XXXX: Periodic dump files at intervals of tsnap=0.01

Cleanup

Remove a simulation directory by deleting its case folder under simulationCases/<CaseNo>/.

Common Modifications

Changing Physics

  • Density ratio: Modify Rho21 in the code
  • Surface tension: Set via Weber number We (lower = stronger tension)
  • Viscosity: Set via Ohnesorge numbers Ohd and Ohs
  • Initial velocity: Modified in init event (currently -1.0*f[])

Mesh Refinement

  • MAXlevel: Maximum refinement level (10 = 2^10 = 1024 cells per direction at finest)
  • MINlevel: Minimum level (currently hardcoded to 4)
  • Refinement criteria in adapt event based on VOF, curvature, and velocity

Domain Size

  • Ldomain: Controls computational domain size
  • Unrefinement at boundaries prevents spurious refinement near outflow

Notes

  • The simulation uses axisymmetric coordinates (cylindrical with azimuthal symmetry)
  • x is radial coordinate, y is axial coordinate in the code
  • VOF field f represents the drop (f=1 inside drop, f=0 in surrounding fluid)
  • Adaptive mesh refinement focuses resolution on interfaces and high-velocity regions
  • The display.html file in output directories can visualize Basilisk dump files

References

Key Publications

Software

  • Basilisk: Open-source CFD solver - https://basilisk.fr
  • qcc: Basilisk's C preprocessor with grid abstractions

Documentation Generation

This rule provides guidance for maintaining and generating documentation for code repositories in the CoMPhy Lab, ensuring consistency and proper workflow for website generation.

Documentation Guidelines

  • Read the GitHub .github/Website-generator-readme.md for the website generation process.
  • Do not auto-deploy the website; generating HTML is permitted using the GitHub .github/scripts/build.sh.
  • Avoid editing HTML files directly; they are generated using the GitHub .github/scripts/build.sh, which utilizes the GitHub .github/scripts/generate_docs.py.
  • The website is deployed at https://comphy-lab.org/repositoryName; refer to the CNAME file for configuration. Update if not done already.

Process Details

The documentation generation process utilizes Python scripts to convert source code files into HTML documentation. The process handles C/C++, Python, Shell, and Markdown files, generating a complete documentation website with navigation, search functionality, and code highlighting.

Documentation Best Practices

  • Always use the build script for generating documentation rather than manually editing HTML files
  • Customize styling through CSS files in .github/assets/css/
  • Modify functionality through JavaScript files in .github/assets/js/
  • For template changes, edit .github/assets/custom_template.html
  • Troubleshoot generation failures by checking error messages and verifying paths and dependencies