From c46136b803e052ccd80cff9417fb85c699d50567 Mon Sep 17 00:00:00 2001 From: zeefaad Date: Thu, 23 Oct 2025 14:28:22 +0200 Subject: [PATCH] 1D constellation + precalculated sqrt(M) --- QAM/out | Bin 20896 -> 20984 bytes QAM/qam.c | 48 +++++++- QAM/save/3/debug.py | 104 +++++++++++++++++ QAM/save/3/qam.c | 278 ++++++++++++++++++++++++++++++++++++++++++++ 4 files changed, 424 insertions(+), 6 deletions(-) create mode 100644 QAM/save/3/debug.py create mode 100644 QAM/save/3/qam.c diff --git a/QAM/out b/QAM/out index bd70fa06ec215ab3b5eb1d5e5d9b2270ed622201..0b0112e36c98286da3209ba41f82a9a7cebf1c00 100755 GIT binary patch delta 3034 zcmaJ@4Nw)=72aLs?;-93za-VT4#PsTPQV;7 zVW4id7@R99PLe4$)7C_7OrOlq&Nz7(5=f?F=!{WJO~sbjN2H1n0Uev|ckW%FwbQFcZw}d-y z+2hKOB2NiaI>r8^e7xkPorMpz?)hGGnsTdPJgmH7WPPXPKNa$uXeHC>FN=9TL|Gfd z7NsQluPrH%mCLF>JN{CbB1aO&(vq(#QiOj|O0wcJ8iTq~KWvm<>eud4iEEp6Qw!>* zzJjdzu&LcWJZ%~0jd8tG?;T#Cw=I!@*^beRtYKXqm{6S#Tm=ymY7AZZ5zX3NN?fB| z+IynCz3jbG-S}K@9?RE_#v!BroNkm37+&9Cp`rDerRPj-P(EX7ed^n14DCx(`*OBG zf6%&NS-PRk^lM{W;964~n~k19`5~Ql&OxMT=6@&}gQ9cl+gjghZESB(zc#*uGj24s z+3pNt9N>&R(db1?9+<87|H#KdJ}Ah?_nsgXABv{;jRjbiD_d#2&bGNyQ`VxN3H70X zq0!VrHK!zDVA>!#`A+tl%jHY6v7p|j1$3i77&eX>w1rkLk|f<|dD4Ps3WK2Qx@8$H zg#b;y_6~;_EjqcSeI~z=2b+Vk>Fql_ecNdHE>EO5y25r3wu7{s0JDvZPd7WLhS|+o zI4Kf8zDpHo`|LRSgP~&cGh#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XF84i)dn7VcFF?74cCQT4D*`vp-6t@+R zUV!;1&0~`ms*$V7=dl^rBho>)constellation); } +// Préambule QAM +void generate_preamble(qam_system* qam, double complex* preamble, int L) { + // L 1er symboles de la constellation + for (int i = 0; i < L; i++) { + preamble[i] = qam->constellation[i % qam->M]; + } +} + +// Concatène le préambule avec le signal modulé +double complex* concat_preamble_signal(double complex* preamble_mod, int preamble_len, double complex* s_mod, int nb_symbols, int N) { + int total_samples = (preamble_len + nb_symbols) * N; + double complex* s_concat = malloc(sizeof(double complex) * total_samples); + + // Copier le préambule modulé + for (int i = 0; i < preamble_len * N; i++) { + s_concat[i] = preamble_mod[i]; + } + + // Copier le signal modulé après le préambule + for (int i = 0; i < nb_symbols * N; i++) { + s_concat[preamble_len * N + i] = s_mod[i]; + } + + return s_concat; +} + int main () { // Initialisation du system qam qam_system qam; @@ -232,13 +258,23 @@ int main () { double complex* symbols = malloc(sizeof(double complex) * nb_symbols); bits_to_symbols(&qam, input_bits, nb_bits, symbols); - // Modulation - int total_samples = qam.N * nb_symbols; + // Initialisation du préambule + int L = 16; + int total_samples = qam.N * (nb_symbols + L); + + double complex* preamble = malloc(sizeof(double complex) * L); + generate_preamble(&qam, preamble, L); + double complex* preamble_mod = malloc(sizeof(double complex) * L * qam.N); + modulate(&qam, preamble, L, preamble_mod); + + double complex* s_mod = malloc(sizeof(double complex) * nb_symbols * qam.N); + modulate(&qam, symbols, nb_symbols, s_mod); + double complex* s = malloc(sizeof(double complex) * total_samples); - modulate(&qam, symbols, nb_symbols, s); + double complex* s_with_preamble = concat_preamble_signal(preamble_mod, L, s_mod, nb_symbols, qam.N); // Ajout du bruit - add_noise(s, total_samples, 0); + add_noise(s_with_preamble, total_samples, 0); FILE *fp_ref = fopen("constellation_ref.dat", "w"); fill_constellation_data(&qam, fp_ref); @@ -248,12 +284,12 @@ int main () { //add_dephasage(s, M_PI / 6.0, total_samples); // AJout de decalage de fréquence - //add_freq(&qam, s, 1, total_samples); + add_freq(&qam, s_with_preamble, 0, total_samples); // Démodulation FILE *fp_constel = fopen("constellation.dat", "w"); uint8_t* output_bits = (uint8_t*)malloc(nb_bits * sizeof(uint8_t)); - demodulate(&qam, s, nb_symbols, output_bits, fp_constel); + demodulate(&qam, s_mod, nb_symbols, output_bits, fp_constel); fclose(fp_constel); // Reconstruction du texte diff --git a/QAM/save/3/debug.py b/QAM/save/3/debug.py new file mode 100644 index 0000000..1c8c4d2 --- /dev/null +++ b/QAM/save/3/debug.py @@ -0,0 +1,104 @@ +#!/usr/bin/env python3 +import pyqtgraph as pg +from pyqtgraph.Qt import QtWidgets, QtCore +import numpy as np +import sys, os + +# -------------------- Fichiers de données -------------------- +REF_FILE = "constellation_ref.dat" +RX_FILE = "constellation.dat" +ERROR_FILE = "pll_error.dat" + +# -------------------- Fonctions de chargement -------------------- +def load_points(filename): + if os.path.exists(filename): + return np.loadtxt(filename) + else: + return np.zeros((0,2)) + +def load_error(filename): + if os.path.exists(filename): + return np.loadtxt(filename) + else: + return np.zeros((0,2)) + +# -------------------- Application -------------------- +app = QtWidgets.QApplication(sys.argv) +win = pg.GraphicsLayoutWidget(show=True, title="Constellation") +win.resize(900, 900) +win.setBackground('#0a0a0a') # fond noir profond + +plot = win.addPlot() +plot.setAspectLocked(True) # axes égaux + +# -------------------- Axes stylés -------------------- +plot.getAxis('left').setPen(pg.mkPen('#AAA', width=2)) +plot.getAxis('bottom').setPen(pg.mkPen('#AAA', width=2)) +plot.getAxis('left').setTextPen(pg.mkPen('#EEE')) +plot.getAxis('bottom').setTextPen(pg.mkPen('#EEE')) +plot.setLabel('left', 'Quadrature (Q)', color='#EEE', size='12pt') +plot.setLabel('bottom', 'In-phase (I)', color='#EEE', size='12pt') + +# -------------------- Grille subtile -------------------- +grid = pg.GridItem() +grid.setPen(pg.mkPen('#444', width=1, style=QtCore.Qt.DotLine)) +plot.addItem(grid) + +# -------------------- Chargement initial -------------------- +ref_data = load_points(REF_FILE) +rx_data = load_points(RX_FILE) +error_data = load_error(ERROR_FILE) + +# Points référence +ref_plot = plot.plot(ref_data[:,0], ref_data[:,1], + pen=None, + symbol='o', + symbolSize=10, + symbolBrush=pg.mkBrush('#1E90FF'), # bleu vif + symbolPen=None, + name='Référence') + +# Points reçus +rx_plot = plot.plot(rx_data[:,0], rx_data[:,1], + pen=None, + symbol='x', + symbolSize=6, + symbolBrush=pg.mkBrush('#FF4500'), # orange vif + symbolPen=None, + name='Reçu') + +# PLL error en vert +error_plot = plot.plot(error_data[:,0], error_data[:,1], + pen=pg.mkPen('#00FF00', width=2), + symbol=None, + name='PLL error') + +# -------------------- Légende stylée -------------------- +legend = plot.addLegend() +for item in legend.items: + item[1].setPen(pg.mkPen('#FFF', width=2)) + +# -------------------- Timer pour mise à jour dynamique -------------------- +def update(): + ref_data = load_points(REF_FILE) + rx_data = load_points(RX_FILE) + error_data = load_error(ERROR_FILE) + + if ref_data.size > 0: + ref_plot.setData(ref_data[:,0], ref_data[:,1]) + if rx_data.size > 0: + rx_plot.setData(rx_data[:,0], rx_data[:,1]) + if error_data.size > 0: + error_plot.setData(error_data[:,0], error_data[:,1]) + +timer = QtCore.QTimer() +timer.timeout.connect(update) +timer.start(500) # ms + +# -------------------- Anti-aliasing -------------------- +pg.setConfigOptions(antialias=True) + +# -------------------- Exécution -------------------- +if __name__ == '__main__': + sys.exit(app.exec_()) + diff --git a/QAM/save/3/qam.c b/QAM/save/3/qam.c new file mode 100644 index 0000000..ad494a8 --- /dev/null +++ b/QAM/save/3/qam.c @@ -0,0 +1,278 @@ +#include +#include +#include +#include +#include +#include + +#define A 10 + +struct qam_system_s { + int M; // Nombre de symboles M-QAM + int k; // Nombre de bits/symboles + int sm; // sqrt M + double Fs; // Fréquence d'échantillionage + double Ts; // Temps d'échantillionage + int N; // Nombre d'échantillions + double Fc; // Fréquence de la porteuse + double complex* constellation; // Tableau de symboles I + j Q 1D +}; +typedef struct qam_system_s qam_system; + +// Initialisation de la constellation (double tableau de taille sqrt(M)), +void init_constellation (qam_system* qam) { + qam->constellation = (double complex*)malloc(sizeof(double complex) * qam->M); + + double norm_factor = sqrt((double)(qam->M - 1) / 3.0); // Pour puissance unitaire + + for (int i = 0; i < qam->sm; i++) { + double ip = -(qam->sm - 1) + 2 * i; + for (int j = 0; j < qam->sm; j++) { + double qp = -(qam->sm - 1) + 2 * j; + int idx = i * qam->sm + j; + qam->constellation[idx] = (ip + I * qp) / norm_factor; + } + } +} + +int bin_to_gray (int x) { + return x ^ (x >> 1); +} + +// Iteration de XOR +int gray_to_bin(int g) { + int b = g; + while (g >>= 1) + b ^= g; + return b; +} + +// Modulation QAM +void modulate (qam_system* qam, double complex* symbols, int nb_symbols, double complex* s) { + for (int k = 0; k < nb_symbols; k++) { + double complex iq = symbols[k]; + for (int n = 0; n < qam->N; n++) { + int idx = k * qam->N + n; + s[idx] = A * iq * cexp(2 * I * M_PI * qam->Fc * ((double)idx / qam->Fs)); + } + } +} + +// Demodulation QAM +void demodulate(qam_system* qam, double complex* s, int nb_symbols, uint8_t* bits_hat, FILE *fp_constel) { + for (int k = 0; k < nb_symbols; k++) { + double complex r = 0; + for (int n = 0; n < qam->N; n++) { + r += s[k * qam->N + n] * cexp(-2 * I * M_PI * qam->Fc * ((double)(k * qam->N + n) / qam->Fs)) / A; + } + r /= qam->N; + + if (fp_constel) { + fprintf(fp_constel, "% .8f % .8f\n", creal(r), cimag(r)); + fflush(fp_constel); + } + + // Distance euclidien de Ir et Qr pour avoir le point le plus proche de la constellation (lent) + double min_d = INFINITY; + int i_cl = 0; + int j_cl = 0; + for (int idx = 0; idx < qam->M; idx++) { + double d = cabs(r - qam->constellation[idx]); + if (d < min_d) { + min_d = d; + i_cl = idx / qam->sm; + j_cl = idx % qam->sm; + } + } + + // Gray mapping + if (qam->k % 2 != 0) { + printf("demodulate : k pair (k = %d)\n", qam->k); + exit(1); + } + int bits_per_axis = qam->k / 2; + + int i_bin = gray_to_bin(i_cl); + int j_bin = gray_to_bin(j_cl); + + for (int b = 0; b < bits_per_axis; b++) { + bits_hat[k * qam->k + b] = (i_bin >> (bits_per_axis - 1 - b)) & 1; + bits_hat[k * qam->k + bits_per_axis + b] = (j_bin >> (bits_per_axis - 1 - b)) & 1; + } + } +} + +// Calcul du bruit gaussien pour un sigma donné +// Formule de Box-Muller +double gaussian_noise (double sigma) { + double u1 = (rand() + 1) / ((double)RAND_MAX + 2); + double u2 = (rand() + 1) / ((double)RAND_MAX + 2); + return sigma * sqrt(-2 * log(u1)) * cos(2 * M_PI * u2); +} + +// Ajout du bruit +void add_noise (double complex* s, int len, double sigma) { + //double signal_power = (2.0/3.0)*(qam.M-1); + //double snr_dB = 5; // SNR en dB + //double snr_lin = pow(10.0, snr_dB / 10.0); + //double sigma = sqrt(signal_power / snr_lin); + for (int i = 0; i < len; i++) { + double nr = gaussian_noise(sigma); + double ni = gaussian_noise(sigma); + s[i] += nr + I * ni; + } +} + +// Changer le tableau de bits en boolen ou alors la represenation binaire et shifter pour extraire les bits (pas bien si M plus grand) +void bits_to_symbols (qam_system* qam, uint8_t* bits, int nb_bits, double complex* symbols) { + int nb_symbols = nb_bits / qam->k; + + // k pair + if (qam->k % 2 != 0) { + printf("bits_to_symbols : k doit être pair (k = %d) \n", qam->k); + exit(1); + } + int bits_per_axis = qam->k / 2; + + for (int sym = 0; sym < nb_symbols; sym++) { + // Construire les indices binaires i_bin (MSB...) et j_bin (LSB...) + int i_bin = 0; + int j_bin = 0; + for (int b = 0; b < bits_per_axis; b++) { + i_bin = (i_bin << 1) | bits[sym * qam->k + b]; + j_bin = (j_bin << 1) | bits[sym * qam->k + bits_per_axis + b]; + } + + int i_gray = bin_to_gray(i_bin); + int j_gray = bin_to_gray(j_bin); + + if (i_gray < 0 || i_gray >= qam->sm || j_gray < 0 || j_gray >= qam->sm) { + printf("bits_to_symbols : IOOR i_gray = %d j_gray = %d sm = %d \n", i_gray, j_gray, qam->sm); + exit(1); + } + symbols[sym] = qam->constellation[i_gray * qam->sm + j_gray]; + } +} + +double compare_bits(uint8_t* bits1, uint8_t* bits2, int nb_bits) { + int errors = 0; + for (int i = 0; i < nb_bits; i++) { + if (bits1[i] != bits2[i]) errors++; + } + return (double)errors / nb_bits; +} + +void add_dephasage(double complex* s, double phi_offset, int total_samples) { + for (int i = 0; i < total_samples; i++) { + s[i] *= cexp(I * phi_offset); + } +} + +void add_freq(qam_system* qam, double complex* s, double freq_offset, int total_samples) { + for (int i = 0; i < total_samples; i++) { + double t = (double)i / qam->Fs; + s[i] *= cexp(I * 2 * M_PI * freq_offset * t); + } +} + +void fill_constellation_data(qam_system* qam, FILE *fp_ref) { + for (int i = 0; i < qam->sm; i++) { + for (int j = 0; j < qam->sm; j++) { + int idx = i * qam->sm + j; + fprintf(fp_ref, "% .8f % .8f\n", creal(qam->constellation[idx]), cimag(qam->constellation[idx])); + } + } +} + +void reconstruction_text(int nb_chars, uint8_t* output_bits, char* texte_recup) { + for(int i = 0; i < nb_chars; i++){ + char c = 0; + for(int b = 0; b < 8; b++){ + c |= output_bits[i*8 + b] << (7-b); + } + texte_recup[i] = c; + } + texte_recup[nb_chars] = '\0'; +} + +void text_to_bits(int nb_chars, int nb_bits, char* texte, uint8_t* input_bits) { + for(int i = 0; i < nb_chars; i++){ + for(int b = 0; b < 8; b++){ + input_bits[i*8 + b] = (texte[i] >> (7-b)) & 1; + } + } +} + +// Libération de la mémoire +void free_constellation(qam_system* qam) { + free(qam->constellation); +} + +int main () { + // Initialisation du system qam + qam_system qam; + qam.M = 16; + qam.k = (int)log2((double)(qam.M)); + qam.sm = (int)sqrt(qam.M); + qam.Fs = 44100; + qam.Ts = 0.01; + qam.N = (int)(qam.Fs * qam.Ts); + qam.Fc = 2000; + init_constellation(&qam); + + // Conversion du texte en bits + char* texte = "Vif juge, trempez ce blond whisky aqueux, Vif juge, trempez ce blond whisky aqueux, Vif juge, trempez ce blond whisky aqueux, Vif juge, trempez ce blond whisky aqueux, Vif juge, trempez ce blond whisky aqueux"; + int nb_chars = strlen(texte); + int nb_bits = nb_chars * 8; + int nb_symbols = (nb_bits + qam.k - 1) / qam.k; + uint8_t* input_bits = malloc(nb_bits * sizeof(uint8_t)); + text_to_bits(nb_chars, nb_bits, texte, input_bits); + + // Conversion en symboles + double complex* symbols = malloc(sizeof(double complex) * nb_symbols); + bits_to_symbols(&qam, input_bits, nb_bits, symbols); + + // Modulation + int total_samples = qam.N * nb_symbols; + double complex* s = malloc(sizeof(double complex) * total_samples); + modulate(&qam, symbols, nb_symbols, s); + + // Ajout du bruit + add_noise(s, total_samples, 0); + + FILE *fp_ref = fopen("constellation_ref.dat", "w"); + fill_constellation_data(&qam, fp_ref); + fclose(fp_ref); + + // Ajout de dephasage + //add_dephasage(s, M_PI / 6.0, total_samples); + + // AJout de decalage de fréquence + //add_freq(&qam, s, 1, total_samples); + + // Démodulation + FILE *fp_constel = fopen("constellation.dat", "w"); + uint8_t* output_bits = (uint8_t*)malloc(nb_bits * sizeof(uint8_t)); + demodulate(&qam, s, nb_symbols, output_bits, fp_constel); + fclose(fp_constel); + + // Reconstruction du texte + char* texte_recup = malloc(nb_chars + 1); + reconstruction_text(nb_chars, output_bits, texte_recup); + + printf("Texte original : %s\n\n", texte); + printf("Texte demodulé : %s\n", texte_recup); + + // Calcul du BER + double ber = compare_bits(input_bits, output_bits, nb_bits); + printf("Taux d'erreur blind QAM: %.4f\n", ber * 100); + + // Libération mémoire + free(input_bits); + free(output_bits); + free(symbols); + free(s); + free_constellation(&qam); + + return 0; +}