diff --git a/PyPIC3D/collisions.py b/PyPIC3D/collisions.py new file mode 100644 index 0000000..c778a4e --- /dev/null +++ b/PyPIC3D/collisions.py @@ -0,0 +1,337 @@ +""" +Particle collisions on tiled particle storage. + +``binary`` Coulomb collisions between particles sharing a cell (intra- + and inter-species): Takizuka-Abe pairing and variance, with + Nanbu's angular distribution as in Smilei (Perez 2012), which + stays accurate for large per-step scattering. +``background_mcc`` Monte Carlo collisions with a uniform Maxwellian neutral gas + (elastic, back, charge_exchange, excitation, ionization) as + in WarpX's background MCC module. Ionization products are + created with their own species' macro-particle weight, so both + must share the projectile's weight; the loader enforces this. + +Velocities are treated non-relativistically; ``particles.u`` holds 3-velocity. +""" + +import math + +import jax +import jax.numpy as jnp +import numpy as np + +E_CHARGE = 1.602176634e-19 +MCC_PROCESSES = ("elastic", "back", "charge_exchange", "excitation", "ionization") + + +def load_collisions_from_toml(config, species_names, species_weights=None): + """Translate ``[collisions.]`` tables into hashable static specs. + + Args: + config (dict): Parsed TOML configuration; only its ``collisions`` tables are read. + species_names (list[str]): Particle species names in species-index order, used to + turn the ``species`` and ``product_species`` names into indices. + species_weights (sequence[float] | None): Macro-particle weight of each species in + species-index order. When given, ionization products are checked against it. + + Returns: + tuple: One spec per table, ``("binary", a, b, coulomb_log)`` or + ``("mcc", species, background_density, background_temperature, background_mass, processes)`` + with ``processes`` a tuple of ``(name, threshold_eV, energies_eV, sigmas_m2, product_a, product_b)``. + Empty when the configuration has no collisions. + """ + index = {name: i for i, name in enumerate(species_names)} + specs = [] + for name, c in config.get("collisions", {}).items(): + species = [index[s] for s in np.atleast_1d(c["species"])] + if c["type"] == "binary": + specs.append(("binary", species[0], species[-1], float(c.get("coulomb_log", 10.0)))) + elif c["type"] == "background_mcc": + processes = [] + for p in (p for p in MCC_PROCESSES if p in c): + energy, sigma = _cross_section(c[p]["cross_section"]) + products = [index[s] for s in c[p].get("product_species", [])] + if p == "ionization": + # One event makes one real pair per real projectile and weight is per + # species, so unequal weights would create charge from nothing. + w = [] if species_weights is None else [float(species_weights[i]) for i in (species[0], *products)] + if len(products) != 2 or any(not math.isclose(v, w[0], rel_tol=1e-9) for v in w[1:]): + raise ValueError(f"[collisions.{name}.ionization] product_species must name two " + f"species sharing the weight of {species_names[species[0]]}") + products = products + [-1, -1] + processes.append((p, float(c[p].get("energy", 0.0)), energy, sigma, products[0], products[1])) + specs.append(("mcc", species[0], float(c["background_density"]), + float(c.get("background_temperature", 0.0)), float(c["background_mass"]), tuple(processes))) + else: + raise ValueError(f"Unknown collision type for {name}: {c['type']}") + return tuple(specs) + + +def _cross_section(value): + """Read a cross section sigma(E) as an (energy, sigma) lookup table. + + Args: + value (float | str | list): A constant cross section [m^2], the path of a + two-column (energy [eV], sigma [m^2]) text file with ``#`` comments, or an + inline ``[[eV, m^2], ...]`` table. + + Returns: + tuple[tuple, tuple]: Energies [eV] and cross sections [m^2], linearly interpolated + during the run and held at the end values outside the table. + """ + if isinstance(value, (int, float)): + return (0.0, 1.0e30), (float(value), float(value)) + table = np.loadtxt(value, comments="#", ndmin=2) if isinstance(value, str) else np.asarray(value, float) + return tuple(table[:, 0].tolist()), tuple(table[:, 1].tolist()) + + +def _isotropic(key, n): + """Draw random unit vectors uniformly distributed over the sphere. + + Args: + key (jax.Array): JAX PRNG key. + n (int): Number of vectors. + + Returns: + jnp.ndarray: Unit vectors, shape ``(n, 3)``. + """ + d = jax.random.normal(key, (n, 3)) + return d / jnp.linalg.norm(d, axis=-1, keepdims=True) + + +def _rotate(g, cos_t, key): + """Rotate vectors g by polar angle acos(cos_t) about g, with uniform azimuth. + + Args: + g (jnp.ndarray): Relative velocities, shape ``(n, 3)`` (m/s). + cos_t (jnp.ndarray): Cosine of the scattering angle for each vector, shape ``(n,)``. + key (jax.Array): JAX PRNG key for the azimuthal angle. + + Returns: + jnp.ndarray: Rotated vectors with the same magnitudes as g, shape ``(n, 3)``. + """ + gn = jnp.linalg.norm(g, axis=-1, keepdims=True) + n = g / jnp.maximum(gn, 1e-300) + a = jnp.where(jnp.abs(n[:, :1]) < 0.9, jnp.array([1.0, 0.0, 0.0]), jnp.array([0.0, 1.0, 0.0])) + e1 = jnp.cross(n, a) + e1 = e1 / jnp.maximum(jnp.linalg.norm(e1, axis=-1, keepdims=True), 1e-300) + e2 = jnp.cross(n, e1) + phi = jax.random.uniform(key, cos_t.shape, maxval=2 * jnp.pi)[:, None] + sin_t = jnp.sqrt(jnp.maximum(1 - cos_t**2, 0.0))[:, None] + return gn * (cos_t[:, None] * n + sin_t * (jnp.cos(phi) * e1 + jnp.sin(phi) * e2)) + + +def _nanbu_cos(s, r): + """Sample cos(theta) from Nanbu's distribution with = exp(-s) (See Perez 2012). + + Args: + s (jnp.ndarray): Accumulated scattering parameter of each pair over one step; + s < 0.1 uses the small-angle limit and s >= 6 is isotropic. + r (jnp.ndarray): Uniform random numbers in (0, 1], same shape as s. + + Returns: + jnp.ndarray: Cosine of the scattering angle in [-1, 1], same shape as s. + """ + inv_a = 0.0056958 + s * (0.9560202 + s * (-0.508139 + s * (0.47913906 + s * (-0.12788975 + s * 0.02389567)))) + a = jnp.where(s < 3, 1 / jnp.maximum(inv_a, 1e-12), 3 * jnp.exp(-s)) + cos_t = 1 + jnp.log(r + (1 - r) * jnp.exp(-2 * a)) / a + cos_t = jnp.where(s < 0.1, 1 + s * jnp.log(r), jnp.where(s < 6, cos_t, 2 * r - 1)) + return jnp.clip(cos_t, -1.0, 1.0) + + +def _binary(key, x, u, active, spec, species_config, dyn): + """Takizuka-Abe collisions for one tile and one species pair. + + Args: + key (jax.Array): JAX PRNG key for this tile and spec. + x (jnp.ndarray): Tile positions, shape ``(species, slots, 3)`` (m). + u (jnp.ndarray): Tile velocities, shape ``(species, slots, 3)`` (m/s). + active (jnp.ndarray): Tile occupancy flags, shape ``(species, slots)``. + spec (tuple): ``("binary", a, b, coulomb_log)``; a == b collides a species with itself. + species_config (SpeciesConfig): Per-species charge, mass and macro-particle weight. + dyn: Dynamic parameters; uses ``dx``, ``dy``, ``dz``, ``dt`` and ``eps``. + + Returns: + jnp.ndarray: Updated tile velocities, shape ``(species, slots, 3)``. + """ + _, sa, sb, coulomb_log = spec + intra = sa == sb + pick = (lambda v: v[sa]) if intra else (lambda v: jnp.concatenate((v[sa], v[sb]))) + xs, us, act = pick(x), pick(u), pick(active) + tag = jnp.arange(xs.shape[0]) >= u.shape[1] + L = xs.shape[0] + cell = jnp.floor(xs / jnp.stack((dyn.dx, dyn.dy, dyn.dz))).astype(jnp.int32) + k_sort, k_round = jax.random.split(key) + order = jnp.lexsort((jax.random.uniform(k_sort, (L,)), tag, cell[:, 2], cell[:, 1], cell[:, 0], ~act)) + # sort active particles by cell, then species, then randomly within each cell + c, t, a = cell[order], tag[order], act[order] + new = jnp.concatenate((jnp.array([True]), jnp.any(c[1:] != c[:-1], -1) | (a[1:] != a[:-1]))) + seg, pos = jnp.cumsum(new) - 1, jnp.arange(L) + start = jax.ops.segment_min(pos, seg, L) + na = jax.ops.segment_sum((a & ~t).astype(jnp.int32), seg, L) + nb = jax.ops.segment_sum((a & t).astype(jnp.int32), seg, L) + if intra: + npairs = na // 2 + 2 * ((na % 2 == 1) & (na >= 3)) + else: + npairs = jnp.where(jnp.minimum(na, nb) > 0, jnp.maximum(na, nb), 0) + cum = jnp.cumsum(npairs) + s = jnp.minimum(jnp.searchsorted(cum, pos, side="right"), L - 1) + valid = pos < cum[-1] + p, n_a, n_b, st = pos - (cum[s] - npairs[s]), na[s], nb[s], start[s] + # enumerate pairs cell by cell: pair p of a cell maps to positions (i, j) and a round + wa, wb = species_config.weight[sa], species_config.weight[sb] + ma, mb = species_config.mass[sa], species_config.mass[sb] + volume = dyn.dx * dyn.dy * dyn.dz + if intra: + m, last = n_a // 2, n_a - 1 + i = jnp.where(p < m, 2 * p, jnp.where(p == m, last - 1, last)) + j = jnp.where(p < m, 2 * p + 1, jnp.where(p == m, last, last - 2)) + rnd = jnp.where(p < m, 0, p - m + 1) + density = wa * n_a / volume * jnp.where((n_a % 2 == 1) & (p >= m - 1), 0.5, 1.0) + # odd cells collide their last three particles pairwise at half weight (Takizuka-Abe) + else: + lo, hi = jnp.maximum(jnp.minimum(n_a, n_b), 1), jnp.maximum(jnp.maximum(n_a, n_b), 1) + i, j, rnd = p % jnp.maximum(n_a, 1), n_a + p % jnp.maximum(n_b, 1), p // lo + density = jnp.maximum(wa, wb) * n_a * n_b / (hi * volume) + # each particle of the larger group collides once; weights corrected by rejection below + i = order[jnp.where(valid, st + i, 0)] + j = order[jnp.where(valid, st + j, 0)] + mu = ma * mb / (ma + mb) + coef = (species_config.charge[sa] * species_config.charge[sb]) ** 2 * density * coulomb_log * dyn.dt / ( + 8 * jnp.pi * dyn.eps**2 * mu**2) + wmax = jnp.maximum(wa, wb) + + def round_(k, us): + k1, k2, k3 = jax.random.split(jax.random.fold_in(k_round, k), 3) + g = us[i] - us[j] + var = coef / jnp.maximum(jnp.linalg.norm(g, axis=-1), 1e-300) ** 3 + cos_t = _nanbu_cos(2 * var, jax.random.uniform(k1, var.shape, minval=1e-300)) + # s = 2 is the Takizuka-Abe small-angle limit of <1 - cos(theta)> + dg = _rotate(g, cos_t, k2) - g + r = jax.random.uniform(k3, var.shape) + sel = valid & (rnd == k) + us = us.at[i].add(jnp.where(sel & (r < wb / wmax), mb / (ma + mb), 0.0)[:, None] * dg) + return us.at[j].add(-jnp.where(sel & (r < wa / wmax), ma / (ma + mb), 0.0)[:, None] * dg) + + us = jax.lax.fori_loop(0, jnp.max(jnp.where(valid, rnd + 1, 0)), round_, us) + return u.at[sa].set(us[: u.shape[1]]) if intra else u.at[sa].set(us[: u.shape[1]]).at[sb].set(us[u.shape[1]:]) + + +def _insert(x, u, active, s, mask, xn, un): + """Place masked new particles into free slots of species s; report overflow. + + Args: + x (jnp.ndarray): Tile positions, shape ``(species, slots, 3)`` (m). + u (jnp.ndarray): Tile velocities, shape ``(species, slots, 3)`` (m/s). + active (jnp.ndarray): Tile occupancy flags, shape ``(species, slots)``. + s (int): Index of the species that receives the new particles. + mask (jnp.ndarray): Which candidate particles to create, shape ``(slots,)``. + xn (jnp.ndarray): Candidate positions, shape ``(slots, 3)`` (m). + un (jnp.ndarray): Candidate velocities, shape ``(slots, 3)`` (m/s). + + Returns: + tuple: Updated ``(x, u, active)`` and a flag that is True when some new + particles found no free slot and were dropped. + """ + free_first = jnp.argsort(active[s], stable=True) + rank = jnp.cumsum(mask) - 1 + ok = mask & (rank < jnp.sum(~active[s])) + slot = jnp.where(ok, free_first[jnp.clip(rank, 0, mask.shape[0] - 1)], mask.shape[0]) + x = x.at[s, slot].set(xn, mode="drop") + u = u.at[s, slot].set(un, mode="drop") + return x, u, active.at[s, slot].set(True, mode="drop"), jnp.any(mask & ~ok) + + +def _mcc(key, x, u, active, spec, species_config, dyn): + """Background-gas Monte Carlo collisions for one tile and one projectile species. + + Args: + key (jax.Array): JAX PRNG key for this tile and spec. + x (jnp.ndarray): Tile positions, shape ``(species, slots, 3)`` (m). + u (jnp.ndarray): Tile velocities, shape ``(species, slots, 3)`` (m/s). + active (jnp.ndarray): Tile occupancy flags, shape ``(species, slots)``. + spec (tuple): ``("mcc", species, background_density, background_temperature, + background_mass, processes)`` from :func:`load_collisions_from_toml`. + species_config (SpeciesConfig): Per-species charge, mass and macro-particle weight. + dyn: Dynamic parameters; uses ``dt`` and ``kb``. + + Returns: + tuple: Updated ``(x, u, active)`` and a flag that is True when ionization + products did not fit in the free slots. + """ + _, s, n_gas, t_gas, M, processes = spec + S, m = u.shape[1], species_config.mass[s] + keys = jax.random.split(key, 5 + 2 * len(processes)) + vn = jnp.sqrt(dyn.kb * t_gas / M) * jax.random.normal(keys[0], (S, 3)) + g = u[s] - vn + gn = jnp.linalg.norm(g, axis=-1) + mu = m * M / (m + M) + energy = 0.5 * mu * gn**2 / E_CHARGE + nu = jnp.stack([n_gas * jnp.interp(energy, jnp.asarray(e), jnp.asarray(sig)) * gn for _, _, e, sig, _, _ in processes]) + nu_cum = jnp.cumsum(nu, axis=0) + hit = active[s] & (jax.random.uniform(keys[1], (S,)) < -jnp.expm1(-nu_cum[-1] * dyn.dt)) + which = jnp.sum(jax.random.uniform(keys[2], (S,)) * nu_cum[-1] > nu_cum, axis=0) + # choose one process per colliding particle with probability nu_k / nu_total + vcm = (m * u[s] + M * vn) / (m + M) + new_u, overflow, births = u[s], jnp.asarray(False), [] + for k, (ptype, cost, _, _, se, si) in enumerate(processes): + sel = hit & (which == k) + g_after = jnp.sqrt(jnp.maximum(gn**2 - 2 * cost * E_CHARGE / mu, 0.0))[:, None] + if ptype == "charge_exchange": + v = vn + elif ptype == "back": + v = vcm - M / (m + M) * g + elif ptype == "ionization": + g_after = g_after / jnp.sqrt(2.0) + # remaining energy shared equally by the scattered and ejected electrons + v = vn + g_after * _isotropic(keys[5 + 2 * k], S) + births += [(se, sel, vn + g_after * _isotropic(keys[6 + 2 * k], S)), (si, sel, vn)] + else: + v = vcm + M / (m + M) * g_after * _isotropic(keys[5 + 2 * k], S) + # elastic and excitation scatter isotropically in the centre-of-mass frame + new_u = jnp.where(sel[:, None], v, new_u) + u = u.at[s].set(new_u) + for target, mask, un in births: + x, u, active, full = _insert(x, u, active, target, mask, x[s], un) + overflow = overflow | full + return x, u, active, overflow + + +def apply_collisions(particles, species_config, static_parameters, dynamic_parameters): + """Apply every configured collision operator to all tiles. + + Called right after the velocity push, so collisions act on ``u^{n+1/2}`` at ``x^n``. + + Args: + particles (TiledParticles): Tile-major particles; ``particles.key`` must be a PRNG key. + species_config (SpeciesConfig): Per-species charge, mass and macro-particle weight. + static_parameters (StaticParameters): Uses ``collisions``, the specs from + :func:`load_collisions_from_toml`. + dynamic_parameters (DynamicParameters): Uses ``dx``, ``dy``, ``dz``, ``dt``, ``eps`` and ``kb``. + + Returns: + tuple: Updated particles with an advanced ``key``, and a flag that is True when + ionization products overflowed a tile. + """ + specs = static_parameters.collisions + if not specs: + return particles, jnp.asarray(False) + if particles.key is None: + raise ValueError("Collisions need TiledParticles.key (a jax.random.PRNGKey).") + key, sub = jax.random.split(particles.key) + tiles = particles.x.shape[:3] + keys = jax.random.split(sub, int(np.prod(tiles))).reshape(tiles + (-1,)) + + def tile(k, x, u, active): + overflow = jnp.asarray(False) + for n, spec in enumerate(specs): + kn = jax.random.fold_in(k, n) + if spec[0] == "binary": + u = _binary(kn, x, u, active, spec, species_config, dynamic_parameters) + else: + x, u, active, full = _mcc(kn, x, u, active, spec, species_config, dynamic_parameters) + overflow = overflow | full + return x, u, active, overflow + + x, u, active, overflow = jax.vmap(jax.vmap(jax.vmap(tile)))(keys, particles.x, particles.u, particles.active) + return particles._replace(x=x, u=u, active=active, key=key), jnp.any(overflow) diff --git a/PyPIC3D/diagnostics/gr_work_energy_theorem.py b/PyPIC3D/diagnostics/gr_work_energy_theorem.py index 2ee99c3..96d54aa 100644 --- a/PyPIC3D/diagnostics/gr_work_energy_theorem.py +++ b/PyPIC3D/diagnostics/gr_work_energy_theorem.py @@ -263,10 +263,10 @@ def sample_energy(particles, species, fields, static, dynamic): from PyPIC3D.relativity.dynamical_relativity import bssn_tile_layout lapse_gradient = map_tiled( lambda lapse, params: jnp.stack(tuple(diff1_physical(lapse, axis, params) for axis in range(3))), - state.lapse, bssn.evolution_parameters, **bssn_tile_layout(static), + state.lapse, static.bssn_evolution_parameters, bssn_tile_layout(static), output_template=jnp.zeros((3,) + state.lapse.shape, dtype=state.lapse.dtype)) else: - lapse_gradient = jnp.stack(tuple(diff1_physical(state.lapse, axis, bssn.evolution_parameters) + lapse_gradient = jnp.stack(tuple(diff1_physical(state.lapse, axis, static.bssn_evolution_parameters) for axis in range(3))) curvature_power = volume_integral( volume * state.lapse * jnp.einsum("ij...,ij...->...", K, stress_up), static, dynamic) diff --git a/PyPIC3D/diagnostics/static_metric.py b/PyPIC3D/diagnostics/static_metric.py index 18bec47..808d0af 100644 --- a/PyPIC3D/diagnostics/static_metric.py +++ b/PyPIC3D/diagnostics/static_metric.py @@ -44,10 +44,10 @@ def bssn_constraint_norms(particles, species, fields, static, dynamic, *, source if tiled: from JAX_BSSN.parallel import tiled_constraint_norms from PyPIC3D.relativity.dynamical_relativity import bssn_tile_layout - return tiled_constraint_norms(bssn.state, bssn.evolution_parameters, rho=rho, - momentum=momentum, **bssn_tile_layout(static)) + return tiled_constraint_norms(bssn.state, static.bssn_evolution_parameters, + bssn_tile_layout(static), rho=rho, momentum=momentum) violations = compute_all_constraints_with_matter( - bssn.state, bssn.evolution_parameters, rho, momentum) + bssn.state, static.bssn_evolution_parameters, rho, momentum) return compute_constraint_norms(violations) diff --git a/PyPIC3D/initialization.py b/PyPIC3D/initialization.py index b9f817f..52abb4c 100644 --- a/PyPIC3D/initialization.py +++ b/PyPIC3D/initialization.py @@ -6,6 +6,7 @@ import jax.numpy as jnp from PyPIC3D.relativity.field_state import densitize_vector +from PyPIC3D.collisions import load_collisions_from_toml from PyPIC3D.particles.particle_initialization import load_particles_from_toml from PyPIC3D.pusher.particle_push import seed_leapfrog_velocity from PyPIC3D.particles.particle_tile_communication import shard_tiled_particles @@ -649,7 +650,9 @@ def initialize_simulation(toml_file, *, bssn_state=None, bssn_evolution_paramete from PyPIC3D.relativity.bssn_parameters import load_bssn_parameters_from_toml from PyPIC3D.relativity.dynamical_relativity import build_bssn_metric - bssn = load_bssn_parameters_from_toml( + # The evolution controls are run constants that JAX_BSSN reads concretely, + # so the loader hands them back on static_parameters. + static_parameters, bssn = load_bssn_parameters_from_toml( config, static_parameters, dynamic_parameters, state=bssn_state, evolution_parameters=bssn_evolution_parameters, ) @@ -676,7 +679,11 @@ def initialize_simulation(toml_file, *, bssn_state=None, bssn_evolution_paramete "Reducing particle_batch_size from " f"{static_parameters.particle_batch_size} to tile capacity {effective_batch_size}." ) - static_parameters = static_parameters._replace(particle_batch_size=effective_batch_size) + static_parameters = static_parameters._replace( + particle_batch_size=effective_batch_size, + collisions=load_collisions_from_toml(config, particle_species_names, species_config.weight), + ) + particles = particles._replace(key=jax.random.PRNGKey(int(config.get("simulation_parameters", {}).get("seed", 0)))) particles = shard_tiled_particles(particles, static_parameters) if static_parameters.lapse_deleting: # Initial output and leapfrog histories must use the surviving ensemble. diff --git a/PyPIC3D/particles/particle_class.py b/PyPIC3D/particles/particle_class.py index 167efa8..9b606b6 100644 --- a/PyPIC3D/particles/particle_class.py +++ b/PyPIC3D/particles/particle_class.py @@ -37,3 +37,5 @@ class TiledParticles(NamedTuple): # velocities at half time steps, u^{n-1/2}; covariant u_i for static_metric active: jax.Array # (ntx, nty, ntz, species, max_particles_per_tile) # boolean array indicating whether the particle is active or not + key: jax.Array = None + # PRNG key advanced by stochastic operators such as collisions diff --git a/PyPIC3D/particles/particle_tile_communication.py b/PyPIC3D/particles/particle_tile_communication.py index 0d8a81b..b56faa6 100644 --- a/PyPIC3D/particles/particle_tile_communication.py +++ b/PyPIC3D/particles/particle_tile_communication.py @@ -39,7 +39,7 @@ def shard_tiled_particles(tiled_particles, static_parameters): state_sharding = NamedSharding(mesh, PARTICLE_STATE_TILE_SPEC) active_sharding = NamedSharding(mesh, PARTICLE_ACTIVE_TILE_SPEC) - return TiledParticles( + return tiled_particles._replace( x=jax.device_put(tiled_particles.x, state_sharding), u=jax.device_put(tiled_particles.u, state_sharding), active=jax.device_put(tiled_particles.active, active_sharding), @@ -451,7 +451,7 @@ def refresh(tiled_particles, dynamic_parameters): tiled_particles.active, dynamic_parameters, ) - return TiledParticles(x=x, u=u, active=active), overflow + return tiled_particles._replace(x=x, u=u, active=active), overflow return refresh diff --git a/PyPIC3D/pusher/hybrid_boris_geodesic.py b/PyPIC3D/pusher/hybrid_boris_geodesic.py index 0d317a4..9735712 100644 --- a/PyPIC3D/pusher/hybrid_boris_geodesic.py +++ b/PyPIC3D/pusher/hybrid_boris_geodesic.py @@ -5,7 +5,6 @@ import jax.numpy as jnp from jax.sharding import PartitionSpec as P -from PyPIC3D.particles.particle_class import TiledParticles from PyPIC3D.particles.particle_batching import ( prepare_particle_batches, particle_batch_indices, number_of_particle_batches, ) @@ -318,6 +317,6 @@ def batches_remaining(batch_state): particles.x, particles.u, particles.active, prepared_fields, (species_q_over_m, species_config.update_x, dt)) - full_step = TiledParticles(x=x_new, u=u_new, active=particles.active) - half_step = TiledParticles(x=x_half, u=u_new, active=particles.active) + full_step = particles._replace(x=x_new, u=u_new) + half_step = particles._replace(x=x_half, u=u_new) return full_step, half_step diff --git a/PyPIC3D/pusher/particle_push.py b/PyPIC3D/pusher/particle_push.py index 273b49b..904d4e6 100644 --- a/PyPIC3D/pusher/particle_push.py +++ b/PyPIC3D/pusher/particle_push.py @@ -1,7 +1,6 @@ import jax import jax.numpy as jnp -from PyPIC3D.particles.particle_class import TiledParticles from PyPIC3D.particles.particle_batching import ( number_of_particle_batches, particle_batch_indices, @@ -236,11 +235,7 @@ def batches_remaining(batch_state): Bz_tiles, ) - return TiledParticles( - x=particles.x, - u=new_u, - active=particles.active, - ) + return particles._replace(u=new_u) def seed_leapfrog_velocity( diff --git a/PyPIC3D/relativity/bssn_parameters.py b/PyPIC3D/relativity/bssn_parameters.py index 27db3de..ef9a284 100644 --- a/PyPIC3D/relativity/bssn_parameters.py +++ b/PyPIC3D/relativity/bssn_parameters.py @@ -21,10 +21,21 @@ class BSSNParameters(NamedTuple): """ state: object - evolution_parameters: object time: object +BSSN_FACE_NAMES = ("xl_bc", "xr_bc", "yl_bc", "yr_bc", "zl_bc", "zr_bc") + + +def _face_code(name, value): + """Normalize one [metric] face entry to the JAX_BSSN code 0 or 1.""" + if isinstance(value, str) and value in ("periodic", "sommerfeld"): + return {"periodic": 0, "sommerfeld": 1}[value] + if isinstance(value, Integral) and not isinstance(value, bool) and value in (0, 1): + return int(value) + raise ValueError(f"[metric] {name} must be 'periodic', 'sommerfeld', 0, or 1") + + def load_bssn_parameters_from_toml(config, static_parameters, dynamic_parameters, *, state=None, evolution_parameters=None): """Read native ``[metric]`` initial arrays and gauge/evolution controls. @@ -36,6 +47,10 @@ def load_bssn_parameters_from_toml(config, static_parameters, dynamic_parameters Without ``[metric]``, retain the legacy flat default, ``[bssn_parameters]`` table, and Python override behavior. + + Returns ``(static_parameters, bssn)``: the evolution controls are run + constants that JAX_BSSN reads concretely, so they ride on the static + parameters rather than through jit as traced leaves. """ if "metric" not in config: legacy = dict(config.get("bssn_parameters", {})) @@ -54,7 +69,7 @@ def load_bssn_parameters_from_toml(config, static_parameters, dynamic_parameters raise ValueError("[metric] must be a TOML table") state_names = BSSNVariables._fields - boundary_names = ("xl_bc", "xr_bc", "yl_bc", "yr_bc", "zl_bc", "zr_bc") + boundary_names = BSSN_FACE_NAMES numeric_names = ("time", "eta", "kappa", "nu", "g", "mad_q") derived_names = {"dx", "dt", "x_min", "y_min", "z_min"} forbidden = set(metric_config) & derived_names @@ -85,13 +100,7 @@ def load_bssn_parameters_from_toml(config, static_parameters, dynamic_parameters for name in boundary_names: if name not in metric_config: continue - value = metric_config[name] - if isinstance(value, str) and value in ("periodic", "sommerfeld"): - controls[name] = {"periodic": 0, "sommerfeld": 1}[value] - elif isinstance(value, Integral) and not isinstance(value, bool) and value in (0, 1): - controls[name] = int(value) - else: - raise ValueError(f"[metric] {name} must be 'periodic', 'sommerfeld', 0, or 1") + controls[name] = _face_code(name, metric_config[name]) time = controls.pop("time", 0.0) if static_parameters.field_mesh.size > 1: @@ -100,15 +109,15 @@ def load_bssn_parameters_from_toml(config, static_parameters, dynamic_parameters for name, value in sources.items(): if value is not False and not isinstance(value, str): raise ValueError(f"[metric] {name} must be an initialization filename or literal false") - parameters = build_bssn_parameters( + static_parameters, parameters = build_bssn_parameters( static_parameters, dynamic_parameters, state=sources, evolution_parameters=controls, time=time) state = parameters.state from JAX_BSSN.parallel import map_tiled, owned_mask from PyPIC3D.relativity.dynamical_relativity import bssn_tile_layout mask = map_tiled(lambda value, params: owned_mask(value.shape, params), - state.conformal_factor, parameters.evolution_parameters, - **bssn_tile_layout(static_parameters)) + state.conformal_factor, static_parameters.bssn_evolution_parameters, + bssn_tile_layout(static_parameters)) if not all(bool(jnp.all(jnp.where(mask, jnp.isfinite(v), True))) for v in state): raise ValueError("[metric] initial geometry must contain finite values") if not bool(jnp.all(jnp.where(mask, state.conformal_factor > 0, True))): @@ -119,11 +128,11 @@ def load_bssn_parameters_from_toml(config, static_parameters, dynamic_parameters raise ValueError("[metric] conformal_metric must be symmetric") if not bool(jnp.all(jnp.where(mask[..., None], jnp.linalg.eigvalsh(gamma) > 0, True))): raise ValueError("[metric] conformal_metric must be positive definite") - return parameters + return static_parameters, parameters # Keep the established serial global-array input contract. - parameters = build_bssn_parameters( + static_parameters, parameters = build_bssn_parameters( static_parameters, dynamic_parameters, evolution_parameters=controls, time=time, ) @@ -157,7 +166,7 @@ def load_bssn_parameters_from_toml(config, static_parameters, dynamic_parameters raise ValueError("[metric] conformal_metric must be symmetric") if not bool(jnp.all(jnp.linalg.eigvalsh(gamma) > 0)): raise ValueError("[metric] conformal_metric must be positive definite; omitted/false creates zeros") - return parameters._replace(state=state) + return static_parameters, parameters._replace(state=state) def build_bssn_parameters(static_parameters, dynamic_parameters, *, state=None, @@ -201,14 +210,20 @@ def build_bssn_parameters(static_parameters, dynamic_parameters, *, state=None, for name in ("xl_bc", "xr_bc", "yl_bc", "yr_bc", "zl_bc", "zr_bc")): raise ValueError("Matched GR filtering requires all six BSSN boundaries to be periodic") - evolution_parameters = jax.tree.map(jnp.asarray, evolution_parameters) + # Native Python scalars, the inverse of an asarray sweep: these are run + # constants carried on static_parameters, JAX_BSSN reads several of them with + # int()/float(), and an array leaf would make StaticParameters unhashable and + # so unusable as a static jit argument. + evolution_parameters = jax.tree.map( + lambda value: value.item() if hasattr(value, "item") else value, + evolution_parameters) if tiled: from JAX_BSSN.parallel import initialize_tiled_bssn from PyPIC3D.relativity.dynamical_relativity import bssn_tile_layout layout = bssn_tile_layout(static_parameters) if not hasattr(state, "conformal_factor") or state.conformal_factor.ndim != 6: - state = initialize_tiled_bssn(state, evolution_parameters, **layout) + state = initialize_tiled_bssn(state, evolution_parameters, layout) else: expected = tuple(tile_counts) + tuple(width + 2 * layout["guard_cells"] for width in static_parameters.tile_shape) @@ -224,4 +239,6 @@ def build_bssn_parameters(static_parameters, dynamic_parameters, *, state=None, elif state.conformal_factor.shape != shape: raise ValueError("BSSN state must match the physical PIC center-node allocation") - return BSSNParameters(state, evolution_parameters, jnp.asarray(time)) + static_parameters = static_parameters._replace( + bssn_evolution_parameters=evolution_parameters) + return static_parameters, BSSNParameters(state, jnp.asarray(time)) diff --git a/PyPIC3D/relativity/dynamical_relativity.py b/PyPIC3D/relativity/dynamical_relativity.py index 7559cb5..c27b0c3 100644 --- a/PyPIC3D/relativity/dynamical_relativity.py +++ b/PyPIC3D/relativity/dynamical_relativity.py @@ -21,12 +21,15 @@ def bssn_tile_layout(static_parameters): """Share PIC ownership and devices, with enough halo for C-to-Yee transfer.""" + from JAX_BSSN.parallel import TileLayout + endpoints = tuple(bc == 1 for bc in static_parameters.boundary_conditions) # An owned upper endpoint occupies one of the nominal upper ghost slots. guard = max(4 + int(any(endpoints)), static_parameters.guard_cells + 1) - return dict(mesh=static_parameters.field_mesh, - tile_shape=static_parameters.tile_shape, - guard_cells=guard, upper_endpoints=endpoints) + # A layout is the cache key of the halo sweep, so every field must be hashable. + return TileLayout(mesh=static_parameters.field_mesh, + tile_shape=tuple(static_parameters.tile_shape), + guard_cells=guard, upper_endpoints=endpoints) def resize_bssn_halos(values, static_parameters, dynamic_parameters, *, exterior="linear", @@ -36,19 +39,19 @@ def resize_bssn_halos(values, static_parameters, dynamic_parameters, *, exterior layout = bssn_tile_layout(static_parameters) old_guard = (values.shape[-3] - static_parameters.tile_shape[0]) // 2 - difference = layout["guard_cells"] - old_guard + difference = layout.guard_cells - old_guard if difference > 0: values = jnp.pad(values, ((0, 0),) * (values.ndim - 3) + ((difference, difference),) * 3) elif difference < 0: trim = -difference values = values[..., trim:-trim, trim:-trim, trim:-trim] - parameters = dynamic_parameters.bssn_parameters.evolution_parameters + parameters = static_parameters.bssn_evolution_parameters if boundary_conditions is not None: boundary = tuple(int(bc != 0) for bc in boundary_conditions) parameters = parameters._replace(xl_bc=boundary[0], xr_bc=boundary[0], yl_bc=boundary[1], yr_bc=boundary[1], zl_bc=boundary[2], zr_bc=boundary[2]) - return refresh_tiled_field(values, parameters, **layout, exterior=exterior) + return refresh_tiled_field(values, parameters, layout, exterior=exterior) def crop_bssn_halos(values, static_parameters, *, extra_guard=0): @@ -120,11 +123,11 @@ def geometry_tiles(value): # The established C-to-Yee exterior follows the EM domain, which # can differ from the BSSN evolution boundary codes. boundaries = tuple(int(bc != 0) for bc in static_parameters.boundary_conditions) - parameters = dynamic_parameters.bssn_parameters.evolution_parameters._replace( + parameters = static_parameters.bssn_evolution_parameters._replace( xl_bc=boundaries[0], xr_bc=boundaries[0], yl_bc=boundaries[1], yr_bc=boundaries[1], zl_bc=boundaries[2], zr_bc=boundaries[2]) - value = refresh_tiled_field(value, parameters, **bssn_tile_layout(static_parameters)) + value = refresh_tiled_field(value, parameters, bssn_tile_layout(static_parameters)) return crop_bssn_halos(value, static_parameters, extra_guard=1) return bssn_to_tiles(value, static_parameters, extra_guard=1) @@ -204,13 +207,13 @@ def initialize_dynamical_relativity(particles, species, fields, static_parameter from PyPIC3D.relativity.filtering import validate_gr_filter validate_gr_filter(static_parameters) - if any(int(getattr(bssn.evolution_parameters, name)) != 0 + if any(int(getattr(static_parameters.bssn_evolution_parameters, name)) != 0 for name in ("xl_bc", "xr_bc", "yl_bc", "yr_bc", "zl_bc", "zr_bc")): raise ValueError("Matched GR filtering requires all six BSSN boundaries to be periodic") if bssn.state.conformal_factor.ndim == 6: from JAX_BSSN.parallel import prepare_tiled_state - state = prepare_tiled_state(bssn.state, bssn.evolution_parameters, - **bssn_tile_layout(static_parameters)) + state = prepare_tiled_state(bssn.state, static_parameters.bssn_evolution_parameters, + bssn_tile_layout(static_parameters)) else: state = enforce_algebraic_constraints(bssn.state) dynamic_parameters = dynamic_parameters._replace(bssn_parameters=bssn._replace(state=state)) diff --git a/PyPIC3D/relativity/energy_momentum_tensor.py b/PyPIC3D/relativity/energy_momentum_tensor.py index f8b43ba..57eb1ad 100644 --- a/PyPIC3D/relativity/energy_momentum_tensor.py +++ b/PyPIC3D/relativity/energy_momentum_tensor.py @@ -302,7 +302,7 @@ def compute_energy_momentum_tensor( if tiled: from PyPIC3D.relativity.dynamical_relativity import bssn_tile_layout filter_parameters = static_parameters._replace( - guard_cells=bssn_tile_layout(static_parameters)["guard_cells"]) + guard_cells=bssn_tile_layout(static_parameters).guard_cells) components = filter_gr_grid(volume * components, filter_parameters, dynamic_parameters, tiled=tiled) / volume stress = jnp.stack(( diff --git a/PyPIC3D/relativity/pair_injection.py b/PyPIC3D/relativity/pair_injection.py index 29235fd..a08ca4a 100644 --- a/PyPIC3D/relativity/pair_injection.py +++ b/PyPIC3D/relativity/pair_injection.py @@ -6,7 +6,6 @@ import jax import jax.numpy as jnp -from PyPIC3D.particles.particle_class import TiledParticles from PyPIC3D.pusher.particle_push import seed_leapfrog_velocity from PyPIC3D.relativity.interpolate_metric import ( interpolate_metric, particle_active_axes, safe_inactive_positions, @@ -89,7 +88,7 @@ def one_tile(x, u, active, positions, momenta, requested, primitive_metric, grid metric.center, dynamic.grids.tiled_center_grid) # Insertion only activates slots; identify births before any push or migration. newborn = active & ~particles.active - result = TiledParticles(x, u, active) + result = particles._replace(x=x, u=u, active=active) seeded = seed_leapfrog_velocity( result._replace(active=newborn), species, D, B, static, dynamic, metric) result = result._replace(u=jnp.where(newborn[..., None], seeded.u, result.u)) diff --git a/PyPIC3D/solvers/GR_yee/time_loop_dynamical_relativity.py b/PyPIC3D/solvers/GR_yee/time_loop_dynamical_relativity.py index 38b82d1..8ce1ab4 100644 --- a/PyPIC3D/solvers/GR_yee/time_loop_dynamical_relativity.py +++ b/PyPIC3D/solvers/GR_yee/time_loop_dynamical_relativity.py @@ -47,7 +47,7 @@ def time_loop_dynamical_relativity( """ bssn = dynamic_parameters.bssn_parameters dt, time = dynamic_parameters.dt, bssn.time - evolution_parameters = bssn.evolution_parameters + evolution_parameters = static_parameters.bssn_evolution_parameters tiled = bssn.state.conformal_factor.ndim == 6 if tiled: from JAX_BSSN.parallel import ( @@ -65,8 +65,8 @@ def apply_callbacks(local_state, local_parameters): lapse, shift, _, _ = prescribed_gauge(local_state, stage_time, params=local_parameters) local_state = local_state._replace(lapse=lapse, shift=shift) return local_state - state = map_tiled(apply_callbacks, state, evolution_parameters, **layout) - return prepare_tiled_state(state, evolution_parameters, **layout) + state = map_tiled(apply_callbacks, state, evolution_parameters, layout) + return prepare_tiled_state(state, evolution_parameters, layout) if gravity_boundary is not None: state = gravity_boundary(state, stage_time) if prescribed_gauge is not None: @@ -125,7 +125,7 @@ def gravity_rhs(stage_state, stage_time): ) if tiled: rhs = compute_tiled_bssn_rhs_with_matter( - stage_state, evolution_parameters, rho, momentum, stress, **layout) + stage_state, evolution_parameters, layout, rho, momentum, stress) else: rhs = compute_bssn_rhs_with_matter( stage_state, evolution_parameters, rho, momentum, stress) @@ -137,7 +137,7 @@ def gauge_rhs(local_values, local_parameters): local_state, stage_time, params=local_parameters) return local_rhs._replace(lapse=lapse_dot, shift=shift_dot) rhs = map_tiled(gauge_rhs, (stage_state, rhs), evolution_parameters, - **layout, output_template=rhs) + layout, output_template=rhs) else: _, _, lapse_dot, shift_dot = prescribed_gauge(stage_state, stage_time) rhs = rhs._replace(lapse=lapse_dot, shift=shift_dot) diff --git a/PyPIC3D/solvers/dark_matter_yee/time_loop.py b/PyPIC3D/solvers/dark_matter_yee/time_loop.py index 2233bfd..057c76b 100644 --- a/PyPIC3D/solvers/dark_matter_yee/time_loop.py +++ b/PyPIC3D/solvers/dark_matter_yee/time_loop.py @@ -1,5 +1,6 @@ """Coupled Maxwell-Proca PIC with E'/phi' at n and A' at n-1/2.""" +from PyPIC3D.collisions import apply_collisions from PyPIC3D.deposition.Esirkepov import Esirkepov_current from PyPIC3D.deposition.J_from_rhov import J_from_rhov from PyPIC3D.particles.particle_tile_communication import ( @@ -41,6 +42,8 @@ def time_loop_dark_photon(particles, species_config, fields, static_parameters, ) particles = particle_push(particles, species_config, push_E, push_B, static_parameters, dynamic_parameters) # first push the particles with the integer-time force fields, including adjoint current filtering + particles, collision_overflow = apply_collisions(particles, species_config, static_parameters, dynamic_parameters) + overflow = overflow | collision_overflow if static_parameters.current_deposition == "esirkepov": diff --git a/PyPIC3D/solvers/electrostatic/time_loop.py b/PyPIC3D/solvers/electrostatic/time_loop.py index a2b04f4..6ce5708 100644 --- a/PyPIC3D/solvers/electrostatic/time_loop.py +++ b/PyPIC3D/solvers/electrostatic/time_loop.py @@ -1,3 +1,4 @@ +from PyPIC3D.collisions import apply_collisions from PyPIC3D.particles.particle_tile_communication import ( refresh_tiled_particle_tiles, update_tiled_particle_positions, @@ -43,6 +44,8 @@ def time_loop_electrostatic( dynamic_parameters, ) # push velocities using the selected tiled particle pusher + particles, collision_overflow = apply_collisions(particles, species_config, static_parameters, dynamic_parameters) + overflow_previous = overflow_previous | collision_overflow particles = update_tiled_particle_positions(particles, species_config, dt) # update particle forward positions before depositing rho diff --git a/PyPIC3D/solvers/yee/time_loop.py b/PyPIC3D/solvers/yee/time_loop.py index 9978501..74a3770 100644 --- a/PyPIC3D/solvers/yee/time_loop.py +++ b/PyPIC3D/solvers/yee/time_loop.py @@ -1,3 +1,4 @@ +from PyPIC3D.collisions import apply_collisions from PyPIC3D.deposition.Esirkepov import Esirkepov_current from PyPIC3D.deposition.J_from_rhov import J_from_rhov from PyPIC3D.particles.particle_tile_communication import ( @@ -43,6 +44,9 @@ def time_loop_electrodynamic( dynamic_parameters, ) # use the selected tiled pusher for particle velocities + particles, collision_overflow = apply_collisions(particles, species_config, static_parameters, dynamic_parameters) + overflow_previous = overflow_previous | collision_overflow + # collide particles at x^n with the freshly pushed u^{n+1/2} def direct_deposition_step(state): particles, J_tiles, overflow_previous = state diff --git a/PyPIC3D/utilities/parameters.py b/PyPIC3D/utilities/parameters.py index f9063b4..620b836 100644 --- a/PyPIC3D/utilities/parameters.py +++ b/PyPIC3D/utilities/parameters.py @@ -50,6 +50,12 @@ class StaticParameters(NamedTuple): metric_backreaction: bool = True lapse_deleting: bool = False lapse_threshold: float = 0.1 + collisions: tuple = () + bssn_evolution_parameters: object = None + # JAX_BSSN's own BSSNParameters: every field is a run constant, and JAX_BSSN + # reads several of them with int()/float() to key its cached halo operator. + # Held static so they stay native Python scalars; jit turns every leaf of a + # dynamic argument into a tracer regardless of how it was stored. class DynamicParameters(NamedTuple): @@ -250,16 +256,22 @@ def _output_value(value): def static_parameters_for_output(static_parameters): - skip = {"field_mesh"} + skip = {"field_mesh", "collisions", "bssn_evolution_parameters"} static_items = static_parameters._asdict() if static_parameters.solver in ("static_metric", "dynamic_metric"): from PyPIC3D.relativity.interpolate_metric import RECONSTRUCTION static_items["particle_metric_reconstruction"] = RECONSTRUCTION - return { + result = { key: _output_value(value) for key, value in static_items.items() if key not in skip } + if static_parameters.bssn_evolution_parameters is not None: + result["bssn_evolution_parameters"] = { + key: _output_value(value) for key, value + in static_parameters.bssn_evolution_parameters._asdict().items() + } + return result def dynamic_parameters_for_output(dynamic_parameters): @@ -273,7 +285,6 @@ def dynamic_parameters_for_output(dynamic_parameters): if dynamic_parameters.bssn_parameters is not None: bssn = dynamic_parameters.bssn_parameters result["bssn_parameters"] = { - **{key: _output_value(value) for key, value in bssn.evolution_parameters._asdict().items()}, "time": _output_value(bssn.time), "units": "geometrized Gaussian, G=c=1", } diff --git a/demos/collisions/binary_relaxation/binary_relaxation.py b/demos/collisions/binary_relaxation/binary_relaxation.py new file mode 100644 index 0000000..9d8fd76 --- /dev/null +++ b/demos/collisions/binary_relaxation/binary_relaxation.py @@ -0,0 +1,189 @@ +"""Binary Coulomb collision demos (0-D, particles paired cell by cell in CELLS^3 cells, no fields): + 1. temperature equilibration of two equal-mass species, against the Spitzer rate + 2. electron-positron thermalization, with the exponential relaxation rate of |T_e - T_p| checked + against the Spitzer rate nu = 2 nu_ep evaluated at t = 0 +Runs are saved to outputs/binary_relaxation/binary_runs.npz; --plot redraws from it without rerunning.""" +import os +import sys +from types import SimpleNamespace + +import jax +import jax.numpy as jnp +import matplotlib.pyplot as plt +import numpy as np + +from PyPIC3D.collisions import apply_collisions +from PyPIC3D.particles.particle_class import SpeciesConfig, TiledParticles + +jax.config.update("jax_enable_x64", True) + +# ----------------------------- input parameters ----------------------------- +N = 20_480 # macro-particles per species +CELLS = 8 # particles fill CELLS^3 cells, paired cell by cell +COULOMB_LOG = 10.0 +EQUIL = dict(t_a=12_000.0, t_b=1_000.0, density=1.0e20, steps=100, relax_steps=25.0) # [K], [m^-3]; ~e-fold in relax_steps +THERM = dict(t_e=2_800.0, t_p=30.0, rate=0.008, dt=1.0, t_end=2000.0) # [K]; target nu / omega_pe; dt, t_end in 1 / omega_pe +OUTPUT_DIR = "outputs/binary_relaxation" +SEEDS = range(5) # independent random seeds; figures show mean +/- 1 std + +E, ME, KB, EPS = 1.602176634e-19, 9.1093837e-31, 1.380649e-23, 8.8541878128e-12 + + +def spitzer(ta, tb, n): + """Equal-mass energy-exchange rate nu_ab (dT_a/dt = nu_ab (T_b - T_a)). + + Args: + ta (float): Temperature of species a (K). + tb (float): Temperature of species b (K). + n (float): Number density of the partner species (m^-3). + + Returns: + float: Energy-exchange rate (1/s). + """ + return 2 * E**4 * n * COULOMB_LOG / (3 * (2 * np.pi) ** 1.5 * EPS**2 * ME**2 * (KB * (ta + tb) / ME) ** 1.5) + + +def band(ax, x, runs, color, label, **kw): + """Mean line with a shaded +/- 1 standard deviation band over seeds. + + Args: + ax (matplotlib.axes.Axes): Axes to draw on. + x (np.ndarray): Horizontal coordinates. + runs (np.ndarray): Values with seeds on axis 0, shape ``(seeds, len(x))``. + color: Matplotlib color for the line and band. + label (str): Legend label. + **kw: Extra keyword arguments for the mean line. + """ + mean, std = runs.mean(0), runs.std(0) + ax.fill_between(x, mean - std, mean + std, color=color, alpha=0.25, lw=0) + ax.plot(x, mean, color=color, label=label, **kw) + + +def run(temps, density, dt, steps, label, seed): + """Collide an electron and a positron population in 8^3 cells with PyPIC3D. + + Args: + temps (tuple[float, float]): Initial electron and positron temperatures (K). + density (float): Number density of each species (m^-3). + dt (float): Time step (s). + steps (int): Number of collision steps. + label (str): Name used in the progress printout. + seed (int): Random seed for the initial velocities, positions and collisions. + + Returns: + np.ndarray: Electron and positron temperatures (K), shape ``(steps + 1, 2)``. + """ + keys = jax.random.split(jax.random.PRNGKey(seed), 4) + u = jnp.stack([jnp.sqrt(KB * t / ME) * jax.random.normal(k, (N, 3)) for k, t in zip(keys, temps)]) + particles = TiledParticles(x=jax.random.uniform(keys[2], (1, 1, 1, 2, N, 3), maxval=CELLS), u=u[None, None, None], + active=jnp.ones((1, 1, 1, 2, N), bool), key=keys[3]) + config = SpeciesConfig(charge=jnp.array([-E, E]), mass=jnp.array([ME, ME]), weight=jnp.full(2, density * CELLS**3 / N), + update_x=jnp.zeros((2, 3), bool)) + specs = (("binary", 0, 0, COULOMB_LOG), ("binary", 1, 1, COULOMB_LOG), ("binary", 0, 1, COULOMB_LOG)) + world = SimpleNamespace(dx=1.0, dy=1.0, dz=1.0, dt=dt, eps=EPS, kb=KB) + step = jax.jit(lambda p: apply_collisions(p, config, SimpleNamespace(collisions=specs), world)[0]) + history = [] + for i in range(steps + 1): + v = np.asarray(particles.u[0, 0, 0]) + history.append(ME * np.mean(np.sum((v - v.mean(1, keepdims=True)) ** 2, -1), -1) / (3 * KB)) + if i % max(steps // 5, 1) == 0: + print(f" {label} seed {seed}: step {i:4d}/{steps} T = {history[-1][0]:8.1f} K, {history[-1][1]:8.1f} K", flush=True) + if i < steps: + particles = step(particles) + return np.array(history) + + +def spitzer_curve(temps, density, dt, steps): + """Integrate dT_a/dt = nu (T_b - T_a), dT_b/dt = nu (T_a - T_b) with the temperature-dependent Spitzer rate. + + Args: + temps (tuple[float, float]): Initial temperatures (K). + density (float): Number density of each species (m^-3). + dt (float): Output interval (s); each interval uses 50 Euler substeps. + steps (int): Number of output intervals. + + Returns: + np.ndarray: Temperatures (K), shape ``(steps + 1, 2)``. + """ + t, out = np.array(temps, float), [np.array(temps, float)] + for _ in range(steps): + for _ in range(50): + t = t + dt / 50 * spitzer(*t, density) * np.array([t[1] - t[0], t[0] - t[1]]) + out.append(t.copy()) + return np.array(out) + + +# ----------------------------- run the simulations ----------------------------- +os.makedirs(OUTPUT_DIR, exist_ok=True) +print("[1/2] Temperature equilibration") +eq = EQUIL +nu_eq = 2 * spitzer(eq["t_a"], eq["t_b"], eq["density"]) +dt_eq = 1 / (nu_eq * eq["relax_steps"]) +saved = os.path.join(OUTPUT_DIR, "binary_runs.npz") # --plot redraws from here without rerunning +if "--plot" in sys.argv: + cached = np.load(saved) + eq_runs, th_runs = cached["eq_runs"], cached["th_runs"] +else: + eq_runs = np.array([run((eq["t_a"], eq["t_b"]), eq["density"], dt_eq, eq["steps"], "equilibration", s) for s in SEEDS]) +eq_spitzer = spitzer_curve((eq["t_a"], eq["t_b"]), eq["density"], dt_eq, eq["steps"]) + +print("[2/2] Electron-positron thermalization") +th = THERM +omega_1 = np.sqrt(E**2 / (EPS * ME)) # omega_pe at n = 1 m^-3 +density = (th["rate"] / (2 * spitzer(th["t_e"], th["t_p"], 1.0) / omega_1)) ** 2 # nu / omega_pe scales as sqrt(n) +omega_pe = omega_1 * np.sqrt(density) +nu = 2 * spitzer(th["t_e"], th["t_p"], density) # rate of d|T_e - T_p| / dt at t = 0 +steps = int(round(th["t_end"] / th["dt"])) +print(f" n = {density:.3e} m^-3, omega_pe = {omega_pe:.3e} 1/s, Spitzer nu = {nu / omega_pe:.4f} omega_pe") +if "--plot" not in sys.argv: + th_runs = np.array([run((th["t_e"], th["t_p"]), density, th["dt"] / omega_pe, steps, "thermalization", s) for s in SEEDS]) + np.savez(saved, eq_runs=eq_runs, th_runs=th_runs) + +# ----------------------------- plot, save, and print ----------------------------- +averaged = rf"mean $\pm 1\sigma$ of {len(SEEDS)} runs" +fig, ax = plt.subplots(figsize=(10, 5)) +steps_axis = np.arange(eq["steps"] + 1) +band(ax, steps_axis, eq_runs[..., 0], "tab:blue", "species A", lw=2) +band(ax, steps_axis, eq_runs[..., 1], "tab:orange", "species B", lw=2) +ax.plot(steps_axis, eq_spitzer[:, 0], color="0.4", ls="-.", lw=1.3, label="Spitzer (Maxwellian) theory") +ax.plot(steps_axis, eq_spitzer[:, 1], color="0.4", ls="-.", lw=1.3) +ax.axhline(eq_runs[:, 0].mean(), color="k", ls="--", lw=1.5, label="isolated-system equilibrium") +ax.set(xlabel="Collision step", ylabel="Temperature [K]", + title=f"Binary-collision temperature equilibration ({averaged})") +ax.legend() +ax.grid(alpha=0.3) +fig.tight_layout() +fig.savefig(os.path.join(OUTPUT_DIR, "binary_equilibration.png"), dpi=300) + +t = np.arange(th_runs.shape[1]) * th["dt"] # time in 1 / omega_pe +dT = np.abs(th_runs[..., 0] - th_runs[..., 1]) +fit = dT.mean(0) > 0.05 * dT[:, 0].mean() # fit before |dT| reaches the particle-noise floor +fits = np.array([np.polyfit(t[fit], np.log(d[fit]), 1) for d in dT]) # per-seed exponential fits +nu_fits = -fits[:, 0] +equilibrium = th_runs[:, 0].mean() +analytic = 0.5 * dT[:, 0].mean() * np.exp(-nu / omega_pe * t) +fig, ax = plt.subplots(1, 2, figsize=(14, 5.5)) +band(ax[0], t, th_runs[..., 0], "#6f9cff", "Electrons", lw=2) +band(ax[0], t, th_runs[..., 1], "#ff7088", "Positrons", lw=2) +ax[0].plot(t, equilibrium + analytic, "k--", lw=1.8, label=f"Analytic Spitzer rate (nu={nu / omega_pe:.4f})") +ax[0].plot(t, equilibrium - analytic, "k--", lw=1.8) +ax[0].axhline(equilibrium, color="0.55", ls=":", label="Theoretical equilibrium") +ax[0].set(title=f"Coupled Temperature Relaxation ({averaged})", xlabel=r"Time ($\omega_{pe}^{-1}$)", ylabel="Temperature (K)") +band(ax[1], t, dT, "#c45bd5", r"$|T_e - T_p|$", lw=2) +ax[1].plot(t[fit], np.exp(fits[:, 1].mean() - nu_fits.mean() * t[fit]), "k--", lw=1.8, + label=rf"Exponential fit (nu={nu_fits.mean():.5f} $\pm$ {nu_fits.std():.5f})") +ax[1].plot(t[fit], dT[:, 0].mean() * np.exp(-nu / omega_pe * t[fit]), color="0.45", ls="-.", lw=1.5, + label=f"Spitzer rate (nu={nu / omega_pe:.4f})") +ax[1].set(title=f"Relaxation Rate Verification ({averaged})", xlabel=r"Time ($\omega_{pe}^{-1}$)", ylabel=r"$|\Delta T|$ (log scale)", yscale="log") +for a in ax: + a.grid(True, linestyle=":", alpha=0.55) + a.legend(fontsize=9) +fig.tight_layout() +fig.savefig(os.path.join(OUTPUT_DIR, "binary_thermalization.png"), dpi=300) + +gap = lambda r: r[:, -1, 0] - r[:, -1, 1] +print(f"Equilibration (final dT, initial {eq['t_a'] - eq['t_b']:.0f} K): PyPIC3D {gap(eq_runs).mean():.0f} +/- {gap(eq_runs).std():.0f} K, " + f"Spitzer {eq_spitzer[-1, 0] - eq_spitzer[-1, 1]:.0f} K") +print(f"Thermalization: Spitzer nu = {nu / omega_pe:.5f} omega_pe, fitted nu = {nu_fits.mean():.5f} +/- {nu_fits.std():.5f} omega_pe, " + f"ratio {nu_fits.mean() * omega_pe / nu:.3f} +/- {nu_fits.std() * omega_pe / nu:.3f}") +print(f"Saved {OUTPUT_DIR}/binary_equilibration.png and binary_thermalization.png") diff --git a/demos/collisions/mcc_maxwellian/mcc_maxwellian.py b/demos/collisions/mcc_maxwellian/mcc_maxwellian.py new file mode 100644 index 0000000..f7c11a1 --- /dev/null +++ b/demos/collisions/mcc_maxwellian/mcc_maxwellian.py @@ -0,0 +1,101 @@ +"""Uniform plasma relaxing to a Maxwellian through background-gas Monte Carlo collisions. +Argon ions start with a flat (box-shaped) velocity distribution and collide elastically with a +300 K argon gas. With sigma ~ 1/g the collision rate nu is speed independent, so the temperature +relaxes exactly as T(t) = T_gas + (T_0 - T_gas) exp(-nu t / 2) while the distribution becomes Maxwellian. +Every curve is the mean over SEEDS independent runs, with a shaded +/- 1 standard deviation band.""" +import os +from types import SimpleNamespace + +import jax +import jax.numpy as jnp +import matplotlib.pyplot as plt +import numpy as np + +from PyPIC3D.collisions import apply_collisions +from PyPIC3D.particles.particle_class import SpeciesConfig, TiledParticles + +jax.config.update("jax_enable_x64", True) + +# ----------------------------- input parameters ----------------------------- +N = 100_000 # macro-ions +T_GAS, T_ION = 300.0, 1000.0 # neutral gas and initial ion temperature [K] +N_GAS, NU = 1.0e20, 1.0e6 # gas density [m^-3], ion-neutral collision rate [1/s] +STEPS, T_END = 400, 10.0 # steps, end time in units of 1 / nu +SNAPSHOTS = (0.0, 0.5, 2.0, 10.0) # times (1 / nu) for the distribution panel +SEEDS = range(5) # independent random seeds +BINS = np.linspace(-4.5, 4.5, 121) +OUTPUT_DIR = "outputs/mcc_maxwellian" + +E, KB, M_AR = 1.602176634e-19, 1.380649e-23, 6.6335209e-26 +VTH = np.sqrt(KB * T_GAS / M_AR) + + +def run(seed): + """One relaxation run of argon ions in a neutral argon gas. + + Args: + seed (int): Random seed for the initial velocities, positions and collisions. + + Returns: + tuple: Ion temperature (K) and excess kurtosis of v_x, each of shape + ``(STEPS + 1,)``, and v_x histograms at SNAPSHOTS of shape ``(len(SNAPSHOTS), len(BINS) - 1)``. + """ + energy = np.logspace(-6, 3, 400) + sigma = NU / (N_GAS * np.sqrt(2 * energy * E / (M_AR / 2))) # sigma ~ 1/g: constant collision rate + specs = (("mcc", 0, N_GAS, T_GAS, M_AR, (("elastic", 0.0, tuple(energy), tuple(sigma), -1, -1),)),) + dt = T_END / NU / STEPS + k1, k2, k3 = jax.random.split(jax.random.PRNGKey(seed), 3) + u0 = np.sqrt(3 * KB * T_ION / M_AR) * jax.random.uniform(k1, (N, 3), minval=-1, maxval=1) + particles = TiledParticles(x=jax.random.uniform(k2, (1, 1, 1, 1, N, 3)), u=u0[None, None, None, None], + active=jnp.ones((1, 1, 1, 1, N), bool), key=k3) + config = SpeciesConfig(charge=jnp.array([E]), mass=jnp.array([M_AR]), weight=jnp.array([1.0]), update_x=jnp.zeros((1, 3), bool)) + world = SimpleNamespace(dx=1.0, dy=1.0, dz=1.0, dt=dt, eps=8.8541878128e-12, kb=KB) + step = jax.jit(lambda p: apply_collisions(p, config, SimpleNamespace(collisions=specs), world)[0]) + temps, kurt, hists = [], [], {} + for i in range(STEPS + 1): + v = np.asarray(particles.u[0, 0, 0, 0]) + v = v - v.mean(0) + temps.append(M_AR * np.mean(v**2) / KB) + kurt.append(np.mean(v[:, 0] ** 4) / np.mean(v[:, 0] ** 2) ** 2 - 3) + for s in SNAPSHOTS: + if abs(i * dt * NU - s) < 0.5 * dt * NU: + hists[s] = np.histogram(v[:, 0] / VTH, bins=BINS, density=True)[0] + if i % (STEPS // 5) == 0: + print(f" seed {seed} step {i:4d}/{STEPS}: T = {temps[-1]:7.1f} K, excess kurtosis = {kurt[-1]:+.3f}", flush=True) + if i < STEPS: + particles = step(particles) + return np.array(temps), np.array(kurt), np.array([hists[s] for s in SNAPSHOTS]) + + +# ----------------------------- run the simulations ----------------------------- +os.makedirs(OUTPUT_DIR, exist_ok=True) +print(f"Relaxing {N:,} argon ions from a {T_ION:g} K box distribution in {T_GAS:g} K argon, {len(SEEDS)} seeds") +temps, kurt, hists = map(np.array, zip(*(run(seed) for seed in SEEDS))) + +# ----------------------------- plot, save, and print ----------------------------- +times = np.arange(STEPS + 1) * T_END / STEPS +theory = T_GAS + (T_ION - T_GAS) * np.exp(-0.5 * times) +centers = 0.5 * (BINS[1:] + BINS[:-1]) +fig, ax = plt.subplots(3, 1, figsize=(8, 10)) +for color, s, h in zip(plt.cm.Blues(np.linspace(0.4, 0.95, len(SNAPSHOTS))), SNAPSHOTS, hists.transpose(1, 0, 2)): + ax[0].fill_between(centers, h.mean(0) - h.std(0), h.mean(0) + h.std(0), step="mid", color=color, alpha=0.3, lw=0) + ax[0].step(centers, h.mean(0), where="mid", lw=2, color=color, label=rf"$\nu t$ = {s:g}") +grid = np.linspace(-4.5, 4.5, 300) +ax[0].plot(grid, np.exp(-grid**2 / 2) / np.sqrt(2 * np.pi), "k--", lw=1.5, label=f"Maxwellian at {T_GAS:g} K") +ax[0].set(xlabel=r"$v_x / \sqrt{k_B T_{gas} / m}$", ylabel="probability density", + title=rf"Relaxation to a Maxwellian (background MCC, mean $\pm 1\sigma$ of {len(SEEDS)} seeds)") +for a, data, ref, ylabel in ((ax[1], kurt, np.zeros_like(times), r"excess kurtosis of $v_x$"), (ax[2], temps, theory, "ion temperature [K]")): + a.fill_between(times, data.mean(0) - data.std(0), data.mean(0) + data.std(0), color="tab:blue", alpha=0.25, lw=0) + a.plot(times, data.mean(0), color="tab:blue", lw=2, label="PyPIC3D") + a.plot(times, ref, "k--", lw=1.5, label="Maxwellian" if a is ax[1] else r"theory $T_g + (T_0 - T_g)\,e^{-\nu t/2}$") + a.set(ylabel=ylabel) +ax[2].set(xlabel=r"$\nu t$") +for a in ax: + a.legend() + a.grid(alpha=0.3) +fig.tight_layout() +fig.savefig(os.path.join(OUTPUT_DIR, "mcc_maxwellian.png"), dpi=300) +err = np.abs(temps - theory).max(1) +print(f"Temperature vs theory: max |T - T_theory| = {err.mean():.1f} +/- {err.std():.1f} K; final T = {temps[:, -1].mean():.1f} " + f"+/- {temps[:, -1].std():.1f} K (theory {theory[-1]:.1f} K); final excess kurtosis = {kurt[:, -1].mean():+.3f} +/- {kurt[:, -1].std():.3f}") +print(f"Saved {OUTPUT_DIR}/mcc_maxwellian.png") diff --git a/demos/collisions/relaxation/relaxation.py b/demos/collisions/relaxation/relaxation.py new file mode 100644 index 0000000..9fcba90 --- /dev/null +++ b/demos/collisions/relaxation/relaxation.py @@ -0,0 +1,206 @@ +"""Collision relaxation benchmarks against theory: Maxwellianization, thermalization, +temperature equilibration (Takizuka-Abe binary collisions), and relaxation to a +neutral bath (background MCC). All particles share one cell (0-D plasma).""" +import os +import time +from types import SimpleNamespace + +import jax +import jax.numpy as jnp +import matplotlib.pyplot as plt +import numpy as np + +from PyPIC3D.collisions import apply_collisions +from PyPIC3D.particles.particle_class import SpeciesConfig, TiledParticles + +jax.config.update("jax_enable_x64", True) + +# ----------------------------- input parameters ----------------------------- +N = 20_000 # macro-particles per species +DENSITY = 1.0e26 # physical density of each species [m^-3] +COULOMB_LOG = 10.0 +SCATTER = 0.01 # binary-collision dt: scattering parameter s = <1 - cos> at thermal speed +MCC_STEPS = 400 # MCC steps +T_HOT, T_COLD = 120.0, 40.0 # thermalization: electron / positron temperature [eV] +T_E, T_I, MASS_RATIO = 100.0, 20.0, 25.0 # equilibration: electron / ion temperature [eV], m_i / m_e +T_CUBE = 50.0 # Maxwellianization: temperature of the uniform velocity cube [eV] +T_GAS, T_ION, NU_MCC = 300.0, 3000.0, 1.0e6 # MCC: bath [K], initial argon ions [K], collision rate [1/s] +OUTPUT_DIR = "outputs/collisions" +SEED = 0 + +E, ME, KB, EPS, M_AR = 1.602176634e-19, 9.1093837e-31, 1.380649e-23, 8.8541878128e-12, 6.6335209e-26 + + +def spitzer(qa, qb, ma, mb, ta, tb, nb): + """Energy exchange rate nu_ab in dT_a/dt = nu_ab (T_b - T_a). + + Args: + qa (float): Charge of species a (C). + qb (float): Charge of species b (C). + ma (float): Mass of species a (kg). + mb (float): Mass of species b (kg). + ta (float): Temperature of species a (J). + tb (float): Temperature of species b (J). + nb (float): Number density of species b (m^-3). + + Returns: + float: Energy-exchange rate (1/s). + """ + return 2 * qa**2 * qb**2 * nb * COULOMB_LOG / (3 * (2 * np.pi) ** 1.5 * EPS**2 * ma * mb * (ta / ma + tb / mb) ** 1.5) + + +def two_temperature_theory(q, m, t0, time_axis): + """Integrate the coupled Spitzer equations for two species. + + Args: + q (tuple[float, float]): Charges (C). + m (tuple[float, float]): Masses (kg). + t0 (tuple[float, float]): Initial temperatures (J). + time_axis (np.ndarray): Output times (s); each interval uses 20 Euler substeps. + + Returns: + np.ndarray: Temperatures (J), shape ``(len(time_axis), 2)``. + """ + t, out = np.array(t0, float), [] + dt = np.diff(time_axis, prepend=0.0) + for h in dt: + for _ in range(20): + rate = spitzer(q[0], q[1], m[0], m[1], t[0], t[1], DENSITY) + t = t + h / 20 * rate * np.array([t[1] - t[0], t[0] - t[1]]) + out.append(t.copy()) + return np.array(out) + + +def collision_dt(q, m, t): + """Largest dt keeping every species pair's scattering parameter at thermal speed below SCATTER. + + Args: + q (tuple[float, ...]): Charges (C). + m (tuple[float, ...]): Masses (kg). + t (tuple[float, ...]): Temperatures (J). + + Returns: + float: Time step (s). + """ + pairs = [(a, b) for a in range(len(m)) for b in range(a, len(m))] + mu = lambda a, b: m[a] * m[b] / (m[a] + m[b]) + g3 = lambda a, b: (3 * (t[a] / m[a] + t[b] / m[b])) ** 1.5 + return min(SCATTER * 4 * np.pi * EPS**2 * mu(a, b) ** 2 * g3(a, b) / (q[a] ** 2 * q[b] ** 2 * DENSITY * COULOMB_LOG) for a, b in pairs) + + +def run(name, mass, charge, temperature, specs, t_end, dt, cube=False): + """Advance a 0-D plasma with the given collision operators and record moments. + + Args: + name (str): Name used in the progress printout. + mass (tuple[float, ...]): Mass of each species (kg). + charge (tuple[float, ...]): Charge of each species (C). + temperature (tuple[float, ...]): Initial temperature of each species (J). + specs (tuple): Collision specs in the :func:`PyPIC3D.collisions.load_collisions_from_toml` format. + t_end (float): Simulated time (s). + dt (float): Time step (s). + cube (bool): Start from a uniform (cube) velocity distribution instead of a Maxwellian. + + Returns: + tuple: Times (s), temperatures (J) of shape ``(steps + 1, species)``, excess + kurtosis of v_x with the same shape, and the final particles. + """ + n_s, steps = len(mass), int(np.ceil(t_end / dt)) + keys = jax.random.split(jax.random.PRNGKey(SEED), 2 * n_s + 1) + if cube: + u = [jnp.sqrt(3 * t / m) * jax.random.uniform(k, (N, 3), minval=-1, maxval=1) for k, t, m in zip(keys, temperature, mass)] + else: + u = [jnp.sqrt(t / m) * jax.random.normal(k, (N, 3)) for k, t, m in zip(keys, temperature, mass)] + particles = TiledParticles( + x=jax.random.uniform(keys[-1], (1, 1, 1, n_s, N, 3)), u=jnp.stack(u)[None, None, None], + active=jnp.ones((1, 1, 1, n_s, N), bool), key=keys[n_s]) + config = SpeciesConfig(charge=jnp.asarray(charge), mass=jnp.asarray(mass), weight=jnp.full(n_s, DENSITY / N), + update_x=jnp.zeros((n_s, 3), bool)) + world = SimpleNamespace(dx=1.0, dy=1.0, dz=1.0, dt=dt, eps=EPS, kb=KB) + step = jax.jit(lambda p: apply_collisions(p, config, SimpleNamespace(collisions=specs), world)[0]) + temps, kurt, start = [], [], time.perf_counter() + for i in range(steps + 1): + v = np.asarray(particles.u[0, 0, 0]) + v = v - v.mean(axis=1, keepdims=True) + temps.append(np.asarray(mass) * np.mean(np.sum(v**2, -1), -1) / 3) + kurt.append(np.mean(v[..., 0] ** 4, -1) / np.mean(v[..., 0] ** 2, -1) ** 2 - 3) + if i < steps: + particles = step(particles) + if i % max(steps // 5, 1) == 0: + print(f" {name}: step {i:5d}/{steps} T = {np.round(temps[-1] / E, 2)} eV ({time.perf_counter() - start:.1f} s)", flush=True) + return np.arange(steps + 1) * dt, np.array(temps), np.array(kurt), particles + + +# ----------------------------- run the simulations ----------------------------- +os.makedirs(OUTPUT_DIR, exist_ok=True) +print(f"JAX devices: {jax.devices()}") +results = {} + +q, m = (-E, E), (ME, ME) +t0 = (T_HOT * E, T_COLD * E) +nu = 2 * spitzer(q[0], q[1], m[0], m[1], *t0, DENSITY) +print("Thermalization (electron/positron, all binary pairs)") +results["thermalization"] = run("thermalization", m, q, t0, (("binary", 0, 0, COULOMB_LOG), ("binary", 1, 1, COULOMB_LOG), + ("binary", 0, 1, COULOMB_LOG)), 2.0 / nu, collision_dt(q, m, t0)) + +q, m = (-E, E), (ME, MASS_RATIO * ME) +t0 = (T_E * E, T_I * E) +nu = 2 * spitzer(q[0], q[1], m[0], m[1], *t0, DENSITY) +print(f"Equilibration (electron/ion, m_i/m_e = {MASS_RATIO:g})") +results["equilibration"] = run("equilibration", m, q, t0, (("binary", 0, 0, COULOMB_LOG), ("binary", 1, 1, COULOMB_LOG), + ("binary", 0, 1, COULOMB_LOG)), 2.0 / nu, collision_dt(q, m, t0)) + +nu_ee = spitzer(-E, -E, ME, ME, T_CUBE * E, T_CUBE * E, DENSITY) +print("Maxwellianization (electron self-collisions from a uniform velocity cube)") +results["maxwellianization"] = run("maxwellianization", (ME,), (-E,), (T_CUBE * E,), (("binary", 0, 0, COULOMB_LOG),), + 4.0 / nu_ee, collision_dt((-E,), (ME,), (T_CUBE * E,)), cube=True) + +n_gas = 1.0e20 +energy = np.logspace(-6, 3, 400) +sigma = NU_MCC / (n_gas * np.sqrt(2 * energy * E / (M_AR / 2))) +# sigma ~ 1/g gives a velocity-independent collision rate (Maxwell molecules) +mcc = (("mcc", 0, n_gas, T_GAS, M_AR, (("elastic", 0.0, tuple(energy), tuple(sigma), -1, -1),)),) +print("Background MCC (argon ions relaxing in a 300 K argon bath)") +results["mcc"] = run("mcc", (M_AR,), (E,), (KB * T_ION,), mcc, 10.0 / NU_MCC, 10.0 / NU_MCC / MCC_STEPS, cube=True) + +# ----------------------------- plot, save, and print ----------------------------- +fig, ax = plt.subplots(2, 2, figsize=(12, 9)) +summary = [] +for panel, (case, labels, mass) in zip(ax.flat[:2], [("thermalization", ("electrons", "positrons"), (ME, ME)), + ("equilibration", ("electrons", "ions"), (ME, MASS_RATIO * ME))]): + t, temps, _, _ = results[case] + theory = two_temperature_theory((-E, E), mass, temps[0], t) + for s, label in enumerate(labels): + panel.plot(t * 1e12, temps[:, s] / E, lw=2, label=f"{label} (PyPIC3D)") + panel.plot(t * 1e12, theory[:, s] / E, "k--", lw=1.2, label="Spitzer (Maxwellian) theory" if s == 0 else None) + panel.set(title=case.capitalize(), xlabel="time [ps]", ylabel="temperature [eV]") + panel.legend() + error = np.max(np.abs(temps - theory)) / np.abs(temps[0, 0] - temps[0, 1]) + summary.append(f"{case:18s} max |T - T_Spitzer| / dT0 = {100 * error:.2f}%") + +t, _, kurt, particles = results["maxwellianization"] +ax[1, 0].plot(t * nu_ee, kurt[:, 0], lw=2, label="PyPIC3D") +ax[1, 0].axhline(0.0, color="k", ls="--", label="Maxwellian") +ax[1, 0].set(title="Maxwellianization", xlabel=r"$\nu_{ee} t$", ylabel=r"excess kurtosis of $v_x$") +inset = ax[1, 0].inset_axes([0.45, 0.15, 0.5, 0.45]) +v = np.asarray(particles.u[0, 0, 0, 0, :, 0]) / np.sqrt(T_CUBE * E / ME) +inset.hist(v, bins=80, density=True, alpha=0.6) +grid = np.linspace(-4, 4, 200) +inset.plot(grid, np.exp(-grid**2 / 2) / np.sqrt(2 * np.pi), "k--") +inset.set_xticks([]), inset.set_yticks([]) +ax[1, 0].legend(loc="upper left") +summary.append(f"{'maxwellianization':18s} final excess kurtosis = {kurt[-1, 0]:+.3f} (Maxwellian: 0, initial: {kurt[0, 0]:+.2f})") + +t, temps, _, _ = results["mcc"] +theory = T_GAS + (T_ION - T_GAS) * np.exp(-0.5 * NU_MCC * t) +ax[1, 1].plot(t * 1e6, temps[:, 0] / KB, lw=2, label="PyPIC3D") +ax[1, 1].plot(t * 1e6, theory, "k--", label=r"$T_g + (T_0 - T_g)e^{-\nu t/2}$") +ax[1, 1].set(title="MCC relaxation to neutral bath", xlabel=r"time [$\mu$s]", ylabel="ion temperature [K]") +ax[1, 1].legend() +summary.append(f"{'mcc':18s} max |T - T_theory| / dT0 = {100 * np.max(np.abs(temps[:, 0] / KB - theory)) / (T_ION - T_GAS):.2f}%") + +fig.tight_layout() +fig.savefig(f"{OUTPUT_DIR}/relaxation.png", dpi=200) +np.savez(f"{OUTPUT_DIR}/relaxation.npz", **{f"{k}_{n}": v for k, r in results.items() for n, v in zip(("t", "T", "kurtosis"), r[:3])}) +print("\n".join(summary)) +print(f"Saved {OUTPUT_DIR}/relaxation.png and relaxation.npz") diff --git a/demos/collisions/two_stream_mcc/plot.py b/demos/collisions/two_stream_mcc/plot.py new file mode 100644 index 0000000..dbbff8e --- /dev/null +++ b/demos/collisions/two_stream_mcc/plot.py @@ -0,0 +1,31 @@ +"""Compare the collisionless and electron-neutral MCC two-stream runs. + +Run from the repository root after + PyPIC3D --config demos/collisions/two_stream_mcc/two_stream.toml + PyPIC3D --config demos/collisions/two_stream_mcc/two_stream_mcc.toml +""" +import os + +import matplotlib.pyplot as plt +import numpy as np + +OUTPUT_DIR = "outputs/two_stream_mcc" +RUNS = {"collisionless": ("collisionless", ("tab:red", "tab:blue", "tab:green")), + "mcc": ("with electron-neutral MCC", ("tab:orange", "tab:cyan", "tab:olive"))} + +fig, ax = plt.subplots(3, 1, figsize=(8, 10), sharex=True) +for run, (label, colors) in RUNS.items(): + load = lambda f: np.loadtxt(os.path.join(OUTPUT_DIR, run, "data", f), delimiter=",", ndmin=2) + field, kinetic, momentum = load("electric_field_energy.txt"), load("kinetic_energy.txt"), load("total_momentum.txt") + for k, y in enumerate((field[:, 1], kinetic[:, 1] / kinetic[0, 1], momentum[:, 1] / momentum[0, 1])): + ax[k].plot(field[:, 0], y, color=colors[k], lw=2, label=label) + print(f"{run:14s} peak E-field energy = {field[:, 1].max():.3e} J, final kinetic / initial = {kinetic[-1, 1] / kinetic[0, 1]:.4f}") +ax[0].set(ylabel="Electric field energy [J]", title="Weakly ionized two-stream comparison") +ax[1].set(ylabel="Kinetic energy / initial") +ax[2].set(ylabel=r"$\sum m|\mathbf{v}|$ / initial", xlabel="Time [s]") +for a in ax: + a.legend() + a.grid(alpha=0.3) +fig.tight_layout() +fig.savefig(os.path.join(OUTPUT_DIR, "two_stream_mcc.png"), dpi=300) +print(f"Saved {OUTPUT_DIR}/two_stream_mcc.png") diff --git a/demos/collisions/two_stream_mcc/two_stream.toml b/demos/collisions/two_stream_mcc/two_stream.toml new file mode 100644 index 0000000..0d046a9 --- /dev/null +++ b/demos/collisions/two_stream_mcc/two_stream.toml @@ -0,0 +1,47 @@ +# Two cold-ish counter-streaming electron beams over an ion background (collisionless reference) +[simulation_parameters] +name = "Two-stream instability, collisionless" +seed = 0 +t_wind = 5.413e-8 +solver = "electrodynamic_yee" +Nx = 100 +Ny = 1 +Nz = 1 +x_wind = 1 +y_wind = 1 +z_wind = 1 +output_dir = "outputs/two_stream_mcc/collisionless" +cfl = 0.99 +shape_factor = 2 +current_calculation = "j_from_rhov" +relativistic = true + +[plotting] +plotting_interval = 4 +plot_openpmd_particles = false +plot_openpmd_fields = false + +[particle1] +name = "electron1" +N_particles = 1500 +number_density = 1.0e15 +charge = -1.602e-19 +mass = 9.1093837e-31 +vth = 1.5e7 +initial_vx = 0.5e8 + +[particle2] +name = "electron2" +N_particles = 1500 +number_density = 1.0e15 +charge = -1.602e-19 +mass = 9.1093837e-31 +vth = 1.5e7 +initial_vx = -0.5e8 + +[particle3] +name = "ions" +N_particles = 3000 +charge = 1.602e-19 +mass = 1.67e-27 +vth = 3.5e4 diff --git a/demos/collisions/two_stream_mcc/two_stream_mcc.toml b/demos/collisions/two_stream_mcc/two_stream_mcc.toml new file mode 100644 index 0000000..d0ac3ab --- /dev/null +++ b/demos/collisions/two_stream_mcc/two_stream_mcc.toml @@ -0,0 +1,74 @@ +# Two cold-ish counter-streaming electron beams over an ion background in a weakly ionized argon gas +[simulation_parameters] +name = "Two-stream instability with electron-neutral MCC" +seed = 0 +t_wind = 5.413e-8 +solver = "electrodynamic_yee" +Nx = 100 +Ny = 1 +Nz = 1 +x_wind = 1 +y_wind = 1 +z_wind = 1 +output_dir = "outputs/two_stream_mcc/mcc" +cfl = 0.99 +shape_factor = 2 +current_calculation = "j_from_rhov" +relativistic = true + +[plotting] +plotting_interval = 4 +plot_openpmd_particles = false +plot_openpmd_fields = false + +[particle1] +name = "electron1" +N_particles = 1500 +number_density = 1.0e15 +charge = -1.602e-19 +mass = 9.1093837e-31 +vth = 1.5e7 +initial_vx = 0.5e8 + +[particle2] +name = "electron2" +N_particles = 1500 +number_density = 1.0e15 +charge = -1.602e-19 +mass = 9.1093837e-31 +vth = 1.5e7 +initial_vx = -0.5e8 + +[particle3] +name = "ions" +N_particles = 3000 +charge = 1.602e-19 +mass = 1.67e-27 +vth = 3.5e4 + +# electron-argon Monte Carlo collisions: 300 K argon at 1.5e20 m^-3, +# constant elastic cross section (nu ~ n sigma v ~ 7.5e8 1/s) and an 11.5 eV excitation channel + +[collisions.electron1_argon] +type = "background_mcc" +species = "electron1" +background_density = 1.5e20 +background_temperature = 300.0 +background_mass = 6.6335209e-26 +[collisions.electron1_argon.elastic] +cross_section = 1.0e-19 +[collisions.electron1_argon.excitation] +energy = 11.5 +cross_section = [[0.0, 0.0], [11.5, 0.0], [11.5115, 2.0e-20], [1.0e4, 2.0e-20]] + +[collisions.electron2_argon] +type = "background_mcc" +species = "electron2" +background_density = 1.5e20 +background_temperature = 300.0 +background_mass = 6.6335209e-26 +[collisions.electron2_argon.elastic] +cross_section = 1.0e-19 +[collisions.electron2_argon.excitation] +energy = 11.5 +cross_section = [[0.0, 0.0], [11.5, 0.0], [11.5115, 2.0e-20], [1.0e4, 2.0e-20]] diff --git a/pyproject.toml b/pyproject.toml index 3a0d54f..3214587 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -23,7 +23,7 @@ dependencies = [ [project.optional-dependencies] relativity = [ - "JAX_BSSN @ git+https://github.com/cwoolfo1/JAX_BSSN.git", + "JAX_BSSN @ git+https://github.com/uwplasma/JAX_BSSN.git", ] test = [ "coverage", diff --git a/tests/code_tests/bssn_parameters_test.py b/tests/code_tests/bssn_parameters_test.py index d27b42f..9f802d9 100644 --- a/tests/code_tests/bssn_parameters_test.py +++ b/tests/code_tests/bssn_parameters_test.py @@ -36,7 +36,7 @@ def runtime(boundaries=(0, 0, 0)): x_min=0., y_min=0., z_min=0., dt=.01, guard_cells=3, solver="dynamic_metric", metric="numerical", current_deposition="GR_direct", particle_pusher="hybrid_boris_geodesic", boundary_conditions=boundaries) - parameters = build_bssn_parameters(static, dynamic, evolution_parameters={"nu": 0.}) + static, parameters = build_bssn_parameters(static, dynamic, evolution_parameters={"nu": 0.}) dynamic = dynamic._replace(bssn_parameters=parameters) scalar = jnp.zeros((1, 1, 1, 14, 7, 7)) zero = (scalar,) * 3 @@ -54,9 +54,9 @@ def test_flat_defaults_and_dynamic_controls(self): static, dynamic, *_ = runtime() parameters = dynamic.bssn_parameters self.assertEqual(parameters.state.conformal_factor.shape, (8, 1, 1)) - self.assertEqual(int(parameters.evolution_parameters.zero_shift), 1) - self.assertEqual(int(parameters.evolution_parameters.gauge), 0) - self.assertEqual(float(parameters.evolution_parameters.x_min), float(dynamic.grids.center[0][1])) + self.assertEqual(int(static.bssn_evolution_parameters.zero_shift), 1) + self.assertEqual(int(static.bssn_evolution_parameters.gauge), 0) + self.assertEqual(float(static.bssn_evolution_parameters.x_min), float(dynamic.grids.center[0][1])) for leaf in jax.tree.leaves(parameters): self.assertTrue(isinstance(leaf, jax.Array)) with self.assertRaisesRegex(ValueError, "C=1"): @@ -75,14 +75,15 @@ def test_gravity_boundaries_and_caller_state_are_independent_of_em(self): static, dynamic, *_ = runtime() initial = dynamic.bssn_parameters state = initial.state._replace(trace_K=jnp.full_like(initial.state.trace_K, .03)) - evolution = initial.evolution_parameters._replace(xl_bc=1, xr_bc=1, gauge=1, zero_shift=0, eta=.7) - parameters = build_bssn_parameters(static, dynamic, state=state, - evolution_parameters=evolution, time=3.) + evolution = static.bssn_evolution_parameters._replace( + xl_bc=1, xr_bc=1, gauge=1, zero_shift=0, eta=.7) + updated, parameters = build_bssn_parameters(static, dynamic, state=state, + evolution_parameters=evolution, time=3.) self.assertIs(parameters.state, state) self.assertEqual(static.boundary_conditions, (0, 0, 0)) - self.assertEqual(int(parameters.evolution_parameters.xl_bc), 1) - self.assertEqual(int(parameters.evolution_parameters.xr_bc), 1) - for actual, expected in zip(jax.tree.leaves(parameters.evolution_parameters), jax.tree.leaves(evolution)): + self.assertEqual(int(updated.bssn_evolution_parameters.xl_bc), 1) + self.assertEqual(int(updated.bssn_evolution_parameters.xr_bc), 1) + for actual, expected in zip(jax.tree.leaves(updated.bssn_evolution_parameters), jax.tree.leaves(evolution)): self.assertTrue(bool(jnp.array_equal(actual, expected))) self.assertEqual(float(parameters.time), 3.) diff --git a/tests/code_tests/collisions_test.py b/tests/code_tests/collisions_test.py new file mode 100644 index 0000000..e18d2ec --- /dev/null +++ b/tests/code_tests/collisions_test.py @@ -0,0 +1,111 @@ +import unittest +from types import SimpleNamespace + +import jax +import jax.numpy as jnp + +from PyPIC3D.collisions import apply_collisions, load_collisions_from_toml +from PyPIC3D.particles.particle_class import SpeciesConfig, TiledParticles + +jax.config.update("jax_enable_x64", True) +DYN = SimpleNamespace(dx=1.0, dy=1.0, dz=1.0, dt=1.0e-9, eps=8.854e-12, kb=1.380649e-23) + + +def make_particles(n=401, species=2, cells=4, scale=1.0e5, seed=0): + kx, ku = jax.random.split(jax.random.PRNGKey(seed)) + x = jax.random.uniform(kx, (1, 1, 1, species, n, 3), maxval=cells) + u = scale * jax.random.normal(ku, (1, 1, 1, species, n, 3)) + active = jnp.ones((1, 1, 1, species, n), bool).at[..., -7:].set(False) + return TiledParticles(x=x, u=u, active=active, key=jax.random.PRNGKey(seed + 1)) + + +def make_config(mass=(9.1e-31, 3.0e-30), charge=(-1.6e-19, 1.6e-19)): + n = len(mass) + return SpeciesConfig(charge=jnp.asarray(charge), mass=jnp.asarray(mass), weight=jnp.full(n, 1.0e10), + update_x=jnp.ones((n, 3), bool)) + + +def run(specs, particles, config, steps=1): + step = jax.jit(lambda p: apply_collisions(p, config, SimpleNamespace(collisions=specs), DYN)) + for _ in range(steps): + particles, overflow = step(particles) + return particles, overflow + + +class TestCollisions(unittest.TestCase): + def moments(self, particles, config): + m = config.mass[None, None, None, :, None, None] * particles.active[..., None] + return jnp.sum(m * particles.u, axis=(0, 1, 2, 3, 4)), jnp.sum(m * particles.u**2) + + def test_binary_conserves_momentum_and_energy(self): + config = make_config() + particles = make_particles() + specs = (("binary", 0, 0, 10.0), ("binary", 0, 1, 10.0), ("binary", 1, 1, 10.0)) + after, _ = run(specs, particles, config, steps=3) + p0, e0 = self.moments(particles, config) + p1, e1 = self.moments(after, config) + self.assertTrue(jnp.allclose(p0, p1, rtol=1e-10, atol=1e-30 + 1e-10 * float(jnp.abs(p0).max()))) + self.assertAlmostEqual(float(e1 / e0), 1.0, places=10) + self.assertFalse(jnp.allclose(after.u, particles.u)) + self.assertTrue(jnp.array_equal(after.u[..., -7:, :], particles.u[..., -7:, :])) + + def test_mcc_heavy_elastic_preserves_speed_and_charge_exchange_takes_neutral(self): + config = make_config() + particles = make_particles(species=1) + elastic = (("mcc", 0, 1.0e30, 0.0, 1.0e10, (("elastic", 0.0, (0.0, 1e30), (1e-19, 1e-19), -1, -1),)),) + after, _ = run(elastic, particles, make_config(mass=(9.1e-31,), charge=(-1.6e-19,))) + speed = lambda p: jnp.linalg.norm(p.u, axis=-1) + self.assertTrue(jnp.allclose(speed(after), speed(particles), rtol=1e-12)) + self.assertFalse(jnp.allclose(after.u, particles.u)) + cx = (("mcc", 0, 1.0e30, 0.0, 1.0e-26, (("charge_exchange", 0.0, (0.0, 1e30), (1e-19, 1e-19), -1, -1),)),) + after, _ = run(cx, particles, make_config(mass=(1e-26,), charge=(1.6e-19,))) + self.assertTrue(jnp.allclose(after.u[after.active], 0.0)) + + def test_ionization_creates_pairs_in_free_slots(self): + config = make_config() + particles = make_particles(scale=1.0e7) + particles = particles._replace(active=particles.active.at[0, 0, 0, 1].set(False)) + ion = (("mcc", 0, 1.0e30, 0.0, 6.6e-26, (("ionization", 15.0, (0.0, 15.0, 1e9), (0.0, 1e-19, 1e-19), 0, 1),)),) + after, overflow = run(ion, particles, config) + new_e = int(after.active[..., 0, :].sum() - particles.active[..., 0, :].sum()) + self.assertEqual(int(after.active[..., 1, :].sum()), int(particles.active[..., 0, :].sum())) + self.assertEqual(new_e, 7) + # every electron ionizes; ions fit, but only 7 free electron slots exist + self.assertTrue(bool(overflow)) + + def test_toml_loader(self): + config = {"collisions": {"ee": {"type": "binary", "species": ["e", "e"], "coulomb_log": 12.0}, + "en": {"type": "background_mcc", "species": "e", "background_density": 1e20, + "background_mass": 6.6e-26, "elastic": {"cross_section": 1e-19}, + "ionization": {"cross_section": [[15.0, 0.0], [100.0, 1e-20]], + "energy": 15.0, "product_species": ["e", "i"]}}}} + specs = load_collisions_from_toml(config, ("e", "i")) + self.assertEqual(specs[0], ("binary", 0, 0, 12.0)) + self.assertEqual([p[0] for p in specs[1][5]], ["elastic", "ionization"]) + self.assertEqual(specs[1][5][1][4:], (0, 1)) + + def ionization_config(self, product_species=("e", "i")): + return {"collisions": {"en": {"type": "background_mcc", "species": "e", "background_density": 1e20, + "background_mass": 6.6e-26, + "ionization": {"cross_section": [[15.0, 0.0], [100.0, 1e-20]], + "energy": 15.0, "product_species": list(product_species)}}}} + + def test_toml_loader_requires_ionization_products_to_share_the_projectile_weight(self): + names = ("e", "i") + config = self.ionization_config() + # One event makes one real pair per real projectile, and weight is per species, + # so unequal weights would deposit a net charge that was never there. + self.assertEqual(load_collisions_from_toml(config, names, [1e11, 1e11])[0][5][0][4:], (0, 1)) + self.assertEqual(load_collisions_from_toml(config, names, [1e15 / 15, 2e15 / 30])[0][5][0][4:], (0, 1)) + with self.assertRaisesRegex(ValueError, "must name two species sharing the weight"): + load_collisions_from_toml(config, names, [1e11, 5e10]) + with self.assertRaisesRegex(ValueError, "must name two species sharing the weight"): + load_collisions_from_toml(self.ionization_config(()), names, [1e11, 1e11]) + # Processes that create nothing are unaffected by the product-species rules. + elastic = {"collisions": {"en": {"type": "background_mcc", "species": "e", "background_density": 1e20, + "background_mass": 6.6e-26, "elastic": {"cross_section": 1e-19}}}} + self.assertEqual(load_collisions_from_toml(elastic, names, [1e11, 5e10])[0][5][0][4:], (-1, -1)) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/code_tests/dynamical_relativity_test.py b/tests/code_tests/dynamical_relativity_test.py index 776ccd4..4cf10ed 100644 --- a/tests/code_tests/dynamical_relativity_test.py +++ b/tests/code_tests/dynamical_relativity_test.py @@ -43,8 +43,7 @@ def coupled_state(*, dt=0.02, backreaction=False, particles=False, boundaries=(0 current_filter="none", boundary_conditions=boundaries, particle_batch_size=8, ) static = static._replace(metric_backreaction=backreaction) - bssn = build_bssn_parameters(static, dynamic) - bssn = bssn._replace(evolution_parameters=bssn.evolution_parameters._replace(nu=0.)) + static, bssn = build_bssn_parameters(static, dynamic, evolution_parameters={"nu": 0.}) if varying_geometry: phase = 2 * jnp.pi * jnp.arange(8)[:, None, None] / 8 q = bssn.state @@ -125,7 +124,7 @@ def test_vacuum_gravity_matches_standalone_projected_rk4(self): fields = (zero, zero, zero) + fields[3:7] + ( (zero, zero, zero, fields[7][3], None), fields[8], ) - expected = rk4_step(state, bssn.evolution_parameters) + expected = rk4_step(state, static.bssn_evolution_parameters) actual_p, actual_f, actual_d = jax.jit( lambda p, f, d: time_loop_dynamical_relativity(p, species, f, static, d) )(particles, fields, dynamic) diff --git a/tests/code_tests/evolve_test.py b/tests/code_tests/evolve_test.py index 1574003..2e6dc01 100644 --- a/tests/code_tests/evolve_test.py +++ b/tests/code_tests/evolve_test.py @@ -27,7 +27,8 @@ def add_tiled_grids_to_parameters(parameter_set, tile_shape): int(parameter_set["Nz"]) // int(tile_shape[2]), ) parameter_set["field_mesh"] = make_field_mesh(tile_grid_shape) - static_parameters = SimpleNamespace(tile_shape=tile_shape, guard_cells=g) + static_parameters = SimpleNamespace(tile_shape=tile_shape, guard_cells=g, + field_mesh=parameter_set["field_mesh"]) dynamic_parameters = SimpleNamespace( dx=parameter_set["dx"], dy=parameter_set["dy"], diff --git a/tests/code_tests/gr_filtered_sources_test.py b/tests/code_tests/gr_filtered_sources_test.py index bc6dada..bbe9699 100644 --- a/tests/code_tests/gr_filtered_sources_test.py +++ b/tests/code_tests/gr_filtered_sources_test.py @@ -39,7 +39,7 @@ def parameters(): particle_pusher="hybrid_boris_geodesic", current_deposition="esirkepov", current_filter="bilinear", particle_batch_size=2, ) - bssn = build_bssn_parameters(static, dynamic) + static, bssn = build_bssn_parameters(static, dynamic) phase = 2*jnp.pi*jnp.arange(8)[:, None, None]/8 state = bssn.state._replace( conformal_factor=.9 + .15*jnp.cos(phase), diff --git a/tests/code_tests/gr_matched_filter_test.py b/tests/code_tests/gr_matched_filter_test.py index 13b1986..4ae4c89 100644 --- a/tests/code_tests/gr_matched_filter_test.py +++ b/tests/code_tests/gr_matched_filter_test.py @@ -283,9 +283,9 @@ def test_filter_requires_all_six_periodic_bssn_faces(self): build_bssn_parameters(static, dynamic, evolution_parameters=controls) # The existing unfiltered solver still permits independent # gravitational boundaries, including Sommerfeld faces. - unfiltered = build_bssn_parameters(static._replace(current_filter="none"), - dynamic, evolution_parameters=controls) - self.assertEqual(int(getattr(unfiltered.evolution_parameters, face)), 1) + unfiltered, _ = build_bssn_parameters(static._replace(current_filter="none"), + dynamic, evolution_parameters=controls) + self.assertEqual(int(getattr(unfiltered.bssn_evolution_parameters, face)), 1) if __name__ == "__main__": diff --git a/tests/code_tests/gr_work_energy_theorem_test.py b/tests/code_tests/gr_work_energy_theorem_test.py index 88211f5..dec08a0 100644 --- a/tests/code_tests/gr_work_energy_theorem_test.py +++ b/tests/code_tests/gr_work_energy_theorem_test.py @@ -52,7 +52,7 @@ def parameters(**kwargs): def native_runtime(static, dynamic, *, gamma=None, curvature=None): """Initialize genuine native histories from common-time uniform EM data.""" - bssn = build_bssn_parameters(static, dynamic) + static, bssn = build_bssn_parameters(static, dynamic, evolution_parameters={"nu": 0.}) state = bssn.state if gamma is not None: W = jnp.linalg.det(gamma) ** (-1. / 6.) @@ -70,7 +70,7 @@ def native_runtime(static, dynamic, *, gamma=None, curvature=None): traceless_K=traceless[:, :, None, None, None] * jnp.ones_like(state.conformal_factor), ) - bssn = bssn._replace(state=state, evolution_parameters=bssn.evolution_parameters._replace(nu=0.)) + bssn = bssn._replace(state=state) dynamic = dynamic._replace(bssn_parameters=bssn) metric = build_bssn_metric(state, static, dynamic) electric = tuple(jnp.full_like(metric.D[i].lapse, (.5, -.3, .2)[i]) for i in range(3)) diff --git a/tests/code_tests/lapse_deleting_dynamic_test.py b/tests/code_tests/lapse_deleting_dynamic_test.py index a676fb5..1f577cf 100644 --- a/tests/code_tests/lapse_deleting_dynamic_test.py +++ b/tests/code_tests/lapse_deleting_dynamic_test.py @@ -35,7 +35,7 @@ def dynamic_lapse_state(*, varying_lapse=False): particle_batch_size=2, ) static = static._replace(lapse_deleting=True, lapse_threshold=.1, metric_backreaction=False) - bssn = build_bssn_parameters(static, dynamic, evolution_parameters={"nu": 0.}) + static, bssn = build_bssn_parameters(static, dynamic, evolution_parameters={"nu": 0.}) if varying_lapse: phase = 2 * jnp.pi * jnp.arange(8)[:, None, None] / 8 bssn = bssn._replace(state=bssn.state._replace(lapse=.15 + .1 * jnp.cos(phase))) diff --git a/tests/code_tests/lapse_deleting_test.py b/tests/code_tests/lapse_deleting_test.py index 16f0d73..5af088a 100644 --- a/tests/code_tests/lapse_deleting_test.py +++ b/tests/code_tests/lapse_deleting_test.py @@ -67,7 +67,7 @@ def test_configurable_threshold_and_repeated_calls_cannot_reactivate_slots(self) def test_disabled_and_empty_storage_do_not_need_a_metric(self): static, dynamic, _, particles = manufactured_lapse() result = lapse_deleting(particles, None, static._replace(lapse_deleting=False), dynamic) - for actual, expected in zip(result, particles): + for actual, expected in zip(jax.tree.leaves(result), jax.tree.leaves(particles)): self.assertTrue(bool(jnp.array_equal(actual, expected, equal_nan=True))) empty_x = jnp.zeros((1, 1, 1, 0, 0, 3)) empty = TiledParticles(empty_x, empty_x, jnp.zeros(empty_x.shape[:-1], bool)) diff --git a/tests/code_tests/sharded_openpmd_test.py b/tests/code_tests/sharded_openpmd_test.py index c7a5bf9..5c29763 100644 --- a/tests/code_tests/sharded_openpmd_test.py +++ b/tests/code_tests/sharded_openpmd_test.py @@ -293,7 +293,7 @@ def test_initial_histograms_match_50_bin_reference_without_global_transfer(self) device_get = jax.device_get def local_device_get(value): - if any(value is array for array in particles): + if any(value is array for array in (particles.x, particles.u, particles.active)): raise AssertionError("Histogram transferred a complete distributed array") return device_get(value) @@ -421,7 +421,9 @@ def local_view(array): return SimpleNamespace(shape=array.shape, addressable_shards=array.addressable_shards[:1]) field_snapshot = async_writer.make_tiled_field_snapshot({"rho": local_view(scalar)}, step=0, time=0.) - particle_snapshot = async_writer.make_tiled_particle_snapshot(TiledParticles(*(local_view(array) for array in particles)), + viewed = TiledParticles(*(local_view(array) for array in + (particles.x, particles.u, particles.active))) + particle_snapshot = async_writer.make_tiled_particle_snapshot(viewed, step=0, time=0., species_names=names, species_config=species) for array, host_shards in ((scalar, field_snapshot.fields["rho"]), (particles.x, particle_snapshot.x_shards), diff --git a/tests/code_tests/static_metric_test.py b/tests/code_tests/static_metric_test.py index a34d49b..34c5cb6 100644 --- a/tests/code_tests/static_metric_test.py +++ b/tests/code_tests/static_metric_test.py @@ -1124,7 +1124,7 @@ def test_empty_storage_evolves_vacuum_without_particle_kernels(self): self.assertTrue(jnp.all(value == 0)) else: new, updated = result - for actual, original in zip(new, particles): + for actual, original in zip(jax.tree.leaves(new), jax.tree.leaves(particles)): self.assertTrue(jnp.array_equal(actual, original)) for actual_vector, expected_vector in zip(updated[:3], expected[:3]): for actual, reference in zip(actual_vector, expected_vector): diff --git a/tests/code_tests/tiled_bssn_coupling_test.py b/tests/code_tests/tiled_bssn_coupling_test.py index 652faf7..8ba8adc 100644 --- a/tests/code_tests/tiled_bssn_coupling_test.py +++ b/tests/code_tests/tiled_bssn_coupling_test.py @@ -44,8 +44,8 @@ def coupled_example(tiles, *, particles=False, current_filter="none", crossing=F state = BSSNVariables(identity, 1. + .003 * jnp.cos(phase), identity * 0, .001 * jnp.sin(phase), vector, 1. + .002 * jnp.sin(phase), vector.at[0].set(.01 * jnp.cos(phase))) - bssn = build_bssn_parameters(static, dynamic, state=state, - evolution_parameters={"nu": .002, "kappa": .03}) + static, bssn = build_bssn_parameters(static, dynamic, state=state, + evolution_parameters={"nu": .002, "kappa": .03}) dynamic = dynamic._replace(bssn_parameters=bssn) D = tuple(bssn_to_tiles(value, static) for value in (.03 + .002 * jnp.sin(phase), .01 * jnp.cos(phase), zero)) @@ -75,7 +75,7 @@ def coupled_example(tiles, *, particles=False, current_filter="none", crossing=F def gather_bssn(value, static): - return tiles_to_bssn(value, static._replace(guard_cells=bssn_tile_layout(static)["guard_cells"])) + return tiles_to_bssn(value, static._replace(guard_cells=bssn_tile_layout(static).guard_cells)) @unittest.skipUnless(jax.device_count() >= 2, "requires two JAX devices") @@ -152,11 +152,11 @@ def test_source_filter_uses_em_exteriors_when_gravity_is_periodic(self): tile_shape=(8, 1, 1), guard_cells=3, solver="dynamic_metric", metric="numerical", boundary_conditions=(boundary, 0, 0)) - bssn = build_bssn_parameters(static, dynamic) + static, bssn = build_bssn_parameters(static, dynamic) dynamic = dynamic._replace(bssn_parameters=bssn) x = jnp.arange(16 + (boundary == 1))[:, None, None] values = 1 + .02 * x**2 - parameters = static._replace(guard_cells=bssn_tile_layout(static)["guard_cells"]) + parameters = static._replace(guard_cells=bssn_tile_layout(static).guard_cells) tiled = bssn_to_tiles(values, parameters) actual = binomial_source_filter(tiled, static.boundary_conditions, static_parameters=static, dynamic_parameters=dynamic) @@ -175,7 +175,7 @@ def test_particle_cloud_straddles_eight_tile_corners(self): guard_cells=3, solver="dynamic_metric", metric="numerical", particle_pusher="hybrid_boris_geodesic", particle_batch_size=8) static = static._replace(metric_backreaction=True) - bssn = build_bssn_parameters(static, dynamic) + static, bssn = build_bssn_parameters(static, dynamic) dynamic = dynamic._replace(bssn_parameters=bssn) metric = build_bssn_metric(bssn.state, static, dynamic) positions = (8 + phase).reshape((count,) * 3 + (1, 8 // count**3, 3)) @@ -207,7 +207,7 @@ def boundary(local_state, time, *, params): return local_state actual = map_tiled(lambda q, p: prescribe(q, dynamic.dt, params=p)[0], state, - dynamic.bssn_parameters.evolution_parameters, **bssn_tile_layout(static), + static.bssn_evolution_parameters, bssn_tile_layout(static), output_template=state.lapse) expected = 1 + .002 * jnp.cos(2 * jnp.pi * jnp.arange(16)[:, None, None] / 16) self.assertClose(gather_bssn(actual, static), expected) diff --git a/tests/distributed_tests/direct_deposition_test.py b/tests/distributed_tests/direct_deposition_test.py index 964b295..55bfca0 100644 --- a/tests/distributed_tests/direct_deposition_test.py +++ b/tests/distributed_tests/direct_deposition_test.py @@ -148,7 +148,7 @@ def test_tiled_direct_deposition_returns_only_local_current_tiles(self): ) for reference_component, tiled_component in zip(J_reference, J_from_tiles): - self.assertTrue(jnp.allclose(tiled_component, reference_component, rtol=1.0e-15, atol=1.0e-15)) + self.assertTrue(jnp.allclose(tiled_component, reference_component, rtol=5.0e-15, atol=5.0e-15)) def test_tiled_direct_deposition_matches_J_from_rhov_for_dummy_species(self): @@ -236,7 +236,7 @@ def test_public_J_from_rhov_dispatches_tiled_particles_to_tile_local_current(sel for tile_component in J_tiles: self.assertEqual(tile_component.ndim, 6) for reference_component, tiled_component in zip(J_reference, J_from_tiles): - self.assertTrue(jnp.allclose(tiled_component, reference_component, rtol=1.0e-15, atol=1.0e-15)) + self.assertTrue(jnp.allclose(tiled_component, reference_component, rtol=5.0e-15, atol=5.0e-15)) def test_tiled_direct_deposition_digital_filter_matches_J_from_rhov(self): diff --git a/tests/distributed_tests/distributed_io_test.py b/tests/distributed_tests/distributed_io_test.py index 17e78e4..3d268f9 100644 --- a/tests/distributed_tests/distributed_io_test.py +++ b/tests/distributed_tests/distributed_io_test.py @@ -76,7 +76,8 @@ def test_bounded_particle_input_preserves_serial_order_and_capacity(self): config = {"particle1": block} serial = load_particles_from_toml(config, self.static, self.dynamic) distributed = load_distributed_particles(config, self.static, self.dynamic, chunk_size=2) - for reference, actual in zip(serial[0], distributed[0]): + for field in ('x', 'u', 'active'): + reference, actual = getattr(serial[0], field), getattr(distributed[0], field) self.assertTrue(bool(jnp.array_equal(reference, actual))) self.assertEqual(serial[0].active.shape, distributed[0].active.shape) self.assertTrue(bool(jnp.array_equal(serial[1].weight, distributed[1].weight))) diff --git a/tests/distributed_tests/fluid_velocity_output_test.py b/tests/distributed_tests/fluid_velocity_output_test.py index 47b47ad..fc60768 100644 --- a/tests/distributed_tests/fluid_velocity_output_test.py +++ b/tests/distributed_tests/fluid_velocity_output_test.py @@ -50,7 +50,7 @@ def setUp(self): def test_nonuniform_metric_matches_analytic_and_serial_particle_velocities(self): velocity = particle_three_velocity(self.particles, self.metric, self.static, self.dynamic) - x, u, active = self.particles + x, u, active = self.particles.x, self.particles.u, self.particles.active diagonal = jnp.stack((2.0 + 0.03*x[..., 0], 1.2 + 0.02*x[..., 1], 1.8 + 0.04*x[..., 2]), axis=-1) expected = (u/diagonal) / jnp.sqrt(1.0 + jnp.sum(u*u/diagonal, axis=-1))[..., None] @@ -113,7 +113,7 @@ def test_lorentz_factor_uses_the_local_nonuniform_metric(self): particles, metric, self.static, self.dynamic)) executable = sample.lower(self.particles, metric).compile() gamma = executable(self.particles, metric) - x, u, active = self.particles + x, u, active = self.particles.x, self.particles.u, self.particles.active diagonal = jnp.stack((2.0 + 0.03*x[..., 0], 1.2 + 0.02*x[..., 1], 1.8 + 0.04*x[..., 2]), axis=-1) expected = jnp.where(active, jnp.sqrt(1.0 + jnp.sum(u*u/diagonal, axis=-1)), 1.0) diff --git a/tests/distributed_tests/pair_injection_test.py b/tests/distributed_tests/pair_injection_test.py index 73ef19a..cc73769 100644 --- a/tests/distributed_tests/pair_injection_test.py +++ b/tests/distributed_tests/pair_injection_test.py @@ -25,7 +25,7 @@ def test_y_and_z_tiles(self): self.assertTrue(bool(jnp.array_equal(result.x[..., 0, 0, :], x[..., 0, :]))) rho = compute_rho(result, species, f[3], s, d) self.assertTrue(bool(jnp.allclose(rho, 0, atol=1e-13, rtol=1e-7, equal_nan=True))) - for value in result: + for value in (result.x, result.u, result.active): self.assertTrue(value.sharding.is_equivalent_to(layout, value.ndim)) diff --git a/tests/physics_tests/einstein_maxwell_wave_test.py b/tests/physics_tests/einstein_maxwell_wave_test.py index 45de958..c57f1a6 100644 --- a/tests/physics_tests/einstein_maxwell_wave_test.py +++ b/tests/physics_tests/einstein_maxwell_wave_test.py @@ -58,8 +58,9 @@ def native_runtime(shape, params, *, boundaries=(0, 0, 0), bssn=None, C=1., eps=1., mu=1., kb=1., alpha=1., grids=dict(center=center, vertex=vertex, tiled_center_grid=tc, tiled_vertex_grid=tv))) bssn = flat_bssn_variables(shape) if bssn is None else bssn - dynamic = dynamic._replace(bssn_parameters=build_bssn_parameters( - static, dynamic, state=bssn, evolution_parameters=params)) + static, bssn_record = build_bssn_parameters( + static, dynamic, state=bssn, evolution_parameters=params) + dynamic = dynamic._replace(bssn_parameters=bssn_record) zero = jnp.zeros((3,) + shape) displacement = zero if displacement is None else displacement magnetic = zero if magnetic is None else magnetic diff --git a/tests/physics_tests/gr_work_energy_theorem_test.py b/tests/physics_tests/gr_work_energy_theorem_test.py index edfc0d6..f961869 100644 --- a/tests/physics_tests/gr_work_energy_theorem_test.py +++ b/tests/physics_tests/gr_work_energy_theorem_test.py @@ -45,10 +45,9 @@ def maxwell_state(n=24, *, dt=None, shift=0., pulse=False, enabled=True, backrea ) static = static._replace(gr_work_energy_theorem=enabled, metric_backreaction=backreaction) - bssn = build_bssn_parameters(static, dynamic) + static, bssn = build_bssn_parameters(static, dynamic, evolution_parameters={"nu": 0.}) state = bssn.state._replace(shift=bssn.state.shift.at[0].set(shift)) - bssn = bssn._replace(state=state, - evolution_parameters=bssn.evolution_parameters._replace(nu=0.)) + bssn = bssn._replace(state=state) dynamic = dynamic._replace(bssn_parameters=bssn) zero = empty_tiled_vector(static, dynamic) diff --git a/tests/support/direct_deposition_fixtures.py b/tests/support/direct_deposition_fixtures.py index 5342e90..0697dee 100644 --- a/tests/support/direct_deposition_fixtures.py +++ b/tests/support/direct_deposition_fixtures.py @@ -79,7 +79,8 @@ def _parameters_with_tiled_grids(self, parameter_set, tile_shape): int(parameter_set["Ny"]) // int(tile_shape[1]), int(parameter_set["Nz"]) // int(tile_shape[2]), )) - grid_static_parameters = SimpleNamespace(tile_shape=tile_shape, guard_cells=g) + grid_static_parameters = SimpleNamespace(tile_shape=tile_shape, guard_cells=g, + field_mesh=parameter_set["field_mesh"]) grid_dynamic_parameters = SimpleNamespace( dx=parameter_set["dx"], dy=parameter_set["dy"], diff --git a/tests/support/esirkepov_fixtures.py b/tests/support/esirkepov_fixtures.py index cbec81f..66f0812 100644 --- a/tests/support/esirkepov_fixtures.py +++ b/tests/support/esirkepov_fixtures.py @@ -207,7 +207,8 @@ def _parameters_with_tiled_grids(self, parameter_set, tile_shape): int(parameter_set["Ny"]) // int(tile_shape[1]), int(parameter_set["Nz"]) // int(tile_shape[2]), )) - grid_static_parameters = SimpleNamespace(tile_shape=tile_shape, guard_cells=g) + grid_static_parameters = SimpleNamespace(tile_shape=tile_shape, guard_cells=g, + field_mesh=parameter_set["field_mesh"]) grid_dynamic_parameters = SimpleNamespace( dx=parameter_set["dx"], dy=parameter_set["dy"], diff --git a/tests/support/particle_metric_fixtures.py b/tests/support/particle_metric_fixtures.py index 4a16ba2..4c3b32f 100644 --- a/tests/support/particle_metric_fixtures.py +++ b/tests/support/particle_metric_fixtures.py @@ -128,7 +128,7 @@ def sample_metric(q,m,s,d): def gather_B(q,B,s,d): return gather_vector(tuple(b[0,0,0] for b in B),B_FIELD_LOCATIONS,q,*tile_grids(d), - s.shape_factor,(True,True,False),(3,3,3)) + s,(True,True,False),(3,3,3)) def norm(u,m):