#!/usr/bin/env python3 """Insert perturb_stress_kernel into observer .cu before calculate_asymmetry_magnifying.""" path = '/mnt/d/resonance-engine-active/cuda/khra_gixx_1024_v5_observer.cu' with open(path, 'r', encoding='utf-8') as f: lines = f.readlines() # Find the line with 'float calculate_asymmetry_magnifying' insert_idx = None for i, line in enumerate(lines): if 'float calculate_asymmetry_magnifying' in line: # Find the closing brace of inject_density_kernel just before it for j in range(i - 1, -1, -1): if lines[j].strip() == '}': insert_idx = j + 1 # insert after this brace break break if insert_idx is None: print('ERROR: could not find insertion point') exit(1) kernel_lines = [ '// === STRESS PERTURBATION KERNEL ===\n', '// Writes a perturbation into the NON-EQUILIBRIUM (shear-stress) moment.\n', '// f[i] += G * d_cx[i] * d_cy[i] -- the sxy basis has zero density moment,\n', '// zero momentum moment, and non-zero sxy shear-stress. Pure f_neq write.\n', '// Same Gaussian targeting as inject_density: (x, y, sigma, strength), periodic.\n', '__global__ void perturb_stress_kernel(float* f,\n', ' float cx, float cy,\n', ' float sigma, float strength) {\n', ' int x = blockIdx.x * blockDim.x + threadIdx.x;\n', ' int y = blockIdx.y * blockDim.y + threadIdx.y;\n', ' if (x >= NX || y >= NY) return;\n', '\n', ' float dx = (float)x - cx;\n', ' float dy = (float)y - cy;\n', ' if (dx > NX * 0.5f) dx -= NX;\n', ' if (dx < -NX * 0.5f) dx += NX;\n', ' if (dy > NY * 0.5f) dy -= NY;\n', ' if (dy < -NY * 0.5f) dy += NY;\n', '\n', ' float r2 = dx * dx + dy * dy;\n', ' float G = strength * expf(-r2 / (2.0f * sigma * sigma));\n', '\n', ' int f_idx = (y * NX + x) * Q;\n', ' for (int i = 0; i < Q; i++) {\n', ' f[f_idx + i] += G * d_cx[i] * d_cy[i];\n', ' }\n', '}\n', '\n', ] # Insert kernel lines for i, line in enumerate(kernel_lines): lines.insert(insert_idx + i, line) with open(path, 'w', encoding='utf-8') as f: f.writelines(lines) print(f'Inserted {len(kernel_lines)} lines at index {insert_idx + 1}') # Verify with open(path, 'r', encoding='utf-8') as f: content = f.read() if 'perturb_stress_kernel' in content: print('VERIFIED: kernel present') else: print('ERROR: kernel not found')