import numpy as np import pandas as pd import matplotlib.pyplot as plt # Path settings BIT_FILE_PATH = r"G:\Users\Chipistil\Desktop\High-throughput-T2NP-Memristor-based-Dual-clock-edge-sampling-TRNG\1Mb.txt" MAX_LAG = 10000 READ_COUNT = 1000000 SAVE_PATH = r"G:\Users\Chipistil\Desktop\High-throughput-T2NP-Memristor-based-Dual-clock-edge-sampling-TRNG\True Random Numbers Verification\03_autocorrelation_function_analysis_ACF_analysis\AHU Black Swan_ACF_plot.png" EXCEL_PATH = r"G:\Users\Chipistil\Desktop\High-throughput-T2NP-Memristor-based-Dual-clock-edge-sampling-TRNG\True Random Numbers Verification\03_autocorrelation_function_analysis_ACF_analysis\AHU Black Swan_ACF_data.xlsx" def calculate_acf(bit_data, max_lag): N = len(bit_data) mu = np.mean(bit_data) sigma = np.std(bit_data, ddof=1) lags = np.arange(0, max_lag + 1) acf_values = [] for k in lags: sum_corr = np.sum((bit_data[:N - k] - mu) * (bit_data[k:] - mu)) acf = sum_corr / ((N - k) * sigma ** 2) acf_values.append(acf) return lags, np.array(acf_values) if __name__ == "__main__": with open(BIT_FILE_PATH, 'r') as f: content = f.read() bit_stream_full = np.array([int(c) for c in content if c in '01'], dtype=np.int64) if READ_COUNT is not None: bit_stream = bit_stream_full[:READ_COUNT] else: bit_stream = bit_stream_full print(f"✅ Data reading completed, bitstream length: {len(bit_stream):,}") lags, acf_vals = calculate_acf(bit_stream, MAX_LAG) print(f"✅ Autocorrelation calculation completed, lag range: 0 ~ {MAX_LAG}") N = len(bit_stream) conf_95_theoretical = 1.96 / np.sqrt(N) conf_95_actual = 1.96 * np.std(acf_vals[1:]) USE_ACTUAL_CI = True if USE_ACTUAL_CI: conf_95 = conf_95_actual print(f"✅ 95% confidence interval (based on actual data): ±{conf_95:.6f}") else: conf_95 = conf_95_theoretical print(f"✅ 95% confidence interval (theoretical): ±{conf_95:.6f}") plt.rcParams['font.sans-serif'] = ['DejaVu Sans'] plt.rcParams['axes.unicode_minus'] = False plt.figure(figsize=(12, 6), dpi=300) plt.scatter(lags[1:], acf_vals[1:], s=1, color='black', alpha=0.8) plt.axhline(y=conf_95, color='gray', linestyle='--', linewidth=1, label=f'95% CI: ±{conf_95:.6f}') plt.axhline(y=-conf_95, color='gray', linestyle='--', linewidth=1) plt.axhline(y=0, color='red', linestyle='-', linewidth=0.8) plt.xlabel('Lag', fontsize=12, fontweight='bold') plt.ylabel('Normalized Autocorrelation Coefficient (ACF)', fontsize=12, fontweight='bold') plt.title('1Mb Random Bitstream Autocorrelation Function', fontsize=14, fontweight='bold', pad=20) plt.legend(loc='upper right', fontsize=10) plt.grid(alpha=0.2, axis='y') plt.xlim(0, MAX_LAG) y_min = min(np.min(acf_vals[1:]), -conf_95) * 1.2 y_max = max(np.max(acf_vals[1:]), conf_95) * 1.2 plt.ylim(y_min, y_max) plt.tight_layout() plt.savefig(SAVE_PATH, dpi=300, bbox_inches='tight') df = pd.DataFrame({'Lag': lags[1:], 'ACF': acf_vals[1:]}) df.to_excel(EXCEL_PATH, index=False, engine='openpyxl') print(f"✅ Data saved to: {EXCEL_PATH}") print(f"Lag data points: {len(lags[1:])}") print(f"✅ Autocorrelation plot saved to: {SAVE_PATH}")