Skip to content
TheChatArchiveThe Chat Archive
Claudeclaude-opus-4-20250514-thinking-16k· AnthropicHugging Face LMArena Human Preference 140K

I have this script to simulate a calibration of a phased array I would like to add to…

From a Chatbot Arena battleThe same person sent this prompt to two anonymous models at once. Compare it with Claudeclaude-sonnet-4-20250514-thinking-32k’s answer.
  1. User

    I have this script to simulate a calibration of a phased array I would like to add to the plots the phase calibration values that should be used in the beamformer import numpy as np import os import matplotlib.pyplot as plt

    === NEC PARSING ===

    def parse_currents_from_outfile(filename, center_seg=6, num_elements=91): currents_x = np.zeros(num_elements, dtype=complex) currents_y = np.zeros(num_elements, dtype=complex) sequence1 = [132 * n - 126 for n in range(1, num_elements + 1)] sequence2 = [132 * n - 60 for n in range(1, num_elements + 1)] with open(filename, "r") as f: lines = f.readlines() idx_x = idx_y = 0 reading = False for line in lines: if "CURRENTS AND LOCATION" in line: reading = True continue if reading: if line.strip() == "" or "----" in line: continue parts = line.split() if len(parts) < 8: continue try: seq_no = int(parts[0]) real = float(parts[6]) imag = float(parts[7]) except ValueError: continue if seq_no in sequence1: currents_x[idx_x] = complex(real, imag) idx_x += 1 if seq_no in sequence2: currents_y[idx_y] = complex(real, imag) idx_y += 1 return currents_x, currents_y

    === LOAD NEC-BASED COUPLING MATRIX ===

    def load_nec_coupling_matrix(out_dir, num_elements, center_seg=6): N = num_elements C = np.zeros((2 * N, 2 * N), dtype=complex) for i in range(1, N + 1): fx = os.path.join(out_dir, f"excitation_X_elem{i}.out") fy = os.path.join(out_dir, f"excitation_Y_elem{i}.out") cx, cy = parse_currents_from_outfile(fx, center_seg, N) C[:N, i - 1] = cx C[N:, i - 1] = cy cx, cy = parse_currents_from_outfile(fy, center_seg, N) C[:N, N + i - 1] = cx C[N:, N + i - 1] = cy return C

    === RX CHAIN ERRORS ===

    def generate_channel_errors(N, phase_std_deg=10, amp_std_db=1, cross_pol_db=-25): """ Generate G matrix: diagonal RX phase + amplitude errors, with optional cross-pol leakage

    Parameters:
        N             : number of elements
        phase_std_deg: standard deviation of per-port phase error
        amp_std_db   : standard deviation of per-port amplitude error
        cross_pol_db : X↔Y leakage level in dB (e.g., -25 dB = 0.056)
    
    Returns:
        G : complex 2N x 2N gain matrix
    """
    total_ports = 2 * N
    G = np.zeros((total_ports, total_ports), dtype=complex)
    
    # Main diagonal (independent per-port gain + phase)
    phase_errors = np.random.normal(0, phase_std_deg * np.pi / 180, total_ports)
    amp_errors = np.random.normal(1, 10 ** (amp_std_db / 20) - 1, total_ports)
    for i in range(total_ports):
        G[i, i] = amp_errors[i] * np.exp(1j * phase_errors[i])
    
    # Cross-pol leakage
    if cross_pol_db is not None:
        cross_mag = 10 ** (cross_pol_db / 20)
        for i in range(N):
            # H -> V and V -> H leakage between same antenna ports
            phase_offset1 = np.random.uniform(0, 2 * np.pi)
            phase_offset2 = np.random.uniform(0, 2 * np.pi)
            G[i + N, i] += cross_mag * np.exp(1j * phase_offset1)  # X to Y
            G[i, i + N] += cross_mag * np.exp(1j * phase_offset2)  # Y to X
    
    return G
    

    === SIMULATE RX DATA ===

    def simulate_rx(C, G, tx_vec, snr_db=40, num_samples=100000): rx_true = C @ G @ tx_vec noise_power = 10 ** (-snr_db / 10) rx_samples = np.zeros((num_samples, len(tx_vec)), dtype=complex) for i in range(num_samples): noise = np.sqrt(noise_power / 2) * ( np.random.randn(len(tx_vec)) + 1j * np.random.randn(len(tx_vec)) ) rx_samples[i, :] = rx_true + noise return np.mean(rx_samples, axis=0)

    === PHASE CALIBRATION USING COUPLING MATRIX ===

    def calibrate(rx_vec, C, lambda_reg=1e-6): C_H = C.conj().T C_inv = np.linalg.inv(C_H @ C + lambda_reg * np.eye(C.shape[0])) @ C_H gain_est = C_inv @ rx_vec ref_phase = np.angle(gain_est[0]) # Anchor to antenna 0 (X-pol) return gain_est * np.exp(-1j * ref_phase)

    === PHASE ERROR METRIC ===

    def residual_phase(estimated, truth): phase_diff = np.angle(estimated / truth, deg=True) return (phase_diff + 180) % 360 - 180 # Wrap to [-180, 180]

    === MAIN PROCEDURE ===

    def main(): # === Parameters === num_elements = 91 nec_dir = "nec_files" # Update as needed snr_db = 40 num_samples = 100000 phase_std_deg = 10 amp_std_db = 1 lambda_reg = 1e-6 cross_pol_db = -20 # ← Try -20, -30, -100, etc. NOTE the model will break with worser values than -20

    print("Loading C matrix from NEC...")
    C = load_nec_coupling_matrix(nec_dir, num_elements)
    print(f"Condition number of C: {np.linalg.cond(C):.2e}")
    
    print("Generating RX channel errors (cables + receivers)...")
    G = generate_channel_errors(num_elements, phase_std_deg, amp_std_db, cross_pol_db)
    
    # === TX-X (H-polarized dipole) ===
    tx_x = np.zeros(2 * num_elements, dtype=complex)
    tx_x[:num_elements] = 1.0  # Only excite X-pol chain
    
    # === TX-Y (V-polarized dipole) ===
    tx_y = np.zeros(2 * num_elements, dtype=complex)
    tx_y[num_elements:] = 1.0  # Only excite Y-pol chain
    
    print("Simulating RX data for TX-X...")
    rx_x = simulate_rx(C, G, tx_x, snr_db, num_samples)
    
    print("Simulating RX data for TX-Y...")
    rx_y = simulate_rx(C, G, tx_y, snr_db, num_samples)
    
    print("Applying mutual coupling correction...")
    gain_est_x = calibrate(rx_x, C, lambda_reg)
    gain_est_y = calibrate(rx_y, C, lambda_reg)
    
    # === Ground truth from system gain matrix ===
    true_gain = np.diag(G)
    true_x = true_gain[:num_elements]
    true_y = true_gain[num_elements:]
    
    # === Get residuals ===
    res_x = residual_phase(gain_est_x[:num_elements], true_x)
    res_y = residual_phase(gain_est_y[num_elements:], true_y)
    
    mean_x, std_x = np.mean(res_x), np.std(res_x)
    mean_y, std_y = np.mean(res_y), np.std(res_y)
    
    print(f"\n🧪 Calibration Results (SNR={snr_db} dB, Samples={num_samples}):")
    print(f"X-pol: Mean {mean_x:+.2f}°, Std {std_x:.2f}°")
    print(f"Y-pol: Mean {mean_y:+.2f}°, Std {std_y:.2f}°")
    
    # === Visualization ===
    plt.figure(figsize=(14, 6))
    
    plt.subplot(1, 2, 1)
    plt.plot(res_x, "bo-", label="X-pol residuals")
    plt.axhline(0, ls="--", color="gray")
    plt.title("X-pol Phase Residuals")
    plt.xlabel("Antenna index")
    plt.ylabel("Phase Error (deg)")
    plt.grid(True)
    
    plt.subplot(1, 2, 2)
    plt.plot(res_y, "ro-", label="Y-pol residuals")
    plt.axhline(0, ls="--", color="gray")
    plt.title("Y-pol Phase Residuals")
    plt.xlabel("Antenna index")
    plt.grid(True)
    
    plt.tight_layout()
    plt.show()
    

    if name == "main": main()

  2. Claude Assistant

    Looking at your script, I can see you're estimating the complex gains through calibration and calculating residual phase errors. To add the phase calibration values that should be used in the beamformer, you'll want to display the negative of the estimated phases (since you apply the conjugate to correct the errors).

    Here's the modified version of your script with the calibration phases added to the plots:

    import numpy as np
    import os
    import matplotlib.pyplot as plt
    
    
    # === NEC PARSING ===
    def parse_currents_from_outfile(filename, center_seg=6, num_elements=91):
        currents_x = np.zeros(num_elements, dtype=complex)
        currents_y = np.zeros(num_elements, dtype=complex)
        sequence1 = [132 * n - 126 for n in range(1, num_elements + 1)]
        sequence2 = [132 * n - 60 for n in range(1, num_elements + 1)]
        with open(filename, "r") as f:
            lines = f.readlines()
        idx_x = idx_y = 0
        reading = False
        for line in lines:
            if "CURRENTS AND LOCATION" in line:
                reading = True
                continue
            if reading:
                if line.strip() == "" or "----" in line:
                    continue
                parts = line.split()
                if len(parts) < 8:
                    continue
                try:
                    seq_no = int(parts[0])
                    real = float(parts[6])
                    imag = float(parts[7])
                except ValueError:
                    continue
                if seq_no in sequence1:
                    currents_x[idx_x] = complex(real, imag)
                    idx_x += 1
                if seq_no in sequence2:
                    currents_y[idx_y] = complex(real, imag)
                    idx_y += 1
        return currents_x, currents_y
    
    
    # === LOAD NEC-BASED COUPLING MATRIX ===
    def load_nec_coupling_matrix(out_dir, num_elements, center_seg=6):
        N = num_elements
        C = np.zeros((2 * N, 2 * N), dtype=complex)
        for i in range(1, N + 1):
            fx = os.path.join(out_dir, f"excitation_X_elem{i}.out")
            fy = os.path.join(out_dir, f"excitation_Y_elem{i}.out")
            cx, cy = parse_currents_from_outfile(fx, center_seg, N)
            C[:N, i - 1] = cx
            C[N:, i - 1] = cy
            cx, cy = parse_currents_from_outfile(fy, center_seg, N)
            C[:N, N + i - 1] = cx
            C[N:, N + i - 1] = cy
        return C
    
    
    # === RX CHAIN ERRORS ===
    def generate_channel_errors(N, phase_std_deg=10, amp_std_db=1, cross_pol_db=-25):
        """
        Generate G matrix: diagonal RX phase + amplitude errors, with optional cross-pol leakage
    
        Parameters:
            N             : number of elements
            phase_std_deg: standard deviation of per-port phase error
            amp_std_db   : standard deviation of per-port amplitude error
            cross_pol_db : X↔Y leakage level in dB (e.g., -25 dB = 0.056)
    
        Returns:
            G : complex 2N x 2N gain matrix
        """
        total_ports = 2 * N
        G = np.zeros((total_ports, total_ports), dtype=complex)
    
        # Main diagonal (independent per-port gain + phase)
        phase_errors = np.random.normal(0, phase_std_deg * np.pi / 180, total_ports)
        amp_errors = np.random.normal(1, 10 ** (amp_std_db / 20) - 1, total_ports)
        for i in range(total_ports):
            G[i, i] = amp_errors[i] * np.exp(1j * phase_errors[i])
    
        # Cross-pol leakage
        if cross_pol_db is not None:
            cross_mag = 10 ** (cross_pol_db / 20)
            for i in range(N):
                # H -> V and V -> H leakage between same antenna ports
                phase_offset1 = np.random.uniform(0, 2 * np.pi)
                phase_offset2 = np.random.uniform(0, 2 * np.pi)
                G[i + N, i] += cross_mag * np.exp(1j * phase_offset1)  # X to Y
                G[i, i + N] += cross_mag * np.exp(1j * phase_offset2)  # Y to X
    
        return G
    
    
    # === SIMULATE RX DATA ===
    def simulate_rx(C, G, tx_vec, snr_db=40, num_samples=100000):
        rx_true = C @ G @ tx_vec
        noise_power = 10 ** (-snr_db / 10)
        rx_samples = np.zeros((num_samples, len(tx_vec)), dtype=complex)
        for i in range(num_samples):
            noise = np.sqrt(noise_power / 2) * (
                np.random.randn(len(tx_vec)) + 1j * np.random.randn(len(tx_vec))
            )
            rx_samples[i, :] = rx_true + noise
        return np.mean(rx_samples, axis=0)
    
    
    # === PHASE CALIBRATION USING COUPLING MATRIX ===
    def calibrate(rx_vec, C, lambda_reg=1e-6):
        C_H = C.conj().T
        C_inv = np.linalg.inv(C_H @ C + lambda_reg * np.eye(C.shape[0])) @ C_H
        gain_est = C_inv @ rx_vec
        ref_phase = np.angle(gain_est[0])  # Anchor to antenna 0 (X-pol)
        return gain_est * np.exp(-1j * ref_phase)
    
    
    # === PHASE ERROR METRIC ===
    def residual_phase(estimated, truth):
        phase_diff = np.angle(estimated / truth, deg=True)
        return (phase_diff + 180) % 360 - 180  # Wrap to [-180, 180]
    
    
    # === MAIN PROCEDURE ===
    def main():
        # === Parameters ===
        num_elements = 91
        nec_dir = "nec_files"  # Update as needed
        snr_db = 40
        num_samples = 100000
        phase_std_deg = 10
        amp_std_db = 1
        lambda_reg = 1e-6
        cross_pol_db = -20  # ← Try -20, -30, -100, etc. NOTE the model will break with worser values than -20
    
        print("Loading C matrix from NEC...")
        C = load_nec_coupling_matrix(nec_dir, num_elements)
        print(f"Condition number of C: {np.linalg.cond(C):.2e}")
    
        print("Generating RX channel errors (cables + receivers)...")
        G = generate_channel_errors(num_elements, phase_std_deg, amp_std_db, cross_pol_db)
    
        # === TX-X (H-polarized dipole) ===
        tx_x = np.zeros(2 * num_elements, dtype=complex)
        tx_x[:num_elements] = 1.0  # Only excite X-pol chain
    
        # === TX-Y (V-polarized dipole) ===
        tx_y = np.zeros(2 * num_elements, dtype=complex)
        tx_y[num_elements:] = 1.0  # Only excite Y-pol chain
    
        print("Simulating RX data for TX-X...")
        rx_x = simulate_rx(C, G, tx_x, snr_db, num_samples)
    
        print("Simulating RX data for TX-Y...")
        rx_y = simulate_rx(C, G, tx_y, snr_db, num_samples)
    
        print("Applying mutual coupling correction...")
        gain_est_x = calibrate(rx_x, C, lambda_reg)
        gain_est_y = calibrate(rx_y, C, lambda_reg)
    
        # === Ground truth from system gain matrix ===
        true_gain = np.diag(G)
        true_x = true_gain[:num_elements]
        true_y = true_gain[num_elements:]
    
        # === Get residuals ===
        res_x = residual_phase(gain_est_x[:num_elements], true_x)
        res_y = residual_phase(gain_est_y[num_elements:], true_y)
    
        # === Calculate calibration phases (negative of estimated phases) ===
        cal_phases_x = -np.angle(gain_est_x[:num_elements], deg=True)
        cal_phases_y = -np.angle(gain_est_y[num_elements:], deg=True)
    
        mean_x, std_x = np.mean(res_x), np.std(res_x)
        mean_y, std_y = np.mean(res_y), np.std(res_y)
    
        print(f"\n🧪 Calibration Results (SNR={snr_db} dB, Samples={num_samples}):")
        print(f"X-pol: Mean {mean_x:+.2f}°, Std {std_x:.2f}°")
        print(f"Y-pol: Mean {mean_y:+.2f}°, Std {std_y:.2f}°")
    
        # === Visualization ===
        fig, axes = plt.subplots(2, 2, figsize=(14, 10))
    
        # X-pol residuals
        ax1 = axes[0, 0]
        ax1.plot(res_x, "bo-", label="X-pol residuals")
        ax1.axhline(0, ls="--", color="gray")
        ax1.set_title("X-pol Phase Residuals")
        ax1.set_xlabel("Antenna index")
        ax1.set_ylabel("Phase Error (deg)")
        ax1.grid(True)
        ax1.legend()
    
        # Y-pol residuals
        ax2 = axes[0, 1]
        ax2.plot(res_y, "ro-", label="Y-pol residuals")
        ax2.axhline(0, ls="--", color="gray")
        ax2.set_title("Y-pol Phase Residuals")
        ax2.set_xlabel("Antenna index")
        ax2.set_ylabel("Phase Error (deg)")
        ax2.grid(True)
        ax2.legend()
    
        # X-pol calibration phases
        ax3 = axes[1, 0]
        ax3.plot(cal_phases_x, "b^-", label="X-pol calibration phases")
        ax3.set_title("X-pol Beamformer Calibration Phases")
        ax3.set_xlabel("Antenna index")
        ax3.set_ylabel("Calibration Phase (deg)")
        ax3.grid(True)
        ax3.legend()
        
        # Add text showing range
        phase_range_x = np.max(cal_phases_x) - np.min(cal_phases_x)
        ax3.text(0.02, 0.98, f"Range: {phase_range_x:.1f}°", 
                 transform=ax3.transAxes, verticalalignment='top',
                 bbox=dict(boxstyle='round', facecolor='wheat', alpha=0.5))
    
        # Y-pol calibration phases
        ax4 = axes[1, 1]
        ax4.plot(cal_phases_y, "r^-", label="Y-pol calibration phases")
        ax4.set_title("Y-pol Beamformer Calibration Phases")
        ax4.set_xlabel("Antenna index")
        ax4.set_ylabel("Calibration Phase (deg)")
        ax4.grid(True)
        ax4.legend()
        
        # Add text showing range
        phase_range_y = np.max(cal_phases_y) - np.min(cal_phases_y)
        ax4.text(0.02, 0.98, f"Range: {phase_range_y:.1f}°", 
                 transform=ax4.transAxes, verticalalignment='top',
                 bbox=dict(boxstyle='round', facecolor='wheat', alpha=0.5))
    
        plt.tight_layout()
        plt.show()
    
        # Optional: Save calibration values to file
        np.savetxt("calibration_phases_x.txt", cal_phases_x, fmt="%.6f", 
                   header="X-pol calibration phases (degrees)")
        np.savetxt("calibration_phases_y.txt", cal_phases_y, fmt="%.6f", 
                   header="Y-pol calibration phases (degrees)")
        print("\nCalibration phases saved to calibration_phases_x.txt and calibration_phases_y.txt")
    
    
    if __name__ == "__main__":
        main()
    

    The key changes I made:

    1. Calculate calibration phases: Added calculation of the beamformer calibration phases as the negative of the estimated phases:

      cal_phases_x = -np.angle(gain_est_x[:num_elements], deg=True)
      cal_phases_y = -np.angle(gain_est_y[num_elements:], deg=True)
      
    2. Expanded visualization: Changed from 1x2 to 2x2 subplot layout to show both residuals and calibration phases.

    3. Added calibration phase plots: The bottom row shows the actual phase values that should be applied in the beamformer to correct for the system errors.

    4. Added phase range indicators: Each calibration plot shows the total phase range, which gives you an idea of the calibration spread.

    5. Save calibration values: The script now saves the calibration phases to text files for use in your beamformer.

    The calibration phases represent the phase corrections that should be applied to each antenna element in the beamformer to compensate for the system phase errors. These are the negative of the estimated phases because you apply them as signal * exp(j * cal_phase) to correct the errors.

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.