459 lines
16 KiB
Python
459 lines
16 KiB
Python
from __future__ import annotations
|
|
|
|
import argparse
|
|
import csv
|
|
import math
|
|
from dataclasses import dataclass
|
|
from pathlib import Path
|
|
|
|
|
|
CASE_NAME = "infinite_underwater_explosion"
|
|
TNT_MASS_KG = 1.0
|
|
WATER_RADIUS_M = 0.90
|
|
WATER_SPACING_M = 0.30
|
|
WATER_INNER_RADIUS_M = 0.24
|
|
PRODUCT_GAS_RADIUS_M = 0.15
|
|
SMOOTHING_LENGTH_M = 0.36
|
|
PARTICLE_MASS_KG = 1.0
|
|
PARTICLE_VOLUME_M3 = 1.0e-3
|
|
TIME_STEP_S = 1.0e-7
|
|
END_TIME_S = 2.0e-7
|
|
MAX_STEPS = 32
|
|
OUTPUT_INTERVAL = 8
|
|
SENSOR_RADII_M = (0.30, 0.60, 0.90)
|
|
|
|
|
|
@dataclass(frozen=True)
|
|
class Particle:
|
|
particle_id: int
|
|
x: float
|
|
y: float
|
|
z: float
|
|
phase: str
|
|
|
|
|
|
def cole_peak_pressure_pa(charge_mass_kg: float, radius_m: float) -> float:
|
|
scaled_distance = charge_mass_kg ** (1.0 / 3.0) / radius_m
|
|
return 52.4e6 * scaled_distance**1.13
|
|
|
|
|
|
def particle_radius(particle: Particle) -> float:
|
|
return math.sqrt(particle.x**2 + particle.y**2 + particle.z**2)
|
|
|
|
|
|
def build_particles() -> list[Particle]:
|
|
particles: list[Particle] = []
|
|
next_id = 1
|
|
|
|
particles.append(Particle(next_id, 0.0, 0.0, 0.0, "explosive"))
|
|
next_id += 1
|
|
|
|
gas_points = (
|
|
(PRODUCT_GAS_RADIUS_M, 0.0, 0.0),
|
|
(-PRODUCT_GAS_RADIUS_M, 0.0, 0.0),
|
|
(0.0, PRODUCT_GAS_RADIUS_M, 0.0),
|
|
(0.0, -PRODUCT_GAS_RADIUS_M, 0.0),
|
|
(0.0, 0.0, PRODUCT_GAS_RADIUS_M),
|
|
(0.0, 0.0, -PRODUCT_GAS_RADIUS_M),
|
|
)
|
|
for x_value, y_value, z_value in gas_points:
|
|
particles.append(Particle(next_id, x_value, y_value, z_value, "gas"))
|
|
next_id += 1
|
|
|
|
lattice_count = int(round(WATER_RADIUS_M / WATER_SPACING_M))
|
|
water_points: list[tuple[float, float, float]] = []
|
|
for ix in range(-lattice_count, lattice_count + 1):
|
|
for iy in range(-lattice_count, lattice_count + 1):
|
|
for iz in range(-lattice_count, lattice_count + 1):
|
|
x_value = ix * WATER_SPACING_M
|
|
y_value = iy * WATER_SPACING_M
|
|
z_value = iz * WATER_SPACING_M
|
|
radius = math.sqrt(x_value**2 + y_value**2 + z_value**2)
|
|
if WATER_INNER_RADIUS_M < radius <= WATER_RADIUS_M + 1.0e-12:
|
|
water_points.append((x_value, y_value, z_value))
|
|
|
|
water_points.sort(key=lambda item: (round(math.sqrt(sum(v * v for v in item)), 12), item))
|
|
for x_value, y_value, z_value in water_points:
|
|
particles.append(Particle(next_id, x_value, y_value, z_value, "water"))
|
|
next_id += 1
|
|
|
|
return particles
|
|
|
|
|
|
def ids_for_phase(particles: list[Particle], phase: str) -> list[int]:
|
|
return [particle.particle_id for particle in particles if particle.phase == phase]
|
|
|
|
|
|
def chunks(values: list[int], size: int = 16) -> list[list[int]]:
|
|
return [values[index : index + size] for index in range(0, len(values), size)]
|
|
|
|
|
|
def append_set(lines: list[str], name: str, ids: list[int]) -> None:
|
|
lines.append(f"*ELSET, ELSET={name}")
|
|
for chunk in chunks(ids):
|
|
lines.append(", ".join(str(value) for value in chunk))
|
|
|
|
|
|
def write_inp(case_dir: Path, particles: list[Particle]) -> Path:
|
|
inp_path = case_dir / f"{CASE_NAME}.inp"
|
|
water_ids = ids_for_phase(particles, "water")
|
|
gas_ids = ids_for_phase(particles, "gas")
|
|
explosive_ids = ids_for_phase(particles, "explosive")
|
|
|
|
lines: list[str] = []
|
|
lines.append("*NODE")
|
|
for particle in particles:
|
|
lines.append(
|
|
f"{particle.particle_id}, {particle.x:.12g}, "
|
|
f"{particle.y:.12g}, {particle.z:.12g}"
|
|
)
|
|
lines.append("*ELEMENT, TYPE=SPH3D")
|
|
for particle in particles:
|
|
lines.append(f"{particle.particle_id}, {particle.particle_id}")
|
|
append_set(lines, "WATER_PARTICLES", water_ids)
|
|
append_set(lines, "PRODUCT_PARTICLES", gas_ids)
|
|
append_set(lines, "CHARGE_PARTICLES", explosive_ids)
|
|
lines.extend(
|
|
[
|
|
"*MATERIAL, NAME=WATER, TYPE=WATER",
|
|
"*DENSITY",
|
|
"1000.0",
|
|
"*SECTION, ELSET=WATER_PARTICLES, MATERIAL=WATER",
|
|
"*MATERIAL, NAME=TNT, TYPE=EXPLOSIVE",
|
|
"*DENSITY",
|
|
"1600.0",
|
|
"*SECTION, ELSET=CHARGE_PARTICLES, MATERIAL=TNT",
|
|
"*MATERIAL, NAME=PRODUCTS, TYPE=GAS",
|
|
"*DENSITY",
|
|
"1600.0",
|
|
"*SECTION, ELSET=PRODUCT_PARTICLES, MATERIAL=PRODUCTS",
|
|
"*SPHLITE EOS, TYPE=TAIT, MATERIAL=WATER, "
|
|
"RHO0=1000.0, C0=1480.0, GAMMA=7.0, P0=0.0",
|
|
"*SPHLITE VISCOSITY, TYPE=MONAGHAN, MATERIAL=WATER, "
|
|
"ALPHA=0.1, BETA=0.0, ETA2=0.01",
|
|
"*SPHLITE EOS, TYPE=JWL, MATERIAL=PRODUCTS, RHO0=1600.0, "
|
|
"A=3.712E11, B=3.231E9, R1=4.15, R2=0.95, "
|
|
"OMEGA=0.3, E0=4.2E6",
|
|
"*SPHLITE EXPLOSIVE, MATERIAL=TNT, TYPE=PROGRAMMED_BURN, "
|
|
"DETONATION_VELOCITY=6900.0, ENERGY=4.2E6, "
|
|
"BURN_TIME=1.0E-7, PRODUCT_MATERIAL=PRODUCTS, CONVERSION=SOURCE",
|
|
"*SPHLITE IGNITION, MATERIAL=TNT, X=0.0, Y=0.0, Z=0.0, TIME=0.0",
|
|
"*SPHLITE BLAST REGION, NAME=INFINITE_WATER_BLAST, "
|
|
"X=0.0, Y=0.0, Z=0.0, RADIUS=0.90, SOURCE_PHASE=GAS, "
|
|
"TARGET_PHASE=WATER, TARGET_SET=WATER_PARTICLES, SCALE=1.0, "
|
|
"TIME_WINDOW=2.0E-7, MODE=RADIAL",
|
|
f"*SPHLITE OUTPUT, DIRECTORY=result, INTERVAL={OUTPUT_INTERVAL}",
|
|
f"*SPHLITE PARTICLE CONTROL, H={SMOOTHING_LENGTH_M:.6g}, "
|
|
f"MASS={PARTICLE_MASS_KG:.6g}, VOLUME={PARTICLE_VOLUME_M3:.6g}",
|
|
f"*SPHLITE TIME CONTROL, DT={TIME_STEP_S:.6E}, "
|
|
f"TIME={END_TIME_S:.6E}, STEPS={MAX_STEPS}, SAFETY=0.5",
|
|
"",
|
|
]
|
|
)
|
|
inp_path.write_text("\n".join(lines), encoding="ascii")
|
|
return inp_path
|
|
|
|
|
|
def nearest_water_particle(particles: list[Particle], radius_m: float) -> Particle:
|
|
water_particles = [particle for particle in particles if particle.phase == "water"]
|
|
target = (radius_m, 0.0, 0.0)
|
|
return min(
|
|
water_particles,
|
|
key=lambda particle: (
|
|
(particle.x - target[0]) ** 2
|
|
+ (particle.y - target[1]) ** 2
|
|
+ (particle.z - target[2]) ** 2
|
|
),
|
|
)
|
|
|
|
|
|
def write_reference_files(case_dir: Path, result_dir: Path, particles: list[Particle]) -> None:
|
|
result_dir.mkdir(parents=True, exist_ok=True)
|
|
|
|
sensor_path = result_dir / "sensor_points.csv"
|
|
with sensor_path.open("w", newline="", encoding="ascii") as handle:
|
|
writer = csv.writer(handle)
|
|
writer.writerow(
|
|
[
|
|
"sensor",
|
|
"radius_m",
|
|
"particle_id",
|
|
"x_m",
|
|
"y_m",
|
|
"z_m",
|
|
"cole_peak_pressure_pa",
|
|
]
|
|
)
|
|
for index, radius in enumerate(SENSOR_RADII_M, start=1):
|
|
particle = nearest_water_particle(particles, radius)
|
|
writer.writerow(
|
|
[
|
|
f"S{index}",
|
|
f"{radius:.6g}",
|
|
particle.particle_id,
|
|
f"{particle.x:.12g}",
|
|
f"{particle.y:.12g}",
|
|
f"{particle.z:.12g}",
|
|
f"{cole_peak_pressure_pa(TNT_MASS_KG, radius):.16e}",
|
|
]
|
|
)
|
|
|
|
reference_path = result_dir / "cole_reference.csv"
|
|
with reference_path.open("w", newline="", encoding="ascii") as handle:
|
|
writer = csv.writer(handle)
|
|
writer.writerow(["radius_m", "tnt_mass_kg", "cole_peak_pressure_pa"])
|
|
for radius in SENSOR_RADII_M:
|
|
writer.writerow(
|
|
[
|
|
f"{radius:.6g}",
|
|
f"{TNT_MASS_KG:.6g}",
|
|
f"{cole_peak_pressure_pa(TNT_MASS_KG, radius):.16e}",
|
|
]
|
|
)
|
|
|
|
metadata_path = result_dir / "case_metadata.csv"
|
|
phase_counts = {
|
|
phase: len(ids_for_phase(particles, phase))
|
|
for phase in ("water", "gas", "explosive")
|
|
}
|
|
with metadata_path.open("w", newline="", encoding="ascii") as handle:
|
|
writer = csv.writer(handle)
|
|
writer.writerow(["metric", "value"])
|
|
writer.writerow(["case_name", CASE_NAME])
|
|
writer.writerow(["tnt_mass_kg", f"{TNT_MASS_KG:.16e}"])
|
|
writer.writerow(["water_radius_m", f"{WATER_RADIUS_M:.16e}"])
|
|
writer.writerow(["water_spacing_m", f"{WATER_SPACING_M:.16e}"])
|
|
writer.writerow(["water_particles", phase_counts["water"]])
|
|
writer.writerow(["product_gas_particles", phase_counts["gas"]])
|
|
writer.writerow(["explosive_particles", phase_counts["explosive"]])
|
|
writer.writerow(["inp_file", f"{CASE_NAME}.inp"])
|
|
writer.writerow(
|
|
[
|
|
"cole_peak_pressure_formula",
|
|
"P=52.4e6*(W^(1/3)/R)^1.13 Pa",
|
|
]
|
|
)
|
|
|
|
|
|
def latest_particle_output(result_dir: Path) -> Path | None:
|
|
files = [
|
|
path
|
|
for path in result_dir.glob("sphlite_*.csv")
|
|
if not path.name.endswith("_summary.csv")
|
|
]
|
|
if not files:
|
|
return None
|
|
return sorted(files)[-1]
|
|
|
|
|
|
def summary_path_for_particle_output(particle_output: Path) -> Path:
|
|
return particle_output.with_name(particle_output.stem + "_summary.csv")
|
|
|
|
|
|
def read_metric_csv(path: Path) -> dict[str, str]:
|
|
values: dict[str, str] = {}
|
|
if not path.exists():
|
|
return values
|
|
with path.open(newline="", encoding="ascii") as handle:
|
|
reader = csv.DictReader(handle)
|
|
for row in reader:
|
|
values[row["metric"]] = row["value"]
|
|
return values
|
|
|
|
|
|
def read_particle_rows(path: Path) -> dict[int, dict[str, str]]:
|
|
rows: dict[int, dict[str, str]] = {}
|
|
with path.open(newline="", encoding="ascii") as handle:
|
|
reader = csv.DictReader(handle)
|
|
for row in reader:
|
|
rows[int(row["id"])] = row
|
|
return rows
|
|
|
|
|
|
def postprocess(result_dir: Path) -> None:
|
|
sensor_path = result_dir / "sensor_points.csv"
|
|
output_path = latest_particle_output(result_dir)
|
|
if output_path is None:
|
|
write_summary_markdown(result_dir, {}, [])
|
|
return
|
|
|
|
summary_metrics = read_metric_csv(summary_path_for_particle_output(output_path))
|
|
particle_rows = read_particle_rows(output_path)
|
|
comparison_rows: list[dict[str, str]] = []
|
|
|
|
with sensor_path.open(newline="", encoding="ascii") as handle:
|
|
reader = csv.DictReader(handle)
|
|
for sensor in reader:
|
|
particle_id = int(sensor["particle_id"])
|
|
output_row = particle_rows.get(particle_id)
|
|
sphlite_pressure = ""
|
|
abs_error = ""
|
|
relative_error = ""
|
|
note = "missing particle output"
|
|
if output_row is not None:
|
|
cole_pressure = float(sensor["cole_peak_pressure_pa"])
|
|
sphlite_value = float(output_row["pressure"])
|
|
sphlite_pressure = f"{sphlite_value:.16e}"
|
|
abs_error = f"{(sphlite_value - cole_pressure):.16e}"
|
|
relative_error = f"{((sphlite_value - cole_pressure) / cole_pressure):.16e}"
|
|
note = (
|
|
"0.8.2 water pressure remains the Water EOS gauge pressure; "
|
|
"this row is a calibration placeholder."
|
|
)
|
|
comparison_rows.append(
|
|
{
|
|
"sensor": sensor["sensor"],
|
|
"radius_m": sensor["radius_m"],
|
|
"particle_id": sensor["particle_id"],
|
|
"cole_peak_pressure_pa": sensor["cole_peak_pressure_pa"],
|
|
"sphlite_pressure_pa": sphlite_pressure,
|
|
"sphlite_minus_cole_pa": abs_error,
|
|
"relative_error": relative_error,
|
|
"note": note,
|
|
}
|
|
)
|
|
|
|
comparison_path = result_dir / "cole_comparison.csv"
|
|
with comparison_path.open("w", newline="", encoding="ascii") as handle:
|
|
fieldnames = [
|
|
"sensor",
|
|
"radius_m",
|
|
"particle_id",
|
|
"cole_peak_pressure_pa",
|
|
"sphlite_pressure_pa",
|
|
"sphlite_minus_cole_pa",
|
|
"relative_error",
|
|
"note",
|
|
]
|
|
writer = csv.DictWriter(handle, fieldnames=fieldnames)
|
|
writer.writeheader()
|
|
writer.writerows(comparison_rows)
|
|
|
|
selected_metrics = [
|
|
"step",
|
|
"time",
|
|
"water_mass",
|
|
"max_pressure",
|
|
"gas_particles",
|
|
"gas_mass",
|
|
"gas_volume",
|
|
"gas_mean_pressure",
|
|
"gas_max_pressure",
|
|
"gas_equivalent_radius",
|
|
"gas_source_mass",
|
|
"gas_source_energy",
|
|
"explosive_particles",
|
|
"explosive_reacted_particles",
|
|
"explosive_lambda_mean",
|
|
"explosive_released_mass",
|
|
"explosive_released_energy",
|
|
"blast_regions",
|
|
"blast_source_count_1",
|
|
"blast_target_count_1",
|
|
"blast_water_count_1",
|
|
"blast_gas_count_1",
|
|
"blast_explosive_count_1",
|
|
"blast_source_pressure_mean_1",
|
|
"blast_water_pressure_min_1",
|
|
"blast_water_pressure_max_1",
|
|
]
|
|
with (result_dir / "simulation_summary.csv").open("w", newline="", encoding="ascii") as handle:
|
|
writer = csv.writer(handle)
|
|
writer.writerow(["metric", "value"])
|
|
for metric in selected_metrics:
|
|
if metric in summary_metrics:
|
|
writer.writerow([metric, summary_metrics[metric]])
|
|
|
|
write_summary_markdown(result_dir, summary_metrics, comparison_rows)
|
|
|
|
|
|
def as_mpa(value: str) -> str:
|
|
if value == "":
|
|
return ""
|
|
return f"{float(value) / 1.0e6:.6g}"
|
|
|
|
|
|
def write_summary_markdown(
|
|
result_dir: Path, summary_metrics: dict[str, str], comparison_rows: list[dict[str, str]]
|
|
) -> None:
|
|
lines: list[str] = []
|
|
lines.append("# Infinite Underwater Explosion Result")
|
|
lines.append("")
|
|
lines.append(
|
|
"This example is a near-field truncated 3D particle model for a 1 kg TNT "
|
|
"underwater explosion. The reference pressure uses the Cole TNT peak "
|
|
"pressure form P=52.4e6*(W^(1/3)/R)^1.13 Pa."
|
|
)
|
|
lines.append("")
|
|
lines.append(
|
|
"SPHLite 0.8.2 records Water particles and Blast Water targets, but Blast "
|
|
"load projection is still stored only for Solid/Shell targets. The Water "
|
|
"pressure comparison is therefore a regression baseline for future shock "
|
|
"propagation work, not a validation claim."
|
|
)
|
|
lines.append("")
|
|
if summary_metrics:
|
|
lines.append("## SPHLite Summary")
|
|
lines.append("")
|
|
lines.append("| Metric | Value |")
|
|
lines.append("| --- | ---: |")
|
|
for metric in (
|
|
"step",
|
|
"time",
|
|
"max_pressure",
|
|
"gas_max_pressure",
|
|
"gas_equivalent_radius",
|
|
"explosive_released_energy",
|
|
"blast_source_count_1",
|
|
"blast_target_count_1",
|
|
):
|
|
if metric in summary_metrics:
|
|
lines.append(f"| {metric} | {summary_metrics[metric]} |")
|
|
lines.append("")
|
|
if comparison_rows:
|
|
lines.append("## Cole Comparison")
|
|
lines.append("")
|
|
lines.append("| Sensor | R (m) | Cole peak (MPa) | SPHLite Water pressure (MPa) |")
|
|
lines.append("| --- | ---: | ---: | ---: |")
|
|
for row in comparison_rows:
|
|
lines.append(
|
|
f"| {row['sensor']} | {row['radius_m']} | "
|
|
f"{as_mpa(row['cole_peak_pressure_pa'])} | "
|
|
f"{as_mpa(row['sphlite_pressure_pa'])} |"
|
|
)
|
|
lines.append("")
|
|
(result_dir / "summary.md").write_text("\n".join(lines) + "\n", encoding="ascii")
|
|
|
|
|
|
def main() -> int:
|
|
parser = argparse.ArgumentParser()
|
|
parser.add_argument("--generate-only", action="store_true")
|
|
parser.add_argument("--postprocess", action="store_true")
|
|
parser.add_argument("--case-dir", default=Path(__file__).resolve().parent, type=Path)
|
|
parser.add_argument("--result-dir", default=None, type=Path)
|
|
args = parser.parse_args()
|
|
|
|
case_dir = args.case_dir.resolve()
|
|
result_dir = args.result_dir
|
|
if result_dir is None:
|
|
result_dir = case_dir / "result"
|
|
else:
|
|
result_dir = result_dir.resolve()
|
|
|
|
particles = build_particles()
|
|
if not args.postprocess:
|
|
inp_path = write_inp(case_dir, particles)
|
|
write_reference_files(case_dir, result_dir, particles)
|
|
print(f"generated: {inp_path}")
|
|
print(f"particles: {len(particles)}")
|
|
|
|
if args.postprocess or not args.generate_only:
|
|
postprocess(result_dir)
|
|
print(f"postprocessed: {result_dir}")
|
|
|
|
return 0
|
|
|
|
|
|
if __name__ == "__main__":
|
|
raise SystemExit(main())
|