├── requirement.txt ├── dataset.npy ├── README.md ├── Data_generation.py ├── config_parameter.py ├── evaluation_antennas.py ├── others ├── Test_beamforming.py ├── Test_function.py └── withinitialpoint.py ├── evaluation_different_rf_antenna.py ├── Trainv2_4inputs.py ├── evaluation_simultaneously.py ├── network.py └── evaluation_parameterssimulataneous.py /requirement.txt: -------------------------------------------------------------------------------- 1 | python==3.9 2 | tensorflow == 2.9.1 3 | numpy == 1.22.4 4 | matplotlib == 3.3.0 5 | -------------------------------------------------------------------------------- /dataset.npy: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/DarmJarlo/Learning-based-Hybrid-precoding-in-ISAC/HEAD/dataset.npy -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | This project is about my master thesis:Learning based hybrid precoding in V2X . 2 | 3 | _**Overview**_ 4 | 5 | - Trainv2_4inputs.py is about the design of the training process. 6 | 7 | - loss.py contains the utility functions used in the whole project, such as the calculation for loss function, the conversion from output to precoding matrices and so on. 8 | 9 | - network.py is the final network structure I‘ve used. 10 | 11 | - config_parameter.py is about the setup for the parameter used in the whole project. 12 | 13 | - The four files beginning with "evaluation" are the evaluation programs to evaluate and to compare the models under different parameter setup. 14 | 15 | - dataset.npy is the dataset generated by Data_generation.py, which is then used for the model training. 16 | 17 | _**Usage tips**_ 18 | 19 | First,while training the model 20 | - check in the bottom of config_parameter.py which goal you wanna train for, only communication. only crb or combined. Here I recommand you first train with the goal of only communication and then go further. It is worth noting that when you train for only crb, you need to modify the loss function in the train_step function of Trainv2_4inputs to make it train for crb_distance or crb_angle. 21 | 22 | - check the network mode in Trainv2_4inputs: In the load_model function, if you wanna train for digital precoding, use model = DL_method_NN_for_v2x_mod(), or you need to use model = DL_method_NN_for_v2x_hybrid() for hybrid precoding. 23 | 24 | - In line 112 of Trainv2_4inputs.py, when you do not have starting point for the training, set zf_matrix = None 25 | 26 | After the model is trained, you can then make use of the files with "evalution" to evaluate it. 27 | 28 | - In the bottom of every file, you need firstly to assign the mode of models and then start evaluation. 29 | 30 | - In evaluation_parameterssimulataneous.py, it is worth noting every time under one single mode you can only evaluate one kind of parameters, which means you cannot evaluate level of noise and transmit power in a single runtime. Like what I have done in the code, you must first comment the other functions and just run with the function different_k uncommented. 31 | 32 | 33 | 34 | 35 | -------------------------------------------------------------------------------- /Data_generation.py: -------------------------------------------------------------------------------- 1 | import random 2 | import tensorflow as tf 3 | import numpy as np 4 | import config_parameter 5 | import evaluation 6 | if config_parameter.mode == "V2I": 7 | antenna_size = config_parameter.antenna_size 8 | num_vehicle = config_parameter.num_vehicle 9 | elif config_parameter.mode == "V2V": 10 | antenna_size = config_parameter.vehicle_antenna_size 11 | num_vehicle = config_parameter.num_uppercar + config_parameter.num_lowercar + config_parameter.num_horizoncar 12 | # Set the number of samples and batch size 13 | num_samples = 9600 14 | batch_size = 32 15 | 16 | # Generate random samples 17 | angles_1 = np.random.uniform(0.2*np.pi, 0.3*np.pi, size=(num_samples, 1)) 18 | angles_2 = np.random.uniform(0.3*np.pi, 0.4*np.pi, size=(num_samples, 1)) 19 | angles_3 = np.random.uniform(0.6*np.pi, 0.7*np.pi, size=(num_samples, 1)) 20 | angles_4 = np.random.uniform(0.7*np.pi, 0.8*np.pi, size=(num_samples, 1)) 21 | angles = np.concatenate((angles_1, angles_2, angles_3,angles_4), axis=1) 22 | distances = np.random.uniform(1500, 2000, size=(num_samples, num_vehicle)) 23 | angles = np.random.uniform(0.2*np.pi, 0.8*np.pi, size=(num_samples, num_vehicle)) 24 | # Combine angles and distances into a single array 25 | angles = np.sort(angles, axis=1) 26 | data = np.concatenate((angles, distances), axis=1) 27 | 28 | distances = None 29 | angles = None 30 | for i in range(96): 31 | distance,angle = evaluation.generate_input_v2i() 32 | angle = angle.T 33 | distance = distance.T 34 | if distances is not None: 35 | distances = np.concatenate((distances, distance), axis=0) 36 | angles = np.concatenate((angles, angle), axis=0) 37 | else: 38 | distances = distance 39 | angles = angle 40 | 41 | 42 | 43 | data = np.concatenate((np.array(angles), np.array(distances)), axis=1) 44 | print(data.shape) 45 | # Shuffle the data 46 | #np.random.shuffle(data) 47 | 48 | # Save data to a file 49 | filename = "dataset.npy" 50 | np.save(filename, data) 51 | 52 | # Create a TensorFlow Dataset from the file with shuffling 53 | tf_dataset = tf.data.Dataset.from_tensor_slices(data) 54 | tf_dataset = tf_dataset.shuffle(num_samples) 55 | tf_dataset = tf_dataset.batch(batch_size) 56 | 57 | # Read 32 samples as separate lists for each batch 58 | for batch in tf_dataset.take(10): # Print 5 batches 59 | angles_batch = batch[:, :num_vehicle].numpy().tolist() 60 | distances_batch = batch[:, num_vehicle:].numpy().tolist() 61 | print("Angles:", angles_batch) 62 | print("Distances:", distances_batch) 63 | -------------------------------------------------------------------------------- /config_parameter.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | import matplotlib.pyplot as plt 3 | import numpy as np 4 | import matplotlib.pyplot as plt 5 | import numpy as np 6 | import matplotlib.pyplot as plt 7 | import numpy as np 8 | 9 | digital = False 10 | #mode = "V2V" 11 | mode = "V2I" 12 | # some training parameters 13 | #imagine the vertical distance between RSU and highway is 20 14 | 15 | iters = 1000 16 | one_iter_period = 0.4#s 17 | train_data_period = 1 #s 18 | num_vehicle = 4 19 | batch_size = 32 20 | matched_filtering_gain =10 21 | 22 | 23 | #parameter for v2v 24 | ################################################################3 25 | num_uppercar =2 26 | num_lowercar =2 27 | num_horizoncar = 0 28 | observer_car_init_loca = np.array([0,0]) 29 | Initial_uppercar1_min = 50 30 | Initial_uppercar1_max = 60 31 | Initial_uppercar2_min = -20 32 | Initial_uppercar2_max = -30 33 | Initial_horizoncar1_min = 50 34 | Initial_horizoncar1_max = 60 35 | Initial_lowercar1_min = 40 36 | Initial_lowercar1_max = 50 37 | Initial_lowercar2_min = -40 38 | Initial_lowercar2_max = -50 39 | lowerspeed_low = -10 40 | lowerspeed_high = -5 41 | upperspeed_low = 5 42 | upperspeed_high = 10 43 | horizonspeed_low = 5 44 | horizonspeed_high = 10 45 | ######################################################### 46 | 47 | 48 | 49 | highway_length = 540 50 | RSU_location = np.array([0,-1000]) 51 | 52 | Radar_measure_slot = 0.01 #s 53 | length_echo = 0.005 # length of echo ms 54 | power = 100 55 | 56 | fading_coefficient = 0.5 + 0.5*1j 57 | """這裏越小,zf的crb越大,因爲zf的幹擾永遠爲0,這個參數越小的話,sinr數量級越小,zf的crb越大""" 58 | """同樣的,pathloss越小,zf的sumrate越小,因爲sinr的數量級越小,zf的sumrate越小""" 59 | #calculation for doppler_frequency 60 | Frequency_original = 30e9 # carrier frequency in Hz 61 | FurtherTrain = True 62 | 63 | #these are for the simulation test 64 | speed_low = 5 65 | speed_high = 10 66 | 67 | Initial_location_min = np.array([1000,650,-450,-850]) 68 | Initial_location_max = np.array([1050,700,-400,-800]) 69 | print(Initial_location_min) 70 | print(Initial_location_max) 71 | #[ 1089.81379201 487.37954435 -1089.81379201 -2064.57288071] 72 | #[ 2064.57288071 1089.81379201 -487.37954435 -1089.81379201] 73 | Initial_uppercar_y = 1000 74 | Initial_lowercar_y = 900 75 | #Initial_location1_min = 100*np.sin(0.4*np.pi) 76 | #Initial_location1_min = 100*np.cos(0.3*np.pi) 77 | #print(Initial_location1_min)#58 78 | #Initial_location1_max = 100*np.cos(0.35*np.pi) 79 | #print(Initial_location1_max)45 80 | 81 | 82 | 83 | train_speed_low = 18 84 | train_speed_high = 25 85 | train_initial_location_min = 30 86 | train_initial_location_max = 120 87 | 88 | #setup for metrics 89 | rf_size = 6 90 | antenna_size = 16 91 | vehicle_antenna_size = 16 92 | receiver_antenna_size = 1 93 | sigma_k = 1e-7 94 | sigma_z = 1e-7 95 | 96 | 97 | #path loss parameters 98 | 99 | d0 = 100 100 | alpha = 1e-3#path_loss alpha at reference distance d0 UNIT: dB 101 | #alpha = 1e-6#path_loss alpha at reference distance d0 UNIT: dB 102 | path_loss_exponent = -2.55 103 | 104 | 105 | #chirp signal parameters 106 | c = 3e8 # speed of light in m/s 107 | sampling_rate = 1000 108 | 109 | bandwidth = 1e6 # bandwidth of the chirp signal in Hz 110 | pulse_duration = 10e-6 # pulse duration in seconds 111 | R_max = 200 # maximum range in meters 112 | Signal_noise_power = 1e-6#noise for echo signal 113 | sigma_rk = Signal_noise_power 114 | rou_timedelay = 2e-8 115 | rou_dopplershift = 2e-8 116 | 117 | 118 | 119 | 120 | #loss_mode = "Upper_sum_rate" # three mode 121 | loss_mode = "lower_bound_crb" 122 | 123 | #loss_mode = "combined_loss" 124 | 125 | 126 | -------------------------------------------------------------------------------- /evaluation_antennas.py: -------------------------------------------------------------------------------- 1 | import random 2 | 3 | import loss 4 | import numpy as np 5 | import config_parameter 6 | import math 7 | import tensorflow as tf 8 | from network import DL_method_NN_for_v2x_mod, DL_method_NN_for_v2x_hybrid 9 | import matplotlib.pyplot as plt 10 | from evaluation_simultaneously import generate_input_v2i, generate_input_v2v, \ 11 | load_model, load_model_hybrid_combine, load_model_digitalwith_combine, \ 12 | load_model_digitalwithout_combine, load_model_only_communication_hybrid, \ 13 | load_model_only_communication_digitalwith, load_model_only_communication_digitalwithout 14 | Test = 'V2I' 15 | 16 | 17 | def load_antenna_32(): 18 | config_parameter.rf_size = 16 19 | config_parameter.antenna_size = 32 20 | config_parameter.vehicle_antenna_size = 32 21 | model = load_model(digital=False) 22 | model.load_weights(filepath='allmodel1/Keras_models_antenna32_onlycomm/new_model') 23 | return model 24 | def load_antenna_64(): 25 | config_parameter.rf_size = 32 26 | config_parameter.antenna_size = 64 27 | config_parameter.vehicle_antenna_size = 64 28 | model = load_model(digital=False) 29 | model.load_weights(filepath='allmodel1/Keras_models_antenna64_onlycomm/new_model') 30 | return model 31 | def load_antenna_16(): 32 | config_parameter.rf_size = 8 33 | config_parameter.antenna_size = 16 34 | config_parameter.vehicle_antenna_size = 16 35 | model = load_model(digital=False) 36 | model.load_weights(filepath='allmodel1/Keras_models_antenna16_onlycomm/new_model') 37 | return model 38 | 39 | 40 | sum_rate_list = [] 41 | crbd_list = [] 42 | crba_list = [] 43 | rf_size = [8,16,32] 44 | antennas = [16,32,64] 45 | if Test == "V2V": 46 | real_distance, real_theta = generate_input_v2v() 47 | elif Test == "V2I": 48 | real_distance, real_theta = generate_input_v2i() 49 | 50 | for i in range(len(antennas)): 51 | if i == 0: 52 | model = load_antenna_16() 53 | config_parameter.rf_size = 8 54 | config_parameter.antenna_size = 16 55 | config_parameter.vehicle_antenna_size = 16 56 | antenna_size = 16 57 | 58 | elif i == 1: 59 | model = load_antenna_32() 60 | config_parameter.rf_size = 16 61 | config_parameter.antenna_size = 32 62 | config_parameter.vehicle_antenna_size = 32 63 | antenna_size = 32 64 | 65 | elif i ==2: 66 | config_parameter.rf_size = 32 67 | config_parameter.antenna_size = 64 68 | config_parameter.vehicle_antenna_size = 64 69 | model = load_antenna_64() 70 | antenna_size = 64 71 | 72 | combined = loss.Conversion2input_small(real_theta.T[:40], real_distance.T[:40]) 73 | combined = tf.expand_dims(combined, axis=3) 74 | CSI = tf.complex(combined[:, :, 6 * antenna_size:7 * antenna_size, 0], 75 | combined[:, :, 7 * antenna_size:8 * antenna_size, 0]) 76 | steering_vector_this_o = tf.complex(combined[:, :, 0:antenna_size, 0], 77 | combined[:, :, antenna_size:2 * antenna_size, 0]) 78 | 79 | distance = combined[:, :, 3 * antenna_size:4 * antenna_size, 0] 80 | beta = loss.Reflection_coefficient(distance) 81 | theta = combined[:, :, 2 * antenna_size, 0] 82 | 83 | output1 = model(combined) 84 | analog1, digital1 = loss.tf_Output2PrecodingMatrix_rad(output1) 85 | precoder1 = loss.tf_Precoding_matrix_combine(analog1, digital1) 86 | sum_rate1_1, sinr = loss.tf_loss_sumrate(CSI, precoder1) 87 | sum_rate1_1 = tf.cast(sum_rate1_1, tf.float32) 88 | sum_rate_list.append(tf.math.log(tf.reduce_mean(sum_rate1_1)) / tf.math.log(2.0)) 89 | Sigma_time_delay1 = loss.tf_sigma_delay_square(steering_vector_this_o, precoder1, beta) 90 | CRB_d1 = tf.reduce_sum(loss.tf_CRB_distance(Sigma_time_delay1), axis=1) / 4 91 | crbd_list.append(tf.math.log(tf.reduce_mean(CRB_d1)) / tf.math.log(2.0)) 92 | CRB_angle1 = tf.reduce_sum(loss.tf_CRB_angle(beta, precoder1, theta), axis=1) / 4 93 | CRB_angle1 =tf.cast(CRB_angle1,tf.float32) 94 | crba_list.append(tf.math.log(tf.reduce_mean(CRB_angle1)) / tf.math.log(2.0)) 95 | 96 | fig, ax1 = plt.subplots() 97 | x = range(len(antennas)) 98 | mode = "crba" 99 | if mode == "sumrate": 100 | ax1.plot(x, sum_rate_list, 'b-.', label='hybrid ISAC') 101 | ax1.set_xlabel("number of antennas") 102 | ax1.set_ylabel('log2(sum rate(bits/s/hz))', color='b') 103 | ax1.tick_params('y', colors='b') 104 | _ = plt.xticks(x, antennas) 105 | 106 | elif mode == "crbd": 107 | ax1.set_xlabel("number of antennas") 108 | ax1.plot(x, crbd_list, 'b-.', label='hybrid ISAC') 109 | # ax2 = ax1.twinx() 110 | #ax1.plot(x, crbd2, 'm--', label='digital ISAC,with initial point') 111 | #ax1.plot(x, crbd3, 'r.-', label='digital ISAC,without initial point') 112 | # ax1.plot(range(10), sum_rate4, 'm:', label='hybrid only communication') 113 | # ax1.plot(range(10), sum_rate5, 'r-', label='digital with initial point only communication') 114 | # ax1.plot(range(10), sum_rate6, 'b-', label='digital without initial point only communication') 115 | #ax1.plot(x, crbd_list, 'g-', label='ZF precoder') 116 | ax1.set_ylabel('log2(CRB distance m\u00B2)', color='b') 117 | ax1.tick_params('y', colors='b') 118 | _ = plt.xticks(x, antennas) 119 | 120 | elif mode == "crba": 121 | ax1.set_xlabel("number of antennas") 122 | ax1.plot(x, crba_list, 'b-.', label='hybrid ISAC') 123 | ax1.set_ylabel('log2(CRB angle m\u00B2)', color='b') 124 | ax1.tick_params('y', colors='b') 125 | _ = plt.xticks(x, antennas) 126 | fig.tight_layout() 127 | 128 | # 添加图例 129 | #lines = [ax1.get_lines()[0], \ 130 | # ax1.get_lines()[1], \ 131 | # ax1.get_lines()[2], \ 132 | # ax1.get_lines()[3]] 133 | 134 | lines = [ax1.get_lines()[0]] 135 | labels = [line.get_label() for line in lines] 136 | labels =[] 137 | ax1.legend(lines,labels, bbox_to_anchor=(0.5, 0.6)) 138 | plt.show() 139 | -------------------------------------------------------------------------------- /others/Test_beamforming.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | import matplotlib.pyplot as plt 3 | import config_parameter 4 | from evaluation import generate_input_v2i 5 | import loss 6 | import loss_all 7 | import tensorflow as tf 8 | from Trainv2_4inputs import load_model 9 | import OnlyCommunication 10 | 11 | def translate_precoding_matrix(matrix): 12 | translated_matrix = np.empty(matrix.shape, dtype=np.complex128) 13 | 14 | for i in range(matrix.shape[0]): 15 | for j in range(matrix.shape[1]): 16 | element = matrix[i, j] 17 | magnitude = np.abs(element) 18 | phase_degrees = np.angle(element, deg=True) 19 | phase_radians = np.deg2rad(phase_degrees) 20 | 21 | translated_element = magnitude * np.exp(1j * phase_radians) 22 | translated_matrix[i, j] = translated_element 23 | 24 | return translated_matrix 25 | import math 26 | model = load_model() 27 | #model.load_weights(filepath='allmodel1/Keras_models_hybrid64/new_model') 28 | #model.load_weights(filepath='allmodel1/Keras_models_SVDcsi2/new_model') 29 | model.load_weights(filepath = 'allmodel1/Keras_models_rf24_onlycomm/new_model') 30 | if config_parameter.mode == "V2I": 31 | antenna_size = config_parameter.antenna_size 32 | num_vehicle = config_parameter.num_vehicle 33 | elif config_parameter.mode == "V2V": 34 | antenna_size = config_parameter.vehicle_antenna_size 35 | num_vehicle = config_parameter.num_uppercar + config_parameter.num_lowercar + config_parameter.num_horizoncar 36 | 37 | distance,angle = generate_input_v2i() 38 | angle = angle.T 39 | distance = distance.T 40 | selected_angle = angle[0:config_parameter.batch_size,:] 41 | selected_distance = distance[0:config_parameter.batch_size,:] 42 | input_single= loss.Conversion2input_small(selected_angle,selected_distance) 43 | input_single = tf.expand_dims(input_single, axis=3) 44 | 45 | 46 | print(input_single.shape) 47 | 48 | #input_single = tf.transpose(input_single,perm=[1,0,2,3]) 49 | 50 | 51 | output = model(input_single) 52 | antenna_size_f = tf.cast(antenna_size, tf.float32) 53 | # dont forget here we are inputing a whole batch 54 | G = tf.math.sqrt(antenna_size_f) 55 | distance = input_single[:, :, 3 * antenna_size:4*antenna_size, 0] 56 | distance = tf.multiply(distance, 100) 57 | distance = tf.cast(distance, tf.float64) 58 | rf_size = config_parameter.rf_size 59 | #analog_rad = tf.concat([input_single[:, :, 8 * antenna_size:9 * antenna_size, 0], \ 60 | # input_single[:, :2, 9 * antenna_size:10 * antenna_size, 0]], axis=1) # (4,16) 61 | # analog_rad = tf.complex(input[:,0:config_parameter.rf_size,8*antenna_size:9*antenna_size,0],\ 62 | # input[:,0:config_parameter.rf_size,9*antenna_size:10*antenna_size,0])#(4,16) 63 | #digital_ref = tf.complex(input_single[:, :, \ 64 | # 4 * antenna_size:4 * antenna_size + rf_size, 0], \ 65 | # input_single[:, :, 5 * antenna_size:5 * antenna_size + rf_size, 0]) 66 | #Analog_matrix, Digital_matrix = loss.tf_Output2PrecodingMatrix_rad_mod(Output=output, \ 67 | # analog_ref=tf.transpose(analog_rad, 68 | # perm=[0, 2, 1]), \ 69 | # digital_ref=tf.transpose(digital_ref, 70 | # perm=[0, 2, 1])) 71 | #precoding_matrix = loss.tf_Output2digitalPrecoding(Output=output, zf_matrix=None,distance=None) 72 | Analog_matrix,Digital_matrix = loss.tf_Output2PrecodingMatrix_rad(Output=output) 73 | precoding_matrix = loss.tf_Precoding_matrix_combine(Analog_matrix, Digital_matrix) 74 | #Analog_matrix, Digital_matrix = loss.tf_Output2PrecodingMatrix_rad_mod(Output=output, analog_ref=analog_rad,digital_ref=digital_ref) 75 | #Analog_matrix, Digital_matrix = loss.tf_Output2PrecodingMatrix_rad(Output=output) 76 | zf_precoding = tf.complex(input_single[:, :, 4 * antenna_size:5 * antenna_size, 0], 77 | input_single[:, :, 5 * antenna_size:6 * antenna_size, 0]) 78 | #precoding_matrix = loss.tf_Precoding_matrix_combine(Analog_matrix=Analog_matrix, Digital_matrix=Digital_matrix) 79 | 80 | #precoding_matrix = loss.tf_Precoding_matrix_comb_Powerallocated(Analog_matrix, Digital_matrix,distance[:,:,0]) 81 | #precoding_matrix = loss.tf_Output2digitalPrecoding(Output=output, zf_matrix=zf_precoding,distance=distance[:,:,0]) 82 | #print("Analog_matrix",Analog_matrix[3]) 83 | #print("Digital_matrix",Digital_matrix[3]) 84 | 85 | #precoding_matrix = loss.tf_Output2digitalPrecoding(Output=output, zf_matrix=zf_precoding) 86 | print("beamforming",precoding_matrix) 87 | 88 | #print("theta",input_single[0,:,8*antenna_size+1,0]) 89 | #print("real distance",input_single[0,:,9*antenna_size+1,0]) 90 | 91 | ''' 92 | steering_vector_this = tf.complex(input_single[0,-1,:,0:antenna_size], input_single[0,-1,:,antenna_size:2*antenna_size]) 93 | steering_vector_this = tf.reshape(steering_vector_this, (antenna_size, num_vehicle)) 94 | steering_hermite = tf.transpose(tf.math.conj(steering_vector_this)) 95 | pathloss = loss.tf_Path_loss(input_single[0, -1, :, 0]) 96 | pathloss = tf.expand_dims(pathloss, axis=1) 97 | pathloss = tf.broadcast_to(pathloss, tf.shape(steering_hermite)) 98 | CSI = tf.multiply(tf.cast(tf.multiply(G, pathloss), dtype=tf.complex128), steering_hermite) 99 | 100 | 101 | # Example beamforming matrix and channel matrix 102 | #beamforming_matrix = np.random.randn(8, 4) + 1j * np.random.randn(8, 4) 103 | #channel_matrix = np.random.randn(4, 6) + 1j * np.random.randn(4, 6) 104 | 105 | ''' 106 | #sv = loss. 107 | idx = np.arange(antenna_size) 108 | angle_set = np.arange(1, 181) / 180 * np.pi 109 | Hset = np.exp(1j * np.pi * idx.reshape(-1, 1) * np.cos(angle_set)) 110 | 111 | #zf_matrix = tf.complex(input_single[0,:,4*antenna_size:5*antenna_size,0], input_single[0,:,5*antenna_size:6*antenna_size,0]) 112 | print(input_single[0,-1,:,0]) 113 | print(Hset.shape) 114 | #print("zf_matrix",zf_matrix.numpy()) 115 | 116 | precoding_matrix = precoding_matrix.numpy() 117 | #x = np.exp(1j * np.pi * idx * np.cos((30/180)*np.pi)).T.reshape(8,1) 118 | #print(x.shape) 119 | #x_hermite=np.transpose(np.conj(x)) 120 | #precoding_matrix =translate_precoding_matrix(precoding_matrix) 121 | precoding_matrix_hermite = np.transpose(np.conj(precoding_matrix)) 122 | Hset_hermite = np.transpose(np.conj(Hset)) 123 | 124 | print("precoding",precoding_matrix[8,:,:]) 125 | #r2 = np.dot(precoding_matrix_hermite, Hset_hermite.T) 126 | zf_matrix = tf.transpose(zf_precoding,perm=[0,2,1]) 127 | #r1 = np.dot(Hset.T, zf_precoding.numpy()[0].T) 128 | r1 = np.dot(Hset.T, precoding_matrix[0,:,:]) 129 | print("r90", r1[28:35]) 130 | 131 | #r = np.dot(r1,r2) 132 | plt.polar(angle_set, np.abs(r1)) 133 | plt.show() 134 | #r0 = np.dot(Hset.T, precoding_matrix[:,0]) 135 | #print("r90",r1[28:35]) 136 | #plt.polar(angle_set, np.abs(r0)) 137 | #plt.show() 138 | # Compute the beam pattern 139 | ''' 140 | beam_pattern = np.abs(np.matmul(precoding_matrix, CSI)) 141 | # Compute the average magnitude for each antenna 142 | average_magnitude = np.mean(beam_pattern, axis=1) 143 | theta = np.linspace(0, 2 * np.pi, len(average_magnitude), endpoint=False) 144 | average_magnitude = np.concatenate((average_magnitude, [average_magnitude[0]])) # Add the first element to the end 145 | theta = np.concatenate((theta, [theta[0]])) 146 | 147 | 148 | ax = plt.subplot(111, polar=True) 149 | ax.plot(theta, average_magnitude) 150 | ax.set_title('Antenna Pattern') 151 | ax.text(0, np.max(average_magnitude) * 1.1, 'Distance: {},Angel:{}'.format(input_single[0,-1,:,2*antenna_size],input_single[0,-1,:,3*antenna_size]), ha='center') 152 | 153 | plt.show() 154 | ''' -------------------------------------------------------------------------------- /others/Test_function.py: -------------------------------------------------------------------------------- 1 | "This file contains all the test cases for the functions in the project" 2 | import random 3 | from math import cos, sqrt,pi,sin 4 | import numpy as np 5 | import cmath 6 | import config_parameter 7 | from scipy.signal import correlate 8 | from scipy.optimize import fmin_bfgs 9 | from scipy import signal 10 | import tensorflow as tf 11 | import loss 12 | import matplotlib.pyplot as plt 13 | antenna_size = 16 14 | def Test_sigma_delay(steering_vector_h,precoding_matrix_c,beta): 15 | sigma = loss.tf_sigma_delay_square(steering_vector_h, precoding_matrix_c, beta) 16 | return sigma 17 | def Test_steering_vector_generation(angle,distance): 18 | theta = angle.T 19 | real_distance = distance.T 20 | if config_parameter.mode == "V2I": 21 | antenna_size = config_parameter.antenna_size 22 | num_vehicle = config_parameter.num_vehicle 23 | elif config_parameter.mode == "V2V": 24 | antenna_size = config_parameter.vehicle_antenna_size 25 | num_vehicle = config_parameter.num_uppercar + config_parameter.num_lowercar + config_parameter.num_horizoncar 26 | num_sample = theta.shape[1] 27 | steering_vector = np.zeros((num_sample, num_vehicle, antenna_size,), dtype=complex) 28 | pathloss = np.zeros((num_sample,num_vehicle,antenna_size)) 29 | beta = np.zeros((num_sample,num_vehicle,antenna_size),dtype=complex) 30 | 31 | for i in range(antenna_size): 32 | for j in range(num_vehicle): 33 | for m in range(num_sample): 34 | steering_vector[m][j][i] = np.exp(-1j * np.pi * i * np.cos(theta[j][m])) 35 | pathloss[m][j][i] = loss.Path_loss(real_distance[j,m]) 36 | beta[m][j][i] = loss.Reflection_coefficient(real_distance[j,m]) 37 | #print("steering_vector",steering_vector) 38 | print("pathloss",pathloss) 39 | print("beta",beta) 40 | print("beta",beta.shape) 41 | return steering_vector,pathloss,beta 42 | def Test_CSI_generation(steering_vector,path_loss): 43 | if config_parameter.mode == "V2I": 44 | antenna_size = config_parameter.antenna_size 45 | num_vehicle = config_parameter.num_vehicle 46 | elif config_parameter.mode == "V2V": 47 | antenna_size = config_parameter.vehicle_antenna_size 48 | num_vehicle = config_parameter.num_uppercar + config_parameter.num_lowercar + config_parameter.num_horizoncar 49 | 50 | CSI_o = np.multiply(path_loss, np.conjugate(steering_vector)) 51 | CSI = sqrt(antenna_size) * CSI_o 52 | print("CSI",CSI) 53 | return CSI 54 | 55 | 56 | def Test_sumrate(CSI,precoding_matrix): 57 | sum_rate=loss.tf_loss_sumrate(CSI, precoding_matrix) 58 | print("sum_rate",sum_rate) 59 | print("sum_rate",sum_rate.numpy()) 60 | def test_pathloss(distance): 61 | result1 = loss.Path_loss(distance) 62 | result2 = loss.tf_Path_loss(distance) 63 | print("result1",result1) 64 | print("result2",result2.numpy()) 65 | print(result1==result2.numpy()) 66 | def Test_svd(): 67 | real_part = np.random.randint(low=-10, high=10, size=(8, 4)) 68 | imaginary_part = np.random.randint(low=-10, high=10, size=(8, 4)) 69 | random.seed(1) 70 | # Create the complex matrix 71 | complex_matrix = real_part + 1j * imaginary_part 72 | matrix_rad = np.angle(complex_matrix) 73 | complex_matrix_norm = np.exp(1j*matrix_rad) 74 | # Print the complex matrix 75 | print("complex_matrix",complex_matrix) 76 | print("complex_matrix_rad",matrix_rad) 77 | # Perform SVD 78 | analog_precoder, digital_precoder = loss.svd_zf(complex_matrix_norm) 79 | print("analog_precoder",analog_precoder) 80 | print("digital_precoder",digital_precoder) 81 | reconstruct = np.dot(analog_precoder, digital_precoder) 82 | reconstruct_rad = np.angle(reconstruct) 83 | print("reconstruct",reconstruct_rad) 84 | print("error_rad",matrix_rad-reconstruct_rad) 85 | print("error",np.exp(1j*matrix_rad)-reconstruct) 86 | 87 | return complex_matrix,complex_matrix_norm,reconstruct,reconstruct_rad 88 | ''' 89 | angle,distance = loss.load_data() 90 | selected_angle = angle[0:4,:] 91 | selected_distance = distance[0:4,:] 92 | precoding_matrix = loss.simple_precoder(selected_angle.T,selected_distance.T) 93 | CSI= np.zeros((4,4,8),dtype=complex) 94 | print(CSI.shape) 95 | for i in range(4): 96 | #cosangle = np.cos(np.pi*cos(selected_angle[i])) 97 | print("selected_angle",selected_angle[i]) 98 | print("selected_angle",np.cos(selected_angle[i])) 99 | print("selected_angle",np.cos(np.pi*np.cos(selected_angle[i]))) 100 | CSI[i] = loss.calculate_steer_vector(selected_angle[i]).T 101 | print("csi",CSI) 102 | CSI_o = np.multiply(5,CSI) 103 | print("csi111111",CSI_o) 104 | Test_sumrate(CSI,precoding_matrix) 105 | ''' 106 | #angle = np.array([[0.1,0.2,0.1,0.2],[0.2,0.3,0.2,0.3],[0.7,0.8,0.7,0.8],[0.8,0.9,0.8,0.9]]) 107 | #angle = np.array([[0.1,0.2,0.1,0.2],[0.2,0.5,0.2,0.5]]) 108 | #distance = np.array([[50,50,100,100],[100,100,200,200],[60,120,60,120],[120,60,120,60]]) 109 | #distance = np.array([[50,20,200,100],[10,20,200,400]]) 110 | #print(distance.shape) 111 | #print(angle.shape) 112 | angle,distance = loss.load_data() 113 | selected_angle = angle[0:4,:] 114 | selected_distance = distance[0:4,:] 115 | input_single = loss.Conversion2input_small(selected_angle,selected_distance) 116 | steering_vector,path_loss,beta=Test_steering_vector_generation(selected_angle,selected_distance) 117 | print("steering_vector",steering_vector) 118 | print("path_loss",path_loss) 119 | print("beta1",beta) 120 | #steering_vector=np.array([[[1+1j,2+2j],[5+5j,6+6j], [2,2],[5,6]],[[1+1j,2+2j],[3+3j,4+4j],[5+5j,6+6j],[7+7j,8+8j]]]) 121 | #precoding_matrix=np.array([[[1,2,3,4],[5,10,20,30]],[[40,50,15,20],[15,30,5,6]],[15,20]],[[15,20],[15,30],[5,6],[15,20]]]) 122 | CSI = Test_CSI_generation(steering_vector,path_loss) 123 | input_single = np.expand_dims(input_single, axis=3) 124 | CSI = tf.complex(input_single[:, :, 6*antenna_size:7*antenna_size, 0], input_single[:, :, 7*antenna_size:8 * antenna_size, 0]) 125 | zf_precoding_matrix = loss.zero_forcing(CSI) 126 | zf_precoding_matrix = tf.complex(input_single[:, :, 4*antenna_size:5*antenna_size, 0], input_single[:, :, 5*antenna_size:6 * antenna_size, 0]) 127 | print("zf_precoding_matrix",zf_precoding_matrix) 128 | print("csi",CSI) 129 | steering_vector = tf.complex(input_single[:, :, 0*antenna_size:1*antenna_size, 0], input_single[:, :, 1*antenna_size:2 * antenna_size, 0]) 130 | #precoding_matrix = abs(loss.simple_precoder(angle.T,distance.T)) 131 | #print("precoding_matrix1",precoding_matrix) 132 | #partial = loss.tf_Echo_partial(beta,zf_precoding_matrix,angle) 133 | distance = input_single[:, :, 3 * antenna_size:4 * antenna_size, 0] 134 | beta = loss.Reflection_coefficient(distance) 135 | sigma = Test_sigma_delay(steering_vector,precoding_matrix_c=tf.transpose(zf_precoding_matrix,perm=[0,2,1]), beta=beta) 136 | crb_d = loss.tf_CRB_distance(sigma) 137 | 138 | print("sigma",sigma) 139 | print("crb_d",crb_d) 140 | #print(test_pathloss(1)) 141 | ''' 142 | complex_matrix,complex_matrix_norm,reconstruct,reconstruct_rad=Test_svd() 143 | idx = np.arange(8) 144 | angle_set = np.arange(1, 361) / 180 * np.pi 145 | Hset = np.exp(-1j * np.pi * idx.reshape(-1, 1) * np.cos(angle_set)) 146 | r1 = np.dot(Hset.T, complex_matrix_norm) 147 | r2 = np.dot(Hset.T, reconstruct) 148 | print("r90", r1[28:35]) 149 | 150 | # r = np.dot(r1,r2) 151 | plt.polar(angle_set, np.abs(r2)) 152 | plt.show() 153 | ''' 154 | ''' 155 | angle = np.array([[0.1,0.2,0.1,0.2],[0.2,0.3,0.2,0.3],[0.7,0.8,0.7,0.8],[0.8,0.9,0.8,0.9]]) 156 | 157 | distance = np.array([[50,50,100,100],[100,100,200,200],[60,120,60,120],[120,60,120,60]]) 158 | print(distance.shape) 159 | print(angle.shape) 160 | steering_vector,path_loss,beta=Test_steering_vector_generation(angle,distance) 161 | print("s2",steering_vector[1,1]) 162 | print(np.exp(-1j * np.pi * 1 * np.cos(0.3))) 163 | print(np.exp(-1j * np.pi * 2 * np.cos(0.3))) 164 | random.seed(1) 165 | precoding_matrix = np.random.randn(4, 8, 4) + 1j * np.random.randn(4, 8, 4) 166 | print(precoding_matrix) 167 | CSI=Test_CSI_generation(steering_vector,path_loss) 168 | 169 | #csi shape(batch,num vehicle,antenna_size) precoding_matrix shape(batch,antenna_size,num vehicle) 170 | CSI=np.array([[[1+1j,2+2j,3+3j,4+4j],[5+5j,6+6j,7+7j,8+8j]], [[2,2,5,5],[5,6,7,8]],[[1+1j,2+2j,3+3j,4+4j],[5+5j,6+6j,7+7j,8+8j]]]) 171 | precoding_matrix=np.array([[[1,2],[5,10],[20,30],[40,50]],[[15,20],[15,30],[5,6],[15,20]],[[15,20],[15,30],[5,6],[15,20]]]) 172 | print(CSI.shape) 173 | print(precoding_matrix.shape) 174 | Test_sumrate(CSI,precoding_matrix) 175 | print("--------------------Test SVD---------------------") 176 | A = np.random.rand(8, 4) + 1j * np.random.rand(8, 4) 177 | analog, digital = loss.svd_zf(A) 178 | print(A) 179 | print(analog*digital) 180 | ''' -------------------------------------------------------------------------------- /evaluation_different_rf_antenna.py: -------------------------------------------------------------------------------- 1 | import random 2 | 3 | import loss 4 | import numpy as np 5 | import config_parameter 6 | import math 7 | import tensorflow as tf 8 | from network import DL_method_NN_for_v2x_mod, DL_method_NN_for_v2x_hybrid 9 | import matplotlib.pyplot as plt 10 | from evaluation_simultaneously import generate_input_v2i, generate_input_v2v, \ 11 | load_model, load_model_hybrid_combine, load_model_digitalwith_combine, \ 12 | load_model_digitalwithout_combine, load_model_only_communication_hybrid, \ 13 | load_model_only_communication_digitalwith, load_model_only_communication_digitalwithout 14 | Test = 'V2I' 15 | rf_size = [8,16,32] 16 | config_parameter.vehicle_antenna_size = 32 17 | config_parameter.antenna_size = 32 18 | #weight = [1,40,1e7] 19 | def load_model_8(): 20 | config_parameter.rf_size = 8 21 | 22 | model = load_model(digital=False) 23 | model.load_weights(filepath='allmodel1/Keras_models_rf8_combine/new_model') 24 | return model 25 | def load_model_16(): 26 | config_parameter.rf_size = 16 27 | model = load_model(digital=False) 28 | model.load_weights(filepath='allmodel1/Keras_models_rf16_combine/new_model') 29 | return model 30 | def load_model_24(): 31 | config_parameter.rf_size = 24 32 | model = load_model(digital=False) 33 | model.load_weights(filepath='allmodel1/Keras_models_rf24_combine/new_model') 34 | return model 35 | def load_antenna_32(): 36 | config_parameter.antenna_size = 32 37 | config_parameter.vehicle_antenna_size = 32 38 | model = load_model() 39 | model.load_weights(filepath='allmodel1/Keras_models_antenna32_combine/new_model') 40 | return model 41 | def load_antenna_64(): 42 | config_parameter.antenna_size = 64 43 | config_parameter.vehicle_antenna_size = 64 44 | model = load_model() 45 | model.load_weights(filepath='allmodel1/Keras_models_antenna64_combine/new_model') 46 | return model 47 | def load_antenna_128(): 48 | config_parameter.antenna_size = 128 49 | config_parameter.vehicle_antenna_size = 128 50 | model = load_model() 51 | model.load_weights(filepath='allmodel1/Keras_models_antenna128_combine/new_model') 52 | return model 53 | 54 | 55 | def comparison(combined,CSI, distance, beta, theta, steering_vector_this_o, 56 | mode): 57 | 58 | rf_size = [8, 16, 24] 59 | #num_vehicle = [1, 2, 3, 4] 60 | model1 = load_model_8() 61 | model2 = load_model_16() 62 | model3 = load_model_24() 63 | 64 | sum_rate_list = [] 65 | crbd_list = [] 66 | crba_list = [] 67 | 68 | config_parameter.rf_size = 8 69 | output1 = model1(combined) 70 | analog1, digital1 = loss.tf_Output2PrecodingMatrix_rad(output1) 71 | precoder1 = loss.tf_Precoding_matrix_combine(analog1, digital1) 72 | sum_rate1_1, sinr = loss.tf_loss_sumrate(CSI, precoder1) 73 | sum_rate1_1 = tf.cast(sum_rate1_1, tf.float32) 74 | sum_rate_list.append(tf.math.log(tf.reduce_mean(sum_rate1_1)) / tf.math.log(2.0)) 75 | Sigma_time_delay1 = loss.tf_sigma_delay_square(steering_vector_this_o, precoder1, beta) 76 | CRB_d1 = tf.reduce_sum(loss.tf_CRB_distance(Sigma_time_delay1), axis=1) / 4 77 | crbd_list.append(tf.math.log(tf.reduce_mean(CRB_d1)) / tf.math.log(2.0)) 78 | CRB_angle1 = tf.reduce_sum(loss.tf_CRB_angle(beta, precoder1, theta), axis=1) / 4 79 | CRB_angle1 =tf.cast(CRB_angle1,tf.float32) 80 | crba_list.append(tf.math.log(tf.reduce_mean(CRB_angle1)) / tf.math.log(2.0)) 81 | 82 | 83 | 84 | config_parameter.rf_size = 16 85 | output2 = model2(combined) 86 | analog2, digital2 = loss.tf_Output2PrecodingMatrix_rad(output2) 87 | precoder2 = loss.tf_Precoding_matrix_combine(analog2, digital2) 88 | sum_rate1_2, sinr = loss.tf_loss_sumrate(CSI, precoder2) 89 | sum_rate1_2 = tf.cast(sum_rate1_2, tf.float32) 90 | sum_rate_list.append(tf.math.log(tf.reduce_mean(sum_rate1_2)) / tf.math.log(2.0)) 91 | Sigma_time_delay2 = loss.tf_sigma_delay_square(steering_vector_this_o, precoder2, beta) 92 | CRB_d2 = tf.reduce_sum(loss.tf_CRB_distance(Sigma_time_delay2), axis=1) / 4 93 | crbd_list.append(tf.math.log(tf.reduce_mean(CRB_d2)) / tf.math.log(2.0)) 94 | CRB_angle2 = tf.reduce_sum(loss.tf_CRB_angle(beta, precoder2, theta), axis=1) / 4 95 | CRB_angle2 = tf.cast(CRB_angle2, tf.float32) 96 | crba_list.append(tf.math.log(tf.reduce_mean(CRB_angle2)) / tf.math.log(2.0)) 97 | 98 | 99 | 100 | 101 | config_parameter.rf_size = 24 102 | output3 = model3(combined) 103 | analog3, digital3 = loss.tf_Output2PrecodingMatrix_rad(output3) 104 | precoder3 = loss.tf_Precoding_matrix_combine(analog3, digital3) 105 | sum_rate1_3, sinr = loss.tf_loss_sumrate(CSI, precoder3) 106 | sum_rate1_3 = tf.cast(sum_rate1_3, tf.float32) 107 | sum_rate_list.append(tf.math.log(tf.reduce_mean(sum_rate1_3)) / tf.math.log(2.0)) 108 | Sigma_time_delay2 = loss.tf_sigma_delay_square(steering_vector_this_o, precoder2, beta) 109 | CRB_d2 = tf.reduce_sum(loss.tf_CRB_distance(Sigma_time_delay2), axis=1) / 4 110 | crbd_list.append(tf.math.log(tf.reduce_mean(CRB_d2)) / tf.math.log(2.0)) 111 | CRB_angle3 = tf.reduce_sum(loss.tf_CRB_angle(beta, precoder3, theta), axis=1) / 4 112 | CRB_angle3 = tf.cast(CRB_angle3, tf.float32) 113 | crba_list.append(tf.math.log(tf.reduce_mean(CRB_angle3)) / tf.math.log(2.0)) 114 | 115 | fig, ax1 = plt.subplots() 116 | x = range(len(rf_size)) 117 | if mode == "sumrate": 118 | ax1.plot(x, sum_rate_list, 'b-.', label='hybrid ISAC') 119 | # ax2 = ax1.twinx() 120 | #ax1.plot(x, sum_rate2, 'm--', label='digital ISAC,with initial point') 121 | #ax1.plot(x, sum_rate3, 'r.-', label='digital ISAC,without initial point') 122 | # ax1.plot(range(10), sum_rate4, 'm:', label='hybrid only communication') 123 | # ax1.plot(range(10), sum_rate5, 'r-', label='digital with initial point only communication') 124 | # ax1.plot(range(10), sum_rate6, 'b-', label='digital without initial point only communication') 125 | #ax1.plot(x, sum_rate7, 'g-', label='ZF precoder') 126 | ax1.set_xlabel("number of rf chains") 127 | ax1.set_ylabel('log2(sum rate(bits/s/hz))', color='b') 128 | ax1.tick_params('y', colors='b') 129 | _ = plt.xticks(x, rf_size) 130 | elif mode == "crba": 131 | ax1.set_xlabel("number of rf chains") 132 | ax1.plot(x, crba_list, 'b-.', label='hybrid ISAC') 133 | # ax2 = ax1.twinx() 134 | #ax1.plot(x, crba2, 'm--', label='digital ISAC,with initial point') 135 | #ax1.plot(x, crba3, 'r.-', label='digital ISAC,without initial point') 136 | # ax1.plot(range(10), sum_rate4, 'm:', label='hybrid only communication') 137 | # ax1.plot(range(10), sum_rate5, 'r-', label='digital with initial point only communication') 138 | # ax1.plot(range(10), sum_rate6, 'b-', label='digital without initial point only communication') 139 | #ax1.plot(x, crba7, 'g-', label='ZF precoder') 140 | 141 | ax1.set_ylabel('log2(CRB angle rad\u00B2)', color='b') 142 | ax1.tick_params('y', colors='b') 143 | _ = plt.xticks(x, rf_size) 144 | elif mode == "crbd": 145 | ax1.set_xlabel("number of rf chains") 146 | ax1.plot(x, crbd_list, 'b-.', label='hybrid ISAC') 147 | # ax2 = ax1.twinx() 148 | #ax1.plot(x, crbd2, 'm--', label='digital ISAC,with initial point') 149 | #ax1.plot(x, crbd3, 'r.-', label='digital ISAC,without initial point') 150 | # ax1.plot(range(10), sum_rate4, 'm:', label='hybrid only communication') 151 | # ax1.plot(range(10), sum_rate5, 'r-', label='digital with initial point only communication') 152 | # ax1.plot(range(10), sum_rate6, 'b-', label='digital without initial point only communication') 153 | #ax1.plot(x, crbd_list, 'g-', label='ZF precoder') 154 | ax1.set_ylabel('log2(CRB distance m\u00B2)', color='b') 155 | ax1.tick_params('y', colors='b') 156 | _ = plt.xticks(x, rf_size) 157 | fig.tight_layout() 158 | 159 | # 添加图例 160 | #lines = [ax1.get_lines()[0], \ 161 | # ax1.get_lines()[1], \ 162 | # ax1.get_lines()[2], \ 163 | # ax1.get_lines()[3]] 164 | 165 | lines = [ax1.get_lines()[0]] 166 | labels = [line.get_label() for line in lines] 167 | labels =[] 168 | ax1.legend(lines,labels, bbox_to_anchor=(0.5, 0.6)) 169 | plt.show() 170 | 171 | #random.seed(2) 172 | if Test == "V2V": 173 | real_distance, real_theta = generate_input_v2v() 174 | elif Test == "V2I": 175 | real_distance, real_theta = generate_input_v2i() 176 | 177 | antenna_size = 32 178 | 179 | config_parameter.antenna_size = 32 180 | #combined = loss.Conversion2CSI(real_distance, real_theta)P 181 | combined = loss.Conversion2input_small(real_theta.T[:40], real_distance.T[:40]) 182 | combined = tf.expand_dims(combined, axis=3) 183 | CSI = tf.complex(combined[:, :, 6 * antenna_size:7 * antenna_size, 0], 184 | combined[:, :, 7 * antenna_size:8 * antenna_size, 0]) 185 | steering_vector_this_o = tf.complex(combined[:, :, 0:antenna_size, 0], 186 | combined[:, :, antenna_size:2 * antenna_size, 0]) 187 | 188 | distance = combined[:, :, 3 * antenna_size:4 * antenna_size, 0] 189 | beta = loss.Reflection_coefficient(distance) 190 | 191 | theta = combined[:, :, 2 * antenna_size, 0] 192 | mode = "crbd" 193 | comparison(combined,CSI, distance, beta, theta, steering_vector_this_o, mode) -------------------------------------------------------------------------------- /others/withinitialpoint.py: -------------------------------------------------------------------------------- 1 | """ 2 | In this file, we want to input transmitsteering vector,distance and angle 3 | 4 | """ 5 | 6 | from __future__ import absolute_import, division, print_function 7 | import tensorflow as tf 8 | 9 | import math 10 | import sys 11 | import loss 12 | import config_parameter 13 | 14 | sys.path.append("..") 15 | import matplotlib.pyplot as plt 16 | 17 | from network import DL_method_NN_for_v2x_hybrid, DL_method_NN_for_v2x_mod,DL_method_NN_for_v2x_hybrid2 18 | from config_parameter import iters 19 | 20 | sys.path.append("..") 21 | import numpy as np 22 | 23 | 24 | # tf.compat.v1.enable_eager_execution() 25 | def load_model(): 26 | # model = DL_method_NN_for_v2x_mod() 27 | model = DL_method_NN_for_v2x_hybrid2() 28 | # model = ResNet() 29 | # model = ResNetLSTMModel() 30 | num_vehicle = config_parameter.num_uppercar + config_parameter.num_lowercar + config_parameter.num_horizoncar 31 | 32 | model.build(input_shape=(None, num_vehicle, 160, 1)) 33 | 34 | model.summary() 35 | if config_parameter.FurtherTrain == True: 36 | # model = tf.saved_model.load('Keras_models/new_model') 37 | model.load_weights(filepath='Keras_models_digital_onlycommunication/new_model') 38 | return model 39 | 40 | 41 | if __name__ == '__main__': 42 | writer = tf.summary.create_file_writer("log.txt") 43 | if config_parameter.mode == "V2I": 44 | antenna_size = config_parameter.antenna_size 45 | num_vehicle = config_parameter.num_vehicle 46 | elif config_parameter.mode == "V2V": 47 | antenna_size = config_parameter.vehicle_antenna_size 48 | num_vehicle = config_parameter.num_uppercar + config_parameter.num_lowercar + config_parameter.num_horizoncar 49 | print(tf.__version__) 50 | 51 | Antenna_Gain = math.sqrt(antenna_size * config_parameter.receiver_antenna_size) 52 | c = config_parameter.c 53 | # GPU settings 54 | gpus = tf.config.experimental.list_physical_devices('GPU') 55 | print(gpus) 56 | 57 | # if gpus: 58 | # for gpu in gpus: 59 | # tf.config.experimental.set_memory_growth(gpu, True) 60 | # optimizer_1 = tf.keras.optimizers.Adam(learning_rate=0.003,beta_1 = 0.91,beta_2 = 0.99) 61 | # optimizer_1 = tf.keras.optimizers.Adagrad(learning_rate=0.004) 62 | ''' 63 | optimizer_1 = tf.keras.optimizers.Adagrad( 64 | learning_rate=0.01, 65 | initial_accumulator_value=0.1, 66 | epsilon=1e-07, 67 | name="Adagrad" 68 | ) 69 | ''' 70 | model = load_model() 71 | 72 | 73 | # profiler = tf.profiler.experimental.Profiler(tf.profiler.experimental.ProfilerOptions(host_tracer_level=2)) 74 | @tf.function # means not eager mode. graph mode 75 | def train_step(input, portions): 76 | # input shape(1,10,3,32) 77 | with tf.GradientTape() as tape: 78 | if config_parameter.mode == "V2I": 79 | antenna_size = config_parameter.antenna_size 80 | num_vehicle = config_parameter.num_vehicle 81 | elif config_parameter.mode == "V2V": 82 | antenna_size = config_parameter.vehicle_antenna_size 83 | num_vehicle = config_parameter.num_uppercar + config_parameter.num_lowercar + config_parameter.num_horizoncar 84 | 85 | output = model(input) 86 | portions = tf.cast(portions, tf.float64) 87 | rf_size = config_parameter.rf_size 88 | analog_rad = tf.concat([input[:,:,8*antenna_size:9*antenna_size,0],\ 89 | input[:,:2,9*antenna_size:10*antenna_size,0]],axis=1)#(4,16) 90 | #analog_rad = tf.complex(input[:,0:config_parameter.rf_size,8*antenna_size:9*antenna_size,0],\ 91 | # input[:,0:config_parameter.rf_size,9*antenna_size:10*antenna_size,0])#(4,16) 92 | digital_ref = tf.complex(input[:,:,\ 93 | 4*antenna_size:4*antenna_size+rf_size,0], \ 94 | input[:,:,5*antenna_size:5*antenna_size+rf_size,0])#(4,6) also transposed 95 | distance = input[:, :, 3 * antenna_size:4 * antenna_size, 0] 96 | # distance = tf.multiply(distance, 100) 97 | distance = tf.cast(distance, tf.float64) 98 | theta = input[:, :, 2 * antenna_size, 0] 99 | steering_vector_this_o = tf.complex(input[:, :, 0:antenna_size, 0], 100 | input[:, :, antenna_size:2 * antenna_size, 0]) 101 | # steering_vector_this = tf.transpose(steering_vector_this_o, perm=[0, 2, 1]) 102 | pathloss = loss.tf_Path_loss(distance) 103 | beta = loss.Reflection_coefficient(distance) 104 | 105 | num_vehicle_f = tf.cast(num_vehicle, tf.float32) 106 | antenna_size_f = tf.cast(antenna_size, tf.float32) 107 | # dont forget here we are inputing a whole batch 108 | G = tf.math.sqrt(antenna_size_f) 109 | CSI = tf.multiply(tf.cast(tf.multiply(G, pathloss), dtype=tf.complex128), steering_vector_this_o) 110 | CSI = tf.complex(input[:, :, 6 * antenna_size:7 * antenna_size, 0], 111 | input[:, :, 7 * antenna_size:8 * antenna_size, 0]) 112 | # zf_matrix = loss.tf_zero_forcing(CSI) 113 | 114 | shape = tf.shape(input) 115 | 116 | batch_size = shape[0] 117 | #Analog_matrix, Digital_matrix = loss.tf_Output2PrecodingMatrix_rad(Output=output) 118 | Analog_matrix, Digital_matrix = loss.tf_Output2PrecodingMatrix_rad_mod(Output=output,\ 119 | analog_ref=tf.transpose(analog_rad,perm=[0,2,1]),\ 120 | digital_ref=tf.transpose(digital_ref,perm=[0,2,1])) 121 | 122 | #precoding_matrix = loss.tf_Precoding_matrix_combine(Analog_matrix, Digital_matrix) 123 | ## 124 | # 125 | # 126 | precoding_matrix = loss.tf_Precoding_matrix_comb_Powerallocated(Analog_matrix, Digital_matrix,distance[:,:,0]) 127 | ## 128 | # # 129 | # precoding_matrix = loss.tf_Precoding_comb_no_powerconstarint(Analog_matrix, Digital_matrix) 130 | zf_matrix = tf.complex(input[:, :, 4 * antenna_size:5 * antenna_size, 0], 131 | input[:, :, 5 * antenna_size:6 * antenna_size, 0]) 132 | #precoding_matrix = loss.tf_Output2digitalPrecoding(output, zf_matrix, distance[:, :, 0]) 133 | pathloss = loss.tf_Path_loss(input[:, :, 2 * antenna_size, 0]) 134 | # below is the real right steering vector 135 | steering_vector_this = tf.transpose(steering_vector_this_o, perm=[0, 2, 1]) 136 | # CSI = tf.complex(input[:,:,2*antenna_size:3*antenna_size,0], input[:,:,3*antenna_size:4*antenna_size,0]) 137 | # CSi here shape is (BATCH,NUMVEHICLE,ANTENNAS) 138 | 139 | # Analog_matrix, Digital_matrix = loss.tf_Output2PrecodingMatrix_rad(Output=output,zf_matrix=zf_matrix) 140 | # precoding_matrix = loss.tf_Precoding_matrix_combine(Analog_matrix, Digital_matrix) 141 | zf_sumrate, zf_sinr = loss.tf_loss_sumrate(CSI, tf.transpose(zf_matrix, perm=[0, 2, 1])) 142 | # zf_sumrate, zf_sinr = loss.tf_loss_sumrate(CSI, zf_matrix) 143 | # sigma_doppler = loss.tf 144 | # steering_hermite = tf.transpose(tf.math.conj(steering_vector_this)) 145 | 146 | # pathloss=loss.tf_Path_loss(input[:,-1,:,0]) 147 | # pathloss = tf.expand_dims(pathloss, axis=1) 148 | # pathloss = tf.broadcast_to(pathloss, tf.shape(steering_hermite)) 149 | # CSI = tf.multiply(tf.cast(tf.multiply(G, pathloss),dtype=tf.complex128), steering_hermite) 150 | # zf_beamformer = loss.tf_zero_forcing(CSI) 151 | # loss_MSE = loss.tf_matrix_mse(zf_beamformer,precoding_matrix) 152 | 153 | # steering_vector = [loss.calculate_steer_vector(predict_theta_list[v] for v in range(config_parameter.num_vehicle) 154 | sum_rate_this, sinr = loss.tf_loss_sumrate(CSI, precoding_matrix) 155 | mean_sinr = tf.reduce_mean(sinr, axis=1, keepdims=True) 156 | shape = tf.shape(sinr) 157 | sum_rate_this = tf.cast(sum_rate_this, tf.float64) 158 | # mean_sinr = tf.tile(mean_sinr,[1,shape[1]]) 159 | # mse_sinr = tf.reduce_mean(tf.square(sinr-mean_sinr),axis=1) 160 | # mse_sinr = tf.cast(mse_sinr, tf.float32) 161 | coeffi = tf.constant(0.05, tf.float32) 162 | 163 | zf_sumrate = tf.cast(zf_sumrate, tf.float64) 164 | batch_size = tf.cast(batch_size, tf.float64) 165 | 166 | # communication_loss = tf.reduce_sum(mse_sinr*coeffi-sum_rate_this)/batch_size 167 | # communication_loss = -sum_rate_this+loss_MSE/(tf.stop_gradient(loss_MSE/(sum_rate_this))) 168 | # communication_loss = tf.reduce_sum(zf_sumrate-sum_rate_this)/batch_size 169 | # beta = tf.complex(input[:,:,6*antenna_size:7*antenna_size,0], input[:,:,7*antenna_size:8*antenna_size,0]) 170 | random_precoding = loss.random_beamforming() 171 | random_sumrate, random_sinr = loss.tf_loss_sumrate(CSI, random_precoding) 172 | random_sumrate = tf.cast(random_sumrate, tf.float32) 173 | # communication_random = tf.reduce_sum(-random_sumrate) / batch_size 174 | Sigma_time_delay_random = loss.tf_sigma_delay_square(steering_vector_this_o, random_precoding, beta) 175 | Sigma_time_delay = loss.tf_sigma_delay_square(steering_vector_this_o, precoding_matrix, beta) 176 | Sigma_time_delay_zf = loss.tf_sigma_delay_square(steering_vector_this_o, 177 | tf.transpose(zf_matrix, perm=[0, 2, 1]), beta) 178 | # Sigma_time_delay_zf = loss.tf_sigma_delay_square(steering_vector_this_o, 179 | # zf_matrix, beta) 180 | # Sigma_doppler = loss.tf_sigma_doppler_square(steering_vector_this,precoding_matrix,beta) 181 | CRB_random = loss.tf_CRB_distance(Sigma_time_delay_random) 182 | CRB_d = loss.tf_CRB_distance(Sigma_time_delay) 183 | CRB_d_zf = loss.tf_CRB_distance(Sigma_time_delay_zf) 184 | # CRB_d = 0.1 185 | # theta = tf.reduce_mean(input[:,:,8*antenna_size:9*antenna_size,0]) 186 | # CRB_angle =0 187 | CRB_angle = loss.tf_CRB_angle(beta, precoding_matrix, theta) 188 | CRB_angle = tf.reduce_sum(CRB_angle, axis=1) / num_vehicle 189 | CRB_d = tf.reduce_sum(CRB_d, axis=1) / num_vehicle 190 | # CRB_angle_zf = loss.tf_CRB_angle(beta,tf.transpose(zf_matrix,perm=[0,2,1]),theta) 191 | CRB_d = tf.cast(CRB_d, tf.float64) 192 | CRB_angle = tf.cast(CRB_angle, tf.float64) 193 | crb_combined_loss = CRB_d * 1 + CRB_angle * 0 194 | # power = tf.constant(config_parameter.power, dtype=tf.float64) 195 | # power_error = tf.reduce_sum(tf.abs(precoding_matrix), axis=(1, 2)) - power 196 | # power_error = tf.cast(power_error, tf.float32) 197 | communication_loss = tf.reduce_sum(-sum_rate_this) / batch_size 198 | # crb_combined_loss = CRB_d_zf*1 +CRB_angle_zf*0 199 | # CRB_d = loss.tf_CRB_distance() 200 | # communication_loss = communication_loss/input.shape[0] 201 | precoding_matrix = tf.cast(precoding_matrix, tf.complex128) 202 | # CRB_d = tf.reduce_sum(CRB_d, axis=1) 203 | # crb_combined_loss = tf.cast(crb_combined_loss, tf.float32) 204 | # crb_combined_loss = -1000/(tf.reduce_sum(crb_combined_loss)/(batch_size*num_vehicle)) 205 | # crb_combined_loss = tf.reduce_sum(crb_combined_loss) / (batch_size * num_vehicle) 206 | combined_loss = tf.reduce_sum(portions[1] * CRB_d + portions[2] * CRB_angle - portions[0] * sum_rate_this, 207 | axis=0) / batch_size 208 | # combined_loss = 1e15*mse_value 209 | # crb_loss = 210 | 211 | # communication_loss = #communication_loss = tf.math.divide(1.0, sum_rate_this) 212 | if config_parameter.loss_mode == "Upper_sum_rate": 213 | gradients = tape.gradient(communication_loss, model.trainable_variables) 214 | 215 | elif config_parameter.loss_mode == "lower_bound_crb": 216 | gradients = tape.gradient(crb_combined_loss, model.trainable_variables) 217 | elif config_parameter.loss_mode == "combined_loss": 218 | gradients = tape.gradient(combined_loss, model.trainable_variables) 219 | ''' 220 | with writer.as_default(): 221 | tf.summary.histogram("CSIIMAG", tf.math.imag(CSI)) 222 | tf.summary.scalar("G", G) 223 | tf.summary.histogram("CSIREAL", tf.math.real(CSI)) 224 | tf.summary.scalar("Digital", Digital_matrix) 225 | tf.summary.scalar("Pathloss", pathloss) 226 | 227 | ''' 228 | optimizer_1.apply_gradients(grads_and_vars=zip(gradients, model.trainable_variables)) 229 | 230 | return communication_loss, output, CSI, gradients, tf.reduce_sum(CRB_d) / batch_size, \ 231 | tf.reduce_sum(CRB_angle) / batch_size, combined_loss 232 | 233 | 234 | crb_d_sum_list = [] # the crb distance sum at all timepoints in this list 235 | crb_angle_sum_list = [] # the crb angle sum at all timepoints in this list 236 | 237 | sum_rate_list_reciprocal = [] # the sum rate at all timepoints in this list 238 | sum_rate_list = [] 239 | angle, distance = loss.load_data() 240 | input_whole = loss.Conversion2input_small3(angle, distance) 241 | # input_whole = loss.Conversion2input_small2(angle, distance) 242 | input_whole = np.expand_dims(input_whole, axis=3) 243 | # normalized_data = (data - np.mean(data)) / np.std(data) 244 | 245 | # input_mean = np.mean(input_whole, axis=0) 246 | # input_var = np.var(input_whole, axis=0) 247 | # input_whole_norm = (input_whole - input_mean)/ 248 | tf_dataset = tf.data.Dataset.from_tensor_slices(input_whole) 249 | tf_dataset = tf_dataset.batch(config_parameter.batch_size) 250 | # tf_dataset = tf_dataset.map(lambda x: tf.expand_dims(x, axis=1)) 251 | # tf_dataset = tf.expand_dims(tf_dataset, axis=0) 252 | # dataset = tf.transpose(tf_dataset, perm=[1, 0, 2, 3]) 253 | # profiler.start() 254 | crb_d_median = 1 255 | crb_angle_median = 1 256 | communication_loss_median = 1 257 | for iter in range(0, config_parameter.iters): 258 | 259 | # iter += 7 260 | if iter < 2: 261 | # optimizer_1 = tf.keras.optimizers.SGD(learning_rate=0.00003, momentum=0.9, nesterov=False) 262 | # optimizer_1 = tf.keras.optimizers.RMSprop(learning_rate=0.003, rho=0.9) 263 | optimizer_1 = tf.keras.optimizers.Adam(learning_rate=0.00015, beta_1=0.9, beta_2=0.99) 264 | # optimizer_1 = tf.keras.optimizers.Adam(learning_rate=0.003, beta_1=0.91, beta_2=0.99) 265 | # optimizer_1 = tf.keras.optimizers.Adagrad(learning_rate=0.0001) 266 | elif iter < 6: 267 | optimizer_1 = tf.keras.optimizers.Adam(learning_rate=0.00004, beta_1=0.9, beta_2=0.99) 268 | # optimizer_1 = tf.keras.optimizers.RMSprop(learning_rate=0.00001, rho=0.9) 269 | else: 270 | optimizer_1 = tf.keras.optimizers.Adam(learning_rate=0.000001, beta_1=0.9, beta_2=0.99) 271 | # optimizer_1 = tf.keras.optimizers.RMSprop(learning_rate=0.00003, rho=0.9) 272 | print(iter) 273 | tf_dataset = tf_dataset.shuffle(9600) 274 | portions = [1, 2, 0.1] 275 | # portions = tf.divide([sum_rate_median, crb_d_median, crb_angle_median],(sum_rate_median+crb_d_median+crb_angle_median)) 276 | # tf_dataset = tf_dataset.batch(config_parameter.batch_size) 277 | for batch in tf_dataset: 278 | crb_angle_this = [] 279 | crb_d_this = [] 280 | communication_loss_list = [] 281 | print(tf.shape(batch)) 282 | input_single = batch 283 | communication_loss, output, CSI, gradients, crb_d, crb_angle, combined_loss = train_step(input_single, 284 | portions) 285 | 286 | print("Epoch: {}/{},losscomm: {},loss_d:{},loss_angle:{},loss_combined_loss:{}".format(iter + 1, 287 | config_parameter.iters, 288 | communication_loss.numpy(), 289 | crb_d.numpy(), 290 | crb_angle.numpy(), 291 | combined_loss.numpy())) 292 | 293 | # portions = tf.divide([communication_loss, crb_d, crb_angle],(communication_loss+crb_d+crb_angle)) 294 | 295 | # portions = [1, -communication_loss / crb_d, -communication_loss / crb_angle] 296 | file_path = "precoding_matrix.txt" 297 | crb_d_this.append(crb_d) 298 | communication_loss_list.append(communication_loss) 299 | crb_angle_this.append(crb_angle) 300 | with open(file_path, "w") as file: 301 | file.write("output") 302 | file.write(str(output.numpy()) + "\n") 303 | file.write("CRB_d") 304 | file.write(str(crb_d_this) + "\n") 305 | # file.write() 306 | # file.write("theta") 307 | # file.write(str(input_single[0, 0:num_vehicle, 2 * antenna_size]) + "\n") 308 | # file.write("distance") 309 | # file.write(str(input_single[0, 0:num_vehicle, 3 * antenna_size]) + "\n") 310 | file.write("sumrate") 311 | file.write(str(communication_loss.numpy()) + "\n") 312 | file.write("gradients") 313 | file.write(str(gradients) + "\n") 314 | sorted_data = tf.sort(communication_loss_list, axis=0) 315 | n = tf.shape(sorted_data)[0] 316 | median_index = n // 2 317 | communication_loss_median = -sorted_data[median_index] 318 | sorted_data = tf.sort(crb_angle_this, axis=0) 319 | n = tf.shape(sorted_data)[0] 320 | median_index = n // 2 321 | crb_angle_median = sorted_data[median_index] 322 | sorted_data = tf.sort(crb_d_this, axis=0) 323 | n = tf.shape(sorted_data)[0] 324 | median_index = n // 2 325 | crb_d_median = sorted_data[median_index] 326 | crb_angle_sum_list.append(tf.reduce_mean(crb_angle_this)) 327 | crb_d_sum_list.append(tf.reduce_mean(crb_d_this)) 328 | sum_rate_list.append(-tf.reduce_mean(communication_loss_list)) 329 | 330 | timestep = list(range(1, len(sum_rate_list) + 1)) 331 | plt.plot(timestep, crb_d_sum_list, 'b-o') 332 | plt.xlabel('Epoch') 333 | plt.ylabel('Loss') 334 | plt.title('Loss vs Epoch') 335 | plt.grid(True) 336 | plt.show() 337 | # plt.plot(timestep, crb_d_sum_list, 'b-o') 338 | # plt.xlabel('Epoch') 339 | # plt.ylabel('Loss') 340 | # plt.title('Loss vs Epoch') 341 | # plt.grid(True) 342 | # plt.show() 343 | # tf.saved_model.save(model, 'Keras_models/new_model') 344 | model.save_weights(filepath='allmodel1/Keras_models_SVDcsi2/new_model', save_format='tf') 345 | '''checkpointer = ModelCheckpoint(filepath="Keras_models/weights.{epoch:02d}-{val_accuracy:.2f}.hdf5", 346 | monitor='val_accuracy', 347 | save_weights_only=False, period=1, verbose=1, save_best_only=False)''' 348 | # tf.saved_model.save(model, ) 349 | model.save_weights(filepath='Keras_models_digital_onlycrb_d/new_model', save_format='tf') 350 | # profiler.stop() 351 | -------------------------------------------------------------------------------- /Trainv2_4inputs.py: -------------------------------------------------------------------------------- 1 | """ 2 | In this file, we want to input transmitsteering vector,distance and angle 3 | 4 | """ 5 | 6 | from __future__ import absolute_import, division, print_function 7 | import tensorflow as tf 8 | 9 | 10 | import math 11 | import sys 12 | import loss 13 | import config_parameter 14 | 15 | sys.path.append("..") 16 | import matplotlib.pyplot as plt 17 | 18 | from network import DL_method_NN_for_v2x_hybrid,DL_method_NN_for_v2x_mod,DL_method_NN_for_v2x_hybrid2 19 | from config_parameter import iters 20 | sys.path.append("..") 21 | import numpy as np 22 | #tf.compat.v1.enable_eager_execution() 23 | def load_model(): 24 | #model = DL_method_NN_for_v2x_mod() 25 | model = DL_method_NN_for_v2x_hybrid() 26 | #model = ResNet() 27 | #model = ResNetLSTMModel() 28 | num_vehicle = config_parameter.num_uppercar + config_parameter.num_lowercar +config_parameter.num_horizoncar 29 | 30 | model.build(input_shape=(None, num_vehicle,640,1)) 31 | 32 | model.summary() 33 | if config_parameter.FurtherTrain ==True: 34 | #model = tf.saved_model.load('Keras_models/new_model') 35 | model.load_weights(filepath='allmodel1/Keras_models_hybrid_onlycommfinal/new_model') 36 | return model 37 | 38 | 39 | if __name__ == '__main__': 40 | writer = tf.summary.create_file_writer("log.txt") 41 | if config_parameter.mode == "V2I": 42 | antenna_size = config_parameter.antenna_size 43 | num_vehicle = config_parameter.num_vehicle 44 | elif config_parameter.mode == "V2V": 45 | antenna_size = config_parameter.vehicle_antenna_size 46 | num_vehicle = config_parameter.num_uppercar + config_parameter.num_lowercar + config_parameter.num_horizoncar 47 | print(tf.__version__) 48 | 49 | Antenna_Gain = math.sqrt(antenna_size * config_parameter.receiver_antenna_size) 50 | c = config_parameter.c 51 | # GPU settings 52 | gpus = tf.config.experimental.list_physical_devices('GPU') 53 | print(gpus) 54 | 55 | #if gpus: 56 | # for gpu in gpus: 57 | # tf.config.experimental.set_memory_growth(gpu, True) 58 | #optimizer_1 = tf.keras.optimizers.Adam(learning_rate=0.003,beta_1 = 0.91,beta_2 = 0.99) 59 | #optimizer_1 = tf.keras.optimizers.Adagrad(learning_rate=0.004) 60 | ''' 61 | optimizer_1 = tf.keras.optimizers.Adagrad( 62 | learning_rate=0.01, 63 | initial_accumulator_value=0.1, 64 | epsilon=1e-07, 65 | name="Adagrad" 66 | ) 67 | ''' 68 | model = load_model() 69 | 70 | #profiler = tf.profiler.experimental.Profiler(tf.profiler.experimental.ProfilerOptions(host_tracer_level=2)) 71 | @tf.function # means not eager mode. graph mode 72 | def train_step(input,portions): 73 | # input shape(1,10,3,32) 74 | with tf.GradientTape() as tape: 75 | if config_parameter.mode == "V2I": 76 | antenna_size = config_parameter.antenna_size 77 | num_vehicle = config_parameter.num_vehicle 78 | elif config_parameter.mode == "V2V": 79 | antenna_size = config_parameter.vehicle_antenna_size 80 | num_vehicle = config_parameter.num_uppercar + config_parameter.num_lowercar + config_parameter.num_horizoncar 81 | 82 | output = model(input) 83 | portions = tf.cast(portions, tf.float64) 84 | #analog_rad = input[:,0:config_parameter.rf_size,6*antenna_size:7*antenna_size,0] 85 | #digital_ref = tf.complex(input[:,0:config_parameter.rf_size,\ 86 | # 2*antenna_size:2*antenna_size+num_vehicle,0], \ 87 | # input[:,:,3*antenna_size:3*antenna_size+num_vehicle,0]) 88 | distance = input[:, :, 3 * antenna_size:4*antenna_size, 0] 89 | #distance = tf.multiply(distance, 100) 90 | distance = tf.cast(distance, tf.float64) 91 | theta = input[:,:, 2 * antenna_size, 0] 92 | steering_vector_this_o = tf.complex(input[:, :, 0:antenna_size, 0], 93 | input[:, :, antenna_size:2 * antenna_size, 0]) 94 | #steering_vector_this = tf.transpose(steering_vector_this_o, perm=[0, 2, 1]) 95 | pathloss = loss.tf_Path_loss(distance) 96 | beta = loss.Reflection_coefficient(distance) 97 | 98 | num_vehicle_f = tf.cast(num_vehicle, tf.float32) 99 | antenna_size_f = tf.cast(antenna_size,tf.float32) 100 | # dont forget here we are inputing a whole batch 101 | G =tf.math.sqrt(antenna_size_f) 102 | CSI = tf.multiply(tf.cast(tf.multiply(G, pathloss),dtype=tf.complex128), steering_vector_this_o) 103 | CSI = tf.complex(input[:, :, 6*antenna_size:7*antenna_size, 0], input[:, :, 7*antenna_size:8 * antenna_size, 0]) 104 | #zf_matrix = loss.tf_zero_forcing(CSI) 105 | zf_matrix = tf.complex(input[:, :, 4 * antenna_size:5 * antenna_size, 0], 106 | input[:, :, 5 * antenna_size:6 * antenna_size, 0]) 107 | #zf_matrix = loss.tf_zero_forcing(CSI) 108 | shape = tf.shape(input) 109 | 110 | batch_size= shape[0] 111 | if config_parameter.digital == True: 112 | precoding_matrix = loss.tf_Output2digitalPrecoding(Output=output,zf_matrix=None,distance=None) 113 | #precoding_matrix = loss.tf_Output2digitalPrecoding(output, zf_matrix, distance=None) 114 | else: 115 | #Analog_matrix, Digital_matrix = loss.tf_Output2digitalPrecoding(Output=output,zf_matrix=zf_matrix,distance=distance) 116 | #Analog_matrix, Digital_matrix = loss.tf_Output2PrecodingMatrix_rad_mod(Output=output,\ 117 | # analog_ref=analog_rad,\ 118 | # digital_ref=digital_ref) 119 | 120 | Analog_matrix, Digital_matrix = loss.tf_Output2PrecodingMatrix_rad(Output=output) 121 | 122 | precoding_matrix = loss.tf_Precoding_matrix_combine(Analog_matrix, Digital_matrix) 123 | ## 124 | # 125 | # 126 | #precoding_matrix = loss.tf_Precoding_matrix_comb_Powerallocated(Analog_matrix, Digital_matrix,distance[:,:,0]) 127 | ## 128 | # # 129 | # precoding_matrix = loss.tf_Precoding_comb_no_powerconstarint(Analog_matrix, Digital_matrix) 130 | 131 | # 132 | pathloss = loss.tf_Path_loss(input[:,:,2*antenna_size,0]) 133 | #below is the real right steering vector 134 | steering_vector_this = tf.transpose(steering_vector_this_o, perm=[0, 2, 1]) 135 | #CSI = tf.complex(input[:,:,2*antenna_size:3*antenna_size,0], input[:,:,3*antenna_size:4*antenna_size,0]) 136 | #CSi here shape is (BATCH,NUMVEHICLE,ANTENNAS) 137 | 138 | #Analog_matrix, Digital_matrix = loss.tf_Output2PrecodingMatrix_rad(Output=output,zf_matrix=zf_matrix) 139 | #precoding_matrix = loss.tf_Precoding_matrix_combine(Analog_matrix, Digital_matrix) 140 | zf_sumrate,zf_sinr = loss.tf_loss_sumrate(CSI,tf.transpose(zf_matrix,perm=[0,2,1])) 141 | #zf_sumrate, zf_sinr = loss.tf_loss_sumrate(CSI, zf_matrix) 142 | #sigma_doppler = loss.tf 143 | #steering_hermite = tf.transpose(tf.math.conj(steering_vector_this)) 144 | 145 | #pathloss=loss.tf_Path_loss(input[:,-1,:,0]) 146 | #pathloss = tf.expand_dims(pathloss, axis=1) 147 | #pathloss = tf.broadcast_to(pathloss, tf.shape(steering_hermite)) 148 | #CSI = tf.multiply(tf.cast(tf.multiply(G, pathloss),dtype=tf.complex128), steering_hermite) 149 | #zf_beamformer = loss.tf_zero_forcing(CSI) 150 | #loss_MSE = loss.tf_matrix_mse(zf_beamformer,precoding_matrix) 151 | 152 | 153 | 154 | # steering_vector = [loss.calculate_steer_vector(predict_theta_list[v] for v in range(config_parameter.num_vehicle) 155 | sum_rate_this,sinr = loss.tf_loss_sumrate(CSI, precoding_matrix) 156 | mean_sinr = tf.reduce_mean(sinr,axis=1,keepdims=True) 157 | shape = tf.shape(sinr) 158 | sum_rate_this = tf.cast(sum_rate_this, tf.float64) 159 | #mean_sinr = tf.tile(mean_sinr,[1,shape[1]]) 160 | #mse_sinr = tf.reduce_mean(tf.square(sinr-mean_sinr),axis=1) 161 | #mse_sinr = tf.cast(mse_sinr, tf.float32) 162 | coeffi = tf.constant(0.05,tf.float32) 163 | 164 | zf_sumrate = tf.cast(zf_sumrate, tf.float64) 165 | batch_size = tf.cast(batch_size, tf.float64) 166 | 167 | #communication_loss = tf.reduce_sum(mse_sinr*coeffi-sum_rate_this)/batch_size 168 | #communication_loss = -sum_rate_this+loss_MSE/(tf.stop_gradient(loss_MSE/(sum_rate_this))) 169 | #communication_loss = tf.reduce_sum(zf_sumrate-sum_rate_this)/batch_size 170 | #beta = tf.complex(input[:,:,6*antenna_size:7*antenna_size,0], input[:,:,7*antenna_size:8*antenna_size,0]) 171 | random_precoding = loss.random_beamforming() 172 | random_sumrate,random_sinr = loss.tf_loss_sumrate(CSI,random_precoding) 173 | random_sumrate = tf.cast(random_sumrate, tf.float32) 174 | #communication_random = tf.reduce_sum(-random_sumrate) / batch_size 175 | Sigma_time_delay_random = loss.tf_sigma_delay_square(steering_vector_this_o,random_precoding,beta) 176 | Sigma_time_delay = loss.tf_sigma_delay_square(steering_vector_this_o,precoding_matrix,beta) 177 | Sigma_time_delay_zf = loss.tf_sigma_delay_square(steering_vector_this_o,tf.transpose(zf_matrix,perm=[0,2,1]),beta) 178 | #Sigma_time_delay_zf = loss.tf_sigma_delay_square(steering_vector_this_o, 179 | # zf_matrix, beta) 180 | #Sigma_doppler = loss.tf_sigma_doppler_square(steering_vector_this,precoding_matrix,beta) 181 | CRB_random = loss.tf_CRB_distance(Sigma_time_delay_random) 182 | CRB_d = loss.tf_CRB_distance(Sigma_time_delay) 183 | CRB_d_zf = loss.tf_CRB_distance(Sigma_time_delay_zf) 184 | #CRB_d = 0.1 185 | #theta = tf.reduce_mean(input[:,:,8*antenna_size:9*antenna_size,0]) 186 | #CRB_angle =0 187 | CRB_angle = loss.tf_CRB_angle(beta,precoding_matrix,theta) 188 | CRB_angle = tf.reduce_sum(CRB_angle,axis=1)/num_vehicle 189 | CRB_d = tf.reduce_sum(CRB_d,axis=1)/num_vehicle 190 | #CRB_angle_zf = loss.tf_CRB_angle(beta,tf.transpose(zf_matrix,perm=[0,2,1]),theta) 191 | CRB_d = tf.cast(CRB_d, tf.float64) 192 | CRB_angle = tf.cast(CRB_angle, tf.float64) 193 | crb_combined_loss = 100*CRB_d + CRB_angle*0 194 | #power = tf.constant(config_parameter.power, dtype=tf.float64) 195 | #power_error = tf.reduce_sum(tf.abs(precoding_matrix), axis=(1, 2)) - power 196 | #power_error = tf.cast(power_error, tf.float32) 197 | communication_loss = tf.reduce_sum(-sum_rate_this) / batch_size 198 | #crb_combined_loss = CRB_d_zf*1 +CRB_angle_zf*0 199 | #CRB_d = loss.tf_CRB_distance() 200 | #communication_loss = communication_loss/input.shape[0] 201 | precoding_matrix = tf.cast(precoding_matrix, tf.complex128) 202 | #CRB_d = tf.reduce_sum(CRB_d, axis=1) 203 | #crb_combined_loss = tf.cast(crb_combined_loss, tf.float32) 204 | #crb_combined_loss = -1000/(tf.reduce_sum(crb_combined_loss)/(batch_size*num_vehicle)) 205 | #crb_combined_loss = tf.reduce_sum(crb_combined_loss) / (batch_size * num_vehicle) 206 | combined_loss = tf.reduce_sum(portions[1]*CRB_d+portions[2]*CRB_angle -portions[0]*sum_rate_this,axis=0)/batch_size 207 | #combined_loss = 1e15*mse_value 208 | #crb_loss = 209 | 210 | #communication_loss = #communication_loss = tf.math.divide(1.0, sum_rate_this) 211 | if config_parameter.loss_mode == "Upper_sum_rate": 212 | gradients = tape.gradient(communication_loss, model.trainable_variables) 213 | 214 | elif config_parameter.loss_mode == "lower_bound_crb": 215 | gradients = tape.gradient(crb_combined_loss, model.trainable_variables) 216 | elif config_parameter.loss_mode == "combined_loss": 217 | gradients = tape.gradient(combined_loss, model.trainable_variables) 218 | ''' 219 | with writer.as_default(): 220 | tf.summary.histogram("CSIIMAG", tf.math.imag(CSI)) 221 | tf.summary.scalar("G", G) 222 | tf.summary.histogram("CSIREAL", tf.math.real(CSI)) 223 | tf.summary.scalar("Digital", Digital_matrix) 224 | tf.summary.scalar("Pathloss", pathloss) 225 | 226 | ''' 227 | optimizer_1.apply_gradients(grads_and_vars=zip(gradients, model.trainable_variables)) 228 | 229 | return communication_loss,output,CSI,gradients,tf.reduce_sum(CRB_d)/batch_size,\ 230 | tf.reduce_sum(CRB_angle)/batch_size,combined_loss 231 | 232 | 233 | crb_d_sum_list = [] # the crb distance sum at all timepoints in this list 234 | crb_angle_sum_list = [] # the crb angle sum at all timepoints in this list 235 | 236 | sum_rate_list_reciprocal = [] # the sum rate at all timepoints in this list 237 | sum_rate_list = [] 238 | combined = [] 239 | angle, distance = loss.load_data() 240 | 241 | input_whole = loss.Conversion2input_small(angle, distance) 242 | #input_whole = loss.Conversion2input_small2(angle, distance) 243 | input_whole = np.expand_dims(input_whole, axis=3) 244 | #normalized_data = (data - np.mean(data)) / np.std(data) 245 | 246 | #input_mean = np.mean(input_whole, axis=0) 247 | #input_var = np.var(input_whole, axis=0) 248 | #input_whole_norm = (input_whole - input_mean)/ 249 | tf_dataset = tf.data.Dataset.from_tensor_slices(input_whole) 250 | tf_dataset = tf_dataset.batch(config_parameter.batch_size) 251 | #tf_dataset = tf_dataset.map(lambda x: tf.expand_dims(x, axis=1)) 252 | #tf_dataset = tf.expand_dims(tf_dataset, axis=0) 253 | #dataset = tf.transpose(tf_dataset, perm=[1, 0, 2, 3]) 254 | #profiler.start() 255 | crb_d_median = 1 256 | crb_angle_median = 1 257 | communication_loss_median = 1 258 | for iter in range(0, config_parameter.iters): 259 | 260 | #iter += 7 261 | if iter < 2: 262 | #portions = [1, 1, 30] 263 | #optimizer_1 = tf.keras.optimizers.SGD(learning_rate=0.00003, momentum=0.9, nesterov=False) 264 | #optimizer_1 = tf.keras.optimizers.RMSprop(learning_rate=0.00001, rho=0.9) 265 | optimizer_1 = tf.keras.optimizers.Adam(learning_rate=0.00001, beta_1=0.9, beta_2=0.99) 266 | #optimizer_1 = tf.keras.optimizers.Adam(learning_rate=0.003, beta_1=0.91, beta_2=0.99) 267 | #optimizer_1 = tf.keras.optimizers.Adagrad(learning_rate=0.0001) 268 | elif iter <7: 269 | #portions = [1, 10, 30] 270 | optimizer_1 = tf.keras.optimizers.Adam(learning_rate=0.000003, beta_1=0.9, beta_2=0.99) 271 | #optimizer_1 = tf.keras.optimizers.RMSprop(learning_rate=0.00001, rho=0.9) 272 | else: 273 | optimizer_1 = tf.keras.optimizers.Adam(learning_rate=0.0000003, beta_1=0.9, beta_2=0.99) 274 | #optimizer_1 = tf.keras.optimizers.RMSprop(learning_rate=0.00003, rho=0.9) 275 | print(iter) 276 | tf_dataset = tf_dataset.shuffle(9600) 277 | portions = [1,40,1e7] 278 | #portions = tf.divide([sum_rate_median, crb_d_median, crb_angle_median],(sum_rate_median+crb_d_median+crb_angle_median)) 279 | #tf_dataset = tf_dataset.batch(config_parameter.batch_size) 280 | for batch in tf_dataset: 281 | crb_angle_this = [] 282 | crb_d_this = [] 283 | communication_loss_list =[] 284 | combined_list = [] 285 | print(tf.shape(batch)) 286 | input_single = batch 287 | communication_loss, output, CSI, gradients,crb_d,crb_angle,combined_loss = train_step(input_single,portions) 288 | 289 | print("Epoch: {}/{},losscomm: {},loss_d:{},loss_angle:{},loss_combined_loss:{}".format(iter + 1, config_parameter.iters, 290 | communication_loss.numpy(),crb_d.numpy(),crb_angle.numpy(),combined_loss.numpy())) 291 | 292 | #portions = tf.divide([communication_loss, crb_d, crb_angle],(communication_loss+crb_d+crb_angle)) 293 | 294 | #portions = [1, -communication_loss / crb_d, -communication_loss / crb_angle] 295 | file_path = "precoding_matrix.txt" 296 | crb_d_this.append(crb_d) 297 | communication_loss_list.append(communication_loss) 298 | crb_angle_this.append(crb_angle) 299 | combined_list.append(combined_loss) 300 | with open(file_path, "w") as file: 301 | file.write("output") 302 | file.write(str(output.numpy()) + "\n") 303 | file.write("CRB_d") 304 | file.write(str(crb_d_this) + "\n") 305 | #file.write() 306 | #file.write("theta") 307 | #file.write(str(input_single[0, 0:num_vehicle, 2 * antenna_size]) + "\n") 308 | #file.write("distance") 309 | #file.write(str(input_single[0, 0:num_vehicle, 3 * antenna_size]) + "\n") 310 | file.write("sumrate") 311 | file.write(str(communication_loss.numpy()) + "\n") 312 | file.write("gradients") 313 | file.write(str(gradients) + "\n") 314 | sorted_data = tf.sort(communication_loss_list, axis=0) 315 | n = tf.shape(sorted_data)[0] 316 | median_index = n // 2 317 | communication_loss_median = -sorted_data[median_index] 318 | sorted_data = tf.sort(crb_angle_this, axis=0) 319 | n = tf.shape(sorted_data)[0] 320 | median_index = n // 2 321 | crb_angle_median = sorted_data[median_index] 322 | sorted_data = tf.sort(crb_d_this, axis=0) 323 | n = tf.shape(sorted_data)[0] 324 | median_index = n // 2 325 | 326 | crb_d_median = sorted_data[median_index] 327 | crb_angle_sum_list.append(tf.reduce_mean(crb_angle_this)) 328 | crb_d_sum_list.append(tf.reduce_mean(crb_d_this)) 329 | sum_rate_list.append(-tf.reduce_mean(communication_loss_list)) 330 | combined.append(tf.reduce_mean(combined_list)) 331 | 332 | 333 | 334 | timestep = list(range(1, len(sum_rate_list) + 1)) 335 | 336 | 337 | 338 | 339 | fig, ax1 = plt.subplots() 340 | ax1.plot(timestep, sum_rate_list, 'b-', label='sum rate') 341 | ax1.set_xlabel('Epoch') 342 | ax1.set_ylabel('sum rate(bits/s/hz)', color='b') 343 | ax1.tick_params('y', colors='b') 344 | 345 | 346 | ax2 = ax1.twinx() 347 | 348 | ax2.plot(timestep, crb_d_sum_list, 'r:', label='crb_distance') 349 | ax2.set_ylabel('CRB distance ', color='r') 350 | ax2.tick_params('y', colors='r') 351 | 352 | 353 | ax3 = ax1.twinx() 354 | ax3.spines['right'].set_position(('outward', 50)) 355 | 356 | #y3 = 0.5 * x 357 | ax3.plot(timestep, crb_angle_sum_list, 'g--', label='crb_angle') 358 | ax3.set_ylabel('CRB angle', color='g') 359 | ax3.tick_params('y', colors='g') 360 | 361 | 362 | ''' 363 | #ax4 = ax1.twinx() 364 | fig, ax4 = plt.subplots() 365 | #ax4.spines['right'].set_position(('outward', 100)) 366 | #ax4.spines['right'].set_visible(True)# 将第四个纵坐标轴移到右侧 367 | # 第四个折线数据 368 | #y4 = -x ** 2 369 | #ax4 = ax3.twinx() 370 | ax4.plot(timestep, combined, 'm-.', label='combined_loss') 371 | ax4.set_ylabel('combined_loss', color='m') 372 | ax4.tick_params('y', colors='m') 373 | ''' 374 | 375 | fig.tight_layout() 376 | 377 | 378 | lines = [ax1.get_lines()[0], ax2.get_lines()[0], ax3.get_lines()[0]] 379 | #lines = [ax4.get_lines()[0]] 380 | labels = [line.get_label() for line in lines] 381 | ax1.legend(lines, labels, bbox_to_anchor=(0.5, 0.7), loc='best') 382 | 383 | plt.show() 384 | 385 | 386 | 387 | ''' 388 | plt.plot(timestep, crb_d_sum_list, 'b-o',label='CRB_distance') 389 | plt.plot(timestep, crb_angle_sum_list, 'r-o',label='CRB_angle') 390 | plt.plot(timestep, sum_rate_list, 'g-o',label='Sum_rate') 391 | plt.legend() 392 | plt.xlabel('Epoch') 393 | plt.ylabel('Loss') 394 | plt.title('Loss vs Epoch') 395 | plt.grid(True) 396 | plt.show() 397 | ''' 398 | #plt.plot(timestep, crb_d_sum_list, 'b-o') 399 | #plt.xlabel('Epoch') 400 | #plt.ylabel('Loss') 401 | #plt.title('Loss vs Epoch') 402 | #plt.grid(True) 403 | #plt.show() 404 | # tf.saved_model.save(model, 'Keras_models/new_model') 405 | model.save_weights(filepath='allmodel1/Keras_models_fading5_onlycrbd/new_model', save_format='tf') 406 | '''checkpointer = ModelCheckpoint(filepath="Keras_models/weights.{epoch:02d}-{val_accuracy:.2f}.hdf5", 407 | monitor='val_accuracy', 408 | save_weights_only=False, period=1, verbose=1, save_best_only=False)''' 409 | # tf.saved_model.save(model, ) 410 | model.save_weights(filepath='Keras_models_hybrid_onlycrb_d/new_model', save_format='tf') 411 | 412 | 413 | 414 | -------------------------------------------------------------------------------- /evaluation_simultaneously.py: -------------------------------------------------------------------------------- 1 | import random 2 | 3 | import loss 4 | import numpy as np 5 | import config_parameter 6 | import math 7 | import tensorflow as tf 8 | from network import DL_method_NN_for_v2x_mod,DL_method_NN_for_v2x_hybrid,DL_method_NN_for_v2x_hybrid2 9 | import matplotlib.pyplot as plt 10 | #Test = "V2V" 11 | Test = "V2I" 12 | if config_parameter.mode == "V2I": 13 | antenna_size = config_parameter.antenna_size 14 | num_vehicle = config_parameter.num_vehicle 15 | elif config_parameter.mode == "V2V": 16 | antenna_size = config_parameter.vehicle_antenna_size 17 | num_vehicle = config_parameter.num_uppercar + config_parameter.num_lowercar + config_parameter.num_horizoncar 18 | def load_model(digital): 19 | if digital==True: 20 | model = DL_method_NN_for_v2x_mod() 21 | else: 22 | #model = DL_method_NN_for_v2x_hybrid2() 23 | model = DL_method_NN_for_v2x_hybrid() 24 | 25 | num_vehicle = config_parameter.num_uppercar + config_parameter.num_lowercar +config_parameter.num_horizoncar 26 | 27 | model.build(input_shape=(None, num_vehicle,320,1)) 28 | 29 | model.summary() 30 | return model 31 | def load_model_hybrid_combine(): 32 | digital = False 33 | model = load_model(digital) 34 | 35 | model.load_weights(filepath='allmodel1/Keras_models_hybrid_combinefinal/new_model') 36 | #model.load_weights(filepath='allmodel1/Keras_models_rf8_combine/new_model') 37 | return model 38 | def load_model_digitalwith_combine(): 39 | digital = True 40 | model = load_model(digital) 41 | 42 | model.load_weights(filepath='allmodel1/Keras_models_digitalwith_combinefinal/new_model') 43 | return model 44 | def load_model_digitalwithout_combine(): 45 | digital = True 46 | model = load_model(digital) 47 | model.load_weights(filepath='allmodel1/Keras_models_digitalwithout_combinefinal/new_model') 48 | return model 49 | 50 | def load_model_only_communication_digitalwith(): 51 | digital = True 52 | model = load_model(digital) 53 | model.load_weights(filepath='allmodel1/Keras_models_digitalwith_sumratefinal/new_model') 54 | return model 55 | def load_model_only_communication_digitalwithout(): 56 | digital = True 57 | model = load_model(digital) 58 | model.load_weights(filepath='allmodel1/Keras_models_digitalwithout_sumratefinal/new_model') 59 | #model.load_weights(filepath='allmodel1/Keras_models_test/new_model') 60 | return model 61 | def load_model_only_communication_hybrid(): 62 | digital = False 63 | model = load_model(digital) 64 | model.load_weights(filepath='allmodel1/Keras_models_hybrid_onlycommfinal/new_model') 65 | return model 66 | def load_model_only_crbd_hybrid(): 67 | digital = False 68 | model = load_model(digital) 69 | #model.load_weights(filepath='allmodel1/Keras_models_hybrid_onlycrbdfinal/new_model') 70 | model.load_weights(filepath='allmodel1/Keras_models_hybrid_onlycommfinal/new_model') 71 | return model 72 | def load_model_only_crbd_digitalwith(): 73 | digital = True 74 | model = load_model(digital) 75 | #model.load_weights(filepath='allmodel1/Keras_models_digitalwith_crbdfinal/new_model') 76 | model.load_weights(filepath='allmodel1/Keras_models_digitalwith_sumratefinal/new_model') 77 | return model 78 | def load_model_only_crbd_digitalwithout(): 79 | digital = True 80 | model = load_model(digital) 81 | #model.load_weights(filepath='allmodel1/Keras_models_digitalwithout_crbdfinal/new_model') 82 | model.load_weights(filepath='allmodel1/Keras_models_digitalwithout_sumratefinal/new_model') 83 | return model 84 | def load_model_only_crbangle_hybrid(): 85 | digital = False 86 | model = load_model(digital) 87 | model.load_weights(filepath='allmodel1/Keras_models_hybrid_onlycrbanglefinal/new_model') 88 | return model 89 | def load_model_only_crbangle_digitalwith(): 90 | digital = True 91 | model = load_model(digital) 92 | model.load_weights(filepath='allmodel1/Keras_models_digitalwith_crbanglefinal/new_model') 93 | return model 94 | def load_model_only_crbangle_digitalwithout(): 95 | digital = True 96 | model = load_model(digital) 97 | model.load_weights(filepath='allmodel1/Keras_models_digitalwithout_crbafinal/new_model') 98 | return model 99 | def load_model_noise1e_11(): 100 | digital =False 101 | model = load_model(digital) 102 | model.load_weights(filepath='allmodel1/Keras_models_hybrid_onlycommfinalnoise1e_11/new_model') 103 | return model 104 | def load_model_noise1e_5(): 105 | digital =False 106 | model = load_model(digital) 107 | model.load_weights(filepath='allmodel2/Keras_models_hybrid_onlycommfinalnoise1e_5/new_model') 108 | return model 109 | def load_modelpower50(): 110 | digital = False 111 | model = load_model(digital) 112 | model.load_weights(filepath='allmodel1/Keras_models_power50_onlycomm/new_model') 113 | return model 114 | def load_modelpower100(): 115 | digital = False 116 | model = load_model(digital) 117 | model.load_weights(filepath='allmodel1/Keras_models_power100_onlycomm/new_model') 118 | return model 119 | def generate_input_v2v(): 120 | 121 | if config_parameter.mode == "V2I": 122 | antenna_size = config_parameter.antenna_size 123 | num_vehicle = config_parameter.num_vehicle 124 | elif config_parameter.mode == "V2V": 125 | antenna_size = config_parameter.vehicle_antenna_size 126 | num_vehicle = config_parameter.num_uppercar + config_parameter.num_lowercar + config_parameter.num_horizoncar 127 | speed_own_dictionary = np.zeros(shape=( 128 | 1, int(config_parameter.one_iter_period / config_parameter.Radar_measure_slot))) 129 | speed_upper_car_dictionary = np.zeros(shape=( 130 | config_parameter.num_uppercar, 131 | int(config_parameter.one_iter_period / config_parameter.Radar_measure_slot))) 132 | real_location_uppercar_x = np.zeros(shape=( 133 | config_parameter.num_uppercar, 134 | int(config_parameter.one_iter_period / config_parameter.Radar_measure_slot))) 135 | 136 | speed_lower_car_dictionary = np.zeros(shape=( 137 | config_parameter.num_lowercar, 138 | int(config_parameter.one_iter_period / config_parameter.Radar_measure_slot))) 139 | real_location_lowercar_x = np.zeros(shape=( 140 | config_parameter.num_lowercar, 141 | int(config_parameter.one_iter_period / config_parameter.Radar_measure_slot))) 142 | totalnum_vehicle = config_parameter.num_uppercar + config_parameter.num_lowercar + config_parameter.num_horizoncar 143 | 144 | speed_own_dictionary = np.random.uniform(config_parameter.horizonspeed_low, 145 | config_parameter.horizonspeed_high, 146 | size=speed_own_dictionary.shape) 147 | speed_lower_car_dictionary = np.random.uniform(config_parameter.lowerspeed_low, 148 | config_parameter.lowerspeed_high, 149 | size=speed_lower_car_dictionary.shape) 150 | speed_upper_car_dictionary = np.random.uniform(config_parameter.upperspeed_low, 151 | config_parameter.upperspeed_high, 152 | size=speed_upper_car_dictionary.shape) 153 | speed_whole_dictionary = np.vstack((speed_own_dictionary, speed_lower_car_dictionary, 154 | speed_upper_car_dictionary)) 155 | print(speed_whole_dictionary.shape) 156 | num_whole = totalnum_vehicle + 1 # 1 is the observer 157 | initial_car_x = np.zeros(shape=(num_whole, 1)) 158 | initial_car_x[0, 0] = 0 159 | location_car_y = np.zeros( 160 | shape=(num_whole, int(config_parameter.one_iter_period / config_parameter.Radar_measure_slot) + 1)) 161 | location_car_y[0, :] = np.full( 162 | (1, int(config_parameter.one_iter_period / config_parameter.Radar_measure_slot) + 1), 0) 163 | 164 | # initial_car_x[1, 0] = np.random.uniform(config_parameter.Initial_horizoncar1_min, 165 | # config_parameter.Initial_horizoncar1_max) 166 | # location_car_y[1, :] = np.full( 167 | # (1, int(config_parameter.one_iter_period / config_parameter.Radar_measure_slot) + 1), 0) 168 | initial_car_x[1, 0] = np.random.uniform(config_parameter.Initial_location_min[0], 169 | config_parameter.Initial_location_max[0]) 170 | location_car_y[1, :] = np.full( 171 | (1, int(config_parameter.one_iter_period / config_parameter.Radar_measure_slot) + 1), \ 172 | config_parameter.Initial_lowercar_y) 173 | initial_car_x[2, 0] = np.random.uniform(config_parameter.Initial_location_min[1], 174 | config_parameter.Initial_location_max[1]) 175 | location_car_y[2, :] = np.full( 176 | (1, int(config_parameter.one_iter_period / config_parameter.Radar_measure_slot) + 1), \ 177 | config_parameter.Initial_lowercar_y) 178 | initial_car_x[3, 0] = np.random.uniform(config_parameter.Initial_location_min[2], 179 | config_parameter.Initial_location_max[2]) 180 | location_car_y[3, :] = np.full( 181 | (1, int(config_parameter.one_iter_period / config_parameter.Radar_measure_slot) + 1), \ 182 | config_parameter.Initial_uppercar_y) 183 | initial_car_x[4, 0] = np.random.uniform(config_parameter.Initial_location_min[3], 184 | config_parameter.Initial_location_max[3]) 185 | location_car_y[4, :] = np.full( 186 | (1, int(config_parameter.one_iter_period / config_parameter.Radar_measure_slot) + 1), \ 187 | config_parameter.Initial_uppercar_y) 188 | # initial_car_x[4,0]=np.random.uniform(config_parameter.Initial_lowercar2_min, config_parameter.Initial_lowercar2_max) 189 | # initial_car_x[5, 0] = np.random.uniform(config_parameter.Initial_uppercar2_min, 190 | # config_parameter.Initial_uppercar2_max) 191 | 192 | location_car_x = np.zeros(shape=( 193 | num_whole, int(config_parameter.one_iter_period / config_parameter.Radar_measure_slot) + 1)) 194 | coordinates_car = np.zeros(shape=( 195 | num_whole, int(config_parameter.one_iter_period / config_parameter.Radar_measure_slot) + 1)) 196 | location_car_x[:, 0] = initial_car_x[:, :].reshape((num_vehicle + 1,)) 197 | real_distance = np.zeros(shape=( 198 | totalnum_vehicle, int(config_parameter.one_iter_period / config_parameter.Radar_measure_slot) + 1)) 199 | real_theta = np.zeros(shape=( 200 | totalnum_vehicle, int(config_parameter.one_iter_period / config_parameter.Radar_measure_slot) + 1)) 201 | 202 | for v in range(num_whole): 203 | for t in range(int(config_parameter.one_iter_period / config_parameter.Radar_measure_slot)): 204 | location_car_x[v, t + 1] = location_car_x[v, t] + speed_whole_dictionary[ 205 | v, t] * config_parameter.Radar_measure_slot 206 | 207 | for v in range(1, num_whole): 208 | for t in range(int(config_parameter.one_iter_period / config_parameter.Radar_measure_slot) + 1): 209 | real_distance[v - 1, t] = math.sqrt((location_car_x[0, t] - location_car_x[v, t]) ** 2 + ( 210 | location_car_y[0, t] - location_car_y[v, t]) ** 2) 211 | real_theta[v - 1, t] = math.atan2(location_car_y[v, t] - location_car_y[0, t], 212 | location_car_x[v, t] - location_car_x[0, t]) 213 | if real_theta[v - 1, t] == 0: 214 | real_theta[v - 1, t] == 0.1 215 | if real_theta[v - 1, t] < 0: 216 | real_theta[v - 1, t] = real_theta[v - 1, t] + 2 * math.pi 217 | print(real_theta[v - 1, t]) 218 | return real_distance,real_theta 219 | def generate_input_v2i(): 220 | 221 | initial_location_x = np.zeros(shape=(config_parameter.num_vehicle, 1)) 222 | # speed at every timepoint 223 | speed_dictionary = np.zeros(shape=( 224 | config_parameter.num_vehicle, int(config_parameter.one_iter_period / config_parameter.Radar_measure_slot))) 225 | # real location at every timepoint 226 | real_location_x = np.zeros(shape=(config_parameter.num_vehicle, 227 | int(config_parameter.one_iter_period / config_parameter.Radar_measure_slot))) # this one doesn't include the initial location 228 | 229 | real_theta = np.zeros(shape=( 230 | config_parameter.num_vehicle, int(config_parameter.one_iter_period / config_parameter.Radar_measure_slot))) 231 | 232 | real_distance_list = np.zeros(shape=( 233 | config_parameter.num_vehicle, int(config_parameter.one_iter_period / config_parameter.Radar_measure_slot))) 234 | # real x coordinates of target including the initial location 235 | location = np.zeros(shape=(config_parameter.num_vehicle, ( 236 | int(config_parameter.one_iter_period / config_parameter.Radar_measure_slot) + 1))) # this one include the initial location 237 | # real y coordinates of target including the initial location 238 | location_y = np.zeros(shape=(config_parameter.num_vehicle, (int(config_parameter.one_iter_period / config_parameter.Radar_measure_slot) + 1))) 239 | # target coordinates combined 240 | target_coordinates = np.zeros(shape=(config_parameter.num_vehicle, int(config_parameter.one_iter_period / config_parameter.Radar_measure_slot))) 241 | Initial_location_min = config_parameter.Initial_location_min 242 | Initial_location_max = config_parameter.Initial_location_max 243 | for vehicle in range(0, config_parameter.num_vehicle): 244 | # initial_location_x[vehicle] = [] 245 | speed_dictionary[vehicle] = [np.random.uniform(low=config_parameter.speed_low, high=config_parameter.speed_high) \ 246 | for _ in 247 | range(int(config_parameter.one_iter_period / config_parameter.Radar_measure_slot))] 248 | print(speed_dictionary.shape) 249 | # initialize location for every car [0,100) 250 | random_location = int(np.random.uniform(Initial_location_min[vehicle], Initial_location_max[vehicle])) 251 | 252 | print(random_location) 253 | 254 | initial_location_x[vehicle] = random_location 255 | location[vehicle, 0] = random_location 256 | # location_y[vehicle] = [0] 257 | for i in range(int(config_parameter.one_iter_period / config_parameter.Radar_measure_slot)): 258 | location[vehicle, i + 1] = config_parameter.Radar_measure_slot * speed_dictionary[vehicle, i] + \ 259 | location[vehicle, i] 260 | 261 | # location_y[vehicle].append(0) 262 | real_theta[vehicle, i] = math.atan2(location_y[vehicle, i] - config_parameter.RSU_location[1],location[vehicle, i] - config_parameter.RSU_location[0]) 263 | if real_theta[vehicle,i] < 0: 264 | real_theta[vehicle, i] = real_theta[vehicle, i] + 2 * math.pi 265 | #target_coordinates[vehicle, i] = (location[vehicle, i + 1], location_y[vehicle, i + 1]) 266 | real_distance_list[vehicle, i] = math.sqrt((location[vehicle, i] - config_parameter.RSU_location[0]) ** 2 \ 267 | + (location_y[vehicle, i] - config_parameter.RSU_location[1]) ** 2) 268 | 269 | 270 | real_location_x[vehicle] = location[vehicle][1:] 271 | # for vehicle in range(0,config_parameter.num_vehicle): 272 | # for time in range(0,int(config_parameter.one_iter_period/config_parameter.Radar_measure_slot)): 273 | # sigma_time_delay[v, time] = loss.Sigma_time_delay_square(index=v,distance_list = real_distance[:, time],estimated_theta_list=real_theta[:,time],\ 274 | # precoding_matrix=precoding_matrix) 275 | # sigma_doppler[v, time] = loss.Sigma_time_delay_square(index=vdistance_list = real_distance[:, time],estimated_theta_list=real_theta[:,time].\ 276 | # precoding_matrix=precoding_matrix) 277 | print("location while start measuring", real_location_x) 278 | 279 | print("initial location", initial_location_x) 280 | return real_distance_list,real_theta 281 | def comparison_between_crb_distance(combined): 282 | #CSI = tf.complex(combined[:,:,0:antenna_size],combined[:,:,antenna_size:2*antenna_size]) 283 | CSI = tf.complex(combined[:, :, 6 * antenna_size:7 * antenna_size, 0], 284 | combined[:, :, 7 * antenna_size:8 * antenna_size, 0]) 285 | steering_vector_this_o = tf.complex(combined[:, :, 0:antenna_size, 0], 286 | combined[:, :, antenna_size:2 * antenna_size, 0]) 287 | zf_matrix = tf.complex(combined[:, :, 4 * antenna_size:5 * antenna_size, 0], 288 | combined[:, :, 5 * antenna_size:6 * antenna_size, 0]) 289 | distance = combined[:, :, 3 * antenna_size:4*antenna_size, 0] 290 | beta = loss.Reflection_coefficient(distance) 291 | model1 = load_model_hybrid_combine() 292 | model2 = load_model_digitalwith_combine() 293 | model3 = load_model_digitalwithout_combine() 294 | model4 = load_model_only_crbd_hybrid() 295 | model5 = load_model_only_crbd_digitalwith() 296 | model6 = load_model_only_crbd_digitalwithout() 297 | output1 = model1(combined) 298 | output2 = model2(combined) 299 | output3 = model3(combined) 300 | output4 = model4(combined) 301 | output5 = model5(combined) 302 | output6 = model6(combined) 303 | analog1, digital1 = loss.tf_Output2PrecodingMatrix_rad(output1) 304 | precoder1 = loss.tf_Precoding_matrix_combine(analog1, digital1) 305 | precoder2 = loss.tf_Output2digitalPrecoding(output2, zf_matrix=zf_matrix, distance=None) 306 | precoder3 = loss.tf_Output2digitalPrecoding(output3, zf_matrix=None, distance=None) 307 | analog4, digital4 = loss.tf_Output2PrecodingMatrix_rad(output4) 308 | precoder4 = loss.tf_Precoding_matrix_combine(analog4, digital4) 309 | precoder5 = loss.tf_Output2digitalPrecoding(output5, zf_matrix=zf_matrix, distance=None) 310 | precoder6 = loss.tf_Output2digitalPrecoding(output6, zf_matrix=None, distance=None) 311 | precoder7 = loss.random_beamforming() 312 | steering_vector_this_o = steering_vector_this_o 313 | Sigma_time_delay1 = loss.tf_sigma_delay_square(steering_vector_this_o, precoder1, beta) 314 | Sigma_time_delay2 = loss.tf_sigma_delay_square(steering_vector_this_o, precoder2, beta) 315 | Sigma_time_delay3 = loss.tf_sigma_delay_square(steering_vector_this_o, precoder3, beta) 316 | Sigma_time_delay4 = loss.tf_sigma_delay_square(steering_vector_this_o, precoder4, beta) 317 | Sigma_time_delay5 = loss.tf_sigma_delay_square(steering_vector_this_o, precoder5, beta) 318 | Sigma_time_delay6 = loss.tf_sigma_delay_square(steering_vector_this_o, precoder6, beta) 319 | Sigma_time_delay7 = loss.tf_sigma_delay_square(steering_vector_this_o, tf.transpose(zf_matrix,perm=[0,2,1]), beta) 320 | CRB_d1 = tf.reduce_sum(loss.tf_CRB_distance(Sigma_time_delay1),axis=1)/4 321 | CRB_d2 = tf.reduce_sum(loss.tf_CRB_distance(Sigma_time_delay2),axis=1)/4 322 | CRB_d3 = tf.reduce_sum(loss.tf_CRB_distance(Sigma_time_delay3),axis=1)/4 323 | CRB_d4 = tf.reduce_sum(loss.tf_CRB_distance(Sigma_time_delay4),axis=1)/4 324 | CRB_d5 = tf.reduce_sum(loss.tf_CRB_distance(Sigma_time_delay5),axis=1)/4 325 | CRB_d6 = tf.reduce_sum(loss.tf_CRB_distance(Sigma_time_delay6),axis=1)/4 326 | CRB_d7 = tf.reduce_sum(loss.tf_CRB_distance(Sigma_time_delay7),axis=1)/4 327 | #shape = tf.shape(CRB_d1)[0] 328 | #CRB_d7 = loss.tf_CRB_distance(Sigma_time_delay7) 329 | fig, ax1 = plt.subplots() 330 | ax1.plot(range(40), CRB_d1, 'b-.', label='hybrid ISAC') 331 | 332 | ax1.plot(range(40), CRB_d2, 'g-', label='digital ISAC with initialization') 333 | ax1.plot(range(40), CRB_d3, 'r.-', label='digital ISAC,without initialization') 334 | ax1.plot(range(40), CRB_d4, 'm.', label='hybrid only crb_distance') 335 | ax1.plot(range(40), CRB_d5, 'r-', label='digital with initialization only CRB_d') 336 | ax1.plot(range(40), CRB_d6, 'b-', label='digital without initialization only CRB_d') 337 | ax1.plot(range(40), CRB_d7, 'g.', label='ZF precoder') 338 | ax1.set_xlabel('time') 339 | ax1.set_ylabel('CRB distance', color='b') 340 | ax1.tick_params('y', colors='b') 341 | 342 | #plot.legend(loc='best') 343 | fig.tight_layout() 344 | 345 | # 添加图例 346 | lines = [ax1.get_lines()[0], \ 347 | ax1.get_lines()[1], \ 348 | ax1.get_lines()[2], \ 349 | ax1.get_lines()[3], \ 350 | ax1.get_lines()[4],ax1.get_lines()[5],ax1.get_lines()[6]] 351 | #lines = [ax1.get_lines()[0], \ 352 | # ax1.get_lines()[1], \ 353 | # ax1.get_lines()[2]] 354 | 355 | # lines = [ax4.get_lines()[0]] 356 | labels = [line.get_label() for line in lines] 357 | #ax1.legend(lines, labels, bbox_to_anchor=(0.5, 0.4),loc='best') 358 | ax1.legend(lines, labels, loc='best') 359 | ax1.legend_.get_frame().set_facecolor('white') # 设置标签框的背景颜色为白色 360 | ax1.legend_.get_frame().set_linewidth(0.5) # 设置标签框的边框宽度 361 | for text in ax1.legend_.get_texts(): 362 | text.set_fontsize(10) 363 | 364 | #ax1.legend(lines, labels, loc='best') 365 | plt.show() 366 | 367 | 368 | def comparison_between_crb_angle(combined): 369 | CSI = tf.complex(combined[:, :, 6 * antenna_size:7 * antenna_size, 0], 370 | combined[:, :, 7 * antenna_size:8 * antenna_size, 0]) 371 | 372 | steering_vector_this_o = tf.complex(combined[:, :, 0:antenna_size, 0], 373 | combined[:, :, antenna_size:2 * antenna_size, 0]) 374 | zf_matrix = tf.complex(combined[:, :, 4 * antenna_size:5 * antenna_size, 0], 375 | combined[:, :, 5 * antenna_size:6 * antenna_size, 0]) 376 | distance = combined[:, :, 3 * antenna_size:4*antenna_size, 0] 377 | theta = combined[:, :, 2 * antenna_size, 0] 378 | beta = loss.Reflection_coefficient(distance) 379 | model1 = load_model_hybrid_combine() 380 | model2 = load_model_digitalwith_combine() 381 | model3 = load_model_digitalwithout_combine() 382 | model4 = load_model_only_crbangle_hybrid() 383 | model5 = load_model_only_crbangle_digitalwith() 384 | model6 = load_model_only_crbangle_digitalwithout() 385 | output1 = model1(combined) 386 | output2 = model2(combined) 387 | output3 = model3(combined) 388 | output4 = model4(combined) 389 | output5 = model5(combined) 390 | output6 = model6(combined) 391 | analog1,digital1 = loss.tf_Output2PrecodingMatrix_rad(output1) 392 | precoder1 = loss.tf_Precoding_matrix_combine(analog1,digital1) 393 | precoder2 = loss.tf_Output2digitalPrecoding(output2,zf_matrix=zf_matrix,distance=None) 394 | precoder3 = loss.tf_Output2digitalPrecoding(output3, zf_matrix=None,distance=None) 395 | analog4,digital4 = loss.tf_Output2PrecodingMatrix_rad(output4) 396 | precoder4 = loss.tf_Precoding_matrix_combine(analog4,digital4) 397 | precoder5 = loss.tf_Output2digitalPrecoding(output5,zf_matrix=zf_matrix,distance=None) 398 | precoder6 = loss.tf_Output2digitalPrecoding(output6,zf_matrix=None,distance=None) 399 | precoder7 = loss.random_beamforming() 400 | CRB_angle1 = tf.reduce_sum(loss.tf_CRB_angle(beta, precoder1, theta),axis=1)/4 401 | CRB_angle2 = tf.reduce_sum(loss.tf_CRB_angle(beta, precoder2, theta),axis=1)/4 402 | CRB_angle3 = tf.reduce_sum(loss.tf_CRB_angle(beta, precoder3, theta),axis=1)/4 403 | CRB_angle4 = tf.reduce_sum(loss.tf_CRB_angle(beta, precoder4, theta),axis=1)/4 404 | CRB_angle5 = tf.reduce_sum(loss.tf_CRB_angle(beta, precoder5, theta),axis=1)/4 405 | CRB_angle6 = tf.reduce_sum(loss.tf_CRB_angle(beta, precoder6, theta),axis=1)/4 406 | CRB_angle7 = tf.reduce_sum(loss.tf_CRB_angle(beta, tf.transpose(zf_matrix,perm=[0,2,1]), theta),axis=1)/4 407 | fig, ax1 = plt.subplots() 408 | ax1.plot(range(40), CRB_angle1, 'b-.', label='hybrid ISAC') 409 | 410 | ax1.plot(range(40), CRB_angle2, 'g-', label='digital ISAC,with initial point') 411 | ax1.plot(range(40), CRB_angle3, 'r.-', label='digital ISAC,without initial point') 412 | ax1.plot(range(40), CRB_angle4, 'ms', label='hybrid only crb_angle') 413 | ax1.plot(range(40), CRB_angle5, 'r-', label='digital with initial point only crb_angle') 414 | ax1.plot(range(40), CRB_angle6, 'b-', label='digital without initial point only crb_angle') 415 | ax1.plot(range(40), CRB_angle7, 'g.', label='ZF precoder') 416 | ax1.set_xlabel('time') 417 | ax1.set_ylabel('CRB angle', color='b') 418 | ax1.tick_params('y', colors='b') 419 | 420 | # plot.legend(loc='best') 421 | fig.tight_layout() 422 | 423 | # 添加图例 424 | lines = [ax1.get_lines()[0], \ 425 | ax1.get_lines()[1], \ 426 | ax1.get_lines()[2], \ 427 | ax1.get_lines()[3], \ 428 | ax1.get_lines()[4], ax1.get_lines()[5],ax1.get_lines()[6]] 429 | # lines = [ax1.get_lines()[0], \ 430 | # ax1.get_lines()[1], \ 431 | # ax1.get_lines()[2]] 432 | 433 | # lines = [ax4.get_lines()[0]] 434 | labels = [line.get_label() for line in lines] 435 | #ax1.legend(lines, labels, bbox_to_anchor=(0.5, 0.45),loc='best') 436 | ax1.legend(lines, labels, loc='best') 437 | ax1.legend_.get_frame().set_facecolor('white') # 设置标签框的背景颜色为白色 438 | ax1.legend_.get_frame().set_linewidth(0.4) # 设置标签框的边框宽度 439 | for text in ax1.legend_.get_texts(): 440 | text.set_fontsize(10) 441 | #ax1.legend(lines, labels, loc='best') 442 | plt.show() 443 | idx = np.arange(antenna_size) 444 | angle_set = np.arange(1, 181) / 180 * np.pi 445 | Hset = np.exp(1j * np.pi * idx.reshape(-1, 1) * np.cos(angle_set)) 446 | 447 | precoder5 = precoder5.numpy() 448 | print(precoder5.shape) 449 | r1 = np.matmul(Hset.T, precoder4[6, :, :]) 450 | plt.polar(angle_set, np.abs(r1)) 451 | #plt.show() 452 | 453 | 454 | 455 | def comparison_between_sumrate(combined): 456 | #CSI = tf.complex(combined[:,:,0:antenna_size],combined[:,:,antenna_size:2*antenna_size]) 457 | CSI = tf.complex(combined[:, :, 6 * antenna_size:7 * antenna_size, 0], 458 | combined[:, :, 7 * antenna_size:8 * antenna_size, 0]) 459 | 460 | 461 | 462 | 463 | zf_matrix = tf.complex(combined[:, :, 4 * antenna_size:5 * antenna_size, 0], 464 | combined[:, :, 5 * antenna_size:6 * antenna_size, 0]) 465 | model1 = load_model_hybrid_combine() 466 | model2 = load_model_digitalwith_combine() 467 | model3 = load_model_digitalwithout_combine() 468 | model4 = load_model_only_communication_hybrid() 469 | model5 = load_model_only_communication_digitalwith() 470 | model6 = load_model_only_communication_digitalwithout() 471 | output1 = model1(combined) 472 | output2 = model2(combined) 473 | output3 = model3(combined) 474 | output4 = model4(combined) 475 | output5 = model5(combined) 476 | output6 = model6(combined) 477 | analog1,digital1 = loss.tf_Output2PrecodingMatrix_rad(output1) 478 | precoder1 = loss.tf_Precoding_matrix_combine(analog1,digital1) 479 | precoder2 = loss.tf_Output2digitalPrecoding(output2,zf_matrix=zf_matrix,distance=None) 480 | precoder3 = loss.tf_Output2digitalPrecoding(output3, zf_matrix=None,distance=None) 481 | analog4,digital4 = loss.tf_Output2PrecodingMatrix_rad(output4) 482 | precoder4 = loss.tf_Precoding_matrix_combine(analog4,digital4) 483 | precoder5 = loss.tf_Output2digitalPrecoding(output5,zf_matrix=zf_matrix,distance=None) 484 | precoder6 = loss.tf_Output2digitalPrecoding(output6,zf_matrix=None,distance=None) 485 | precoder7 = loss.random_beamforming() 486 | sum_rate1,sinr = loss.tf_loss_sumrate(CSI,precoder1) 487 | sum_rate2,sinr = loss.tf_loss_sumrate(CSI,precoder2) 488 | sum_rate3,sinr = loss.tf_loss_sumrate(CSI,precoder3) 489 | sum_rate4,sinr = loss.tf_loss_sumrate(CSI,precoder4) 490 | sum_rate5,sinr = loss.tf_loss_sumrate(CSI,precoder5) 491 | sum_rate6,sinr = loss.tf_loss_sumrate(CSI,precoder6) 492 | sum_rate7,sinr = loss.tf_loss_sumrate(CSI,tf.transpose(zf_matrix,perm=[0,2,1])) 493 | #sum_rate8,sinr = loss.tf_loss_sumrate(CSI,precoder7) 494 | 495 | 496 | 497 | fig, ax1 = plt.subplots() 498 | ax1.plot(range(40), sum_rate1, 'b-.', label='hybrid ISAC') 499 | #ax2 = ax1.twinx() 500 | ax1.plot(range(40), sum_rate2, 'r--', label='digital ISAC,with initial point') 501 | ax1.plot(range(40), sum_rate3, 'r.-', label='digital ISAC,without initial point') 502 | ax1.plot(range(40), sum_rate4, 'ms', label='hybrid only communication') 503 | ax1.plot(range(40), sum_rate5, 'b-', label='digital with initial point only communication') 504 | ax1.plot(range(40), sum_rate6, 'r-', label='digital without initial point only communication') 505 | ax1.plot(range(40), sum_rate7, 'g.', label='ZF precoder') 506 | ax1.set_xlabel('time') 507 | ax1.set_ylabel('sum rate(bits/s/hz)', color='b') 508 | ax1.tick_params('y', colors='b') 509 | 510 | #plot.legend(loc='best') 511 | fig.tight_layout() 512 | 513 | # 添加图例 514 | lines = [ax1.get_lines()[0], \ 515 | ax1.get_lines()[1], \ 516 | ax1.get_lines()[2], \ 517 | ax1.get_lines()[3], \ 518 | ax1.get_lines()[4],ax1.get_lines()[5],ax1.get_lines()[6]] 519 | 520 | # lines = [ax4.get_lines()[0]] 521 | labels = [line.get_label() for line in lines] 522 | 523 | 524 | 525 | ax1.legend(lines, labels, bbox_to_anchor=(0.55, 0.65),loc = 'center',ncol=1,fontsize=10) 526 | 527 | 528 | #ax1.legend(lines, labels, loc='best', ncol=1, fontsize=10) 529 | 530 | 531 | ax1.legend_.get_frame().set_facecolor('white') # 设置标签框的背景颜色为白色 532 | ax1.legend_.get_frame().set_linewidth(0.4) # 设置标签框的边框宽度 533 | for text in ax1.legend_.get_texts(): 534 | text.set_fontsize(10) 535 | plt.show() 536 | 537 | 538 | idx = np.arange(antenna_size) 539 | angle_set = np.arange(1, 181) / 180 * np.pi 540 | Hset = np.exp(1j * np.pi * idx.reshape(-1, 1) * np.cos(angle_set)) 541 | 542 | precoder5 = precoder5.numpy() 543 | print(precoder5.shape) 544 | r1 = np.matmul(Hset.T, tf.transpose(zf_matrix[30, :, :],perm=[1,0]).numpy()) 545 | r1 = np.matmul(Hset.T, precoder3[10, :, :]) 546 | plt.polar(angle_set, np.abs(r1)) 547 | plt.show() 548 | 549 | def eva(Test): 550 | if Test == "V2V": 551 | real_distance, real_theta = generate_input_v2v() 552 | elif Test == "V2I": 553 | real_distance, real_theta = generate_input_v2i() 554 | #combined = loss.Conversion2CSI(real_distance, real_theta) 555 | combined = loss.Conversion2input_small(real_theta, real_distance) 556 | # this one output the CSI and zf matrix 557 | zf_matrix = tf.complex(combined[:,:,2*antenna_size:3*antenna_size],combined[:,:,3*antenna_size:4*antenna_size]) 558 | #CSI = tf.complex(combined[:,:,0:antenna_size],combined[:,:,antenna_size:2*antenna_size]) 559 | CSI = tf.complex(input[:, :, 6 * antenna_size:7 * antenna_size, 0], 560 | input[:, :, 7 * antenna_size:8 * antenna_size, 0]) 561 | model1 = load_model_hybrid() 562 | model2 = load_model_digital() 563 | model3 = load_model_only_communication_hybrid() 564 | model4 = load_model_only_communication_digital() 565 | output1 = model1(combined) 566 | output2 = model2(combined) 567 | output3 = model3(combined) 568 | output4 = model4(combined) 569 | 570 | 571 | 572 | # 创建一个图形窗口 573 | plt.figure() 574 | 575 | # 绘制第一个模型的输出 576 | plt.plot(range(100), sum_rate1, label='') 577 | 578 | # 绘制第二个模型的输出 579 | plt.plot(range(100), sum_rate2, label='Model 2') 580 | 581 | # 绘制第三个模型的输出 582 | plt.plot(range(100), sum_rate3, label='Model 3') 583 | 584 | # 绘制第四个模型的输出 585 | plt.plot(range(100), sum_rate4, label='Model 4') 586 | 587 | # 添加图例 588 | plt.legend() 589 | 590 | # 添加标题和轴标签 591 | plt.title('Sum rate at every timepoint') 592 | plt.xlabel('time') 593 | plt.ylabel('sum rate: bits/s/Hz') 594 | 595 | # 显示图形 596 | plt.show() 597 | 598 | 599 | #random.seed(2) 600 | if Test == "V2V": 601 | real_distance, real_theta = generate_input_v2v() 602 | elif Test == "V2I": 603 | real_distance, real_theta = generate_input_v2i() 604 | 605 | 606 | #combined = loss.Conversion2CSI(real_distance, real_theta)P 607 | combined = loss.Conversion2input_small(real_theta.T[:40], real_distance.T[:40]) 608 | 609 | combined = tf.expand_dims(combined, axis=3) 610 | #comparison_between_sumrate(combined) 611 | #comparison_between_crb_distance(combined) 612 | #comparison_between_crb_angle(combined) 613 | #print("real_distance",real_distance.T.shape) 614 | #print("real_theta",real_theta.T.shape) 615 | 616 | 617 | 618 | 619 | 620 | 621 | -------------------------------------------------------------------------------- /network.py: -------------------------------------------------------------------------------- 1 | ''' 2 | this is the NN for beamforming 3 | input contains three factors maybe ( angle, distance, velocity) 4 | think we need to add the velocity(not sure estimated or the real) as the input 5 | 6 | the question remains is if we need to use real_angle and real_distance or the estimated one 7 | 8 | 9 | 2. need to consider the specific output should link to the specific input, to let every user has 10 | linked element of matrix 11 | 12 | ResNet code snippet partly refers to 13 | MIT License 14 | 15 | Copyright (c) 2019 calmisential 16 | 17 | Permission is hereby granted, free of charge, to any person obtaining a copy 18 | of this software and associated documentation files (the "Software"), to deal 19 | in the Software without restriction, including without limitation the rights 20 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 21 | copies of the Software, and to permit persons to whom the Software is 22 | furnished to do so, subject to the following conditions: 23 | 24 | The above copyright notice and this permission notice shall be included in all 25 | copies or substantial portions of the Software. 26 | 27 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 28 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 29 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 30 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 31 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 32 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 33 | SOFTWARE. 34 | ''' 35 | 36 | 37 | import tensorflow.keras as keras 38 | from keras.layers import Dense,LSTM,Concatenate 39 | from keras.layers import Conv2D 40 | from keras.layers import MaxPooling2D 41 | from keras.layers import Flatten 42 | import tensorflow as tf 43 | import numpy as np 44 | import config_parameter 45 | from tensorflow import keras 46 | from tensorflow.keras.layers import Conv1D, LSTM, Dense, BatchNormalization, Activation, Add,Reshape 47 | from tensorflow.keras.regularizers import l2 48 | class ResNet(tf.keras.Model): 49 | def __init__(self, layer_params=[0,0,1,0]): 50 | super(ResNet, self).__init__() 51 | self.conv1 = tf.keras.layers.Conv2D(filters=64, 52 | kernel_size=(3, 3), 53 | strides=2, 54 | padding="same") 55 | self.bn1 = tf.keras.layers.BatchNormalization() 56 | self.pool1 = tf.keras.layers.MaxPool2D(pool_size=(3, 3), 57 | strides=2, 58 | padding="same") 59 | 60 | self.layer1 = make_bottleneck_layer(filter_num=64, 61 | blocks=layer_params[0]) 62 | self.layer2 = make_bottleneck_layer(filter_num=128, 63 | blocks=layer_params[1], 64 | stride=2) 65 | self.layer3 = make_bottleneck_layer(filter_num=256, 66 | blocks=layer_params[2], 67 | stride=2) 68 | self.layer4 = make_bottleneck_layer(filter_num=512, 69 | blocks=layer_params[3], 70 | stride=2) 71 | 72 | self.avgpool = tf.keras.layers.GlobalAveragePooling2D() 73 | num_vehicle = config_parameter.num_uppercar + config_parameter.num_lowercar + config_parameter.num_horizoncar 74 | 75 | #parameter_size = config_parameter.rf_size * config_parameter.vehicle_antenna_size + 2 * config_parameter.rf_size * num_vehicle 76 | parameter_size = 2*config_parameter.vehicle_antenna_size*num_vehicle 77 | #parameter_size = config_parameter.rf_size * config_parameter.vehicle_antenna_size + 2 * config_parameter.rf_size * num_vehicle #e64777e4300db20e83b8d9ae1526e548fcb0d836 78 | self.lstm = tf.keras.layers.LSTM(units=64) 79 | self.fc = tf.keras.layers.Dense(units=parameter_size, activation=tf.keras.activations.softmax) 80 | 81 | def call(self, inputs, training=None, mask=None): 82 | x = self.conv1(inputs) 83 | x = self.bn1(x, training=training) 84 | x = tf.nn.leaky_relu(x) 85 | x = self.pool1(x) 86 | x = self.layer1(x, training=training) 87 | x = self.layer2(x, training=training) 88 | x = self.layer3(x, training=training) 89 | x = self.layer4(x, training=training) 90 | #x = self.lstm(x) 91 | x = self.avgpool(x) 92 | output = self.fc(x) 93 | 94 | return output 95 | 96 | from config_parameter import rf_size, antenna_size 97 | def make_bottleneck_layer(filter_num, blocks, stride=1): 98 | 99 | res_block = tf.keras.Sequential() 100 | #res_block.add(BottleNeck(filter_num, stride=stride)) 101 | #res_block.add(OneD_BottleNeck(filter_num, stride=stride)) 102 | res_block.add(BottleNeck(filter_num, stride=stride)) 103 | for _ in range(1, blocks): 104 | res_block.add(BottleNeck(filter_num, stride=stride)) 105 | #res_block.add(BottleNeck(filter_num, stride=stride)) 106 | 107 | #res_block.add(OneD_BottleNeck(filter_num, stride=stride)) 108 | return res_block 109 | 110 | 111 | 112 | 113 | 114 | class DL_method_NN_for_v2x_mod1(keras.Model): 115 | def __init__(self): 116 | super().__init__() 117 | act_func = "LeakyReLU" 118 | init = keras.initializers.GlorotNormal() #Xavier initializer 119 | 120 | num_vehicle = config_parameter.num_uppercar + config_parameter.num_lowercar + config_parameter.num_horizoncar 121 | self.conv_layer1 = Conv2D(32, kernel_size=3, activation=act_func, kernel_initializer=init, padding="same") 122 | self.bn1 = keras.layers.BatchNormalization() 123 | self.maxpool1 = MaxPooling2D() 124 | self.conv_layer2 = Conv2D(64, kernel_size=3, activation=act_func, kernel_initializer=init, padding="same") 125 | self.dropout2 = keras.layers.Dropout(0.2) 126 | self.bn2 = keras.layers.BatchNormalization() 127 | self.maxpool2 = MaxPooling2D() 128 | self.conv_layer3 = Conv2D(128, kernel_size=3, activation=act_func, kernel_initializer=init, padding="same") 129 | self.bn3 = keras.layers.BatchNormalization() 130 | self.conv_layer4 = Conv2D(256,kernel_size=3,activation=act_func,kernel_initializer=init,padding="same") 131 | self.bn4 = keras.layers.BatchNormalization() 132 | self.dropout3 = keras.layers.Dropout(0.15) 133 | 134 | self.maxpool3 = MaxPooling2D() 135 | self.avgpool = tf.keras.layers.GlobalAveragePooling2D() 136 | self.flatten = Flatten() 137 | #self.dense_1 = Dense(1200, activation=act_func, kernel_initializer=init) 138 | #self.dense_2 = Dense(1200, activation=act_func, kernel_initializer=init) 139 | #self.dense_3 = Dense(600, activation=act_func, kernel_initializer=init) 140 | 141 | #self.dense_5 = Dense(20, activation=act_func, kernel_initializer=init) 142 | #self.dense_6 = Dense(20, activation=act_func, kernel_initializer=init) 143 | num_vehicle = config_parameter.num_uppercar + config_parameter.num_lowercar +config_parameter.num_horizoncar 144 | #parameter_size = config_parameter.rf_size*config_parameter.vehicle_antenna_size + 2*config_parameter.rf_size*num_vehicle 145 | parameter_size = 2 * config_parameter.vehicle_antenna_size * num_vehicle 146 | #self.out = Dense(parameter_size, activation='softmax', kernel_initializer=init) 147 | #self.dense_4 = Dense(parameter_size, activation='softmax', kernel_initializer=init) 148 | #self.dense_4 = Dense(600, activation=act_func, kernel_initializer=init) 149 | self.fc = tf.keras.layers.Dense(units=parameter_size) 150 | self.act = tf.keras.layers.LeakyReLU(alpha=1) 151 | 152 | def call(self, input): 153 | out = self.conv_layer1(input) 154 | #out = self.maxpool1(out) 155 | out = self.bn1(out) 156 | out = self.conv_layer2(out) 157 | out= self.dropout2(out) 158 | #out = self.maxpool2(out) 159 | out = self.bn2(out) 160 | out = self.conv_layer3(out) 161 | out = self.bn3(out) 162 | out =self.conv_layer4(out) 163 | out =self.bn4(out) 164 | out = self.dropout3(out) 165 | out = self.avgpool(out) 166 | #out = self.maxpool3(out) 167 | #out = self.bn3(out) 168 | out = self.flatten(out) 169 | 170 | #out = self.dense_1(out) 171 | #out = self.dense_2(out) 172 | #out = self.dense_3(out) 173 | #out = self.dense_4(out) 174 | out = self.fc(out) 175 | x = self.act(out) 176 | x = tf.where(tf.math.greater(x, 0), tf.minimum(x, 5.0), tf.maximum(x, -5.0)) 177 | #out = tf.clip_by_value(out, 1e-10, 5-(1e-10)) 178 | #Parameter = tf.clip_by_value(out,1e-10,1-1e-10) 179 | 180 | 181 | return x 182 | class DL_method_NN_for_v2x_hybrid(keras.Model): 183 | def __init__(self): 184 | super().__init__() 185 | act_func = "LeakyReLU" 186 | init = keras.initializers.GlorotNormal() #Xavier initializer 187 | 188 | num_vehicle = config_parameter.num_uppercar + config_parameter.num_lowercar + config_parameter.num_horizoncar 189 | self.conv_layer1 = Conv2D(32, kernel_size=1, activation=act_func, kernel_initializer=init, padding="same",kernel_regularizer=l2(1e-4)) 190 | self.bn1 = keras.layers.BatchNormalization() 191 | self.maxpool1 = MaxPooling2D() 192 | self.conv_layer7 = Conv2D(32, kernel_size=1, activation=act_func, kernel_initializer=init, padding="same", 193 | kernel_regularizer=l2(1e-4)) 194 | self.bn7 = keras.layers.BatchNormalization() 195 | self.conv_layer2 = Conv2D(64, kernel_size=3, activation=act_func, kernel_initializer=init, padding="same",kernel_regularizer=l2(1e-4)) 196 | self.dropout2 = keras.layers.Dropout(0.2) 197 | self.bn2 = keras.layers.BatchNormalization() 198 | self.maxpool2 = MaxPooling2D() 199 | self.conv_layer3 = Conv2D(64, kernel_size=3, activation=act_func, kernel_initializer=init, padding="same",kernel_regularizer=l2(1e-4)) 200 | self.bn3 = keras.layers.BatchNormalization() 201 | self.maxpool3 = tf.keras.layers.GlobalAveragePooling2D() 202 | self.conv_layer4 = Conv2D(128,kernel_size=3,activation=act_func,kernel_initializer=init,padding="same",kernel_regularizer=l2(1e-4)) 203 | self.bn4 = keras.layers.BatchNormalization() 204 | self.maxpool4 = tf.keras.layers.GlobalAveragePooling2D() 205 | self.conv_layer5 = Conv2D(128,kernel_size=3,activation=act_func,kernel_initializer=init,padding="same",kernel_regularizer=l2(1e-4)) 206 | self.bn5 = keras.layers.BatchNormalization() 207 | #self.maxpool5 = MaxPooling2D() 208 | self.conv_layer6 = Conv2D(256,kernel_size=3,activation=act_func,kernel_initializer=init,padding="same",kernel_regularizer=l2(1e-4)) 209 | self.bn6 = keras.layers.BatchNormalization() 210 | self.maxpool5 = tf.keras.layers.GlobalAveragePooling2D() 211 | self.dropout3 = keras.layers.Dropout(0.3) 212 | 213 | self.maxpool3 = MaxPooling2D() 214 | self.avgpool = tf.keras.layers.GlobalAveragePooling2D() 215 | self.flatten = Flatten() 216 | self.dense_1 = Dense(1024, activation=act_func, kernel_initializer=init) 217 | self.dense_2 = Dense(512, activation=act_func, kernel_initializer=init) 218 | #self.dense_3 = Dense(600, activation=act_func, kernel_initializer=init) 219 | 220 | #self.dense_5 = Dense(20, activation=act_func, kernel_initializer=init) 221 | #self.dense_6 = Dense(20, activation=act_func, kernel_initializer=init) 222 | num_vehicle = config_parameter.num_uppercar + config_parameter.num_lowercar +config_parameter.num_horizoncar 223 | parameter_size = config_parameter.rf_size*config_parameter.vehicle_antenna_size + 2*config_parameter.rf_size*num_vehicle 224 | #parameter_size = 2 * config_parameter.vehicle_antenna_size * num_vehicle 225 | #self.out = Dense(parameter_size, activation='softmax', kernel_initializer=init) 226 | #self.dense_4 = Dense(parameter_size, activation='softmax', kernel_initializer=init) 227 | #self.dense_4 = Dense(600, activation=act_func, kernel_initializer=init) 228 | #self. 229 | self.fc = tf.keras.layers.Dense(units=parameter_size) 230 | self.act = tf.keras.layers.LeakyReLU(alpha=1) 231 | 232 | def call(self, input): 233 | out = self.conv_layer1(input) 234 | #out = self.maxpool1(out) 235 | out = self.bn1(out) 236 | out = self.conv_layer7(out) 237 | #out = self.bn7(out) 238 | #out = self.conv_layer2(out) 239 | 240 | #out = self.maxpool2(out) 241 | # 242 | out = self.bn2(out) 243 | out = self.dropout2(out) 244 | out = self.conv_layer3(out) 245 | 246 | out = self.maxpool3(out) 247 | out = self.bn3(out) 248 | out =self.conv_layer4(out) 249 | #out = self.maxpool4(out) 250 | out =self.bn4(out) 251 | 252 | out =self.conv_layer5(out) 253 | #out = self.maxpool5(out) 254 | out =self.bn5(out) 255 | #out =self.conv_layer6(out) 256 | #out = self.maxpool6(out) 257 | #out =self.bn6(out) 258 | out = self.dropout3(out) 259 | out = self.avgpool(out) 260 | 261 | #out = self.bn3(out) 262 | out = self.flatten(out) 263 | 264 | #out = self.dense_1(out) 265 | #out = self.dense_2(out) 266 | #out = self.dense_3(out) 267 | #out = self.dense_4(out) 268 | #out = self.dense_1(out) 269 | #out = self.dense_2(out) 270 | out = self.fc(out) 271 | x = self.act(out) 272 | #x = tf.where(tf.math.greater(x, 0), tf.minimum(x, 5.0), tf.maximum(x, -5.0)) 273 | #out = tf.clip_by_value(out, 1e-10, 5-(1e-10)) 274 | #Parameter = tf.clip_by_value(out,1e-10,1-1e-10) 275 | 276 | 277 | return x 278 | class DL_method_NN_for_v2x_hybrid2(keras.Model): 279 | def __init__(self): 280 | super().__init__() 281 | act_func = "LeakyReLU" 282 | init = keras.initializers.GlorotNormal() #Xavier initializer 283 | 284 | num_vehicle = config_parameter.num_uppercar + config_parameter.num_lowercar + config_parameter.num_horizoncar 285 | self.conv_layer1 = Conv2D(32, kernel_size=1, activation=act_func, kernel_initializer=init, padding="same",kernel_regularizer=l2(1e-4)) 286 | self.bn1 = keras.layers.BatchNormalization() 287 | self.maxpool1 = MaxPooling2D() 288 | self.conv_layer7 = Conv2D(32, kernel_size=1, activation=act_func, kernel_initializer=init, padding="same", 289 | kernel_regularizer=l2(1e-4)) 290 | self.bn7 = keras.layers.BatchNormalization() 291 | self.conv_layer2 = Conv2D(64, kernel_size=3, activation=act_func, kernel_initializer=init, padding="same",kernel_regularizer=l2(1e-4)) 292 | self.dropout2 = keras.layers.Dropout(0.3) 293 | self.bn2 = keras.layers.BatchNormalization() 294 | self.maxpool2 = MaxPooling2D() 295 | self.conv_layer3 = Conv2D(64, kernel_size=3, activation=act_func, kernel_initializer=init, padding="same",kernel_regularizer=l2(1e-4)) 296 | self.bn3 = keras.layers.BatchNormalization() 297 | self.maxpool3 = tf.keras.layers.GlobalAveragePooling2D() 298 | self.conv_layer4 = Conv2D(128,kernel_size=3,activation=act_func,kernel_initializer=init,padding="same",kernel_regularizer=l2(1e-4)) 299 | self.bn4 = keras.layers.BatchNormalization() 300 | self.maxpool4 = tf.keras.layers.GlobalAveragePooling2D() 301 | self.conv_layer5 = Conv2D(128,kernel_size=3,activation=act_func,kernel_initializer=init,padding="same",kernel_regularizer=l2(1e-4)) 302 | self.bn5 = keras.layers.BatchNormalization() 303 | #self.maxpool5 = MaxPooling2D() 304 | self.conv_layer6 = Conv2D(256,kernel_size=3,activation=act_func,kernel_initializer=init,padding="same",kernel_regularizer=l2(1e-4)) 305 | self.bn6 = keras.layers.BatchNormalization() 306 | self.maxpool5 = tf.keras.layers.GlobalAveragePooling2D() 307 | self.dropout3 = keras.layers.Dropout(0.3) 308 | 309 | self.maxpool3 = MaxPooling2D() 310 | self.avgpool = tf.keras.layers.GlobalAveragePooling2D() 311 | self.flatten = Flatten() 312 | self.dense_1 = Dense(1024, activation=act_func, kernel_initializer=init) 313 | self.dense_2 = Dense(512, activation=act_func, kernel_initializer=init) 314 | #self.dense_3 = Dense(600, activation=act_func, kernel_initializer=init) 315 | 316 | #self.dense_5 = Dense(20, activation=act_func, kernel_initializer=init) 317 | #self.dense_6 = Dense(20, activation=act_func, kernel_initializer=init) 318 | num_vehicle = config_parameter.num_uppercar + config_parameter.num_lowercar +config_parameter.num_horizoncar 319 | parameter_size = config_parameter.rf_size*config_parameter.vehicle_antenna_size + 2*config_parameter.rf_size*num_vehicle 320 | #parameter_size = 2 * config_parameter.vehicle_antenna_size * num_vehicle 321 | #self.out = Dense(parameter_size, activation='softmax', kernel_initializer=init) 322 | #self.dense_4 = Dense(parameter_size, activation='softmax', kernel_initializer=init) 323 | #self.dense_4 = Dense(600, activation=act_func, kernel_initializer=init) 324 | #self. 325 | self.fc = tf.keras.layers.Dense(units=parameter_size) 326 | self.act = tf.keras.layers.LeakyReLU(alpha=1) 327 | 328 | def call(self, input): 329 | out = self.conv_layer1(input) 330 | #out = self.maxpool1(out) 331 | out = self.bn1(out) 332 | out = self.conv_layer7(out) 333 | out = self.bn7(out) 334 | #out = self.conv_layer2(out) 335 | 336 | out = self.maxpool2(out) 337 | # 338 | out = self.bn2(out) 339 | out = self.dropout2(out) 340 | out = self.conv_layer3(out) 341 | 342 | out = self.maxpool3(out) 343 | out = self.bn3(out) 344 | out =self.conv_layer4(out) 345 | #out = self.maxpool4(out) 346 | out =self.bn4(out) 347 | 348 | out =self.conv_layer5(out) 349 | #out = self.maxpool5(out) 350 | out =self.bn5(out) 351 | #out =self.conv_layer6(out) 352 | #out = self.maxpool6(out) 353 | #out =self.bn6(out) 354 | out = self.dropout3(out) 355 | out = self.avgpool(out) 356 | 357 | #out = self.bn3(out) 358 | out = self.flatten(out) 359 | 360 | #out = self.dense_1(out) 361 | #out = self.dense_2(out) 362 | #out = self.dense_3(out) 363 | #out = self.dense_4(out) 364 | #out = self.dense_1(out) 365 | #out = self.dense_2(out) 366 | out = self.fc(out) 367 | x = self.act(out) 368 | #x = tf.where(tf.math.greater(x, 0), tf.minimum(x, 5.0), tf.maximum(x, -5.0)) 369 | #out = tf.clip_by_value(out, 1e-10, 5-(1e-10)) 370 | #Parameter = tf.clip_by_value(out,1e-10,1-1e-10) 371 | 372 | 373 | return x 374 | 375 | class DL_method_NN_for_v2x_mod(keras.Model): 376 | def __init__(self): 377 | super().__init__() 378 | act_func = "LeakyReLU" 379 | init = keras.initializers.GlorotNormal() #Xavier initializer 380 | 381 | num_vehicle = config_parameter.num_uppercar + config_parameter.num_lowercar + config_parameter.num_horizoncar 382 | self.conv_layer1 = Conv2D(32, kernel_size=1, activation=act_func, kernel_initializer=init, padding="same",kernel_regularizer=l2(1e-4)) 383 | self.bn1 = keras.layers.BatchNormalization() 384 | self.maxpool1 = MaxPooling2D() 385 | self.conv_layer7 = Conv2D(32, kernel_size=1, activation=act_func, kernel_initializer=init, padding="same", 386 | kernel_regularizer=l2(1e-4)) 387 | self.bn7 = keras.layers.BatchNormalization() 388 | self.conv_layer2 = Conv2D(64, kernel_size=3, activation=act_func, kernel_initializer=init, padding="same",kernel_regularizer=l2(1e-4)) 389 | self.dropout2 = keras.layers.Dropout(0.2) 390 | self.bn2 = keras.layers.BatchNormalization() 391 | self.maxpool2 = MaxPooling2D() 392 | self.conv_layer3 = Conv2D(64, kernel_size=3, activation=act_func, kernel_initializer=init, padding="same",kernel_regularizer=l2(1e-4)) 393 | self.bn3 = keras.layers.BatchNormalization() 394 | self.maxpool3 = tf.keras.layers.GlobalAveragePooling2D() 395 | self.conv_layer4 = Conv2D(128,kernel_size=3,activation=act_func,kernel_initializer=init,padding="same",kernel_regularizer=l2(1e-4)) 396 | self.bn4 = keras.layers.BatchNormalization() 397 | self.maxpool4 = tf.keras.layers.GlobalAveragePooling2D() 398 | self.conv_layer5 = Conv2D(128,kernel_size=3,activation=act_func,kernel_initializer=init,padding="same",kernel_regularizer=l2(1e-4)) 399 | self.bn5 = keras.layers.BatchNormalization() 400 | #self.maxpool5 = MaxPooling2D() 401 | self.conv_layer6 = Conv2D(256,kernel_size=3,activation=act_func,kernel_initializer=init,padding="same",kernel_regularizer=l2(1e-4)) 402 | self.bn6 = keras.layers.BatchNormalization() 403 | self.maxpool5 = tf.keras.layers.GlobalAveragePooling2D() 404 | self.dropout3 = keras.layers.Dropout(0.3) 405 | 406 | self.maxpool3 = MaxPooling2D() 407 | self.avgpool = tf.keras.layers.GlobalAveragePooling2D() 408 | self.flatten = Flatten() 409 | self.dense_1 = Dense(1024, activation=act_func, kernel_initializer=init) 410 | self.dense_2 = Dense(512, activation=act_func, kernel_initializer=init) 411 | #self.dense_3 = Dense(600, activation=act_func, kernel_initializer=init) 412 | 413 | #self.dense_5 = Dense(20, activation=act_func, kernel_initializer=init) 414 | #self.dense_6 = Dense(20, activation=act_func, kernel_initializer=init) 415 | num_vehicle = config_parameter.num_uppercar + config_parameter.num_lowercar +config_parameter.num_horizoncar 416 | #parameter_size = config_parameter.rf_size*config_parameter.vehicle_antenna_size + 2*config_parameter.rf_size*num_vehicle 417 | parameter_size = 2 * config_parameter.vehicle_antenna_size * num_vehicle 418 | #self.out = Dense(parameter_size, activation='softmax', kernel_initializer=init) 419 | #self.dense_4 = Dense(parameter_size, activation='softmax', kernel_initializer=init) 420 | #self.dense_4 = Dense(600, activation=act_func, kernel_initializer=init) 421 | #self. 422 | self.fc = tf.keras.layers.Dense(units=parameter_size) 423 | self.act = tf.keras.layers.LeakyReLU(alpha=1) 424 | 425 | def call(self, input): 426 | out = self.conv_layer1(input) 427 | #out = self.maxpool1(out) 428 | out = self.bn1(out) 429 | out = self.conv_layer7(out) 430 | #out = self.bn7(out) 431 | #out = self.conv_layer2(out) 432 | 433 | #out = self.maxpool2(out) 434 | # 435 | out = self.bn2(out) 436 | out = self.dropout2(out) 437 | out = self.conv_layer3(out) 438 | 439 | out = self.maxpool3(out) 440 | out = self.bn3(out) 441 | out =self.conv_layer4(out) 442 | #out = self.maxpool4(out) 443 | out =self.bn4(out) 444 | 445 | out =self.conv_layer5(out) 446 | #out = self.maxpool5(out) 447 | out =self.bn5(out) 448 | #out =self.conv_layer6(out) 449 | #out = self.maxpool6(out) 450 | #out =self.bn6(out) 451 | out = self.dropout3(out) 452 | out = self.avgpool(out) 453 | 454 | #out = self.bn3(out) 455 | out = self.flatten(out) 456 | 457 | #out = self.dense_1(out) 458 | #out = self.dense_2(out) 459 | #out = self.dense_3(out) 460 | #out = self.dense_4(out) 461 | #out = self.dense_1(out) 462 | #out = self.dense_2(out) 463 | out = self.fc(out) 464 | x = self.act(out) 465 | #x = tf.where(tf.math.greater(x, 0), tf.minimum(x, 5.0), tf.maximum(x, -5.0)) 466 | #out = tf.clip_by_value(out, 1e-10, 5-(1e-10)) 467 | #Parameter = tf.clip_by_value(out,1e-10,1-1e-10) 468 | 469 | 470 | return x 471 | 472 | class DL_method_NN_with_theta(keras.Model): 473 | def __init__(self): 474 | super().__init__() 475 | act_func = "relu" 476 | init = keras.initializers.GlorotNormal() #Xavier initializer 477 | self.conv_layer1 = Conv2D(32, kernel_size=3, activation=act_func, input_shape=(1, 10, 5, 2), kernel_initializer=init, padding="same") 478 | self.bn1 = keras.layers.BatchNormalization() 479 | self.maxpool1 = MaxPooling2D() 480 | self.conv_layer2 = Conv2D(64, kernel_size=3, activation=act_func, kernel_initializer=init, padding="same") 481 | self.bn2 = keras.layers.BatchNormalization() 482 | self.maxpool2 = MaxPooling2D() 483 | self.conv_layer3 = Conv2D(64, kernel_size=3, activation=act_func, kernel_initializer=init, padding="same") 484 | self.bn3 = keras.layers.BatchNormalization() 485 | self.maxpool3 = MaxPooling2D() 486 | self.flatten = Flatten() 487 | self.dense_1 = Dense(1200, activation=act_func, kernel_initializer=init) 488 | self.dense_2 = Dense(1200, activation=act_func, kernel_initializer=init) 489 | self.dense_3 = Dense(600, activation=act_func, kernel_initializer=init) 490 | self.dense_4 = Dense(600, activation=act_func, kernel_initializer=init) 491 | #self.dense_5 = Dense(20, activation=act_func, kernel_initializer=init) 492 | #self.dense_6 = Dense(20, activation=act_func, kernel_initializer=init) 493 | parameter_size = config_parameter.rf_size*config_parameter.antenna_size + 2*config_parameter.rf_size*config_parameter.num_vehicle +\ 494 | config_parameter.num_vehicle# the last item is the theta prediction 495 | self.out = Dense(parameter_size, activation='softmax', kernel_initializer=init) 496 | 497 | 498 | def call(self, input): 499 | out = self.conv_layer1(input) 500 | out = self.maxpool1(out) 501 | out = self.bn1(out) 502 | out = self.conv_layer2(out) 503 | out = self.maxpool2(out) 504 | out = self.bn2(out) 505 | out = self.conv_layer3(out) 506 | out = self.maxpool3(out) 507 | out = self.bn3(out) 508 | out = self.flatten(out) 509 | 510 | out = self.dense_1(out) 511 | out = self.dense_2(out) 512 | out = self.dense_3(out) 513 | out = self.out(out) 514 | Parameter = tf.clip_by_value(out,1e-10,1-1e-10) 515 | 516 | 517 | return Parameter 518 | 519 | class DL_method_NN(keras.Model): 520 | def __init__(self): 521 | super().__init__() 522 | act_func = "relu" 523 | init = keras.initializers.GlorotNormal() #Xavier initializer 524 | self.conv_layer1 = Conv2D(32, kernel_size=3, activation=act_func, input_shape=(1, 10, 5, 3), kernel_initializer=init, padding="same") 525 | self.bn1 = keras.layers.BatchNormalization() 526 | self.maxpool1 = MaxPooling2D() 527 | self.conv_layer2 = Conv2D(64, kernel_size=3, activation=act_func, kernel_initializer=init, padding="same") 528 | self.bn2 = keras.layers.BatchNormalization() 529 | self.maxpool2 = MaxPooling2D() 530 | self.conv_layer3 = Conv2D(64, kernel_size=3, activation=act_func, kernel_initializer=init, padding="same") 531 | self.bn3 = keras.layers.BatchNormalization() 532 | self.maxpool3 = MaxPooling2D() 533 | self.flatten = Flatten() 534 | #self.dense_1 = Dense(1200, activation=act_func, kernel_initializer=init) 535 | #self.dense_2 = Dense(1200, activation=act_func, kernel_initializer=init) 536 | self.dense_3 = Dense(600, activation=act_func, kernel_initializer=init) 537 | self.dense_4 = Dense(600, activation=act_func, kernel_initializer=init) 538 | #self.dense_5 = Dense(20, activation=act_func, kernel_initializer=init) 539 | #self.dense_6 = Dense(20, activation=act_func, kernel_initializer=init) 540 | parameter_size = config_parameter.rf_size*config_parameter.antenna_size + 2*config_parameter.rf_size*config_parameter.num_vehicle 541 | self.out = Dense(parameter_size, activation='softmax', kernel_initializer=init) 542 | 543 | 544 | def call(self, input): 545 | out = self.conv_layer1(input) 546 | out = self.maxpool1(out) 547 | out = self.bn1(out) 548 | out = self.conv_layer2(out) 549 | out = self.maxpool2(out) 550 | out = self.bn2(out) 551 | #out = self.conv_layer3(out) 552 | #out = self.maxpool3(out) 553 | #out = self.bn3(out) 554 | out = self.flatten(out) 555 | 556 | out = self.dense_1(out) 557 | out = self.dense_2(out) 558 | out = self.dense_3(out) 559 | out = self.out(out) 560 | #Parameter = tf.clip_by_value(out,1e-10,1-1e-10) 561 | Parameter = tf.clip_by_value(out, 0.001, 0.999) 562 | 563 | 564 | return Parameter 565 | class DL_method_NN_Digital(keras.Model): 566 | def __init__(self): 567 | super().__init__() 568 | act_func = "relu" 569 | init = keras.initializers.GlorotNormal() #Xavier initializer 570 | self.conv_layer1 = Conv2D(32, kernel_size=3, activation=act_func, input_shape=(1, 10, 5, 2), kernel_initializer=init, padding="same") 571 | self.bn1 = keras.layers.BatchNormalization() 572 | self.maxpool1 = MaxPooling2D() 573 | self.conv_layer2 = Conv2D(64, kernel_size=3, activation=act_func, kernel_initializer=init, padding="same") 574 | self.bn2 = keras.layers.BatchNormalization() 575 | self.maxpool2 = MaxPooling2D() 576 | self.conv_layer3 = Conv2D(64, kernel_size=3, activation=act_func, kernel_initializer=init, padding="same") 577 | self.bn3 = keras.layers.BatchNormalization() 578 | self.maxpool3 = MaxPooling2D() 579 | self.flatten = Flatten() 580 | self.dense_1 = Dense(1200, activation=act_func, kernel_initializer=init) 581 | self.dense_2 = Dense(1200, activation=act_func, kernel_initializer=init) 582 | self.dense_3 = Dense(600, activation=act_func, kernel_initializer=init) 583 | self.dense_4 = Dense(600, activation=act_func, kernel_initializer=init) 584 | #self.dense_5 = Dense(20, activation=act_func, kernel_initializer=init) 585 | #self.dense_6 = Dense(20, activation=act_func, kernel_initializer=init) 586 | parameter_size = 2*config_parameter.antenna_size*config_parameter.num_vehicle 587 | self.out = Dense(parameter_size, activation='softmax', kernel_initializer=init) 588 | 589 | 590 | def call(self, input): 591 | out = self.conv_layer1(input) 592 | out = self.maxpool1(out) 593 | out = self.bn1(out) 594 | out = self.conv_layer2(out) 595 | out = self.maxpool2(out) 596 | out = self.bn2(out) 597 | #out = self.conv_layer3(out) 598 | #out = self.maxpool3(out) 599 | #out = self.bn3(out) 600 | out = self.flatten(out) 601 | 602 | out = self.dense_1(out) 603 | out = self.dense_2(out) 604 | out = self.dense_3(out) 605 | out = self.out(out) 606 | #Parameter = tf.clip_by_value(out,1e-10,1-1e-10) 607 | Parameter = tf.clip_by_value(out, 0.001, 0.999) 608 | 609 | return Parameter 610 | class DL_method_NN_naive_digital(keras.Model): 611 | def __init__(self): 612 | super().__init__() 613 | act_func = "relu" 614 | init = keras.initializers.GlorotNormal() #Xavier initializer 615 | self.dense_1 = Dense(1200, activation=act_func,input_shape=(1, 10, 5, 2), kernel_initializer=init) 616 | self.dense_2 = Dense(1200, activation=act_func, kernel_initializer=init) 617 | self.dense_3 = Dense(600, activation=act_func, kernel_initializer=init) 618 | #self.dense_4 = Dense(600, activation=act_func, kernel_initializer=init) 619 | #self.dense_5 = Dense(20, activation=act_func, kernel_initializer=init) 620 | #self.dense_6 = Dense(20, activation=act_func, kernel_initializer=init) 621 | parameter_size = 2*config_parameter.antenna_size*config_parameter.num_vehicle 622 | self.out = Dense(parameter_size, activation='softmax', kernel_initializer=init) 623 | 624 | 625 | def call(self, input): 626 | 627 | 628 | out = self.dense_1(input) 629 | out = self.dense_2(out) 630 | out = self.dense_3(out) 631 | out = self.out(out) 632 | Parameter = tf.clip_by_value(out,1e-10,1-1e-10) 633 | 634 | 635 | return Parameter 636 | 637 | 638 | class DL_method_NN_naive_hybrid(keras.Model): 639 | def __init__(self): 640 | super().__init__() 641 | act_func = "relu" 642 | init = keras.initializers.GlorotNormal() # Xavier initializer 643 | self.dense_1 = Dense(1200, activation=act_func, input_shape=(1, 10, config_parameter.num_vehicle, 2), kernel_initializer=init) 644 | self.dense_2 = Dense(1200, activation=act_func, kernel_initializer=init) 645 | self.dense_3 = Dense(600, activation=act_func, kernel_initializer=init) 646 | #self.dense_4 = Dense(600, activation=act_func, kernel_initializer=init) 647 | # self.dense_5 = Dense(20, activation=act_func, kernel_initializer=init) 648 | # self.dense_6 = Dense(20, activation=act_func, kernel_initializer=init) 649 | parameter_size = config_parameter.rf_size * config_parameter.antenna_size + 2 * config_parameter.rf_size * config_parameter.num_vehicle 650 | self.out = Dense(parameter_size, activation='softmax', kernel_initializer=init) 651 | 652 | def call(self, input): 653 | out = self.dense_1(input) 654 | out = self.dense_2(out) 655 | out = self.dense_3(out) 656 | out = self.out(out) 657 | Parameter = tf.clip_by_value(out, 1e-10, 1 - 1e-10) 658 | 659 | return Parameter 660 | class BottleNeck(tf.keras.layers.Layer): 661 | def __init__(self, filter_num, stride=1): 662 | super(BottleNeck, self).__init__() 663 | self.conv1 = tf.keras.layers.Conv2D(filters=filter_num, 664 | kernel_size=(1, 1), 665 | strides=1, 666 | padding='same') 667 | self.bn1 = tf.keras.layers.BatchNormalization() 668 | self.conv2 = tf.keras.layers.Conv2D(filters=filter_num, 669 | kernel_size=(3, 3), 670 | strides=stride, 671 | padding='same') 672 | self.bn2 = tf.keras.layers.BatchNormalization() 673 | self.conv3 = tf.keras.layers.Conv2D(filters=filter_num * 4, 674 | kernel_size=(1, 1), 675 | strides=1, 676 | padding='same') 677 | self.bn3 = tf.keras.layers.BatchNormalization() 678 | 679 | self.downsample = tf.keras.Sequential() 680 | self.downsample.add(tf.keras.layers.Conv2D(filters=filter_num * 4, 681 | kernel_size=(1, 1), 682 | strides=stride)) 683 | self.downsample.add(tf.keras.layers.BatchNormalization()) 684 | 685 | def call(self, inputs, training=None, **kwargs): 686 | residual = self.downsample(inputs) 687 | 688 | x = self.conv1(inputs) 689 | x = self.bn1(x, training=training) 690 | x = tf.nn.leaky_relu(x) 691 | x = self.conv2(x) 692 | x = self.bn2(x, training=training) 693 | x = tf.nn.leaky_relu(x) 694 | x = self.conv3(x) 695 | x = self.bn3(x, training=training) 696 | 697 | output = tf.nn.relu(tf.keras.layers.add([residual, x])) 698 | 699 | return output -------------------------------------------------------------------------------- /evaluation_parameterssimulataneous.py: -------------------------------------------------------------------------------- 1 | import random 2 | 3 | import loss 4 | import numpy as np 5 | import config_parameter 6 | import math 7 | import tensorflow as tf 8 | from network import DL_method_NN_for_v2x_mod, DL_method_NN_for_v2x_hybrid 9 | import matplotlib.pyplot as plt 10 | from evaluation_simultaneously import generate_input_v2i, generate_input_v2v, \ 11 | load_model, load_model_hybrid_combine, load_model_digitalwith_combine, \ 12 | load_model_digitalwithout_combine, load_model_only_communication_hybrid, \ 13 | load_model_only_communication_digitalwith, \ 14 | load_model_only_communication_digitalwithout,load_model_noise1e_11,load_model_noise1e_5,load_modelpower50,load_modelpower100 15 | import evaluation 16 | 17 | Test = "V2V" 18 | Test = "V2I" 19 | if config_parameter.mode == "V2I": 20 | antenna_size = config_parameter.antenna_size 21 | num_vehicle = config_parameter.num_vehicle 22 | elif config_parameter.mode == "V2V": 23 | antenna_size = config_parameter.vehicle_antenna_size 24 | num_vehicle = config_parameter.num_uppercar + config_parameter.num_lowercar + config_parameter.num_horizoncar 25 | 26 | 27 | def comparison(combined, mode): 28 | # CSI = tf.complex(combined[:,:,0:antenna_size],combined[:,:,antenna_size:2*antenna_size]) 29 | CSI = tf.complex(combined[:, :, 6 * antenna_size:7 * antenna_size, 0], 30 | combined[:, :, 7 * antenna_size:8 * antenna_size, 0]) 31 | 32 | #CSI = CSI[1:] 33 | 34 | zf_matrix = tf.complex(combined[:, :, 4 * antenna_size:5 * antenna_size, 0], 35 | combined[:, :, 5 * antenna_size:6 * antenna_size, 0]) 36 | #zf_matrix = zf_matrix[:-1] 37 | 38 | distance = combined[:, :, 3 * antenna_size:4 * antenna_size, 0] 39 | #distance = distance[1:] 40 | beta = loss.Reflection_coefficient(distance) 41 | #beta = beta[1:] 42 | 43 | steering_vector_this_o = tf.complex(combined[:, :, 0:antenna_size, 0], 44 | combined[:, :, antenna_size:2 * antenna_size, 0]) 45 | 46 | #steering_vector_this_o = steering_vector_this_o[1:] 47 | theta = combined[:, :, 2 * antenna_size, 0] 48 | #theta = theta 49 | model1 = load_model_hybrid_combine() 50 | model2 = load_model_digitalwith_combine() 51 | model3 = load_model_digitalwithout_combine() 52 | model4 = load_model_only_communication_hybrid() 53 | model5 = load_model_only_communication_digitalwith() 54 | model6 = load_model_only_communication_digitalwithout() 55 | model7 = load_model_noise1e_11() 56 | model8= load_model_noise1e_5() 57 | model9 = load_modelpower50() 58 | model10 = load_modelpower100() 59 | output1 = model1(combined) 60 | output2 = model2(combined) 61 | output3 = model3(combined) 62 | output4 = model4(combined) 63 | output5 = model5(combined) 64 | output6 = model6(combined) 65 | output7 = model7(combined) 66 | output8 = model8(combined) 67 | output9 = model9(combined) 68 | output10 = model10(combined) 69 | analog1, digital1 = loss.tf_Output2PrecodingMatrix_rad(output1) 70 | precoder1 = loss.tf_Precoding_matrix_combine(analog1, digital1) 71 | precoder2 = loss.tf_Output2digitalPrecoding(output2, zf_matrix=zf_matrix, distance=None) 72 | precoder3 = loss.tf_Output2digitalPrecoding(output3, zf_matrix=None, distance=None) 73 | analog4,digital4 = loss.tf_Output2PrecodingMatrix_rad(output4) 74 | precoder4 = loss.tf_Precoding_matrix_combine(analog4,digital4) 75 | precoder5 = loss.tf_Output2digitalPrecoding(output5,zf_matrix=zf_matrix,distance=None) 76 | precoder6 = loss.tf_Output2digitalPrecoding(output6,zf_matrix=None,distance=None) 77 | # precoder7 = loss.random_beamforming() 78 | analog7,digital7 = loss.tf_Output2PrecodingMatrix_rad(output7) 79 | precoder7 = loss.tf_Precoding_matrix_combine(analog7,digital7) 80 | analog8,digital8 = loss.tf_Output2PrecodingMatrix_rad(output8) 81 | precoder8 = loss.tf_Precoding_matrix_combine(analog8,digital8) 82 | analog9,digital9 = loss.tf_Output2PrecodingMatrix_rad(output9) 83 | precoder9 = loss.tf_Precoding_matrix_combine(analog9,digital9) 84 | analog10,digital10 = loss.tf_Output2PrecodingMatrix_rad(output10) 85 | precoder10 = loss.tf_Precoding_matrix_combine(analog10,digital10) 86 | if mode == "sumrate": 87 | #different_k(CSI, distance, beta, theta, steering_vector_this_o, precoder4, precoder5, precoder6, zf_matrix, 88 | # mode,precoder4,precoder7,precoder8) 89 | different_power(CSI, distance, beta, theta, steering_vector_this_o, precoder1, precoder2, precoder3, zf_matrix, 90 | mode,precoder4,precoder9,precoder10) 91 | #different_rf_size(CSI, distance, beta, theta, steering_vector_this_o, analog1,digital1,mode) 92 | #different_users(CSI, distance, beta, theta, steering_vector_this_o, analog1, digital1, precoder2, precoder3,zf_matrix, mode) 93 | elif mode == "crbd": 94 | #different_users(CSI, distance, beta, theta, steering_vector_this_o, analog1, digital1, precoder2, precoder3, 95 | # zf_matrix, mode) 96 | #different_k(CSI, distance, beta, theta, steering_vector_this_o, precoder1, precoder2, precoder3, zf_matrix, 97 | #mode,precoder4,precoder7,precoder8) 98 | different_power(CSI, distance, beta, theta, steering_vector_this_o, precoder1, precoder2, precoder3, zf_matrix, 99 | mode,precoder4,precoder9,precoder10) 100 | #different_reflection_coefficient(CSI, distance, beta, theta, steering_vector_this_o, precoder1, precoder2, 101 | # precoder3, zf_matrix, mode) 102 | #different_rf_size(CSI, distance, beta, theta, steering_vector_this_o, analog1, digital1, mode) 103 | elif mode == "crba": 104 | #different_users(CSI, distance, beta, theta, steering_vector_this_o, analog1, digital1, precoder2, precoder3, 105 | # zf_matrix, mode) 106 | #different_k(CSI, distance, beta, theta, steering_vector_this_o, precoder1, precoder2, precoder3, zf_matrix, 107 | # mode) 108 | different_power(CSI, distance, beta, theta, steering_vector_this_o, precoder1, precoder2, precoder3, zf_matrix, 109 | mode,precoder4,precoder9,precoder10) 110 | #different_reflection_coefficient(CSI, distance, beta, theta, steering_vector_this_o, precoder1, precoder2, 111 | #precoder3, zf_matrix, mode) 112 | #different_rf_size(CSI, distance, beta, theta, steering_vector_this_o, analog1, digital1, mode) 113 | def different_num_user(combined,mode): 114 | num_vehicle = [1,2,3,4] 115 | model1 = load_model_hybrid_combine() 116 | model2 = load_model_digitalwith_combine() 117 | model3 = load_model_digitalwithout_combine() 118 | antenna_size =16 119 | sum_rate1 = [] 120 | sum_rate2 = [] 121 | sum_rate3 = [] 122 | sum_rate7 = [] 123 | crbd1 = [] 124 | crbd2 = [] 125 | crbd3 = [] 126 | crbd7 = [] 127 | 128 | crba1 = [] 129 | crba2 = [] 130 | crba3 = [] 131 | crba7 = [] 132 | for i in range(len(num_vehicle)): 133 | v1 = num_vehicle[i] 134 | combined = combined.numpy() 135 | combined[:,v1:] = 0 136 | CSI = tf.complex(combined[:, :, 6 * antenna_size:7 * antenna_size, 0],\ 137 | combined[:, :, 7 * antenna_size:8 * antenna_size, 0]) 138 | 139 | zf_matrix = np.zeros((tf.shape(CSI)[0], v1, antenna_size), dtype=complex) 140 | for m in range(tf.shape(CSI)[0]): 141 | zf_matrix[m] = loss.zero_forcing(CSI[m,:,:]).T 142 | combined[:, :num_vehicle, 4 * antenna_size:5 * antenna_size, 0] = tf.real(zf_matrix) 143 | combined[:, :num_vehicle, 5 * antenna_size:6 * antenna_size, 0] = tf.imag(zf_matrix) 144 | steering_vector_this_o = tf.complex(combined[:, :, 0:antenna_size, 0],\ 145 | combined[:, :, antenna_size:2 * antenna_size, 0]) 146 | theta = combined[:, :, 2 * antenna_size, 0] 147 | distance = combined[:, :, 3 * antenna_size:4 * antenna_size, 0] 148 | beta = loss.Reflection_coefficient(distance) 149 | output1 = model1(combined) 150 | output2 = model2(combined) 151 | output3 = model3(combined) 152 | zf_matrix_o = np.zeros((tf.shape(CSI)[0], 4, antenna_size), dtype=complex) 153 | for v in range(len(num_vehicle)): 154 | zf_matrix_o[:,v,:] = zf_matrix[:,v,:] 155 | zf_matrix = zf_matrix_o 156 | analog1, digital1 = loss.tf_Output2PrecodingMatrix_rad(output1) 157 | precoder1 = loss.tf_Precoding_matrix_combine(analog1, digital1) 158 | precoder2 = loss.tf_Output2digitalPrecoding(output2, zf_matrix=zf_matrix, distance=None) 159 | precoder3 = loss.tf_Output2digitalPrecoding(output3, zf_matrix=None, distance=None) 160 | sum_rate1_1, sinr = loss.tf_loss_sumrate(CSI, precoder1) 161 | sum_rate1_1 = tf.cast(sum_rate1_1, tf.float32) 162 | print("sum_rate1_1", sum_rate1_1) 163 | sum_rate1.append(tf.math.log(tf.reduce_mean(sum_rate1_1)) / tf.math.log(2.0)) 164 | 165 | sum_rate2_1, sinr = loss.tf_loss_sumrate(CSI, precoder2) 166 | sum_rate2_1 = tf.cast(sum_rate2_1, tf.float32) 167 | sum_rate2.append(tf.math.log(tf.reduce_mean(sum_rate2_1)) / tf.math.log(2.0)) 168 | 169 | sum_rate3_1, sinr = loss.tf_loss_sumrate(CSI, precoder3) 170 | sum_rate3_1 = tf.cast(sum_rate3_1, tf.float32) 171 | sum_rate3.append(tf.math.log(tf.reduce_mean(sum_rate3_1)) / tf.math.log(2.0)) 172 | fig, ax1 = plt.subplots() 173 | x = range(len(num_vehicle)) 174 | if mode == "sumrate": 175 | ax1.plot(x, sum_rate1, 'b-.', label='hybrid ISAC') 176 | # ax2 = ax1.twinx() 177 | ax1.plot(x, sum_rate2, 'm--', label='digital ISAC,with initial point') 178 | ax1.plot(x, sum_rate3, 'r.-', label='digital ISAC,without initial point') 179 | # ax1.plot(range(10), sum_rate4, 'm:', label='hybrid only communication') 180 | # ax1.plot(range(10), sum_rate5, 'r-', label='digital with initial point only communication') 181 | # ax1.plot(range(10), sum_rate6, 'b-', label='digital without initial point only communication') 182 | ax1.plot(x, sum_rate7, 'g-', label='ZF precoder') 183 | ax1.set_xlabel("number of users") 184 | ax1.set_ylabel('log2(sum rate(bits/s/hz))', color='b') 185 | ax1.tick_params('y', colors='b') 186 | _ = plt.xticks(x, num_vehicle) 187 | elif mode == "crba": 188 | ax1.set_xlabel("number of users") 189 | ax1.plot(x, crba1, 'b-.', label='hybrid ISAC') 190 | # ax2 = ax1.twinx() 191 | ax1.plot(x, crba2, 'm--', label='digital ISAC,with initial point') 192 | ax1.plot(x, crba3, 'r.-', label='digital ISAC,without initial point') 193 | # ax1.plot(range(10), sum_rate4, 'm:', label='hybrid only communication') 194 | # ax1.plot(range(10), sum_rate5, 'r-', label='digital with initial point only communication') 195 | # ax1.plot(range(10), sum_rate6, 'b-', label='digital without initial point only communication') 196 | ax1.plot(x, crba7, 'g-', label='ZF precoder') 197 | 198 | ax1.set_ylabel('log2(CRB angle rad\u00B2)', color='b') 199 | ax1.tick_params('y', colors='b') 200 | _ = plt.xticks(x, num_vehicle) 201 | elif mode == "crbd": 202 | ax1.set_xlabel("number of users") 203 | ax1.plot(x, crbd1, 'b-.', label='hybrid ISAC') 204 | # ax2 = ax1.twinx() 205 | ax1.plot(x, crbd2, 'm--', label='digital ISAC,with initial point') 206 | ax1.plot(x, crbd3, 'r.-', label='digital ISAC,without initial point') 207 | # ax1.plot(range(10), sum_rate4, 'm:', label='hybrid only communication') 208 | # ax1.plot(range(10), sum_rate5, 'r-', label='digital with initial point only communication') 209 | # ax1.plot(range(10), sum_rate6, 'b-', label='digital without initial point only communication') 210 | ax1.plot(x, crbd7, 'g-', label='ZF precoder') 211 | ax1.set_ylabel('log2(CRB distance m\u00B2)', color='b') 212 | ax1.tick_params('y', colors='b') 213 | _ = plt.xticks(x, num_vehicle) 214 | fig.tight_layout() 215 | 216 | # 添加图例 217 | lines = [ax1.get_lines()[0], \ 218 | ax1.get_lines()[1], \ 219 | ax1.get_lines()[2], \ 220 | ax1.get_lines()[3]] 221 | 222 | # lines = [ax4.get_lines()[0]] 223 | labels = [line.get_label() for line in lines] 224 | ax1.legend(lines, labels, bbox_to_anchor=(0.5, 0.6)) 225 | plt.show() 226 | idx = np.arange(antenna_size) 227 | angle_set = np.arange(1, 181) / 180 * np.pi 228 | Hset = np.exp(1j * np.pi * idx.reshape(-1, 1) * np.cos(angle_set)) 229 | r1 = np.matmul(Hset.T, precoder1[0, :, :]) 230 | plt.polar(angle_set, np.abs(r1)) 231 | plt.show() 232 | 233 | 234 | 235 | 236 | def different_reflection_coefficient(CSI, distance, beta, theta, steering_vector_this_o, precoder1, precoder2, 237 | precoder3, zf_matrix, mode): 238 | refle = [0.1j + 0.1, 0.2j + 0.2, 0.5j + 0.5, 1j + 1, 2j + 2] 239 | crbd1 = [] 240 | crbd2 = [] 241 | crbd3 = [] 242 | crbd7 = [] 243 | 244 | crba1 = [] 245 | crba2 = [] 246 | crba3 = [] 247 | crba7 = [] 248 | for i in range(len(refle)): 249 | config_parameter.fading_coefficient = refle[i] 250 | beta = loss.Reflection_coefficient(distance) 251 | Sigma_time_delay1 = loss.tf_sigma_delay_square(steering_vector_this_o, precoder1, beta) 252 | Sigma_time_delay2 = loss.tf_sigma_delay_square(steering_vector_this_o, precoder2, beta) 253 | Sigma_time_delay3 = loss.tf_sigma_delay_square(steering_vector_this_o, precoder3, beta) 254 | Sigma_time_delay7 = loss.tf_sigma_delay_square(steering_vector_this_o, tf.transpose(zf_matrix, perm=[0, 2, 1]), 255 | beta) 256 | CRB_d1 = tf.reduce_sum(loss.tf_CRB_distance(Sigma_time_delay1), axis=1) / 4 257 | CRB_d2 = tf.reduce_sum(loss.tf_CRB_distance(Sigma_time_delay2), axis=1) / 4 258 | CRB_d3 = tf.reduce_sum(loss.tf_CRB_distance(Sigma_time_delay3), axis=1) / 4 259 | CRB_d7 = tf.reduce_sum(loss.tf_CRB_distance(Sigma_time_delay7), axis=1) / 4 260 | crbd1.append(tf.math.log(tf.reduce_mean(CRB_d1)) / tf.math.log(2.0)) 261 | crbd2.append(tf.math.log(tf.reduce_mean(CRB_d2)) / tf.math.log(2.0)) 262 | crbd3.append(tf.math.log(tf.reduce_mean(CRB_d3)) / tf.math.log(2.0)) 263 | crbd7.append(tf.math.log(tf.reduce_mean(CRB_d7)) / tf.math.log(2.0)) 264 | 265 | CRB_angle1 = tf.reduce_sum(loss.tf_CRB_angle(beta, precoder1, theta), axis=1) / 4 266 | CRB_angle2 = tf.reduce_sum(loss.tf_CRB_angle(beta, precoder2, theta), axis=1) / 4 267 | CRB_angle3 = tf.reduce_sum(loss.tf_CRB_angle(beta, precoder3, theta), axis=1) / 4 268 | CRB_angle7 = tf.reduce_sum(loss.tf_CRB_angle(beta, tf.transpose(zf_matrix, perm=[0, 2, 1]), theta), axis=1) / 4 269 | CRB_angle1 =tf.cast(CRB_angle1,tf.float32) 270 | CRB_angle2 =tf.cast(CRB_angle2,tf.float32) 271 | CRB_angle3 =tf.cast(CRB_angle3,tf.float32) 272 | CRB_angle7 =tf.cast(CRB_angle7,tf.float32) 273 | crba1.append(tf.math.log(tf.reduce_mean(CRB_angle1)) / tf.math.log(2.0)) 274 | crba2.append(tf.math.log(tf.reduce_mean(CRB_angle2)) / tf.math.log(2.0)) 275 | crba3.append(tf.math.log(tf.reduce_mean(CRB_angle3)) / tf.math.log(2.0)) 276 | crba7.append(tf.math.log(tf.reduce_mean(CRB_angle7)) / tf.math.log(2.0)) 277 | 278 | fig, ax1 = plt.subplots() 279 | x = range(len(refle)) 280 | if mode == "crba": 281 | ax1.set_xlabel('fading coefficient') 282 | ax1.plot(x, crba1, 'b-.', label='hybrid ISAC') 283 | # ax2 = ax1.twinx() 284 | ax1.plot(x, crba2, 'm--', label='digital ISAC,with initial point') 285 | ax1.plot(x, crba3, 'r.-', label='digital ISAC,without initial point') 286 | # ax1.plot(range(10), sum_rate4, 'm:', label='hybrid only communication') 287 | # ax1.plot(range(10), sum_rate5, 'r-', label='digital with initial point only communication') 288 | # ax1.plot(range(10), sum_rate6, 'b-', label='digital without initial point only communication') 289 | #ax1.plot(x, crba7, 'g-', label='ZF precoder') 290 | 291 | ax1.set_ylabel('log2(CRB angle rad\u00B2)', color='b') 292 | ax1.tick_params('y', colors='b') 293 | _ = plt.xticks(x, refle) 294 | elif mode == "crbd": 295 | 296 | ax1.set_xlabel('fading coefficient') 297 | ax1.plot(x, crbd1, 'b-.', label='hybrid ISAC') 298 | # ax2 = ax1.twinx() 299 | ax1.plot(x, crbd2, 'm--', label='digital ISAC,with initial point') 300 | ax1.plot(x, crbd3, 'r.-', label='digital ISAC,without initial point') 301 | # ax1.plot(range(10), sum_rate4, 'm:', label='hybrid only communication') 302 | # ax1.plot(range(10), sum_rate5, 'r-', label='digital with initial point only communication') 303 | # ax1.plot(range(10), sum_rate6, 'b-', label='digital without initial point only communication') 304 | #ax1.plot(x, crbd7, 'g-', label='ZF precoder') 305 | ax1.set_ylabel('log2(CRB distance m\u00B2)', color='b') 306 | ax1.tick_params('y', colors='b') 307 | _ = plt.xticks(x, refle) 308 | fig.tight_layout() 309 | 310 | # 添加图例 311 | lines = [ax1.get_lines()[0], \ 312 | ax1.get_lines()[1], \ 313 | ax1.get_lines()[2]] 314 | 315 | # lines = [ax4.get_lines()[0]] 316 | labels = [line.get_label() for line in lines] 317 | ax1.legend(lines, labels, bbox_to_anchor=(0.5, 0.6)) 318 | plt.show() 319 | idx = np.arange(antenna_size) 320 | angle_set = np.arange(1, 181) / 180 * np.pi 321 | Hset = np.exp(1j * np.pi * idx.reshape(-1, 1) * np.cos(angle_set)) 322 | r1 = np.matmul(Hset.T, precoder1[0, :, :]) 323 | plt.polar(angle_set, np.abs(r1)) 324 | #plt.show() 325 | # precoder5 = precoder5.numpy() 326 | # print(precoder5.shape) 327 | # r1 = np.matmul(Hset.T, precoder1[9, :, :]) 328 | # plt.polar(angle_set, np.abs(r1)) 329 | # plt.show() 330 | 331 | 332 | def different_k(CSI, distance, beta, theta, steering_vector_this_o, \ 333 | precoder1, precoder2, precoder3, zf_matrix, mode,precoder4, precoder8,precoder9): 334 | k = [1e-4, 1e-5, 1e-6, 1e-7, 1e-8, 1e-9,1e-10,1e-11,1e-12,1e-13] 335 | sum_rate1 = [] 336 | sum_rate2 = [] 337 | sum_rate3 = [] 338 | sum_rate4 = [] 339 | 340 | sum_rate7 = [] 341 | sum_rate8 = [] 342 | sum_rate9 = [] 343 | crbd1 = [] 344 | crbd2 = [] 345 | crbd3 = [] 346 | crbd4 = [] 347 | crbd7 = [] 348 | crbd8 = [] 349 | crbd9 = [] 350 | 351 | crba1 = [] 352 | crba2 = [] 353 | crba3 = [] 354 | crba7 = [] 355 | 356 | for i in range(len(k)): 357 | config_parameter.sigma_k = k[i] 358 | config_parameter.sigma_z = k[i] 359 | sum_rate1_1, sinr = loss.tf_loss_sumrate(CSI, precoder1) 360 | sum_rate1_1 = tf.cast(sum_rate1_1, tf.float32) 361 | print("sum_rate1_1", sum_rate1_1) 362 | sum_rate1.append(tf.math.log(tf.reduce_mean(sum_rate1_1)) / tf.math.log(2.0)) 363 | 364 | sum_rate2_1, sinr = loss.tf_loss_sumrate(CSI, precoder2) 365 | sum_rate2_1 = tf.cast(sum_rate2_1, tf.float32) 366 | sum_rate2.append(tf.math.log(tf.reduce_mean(sum_rate2_1)) / tf.math.log(2.0)) 367 | 368 | sum_rate3_1, sinr = loss.tf_loss_sumrate(CSI, precoder3) 369 | sum_rate3_1 = tf.cast(sum_rate3_1, tf.float32) 370 | sum_rate3.append(tf.math.log(tf.reduce_mean(sum_rate3_1)) / tf.math.log(2.0)) 371 | sum_rate4_1, sinr = loss.tf_loss_sumrate(CSI, precoder4) 372 | sum_rate4_1 = tf.cast(sum_rate4_1, tf.float32) 373 | sum_rate4.append(tf.math.log(tf.reduce_mean(sum_rate4_1)) / tf.math.log(2.0)) 374 | sum_rate7_1, sinr = loss.tf_loss_sumrate(CSI, tf.transpose(zf_matrix, perm=[0, 2, 1])) 375 | sum_rate7_1 = tf.cast(sum_rate7_1, tf.float32) 376 | sum_rate8_1, sinr = loss.tf_loss_sumrate(CSI, precoder8) 377 | sum_rate8_1 = tf.cast(sum_rate8_1, tf.float32) 378 | sum_rate8.append(tf.math.log(tf.reduce_mean(sum_rate8_1)) / tf.math.log(2.0)) 379 | sum_rate7.append(tf.math.log(tf.reduce_mean(sum_rate7_1)) / tf.math.log(2.0)) 380 | sum_rate9_1, sinr = loss.tf_loss_sumrate(CSI, precoder9) 381 | sum_rate9_1 = tf.cast(sum_rate9_1, tf.float32) 382 | sum_rate9.append(tf.math.log(tf.reduce_mean(sum_rate9_1)) / tf.math.log(2.0)) 383 | Sigma_time_delay1 = loss.tf_sigma_delay_square(steering_vector_this_o, precoder1, beta) 384 | Sigma_time_delay2 = loss.tf_sigma_delay_square(steering_vector_this_o, precoder2, beta) 385 | Sigma_time_delay3 = loss.tf_sigma_delay_square(steering_vector_this_o, precoder3, beta) 386 | Sigma_time_delay4 = loss.tf_sigma_delay_square(steering_vector_this_o, precoder4, beta) 387 | Sigma_time_delay7 = loss.tf_sigma_delay_square(steering_vector_this_o, tf.transpose(zf_matrix, perm=[0, 2, 1]), 388 | beta) 389 | Sigma_time_delay8 = loss.tf_sigma_delay_square(steering_vector_this_o, precoder8, beta) 390 | Sigma_time_delay9 = loss.tf_sigma_delay_square(steering_vector_this_o, precoder9, beta) 391 | 392 | CRB_d1 = tf.reduce_sum(loss.tf_CRB_distance(Sigma_time_delay1), axis=1) / 4 393 | CRB_d2 = tf.reduce_sum(loss.tf_CRB_distance(Sigma_time_delay2), axis=1) / 4 394 | CRB_d3 = tf.reduce_sum(loss.tf_CRB_distance(Sigma_time_delay3), axis=1) / 4 395 | CRB_d4 = tf.reduce_sum(loss.tf_CRB_distance(Sigma_time_delay4), axis=1) / 4 396 | CRB_d7 = tf.reduce_sum(loss.tf_CRB_distance(Sigma_time_delay7), axis=1) / 4 397 | CRB_d8 = tf.reduce_sum(loss.tf_CRB_distance(Sigma_time_delay8), axis=1) / 4 398 | CRB_d9 = tf.reduce_sum(loss.tf_CRB_distance(Sigma_time_delay9), axis=1) / 4 399 | 400 | crbd1.append(tf.math.log(tf.reduce_mean(CRB_d1)) / tf.math.log(2.0)) 401 | crbd2.append(tf.math.log(tf.reduce_mean(CRB_d2)) / tf.math.log(2.0)) 402 | crbd3.append(tf.math.log(tf.reduce_mean(CRB_d3)) / tf.math.log(2.0)) 403 | crbd4.append(tf.math.log(tf.reduce_mean(CRB_d4)) / tf.math.log(2.0)) 404 | crbd7.append(tf.math.log(tf.reduce_mean(CRB_d7)) / tf.math.log(2.0)) 405 | crbd8.append(tf.math.log(tf.reduce_mean(CRB_d8)) / tf.math.log(2.0)) 406 | crbd9.append(tf.math.log(tf.reduce_mean(CRB_d9)) / tf.math.log(2.0)) 407 | 408 | CRB_angle1 = tf.reduce_sum(loss.tf_CRB_angle(beta, precoder1, theta), axis=1) / 4 409 | CRB_angle2 = tf.reduce_sum(loss.tf_CRB_angle(beta, precoder2, theta), axis=1) / 4 410 | CRB_angle3 = tf.reduce_sum(loss.tf_CRB_angle(beta, precoder3, theta), axis=1) / 4 411 | CRB_angle7 = tf.reduce_sum(loss.tf_CRB_angle(beta, tf.transpose(zf_matrix, perm=[0, 2, 1]), theta), axis=1) / 4 412 | CRB_angle1 = tf.cast(CRB_angle1, tf.float32) 413 | CRB_angle2 = tf.cast(CRB_angle2, tf.float32) 414 | CRB_angle3 = tf.cast(CRB_angle3, tf.float32) 415 | CRB_angle7 = tf.cast(CRB_angle7, tf.float32) 416 | 417 | crba1.append(tf.math.log(tf.reduce_mean(CRB_angle1)) / tf.math.log(2.0)) 418 | crba2.append(tf.math.log(tf.reduce_mean(CRB_angle2)) / tf.math.log(2.0)) 419 | crba3.append(tf.math.log(tf.reduce_mean(CRB_angle3)) / tf.math.log(2.0)) 420 | crba7.append(tf.math.log(tf.reduce_mean(CRB_angle7)) / tf.math.log(2.0)) 421 | 422 | # sum_rate8,sinr = loss.tf_loss_sumrate(CSI,precoder7) 423 | print("sum_rate1", sum_rate1) 424 | fig, ax1 = plt.subplots() 425 | x = range(len(k)) 426 | if mode == "sumrate": 427 | #ax1.plot(x, sum_rate1, 'b-.', label='hybrid ISAC') 428 | # ax2 = ax1.twinx() 429 | #ax1.plot(x, sum_rate2, 'm--', label='digital ISAC,with initial point') 430 | #ax1.plot(x, sum_rate3, 'r.-', label='digital ISAC,without initial point') 431 | ax1.plot(x, sum_rate4, 'm:', label='hybrid only communication,noise 1e-7') 432 | # ax1.plot(range(10), sum_rate5, 'r-', label='digital with initial point only communication') 433 | # ax1.plot(range(10), sum_rate6, 'b-', label='digital without initial point only communication') 434 | #ax1.plot(x, sum_rate7, 'g-', label='ZF precoder') 435 | ax1.plot(x, sum_rate8, 'r-', label='hybrid only communication, noise 1e-11') 436 | ax1.plot(x, sum_rate9, 'b-', label='hybrid only communication, noise 1e-5') 437 | ax1.set_xlabel("Noise:\u03C3\u2096\u00B2") 438 | ax1.set_ylabel('log2(sum rate(bits/s/hz))', color='b') 439 | ax1.tick_params('y', colors='b') 440 | _ = plt.xticks(x, k) 441 | elif mode == "crba": 442 | ax1.set_xlabel("Noise:\u03C3\u2096\u00B2") 443 | ax1.plot(x, crba1, 'b-.', label='hybrid ISAC') 444 | # ax2 = ax1.twinx() 445 | ax1.plot(x, crba2, 'm--', label='digital ISAC,with initial point') 446 | ax1.plot(x, crba3, 'r.-', label='digital ISAC,without initial point') 447 | #ax1.plot(x,sum_4, 'm:', label='hybrid only communication') 448 | # ax1.plot(range(10), sum_rate5, 'r-', label='digital with initial point only communication') 449 | # ax1.plot(range(10), sum_rate6, 'b-', label='digital without initial point only communication') 450 | #ax1.plot(x, crba7, 'g-', label='ZF precoder') 451 | 452 | ax1.set_ylabel('log2(CRB angle rad\u00B2)', color='b') 453 | ax1.tick_params('y', colors='b') 454 | _ = plt.xticks(x, k) 455 | elif mode == "crbd": 456 | ax1.set_xlabel("Noise:\u03C3\u2096\u00B2") 457 | #ax1.plot(x, crbd1, 'b-.', label='hybrid ISAC') 458 | # ax2 = ax1.twinx() 459 | #ax1.plot(x, crbd2, 'm--', label='digital ISAC,with initial point') 460 | #ax1.plot(x, crbd3, 'r.-', label='digital ISAC,without initial point') 461 | ax1.plot(x, crbd4, 'b-', label='hybrid only communication,noise 1e-7') 462 | ax1.plot(x, crbd8, 'm:', label='hybrid only communication,noise 1e-11') 463 | ax1.plot(x, crbd9, 'r.-', label='hybrid only communication,noise 1e-5') 464 | # ax1.plot(range(10), sum_rate4, 'm:', label='hybrid only communication') 465 | # ax1.plot(range(10), sum_rate5, 'r-', label='digital with initial point only communication') 466 | # ax1.plot(range(10), sum_rate6, 'b-', label='digital without initial point only communication') 467 | #ax1.plot(x, crbd7, 'g-', label='ZF precoder') 468 | ax1.set_ylabel('log2(CRB distance m\u00B2)', color='b') 469 | ax1.tick_params('y', colors='b') 470 | _ = plt.xticks(x, k) 471 | 472 | # plt.xticks(k, rotation='vertical') 473 | 474 | # plot.legend(loc='best') 475 | fig.tight_layout() 476 | 477 | # 添加图例 478 | lines = [ax1.get_lines()[0], \ 479 | ax1.get_lines()[1],\ 480 | ax1.get_lines()[2]] 481 | 482 | # lines = [ax4.get_lines()[0]] 483 | labels = [line.get_label() for line in lines] 484 | ax1.legend(lines, labels, bbox_to_anchor=(0.3, 0.5),loc='best') 485 | plt.show() 486 | idx = np.arange(antenna_size) 487 | angle_set = np.arange(1, 181) / 180 * np.pi 488 | Hset = np.exp(1j * np.pi * idx.reshape(-1, 1) * np.cos(angle_set)) 489 | 490 | precoder9 = precoder9.numpy() 491 | # print(precoder5.shape) 492 | r1 = np.matmul(Hset.T, precoder9[9, :, :]) 493 | plt.polar(angle_set, np.abs(r1)) 494 | #plt.show() 495 | 496 | 497 | def different_power(CSI, distance, beta, theta, steering_vector_this_o, precoder1, precoder2, precoder3, zf_matrix, 498 | mode,precoder4,precoder9,precoder10): 499 | sum_rate1 = [] 500 | sum_rate2 = [] 501 | sum_rate3 = [] 502 | sum_rate4 = [] 503 | sum_rate7 = [] 504 | sum_rate9 = [] 505 | sum_rate10 = [] 506 | crbd1 = [] 507 | crbd2 = [] 508 | crbd3 = [] 509 | crbd4 = [] 510 | crbd7 = [] 511 | crbd9 = [] 512 | crbd10 = [] 513 | 514 | crba1 = [] 515 | crba2 = [] 516 | crba3 = [] 517 | crba7 = [] 518 | 519 | p = [0.1, 0.2, 0.5, 1, 2,5, 10, 20, 50, 100] 520 | p1 = [20, 23, 27, 30, 33,37,40,43,47,50] 521 | for i in range(len(p)): 522 | config_parameter.power = p[i] 523 | p2 = math.sqrt(p[i]) 524 | # config_parameter.sigma_z = k[i] 525 | sum_rate1_1, sinr = loss.tf_loss_sumrate(CSI, p2 * precoder1) 526 | sum_rate1_1 = tf.cast(sum_rate1_1, tf.float32) 527 | print("sum_rate1_1", sum_rate1_1) 528 | sum_rate1.append(tf.math.log(tf.reduce_mean(sum_rate1_1)) / tf.math.log(2.0)) 529 | 530 | sum_rate2_1, sinr = loss.tf_loss_sumrate(CSI, p2 * precoder2) 531 | sum_rate2_1 = tf.cast(sum_rate2_1, tf.float32) 532 | sum_rate2.append(tf.math.log(tf.reduce_mean(sum_rate2_1)) / tf.math.log(2.0)) 533 | 534 | sum_rate3_1, sinr = loss.tf_loss_sumrate(CSI, p2 * precoder3) 535 | sum_rate3_1 = tf.cast(sum_rate3_1, tf.float32) 536 | sum_rate3.append(tf.math.log(tf.reduce_mean(sum_rate3_1)) / tf.math.log(2.0)) 537 | 538 | sum_rate4_1, sinr = loss.tf_loss_sumrate(CSI, p2 * precoder4) 539 | sum_rate4_1 = tf.cast(sum_rate4_1, tf.float32) 540 | sum_rate4.append(tf.math.log(tf.reduce_mean(sum_rate4_1)) / tf.math.log(2.0)) 541 | 542 | sum_rate7_1, sinr = loss.tf_loss_sumrate(CSI, p2 * tf.transpose(zf_matrix, perm=[0, 2, 1])) 543 | sum_rate7_1 = tf.cast(sum_rate7_1, tf.float32) 544 | sum_rate7.append(tf.math.log(tf.reduce_mean(sum_rate7_1)) / tf.math.log(2.0)) 545 | 546 | sum_rate9_1, sinr = loss.tf_loss_sumrate(CSI, p2 * precoder9) 547 | sum_rate9_1 = tf.cast(sum_rate9_1, tf.float32) 548 | sum_rate9.append(tf.math.log(tf.reduce_mean(sum_rate9_1)) / tf.math.log(2.0)) 549 | 550 | sum_rate10_1, sinr = loss.tf_loss_sumrate(CSI, p2 * precoder10) 551 | sum_rate10_1 = tf.cast(sum_rate10_1, tf.float32) 552 | sum_rate10.append(tf.math.log(tf.reduce_mean(sum_rate10_1)) / tf.math.log(2.0)) 553 | 554 | Sigma_time_delay1 = loss.tf_sigma_delay_square(steering_vector_this_o, p2 * precoder1, beta) 555 | Sigma_time_delay2 = loss.tf_sigma_delay_square(steering_vector_this_o, p2 * precoder2, beta) 556 | Sigma_time_delay3 = loss.tf_sigma_delay_square(steering_vector_this_o, p2 * precoder3, beta) 557 | Sigma_time_delay4 = loss.tf_sigma_delay_square(steering_vector_this_o, p2 * precoder4, beta) 558 | Sigma_time_delay7 = loss.tf_sigma_delay_square(steering_vector_this_o, 559 | p2 * tf.transpose(zf_matrix, perm=[0, 2, 1]), 560 | beta) 561 | Sigma_time_delay9 = loss.tf_sigma_delay_square(steering_vector_this_o, p2 * precoder9, beta) 562 | Sigma_time_delay10 = loss.tf_sigma_delay_square(steering_vector_this_o, p2 * precoder10, beta) 563 | 564 | CRB_d1 = tf.reduce_sum(loss.tf_CRB_distance(Sigma_time_delay1), axis=1) / 4 565 | CRB_d2 = tf.reduce_sum(loss.tf_CRB_distance(Sigma_time_delay2), axis=1) / 4 566 | CRB_d3 = tf.reduce_sum(loss.tf_CRB_distance(Sigma_time_delay3), axis=1) / 4 567 | CRB_d4 = tf.reduce_sum(loss.tf_CRB_distance(Sigma_time_delay4), axis=1) / 4 568 | CRB_d7 = tf.reduce_sum(loss.tf_CRB_distance(Sigma_time_delay7), axis=1) / 4 569 | CRB_d9 = tf.reduce_sum(loss.tf_CRB_distance(Sigma_time_delay9), axis=1) / 4 570 | CRB_d10 = tf.reduce_sum(loss.tf_CRB_distance(Sigma_time_delay10), axis=1) / 4 571 | 572 | crbd1.append(tf.math.log(tf.reduce_mean(CRB_d1)) / tf.math.log(2.0)) 573 | crbd2.append(tf.math.log(tf.reduce_mean(CRB_d2)) / tf.math.log(2.0)) 574 | crbd3.append(tf.math.log(tf.reduce_mean(CRB_d3)) / tf.math.log(2.0)) 575 | crbd4.append(tf.math.log(tf.reduce_mean(CRB_d4)) / tf.math.log(2.0)) 576 | crbd7.append(tf.math.log(tf.reduce_mean(CRB_d7)) / tf.math.log(2.0)) 577 | crbd9.append(tf.math.log(tf.reduce_mean(CRB_d9)) / tf.math.log(2.0)) 578 | crbd10.append(tf.math.log(tf.reduce_mean(CRB_d10)) / tf.math.log(2.0)) 579 | 580 | CRB_angle1 = tf.reduce_sum(loss.tf_CRB_angle(beta, p2 * precoder1, theta), axis=1) / 4 581 | CRB_angle2 = tf.reduce_sum(loss.tf_CRB_angle(beta, p2 * precoder2, theta), axis=1) / 4 582 | CRB_angle3 = tf.reduce_sum(loss.tf_CRB_angle(beta, p2 * precoder3, theta), axis=1) / 4 583 | 584 | CRB_angle7 = tf.reduce_sum(loss.tf_CRB_angle(beta, p2 * tf.transpose(zf_matrix, perm=[0, 2, 1]), theta), 585 | axis=1) / 4 586 | 587 | CRB_angle1 = tf.cast(CRB_angle1, tf.float32) 588 | CRB_angle2 = tf.cast(CRB_angle2, tf.float32) 589 | CRB_angle3 = tf.cast(CRB_angle3, tf.float32) 590 | CRB_angle7 = tf.cast(CRB_angle7, tf.float32) 591 | 592 | crba1.append(tf.math.log(tf.reduce_mean(CRB_angle1)) / tf.math.log(2.0)) 593 | crba2.append(tf.math.log(tf.reduce_mean(CRB_angle2)) / tf.math.log(2.0)) 594 | crba3.append(tf.math.log(tf.reduce_mean(CRB_angle3)) / tf.math.log(2.0)) 595 | crba7.append(tf.math.log(tf.reduce_mean(CRB_angle7)) / tf.math.log(2.0)) 596 | 597 | # sum_rate8,sinr = loss.tf_loss_sumrate(CSI,precoder7) 598 | print("sum_rate1", sum_rate1) 599 | fig, ax1 = plt.subplots() 600 | x = range(len(p)) 601 | if mode == "sumrate": 602 | #ax1.plot(x, sum_rate1, 'b-.', label='hybrid ISAC') 603 | # ax2 = ax1.twinx() 604 | #ax1.plot(x, sum_rate2, 'm--', label='digital ISAC,with initial point') 605 | #ax1.plot(x, sum_rate3, 'r.-', label='digital ISAC,without initial point') 606 | ax1.plot(x, sum_rate4, 'g-', label='hybrid only communication, power 30dBm') 607 | ax1.plot(x, sum_rate9, 'r.-', label='hybrid only communication, power 47dBm') 608 | ax1.plot(x, sum_rate10, 'm--', label='hybrid only communication, power 50dBm') 609 | # ax1.plot(range(10), sum_rate4, 'm:', label='hybrid only communication') 610 | # ax1.plot(range(10), sum_rate5, 'r-', label='digital with initial point only communication') 611 | # ax1.plot(range(10), sum_rate6, 'b-', label='digital without initial point only communication') 612 | #ax1.plot(x, sum_rate7, 'g-', label='ZF precoder') 613 | ax1.set_xlabel("Power/dBm") 614 | ax1.set_ylabel('log2(sum rate(bits/s/hz))', color='b') 615 | ax1.tick_params('y', colors='b') 616 | _ = plt.xticks(x, p1) 617 | elif mode == "crba": 618 | ax1.set_xlabel("Power/dBm") 619 | ax1.plot(x, crba1, 'b-.', label='hybrid ISAC') 620 | # ax2 = ax1.twinx() 621 | ax1.plot(x, crba2, 'm--', label='digital ISAC,with initial point') 622 | ax1.plot(x, crba3, 'r.-', label='digital ISAC,without initial point') 623 | # ax1.plot(range(10), sum_rate4, 'm:', label='hybrid only communication') 624 | # ax1.plot(range(10), sum_rate5, 'r-', label='digital with initial point only communication') 625 | # ax1.plot(range(10), sum_rate6, 'b-', label='digital without initial point only communication') 626 | #ax1.plot(x, crba7, 'g-', label='ZF precoder') 627 | 628 | ax1.set_ylabel('log2(CRB angle rad\u00B2)', color='b') 629 | ax1.tick_params('y', colors='b') 630 | _ = plt.xticks(x, p1) 631 | elif mode == "crbd": 632 | ax1.set_xlabel("Power/dBm") 633 | ax1.plot(x, crbd1, 'b-.', label='hybrid ISAC') 634 | # ax2 = ax1.twinx() 635 | ax1.plot(x, crbd2, 'm--', label='digital ISAC,with initial point') 636 | ax1.plot(x, crbd3, 'r.-', label='digital ISAC,without initial point') 637 | # ax1.plot(range(10), sum_rate4, 'm:', label='hybrid only communication') 638 | # ax1.plot(range(10), sum_rate5, 'r-', label='digital with initial point only communication') 639 | # ax1.plot(range(10), sum_rate6, 'b-', label='digital without initial point only communication') 640 | #ax1.plot(x, crbd7, 'g-', label='ZF precoder') 641 | ax1.set_ylabel('log2(CRB distance m\u00B2)', color='b') 642 | ax1.tick_params('y', colors='b') 643 | _ = plt.xticks(x, p1) 644 | 645 | # sum_rate8,sinr = loss.tf_loss_sumrate(CSI,precoder7) 646 | # print("sum_rate1", sum_rate1) 647 | # fig, ax1 = plt.subplots() 648 | # x = range(len(p)) 649 | # ax1.plot(x, sum_rate1, 'b-.', label='hybrid ISAC') 650 | # ax2 = ax1.twinx() 651 | # ax1.plot(x, sum_rate2, 'm--', label='digital ISAC,with initial point') 652 | # ax1.plot(x, sum_rate3, 'r.-', label='digital ISAC,without initial point') 653 | # ax1.plot(range(10), sum_rate4, 'm:', label='hybrid only communication') 654 | # ax1.plot(range(10), sum_rate5, 'r-', label='digital with initial point only communication') 655 | # ax1.plot(range(10), sum_rate6, 'b-', label='digital without initial point only communication') 656 | # ax1.plot(x, sum_rate7, 'g-', label='ZF precoder') 657 | # ax1.set_xlabel("Power/dBm") 658 | # ax1.set_ylabel('log2(sum rate(bits/s/hz))', color='b') 659 | # ax1.tick_params('y', colors='b') 660 | # _ = plt.xticks(x, p1) 661 | 662 | # plt.xticks(k, rotation='vertical') 663 | 664 | # plot.legend(loc='best') 665 | fig.tight_layout() 666 | 667 | # 添加图例 668 | lines = [ax1.get_lines()[0], \ 669 | ax1.get_lines()[1], \ 670 | ax1.get_lines()[2]] 671 | 672 | # lines = [ax4.get_lines()[0]] 673 | labels = [line.get_label() for line in lines] 674 | ax1.legend(lines, labels, bbox_to_anchor=(0.35, 0.3)) 675 | plt.show() 676 | idx = np.arange(antenna_size) 677 | angle_set = np.arange(1, 181) / 180 * np.pi 678 | Hset = np.exp(1j * np.pi * idx.reshape(-1, 1) * np.cos(angle_set)) 679 | 680 | # different_k() 681 | def different_rf_size(CSI, distance, beta, theta, steering_vector_this_o, analog1,digital1, mode): 682 | 683 | sum_rate1 = [] 684 | sum_rate2 = [] 685 | sum_rate3 = [] 686 | sum_rate7 = [] 687 | crbd1 = [] 688 | crbd2 = [] 689 | crbd3 = [] 690 | crbd7 = [] 691 | 692 | crba1 = [] 693 | crba2 = [] 694 | crba3 = [] 695 | crba7 = [] 696 | 697 | rf = [2,3] 698 | for i in range(len(rf)): 699 | analoger = analog1[:,:, :rf[i]] 700 | digitaler = digital1[:,:rf[i], :] 701 | precoder1 = loss.tf_Precoding_matrix_combine(analoger,digitaler) 702 | sum_rate1_1,sinr = loss.tf_loss_sumrate(CSI, precoder1) 703 | sum_rate1_1 = tf.cast(sum_rate1_1, tf.float32) 704 | print("analoger",analoger) 705 | print("digitaler",digitaler) 706 | print("sumrate1_1",sum_rate1_1) 707 | sum_rate1.append(tf.math.log(tf.reduce_mean(sum_rate1_1)) / tf.math.log(2.0)) 708 | Sigma_time_delay1 = loss.tf_sigma_delay_square(steering_vector_this_o, precoder1, beta) 709 | 710 | crbd1_1 = tf.reduce_sum(loss.tf_CRB_distance(Sigma_time_delay1), axis=1) / 4 711 | crbd1.append(tf.math.log(tf.reduce_mean(crbd1_1)) / tf.math.log(2.0)) 712 | CRB_angle1 = tf.reduce_sum(loss.tf_CRB_angle(beta, precoder1, theta), axis=1) / 4 713 | CRB_angle1 = tf.cast(CRB_angle1, tf.float32) 714 | crba1.append(tf.math.log(tf.reduce_mean(CRB_angle1)) / tf.math.log(2.0)) 715 | fig, ax1 = plt.subplots() 716 | x = range(len(rf)) 717 | if mode == "sumrate": 718 | ax1.plot(x, sum_rate1, 'b-.', label='hybrid ISAC') 719 | # ax2 = ax1.twinx() 720 | #ax1.plot(x, sum_rate2, 'm--', label='digital ISAC,with initial point') 721 | #ax1.plot(x, sum_rate3, 'r.-', label='digital ISAC,without initial point') 722 | # ax1.plot(range(10), sum_rate4, 'm:', label='hybrid only communication') 723 | # ax1.plot(range(10), sum_rate5, 'r-', label='digital with initial point only communication') 724 | # ax1.plot(range(10), sum_rate6, 'b-', label='digital without initial point only communication') 725 | #ax1.plot(x, sum_rate7, 'g-', label='ZF precoder') 726 | ax1.set_xlabel("number of RF chains") 727 | ax1.set_ylabel('log2(sum rate(bits/s/hz))', color='b') 728 | ax1.tick_params('y', colors='b') 729 | _ = plt.xticks(x, rf) 730 | elif mode == "crba": 731 | ax1.set_xlabel("number of RF chains") 732 | ax1.plot(x, crba1, 'b-.', label='hybrid ISAC') 733 | # ax2 = ax1.twinx() 734 | #ax1.plot(x, crba2, 'm--', label='digital ISAC,with initial point') 735 | #ax1.plot(x, crba3, 'r.-', label='digital ISAC,without initial point') 736 | # ax1.plot(range(10), sum_rate4, 'm:', label='hybrid only communication') 737 | # ax1.plot(range(10), sum_rate5, 'r-', label='digital with initial point only communication') 738 | # ax1.plot(range(10), sum_rate6, 'b-', label='digital without initial point only communication') 739 | #ax1.plot(x, crba7, 'g-', label='ZF precoder') 740 | 741 | ax1.set_ylabel('log2(CRB angle rad\u00B2)', color='b') 742 | ax1.tick_params('y', colors='b') 743 | _ = plt.xticks(x, rf) 744 | elif mode == "crbd": 745 | ax1.set_xlabel("number of RF chains") 746 | ax1.plot(x, crbd1, 'b-.', label='hybrid ISAC') 747 | # ax2 = ax1.twinx() 748 | #ax1.plot(x, crbd2, 'm--', label='digital ISAC,with initial point') 749 | #ax1.plot(x, crbd3, 'r.-', label='digital ISAC,without initial point') 750 | # ax1.plot(range(10), sum_rate4, 'm:', label='hybrid only communication') 751 | # ax1.plot(range(10), sum_rate5, 'r-', label='digital with initial point only communication') 752 | # ax1.plot(range(10), sum_rate6, 'b-', label='digital without initial point only communication') 753 | #ax1.plot(x, crbd7, 'g-', label='ZF precoder') 754 | ax1.set_ylabel('log2(CRB distance m\u00B2)', color='b') 755 | ax1.tick_params('y', colors='b') 756 | _ = plt.xticks(x, rf) 757 | 758 | 759 | fig.tight_layout() 760 | 761 | # 添加图例 762 | #lines = [ax1.get_lines()[0], \ 763 | # ax1.get_lines()[1], \ 764 | # ax1.get_lines()[2], \ 765 | # ax1.get_lines()[3]] 766 | 767 | lines = [ax1.get_lines()[0]] 768 | labels = [line.get_label() for line in lines] 769 | ax1.legend(lines, labels, bbox_to_anchor=(0.5, 0.6)) 770 | plt.show() 771 | idx = np.arange(antenna_size) 772 | angle_set = np.arange(1, 181) / 180 * np.pi 773 | Hset = np.exp(1j * np.pi * idx.reshape(-1, 1) * np.cos(angle_set)) 774 | r1 = np.matmul(Hset.T, precoder1[0, :, :]) 775 | plt.polar(angle_set, np.abs(r1)) 776 | #plt.show() 777 | 778 | def different_users(CSI_o, distance, beta_o, theta_o, steering_vector_this_oo, analog1,digital1,precoder2_o,precoder3_o,zf_matrix_o, mode): 779 | 780 | sum_rate1 = [] 781 | sinr1 = [] 782 | sum_rate2 = [] 783 | sum_rate3 = [] 784 | sum_rate7 = [] 785 | crbd1 = [] 786 | crbd2 = [] 787 | crbd3 = [] 788 | crbd7 = [] 789 | 790 | crba1 = [] 791 | crba2 = [] 792 | crba3 = [] 793 | crba7 = [] 794 | 795 | users = [2,3,4] 796 | for i in range(len(users)): 797 | analoger = analog1 798 | digitaler = digital1.numpy() 799 | #digitaler[:,:,users[i]:]=0 800 | digitaler = digitaler[:, :, :users[i]] 801 | 802 | precoder2 = precoder2_o.numpy() 803 | precoder3 = precoder3_o.numpy() 804 | #precoder2[:, :, users[i]:] = 0 805 | precoder2 = precoder2[:, :, :users[i]] 806 | precoder2 = loss.Powerscale(precoder2) 807 | #precoder3[:, :, users[i]:] = 0 808 | precoder3 = precoder3[:, :, :users[i]] 809 | 810 | precoder3 = loss.Powerscale(precoder3) 811 | zf_matrix = zf_matrix_o.numpy() 812 | #zf_matrix[:, users[i]:,:] = 0 813 | zf_matrix = zf_matrix[:, :users[i],:] 814 | zf_matrix = loss.Powerscale(zf_matrix) 815 | #CSI = CSI.numpy() 816 | #CSI[:,users[i]:] = 0 817 | #beta[:,users[i]:] = 0 818 | 819 | CSI = CSI_o.numpy() 820 | CSI = CSI[:,:users[i]] 821 | beta = beta_o.numpy() 822 | steering_vector_this_o = steering_vector_this_oo.numpy() 823 | steering_vector_this_o = steering_vector_this_o[:,:users[i]] 824 | beta = beta[:,:users[i]] 825 | theta = theta_o.numpy() 826 | theta = theta[:,:users[i]] 827 | 828 | 829 | #print("analoger",analoger) 830 | #print("digitaler",digitaler) 831 | precoder1 = loss.tf_Precoding_matrix_combine(analoger,digitaler) 832 | sum_rate1_1,sinr = loss.tf_loss_sumrate(CSI, precoder1) 833 | sum_rate1_1 = tf.cast(sum_rate1_1, tf.float32) 834 | sinr1.append(tf.reduce_mean(sinr)) 835 | sum_rate1.append(tf.math.log(tf.reduce_mean(sum_rate1_1)) / tf.math.log(2.0)) 836 | sum_rate2_1, sinr = loss.tf_loss_sumrate(CSI, precoder2) 837 | sum_rate2_1 = tf.cast(sum_rate2_1, tf.float32) 838 | sum_rate2.append(tf.math.log(tf.reduce_mean(sum_rate2_1)) / tf.math.log(2.0)) 839 | 840 | sum_rate3_1, sinr = loss.tf_loss_sumrate(CSI, precoder3) 841 | sum_rate3_1 = tf.cast(sum_rate3_1, tf.float32) 842 | sum_rate3.append(tf.math.log(tf.reduce_mean(sum_rate3_1)) / tf.math.log(2.0)) 843 | sum_rate7_1, sinr = loss.tf_loss_sumrate(CSI, tf.transpose(zf_matrix, perm=[0, 2, 1])) 844 | sum_rate7_1 = tf.cast(sum_rate7_1, tf.float32) 845 | sum_rate7.append(tf.math.log(tf.reduce_mean(sum_rate7_1)) / tf.math.log(2.0)) 846 | 847 | Sigma_time_delay1 = loss.tf_sigma_delay_square(steering_vector_this_o, precoder1, beta) 848 | Sigma_time_delay2 = loss.tf_sigma_delay_square(steering_vector_this_o, precoder2, beta) 849 | Sigma_time_delay3 = loss.tf_sigma_delay_square(steering_vector_this_o, precoder3, beta) 850 | Sigma_time_delay7 = loss.tf_sigma_delay_square(steering_vector_this_o, tf.transpose(zf_matrix, perm=[0, 2, 1]), 851 | beta) 852 | CRB_d1 = tf.reduce_sum(loss.tf_CRB_distance(Sigma_time_delay1), axis=1)/users[i] 853 | CRB_d2 = tf.reduce_sum(loss.tf_CRB_distance(Sigma_time_delay2), axis=1)/users[i] 854 | CRB_d3 = tf.reduce_sum(loss.tf_CRB_distance(Sigma_time_delay3), axis=1)/users[i] 855 | CRB_d7 = tf.reduce_sum(loss.tf_CRB_distance(Sigma_time_delay7), axis=1)/users[i] 856 | crbd1.append(tf.math.log(tf.reduce_mean(CRB_d1)) / tf.math.log(2.0)) 857 | crbd2.append(tf.math.log(tf.reduce_mean(CRB_d2)) / tf.math.log(2.0)) 858 | crbd3.append(tf.math.log(tf.reduce_mean(CRB_d3)) / tf.math.log(2.0)) 859 | crbd7.append(tf.math.log(tf.reduce_mean(CRB_d7)) / tf.math.log(2.0)) 860 | 861 | CRB_angle1 = tf.reduce_sum(loss.tf_CRB_angle(beta, precoder1, theta), axis=1) / users[i] 862 | CRB_angle2 = tf.reduce_sum(loss.tf_CRB_angle(beta, precoder2, theta), axis=1) / users[i] 863 | CRB_angle3 = tf.reduce_sum(loss.tf_CRB_angle(beta, precoder3, theta), axis=1) / users[i] 864 | CRB_angle7 = tf.reduce_sum(loss.tf_CRB_angle(beta, tf.transpose(zf_matrix, perm=[0, 2, 1]), theta), axis=1) / users[i] 865 | CRB_angle1 = tf.cast(CRB_angle1, tf.float32) 866 | CRB_angle2 = tf.cast(CRB_angle2, tf.float32) 867 | CRB_angle3 = tf.cast(CRB_angle3, tf.float32) 868 | CRB_angle7 = tf.cast(CRB_angle7, tf.float32) 869 | 870 | crba1.append(tf.math.log(tf.reduce_mean(CRB_angle1)) / tf.math.log(2.0)) 871 | crba2.append(tf.math.log(tf.reduce_mean(CRB_angle2)) / tf.math.log(2.0)) 872 | crba3.append(tf.math.log(tf.reduce_mean(CRB_angle3)) / tf.math.log(2.0)) 873 | crba7.append(tf.math.log(tf.reduce_mean(CRB_angle7)) / tf.math.log(2.0)) 874 | 875 | fig, ax1 = plt.subplots() 876 | x = range(len(users)) 877 | if mode == "sumrate": 878 | ax1.plot(x, sum_rate1, 'b-.', label='hybrid ISAC') 879 | #ax1.plot(x,sinr1,'r-.',label='hybrid ISAC') 880 | # ax2 = ax1.twinx() 881 | #ax1.plot(x, sum_rate2, 'm--', label='digital ISAC,with initial point') 882 | #ax1.plot(x, sum_rate3, 'r.-', label='digital ISAC,without initial point') 883 | # ax1.plot(range(10), sum_rate4, 'm:', label='hybrid only communication') 884 | # ax1.plot(range(10), sum_rate5, 'r-', label='digital with initial point only communication') 885 | # ax1.plot(range(10), sum_rate6, 'b-', label='digital without initial point only communication') 886 | #ax1.plot(x, sum_rate7, 'g-', label='ZF precoder') 887 | ax1.set_xlabel("number of users") 888 | ax1.set_ylabel('log2(sum rate(bits/s/hz))', color='b') 889 | ax1.tick_params('y', colors='b') 890 | _ = plt.xticks(x, users) 891 | elif mode == "crba": 892 | ax1.set_xlabel("number of users") 893 | ax1.plot(x, crba1, 'b-.', label='hybrid ISAC') 894 | # ax2 = ax1.twinx() 895 | #ax1.plot(x, crba2, 'm--', label='digital ISAC,with initial point') 896 | #ax1.plot(x, crba3, 'r.-', label='digital ISAC,without initial point') 897 | # ax1.plot(range(10), sum_rate4, 'm:', label='hybrid only communication') 898 | # ax1.plot(range(10), sum_rate5, 'r-', label='digital with initial point only communication') 899 | # ax1.plot(range(10), sum_rate6, 'b-', label='digital without initial point only communication') 900 | #ax1.plot(x, crba7, 'g-', label='ZF precoder') 901 | 902 | ax1.set_ylabel('log2(CRB angle rad\u00B2)', color='b') 903 | ax1.tick_params('y', colors='b') 904 | _ = plt.xticks(x, users) 905 | elif mode == "crbd": 906 | ax1.set_xlabel("number of users") 907 | ax1.plot(x, crbd1, 'b-.', label='hybrid ISAC') 908 | # ax2 = ax1.twinx() 909 | #ax1.plot(x, crbd2, 'm--', label='digital ISAC,with initial point') 910 | #ax1.plot(x, crbd3, 'r.-', label='digital ISAC,without initial point') 911 | # ax1.plot(range(10), sum_rate4, 'm:', label='hybrid only communication') 912 | # ax1.plot(range(10), sum_rate5, 'r-', label='digital with initial point only communication') 913 | # ax1.plot(range(10), sum_rate6, 'b-', label='digital without initial point only communication') 914 | #ax1.plot(x, crbd7, 'g-', label='ZF precoder') 915 | ax1.set_ylabel('log2(CRB distance m\u00B2)', color='b') 916 | ax1.tick_params('y', colors='b') 917 | _ = plt.xticks(x, users) 918 | 919 | 920 | fig.tight_layout() 921 | 922 | # 添加图例 923 | #lines = [ax1.get_lines()[0], \ 924 | # ax1.get_lines()[1], \ 925 | # ax1.get_lines()[2], \ 926 | # ] 927 | 928 | lines = [ax1.get_lines()[0]] 929 | labels = [line.get_label() for line in lines] 930 | ax1.legend(lines, labels, bbox_to_anchor=(0.5, 0.6)) 931 | plt.show() 932 | idx = np.arange(antenna_size) 933 | angle_set = np.arange(1, 181) / 180 * np.pi 934 | Hset = np.exp(1j * np.pi * idx.reshape(-1, 1) * np.cos(angle_set)) 935 | r1 = np.matmul(Hset.T, precoder1[0,:,:]) 936 | print(crbd1) 937 | plt.polar(angle_set, np.abs(r1)) 938 | #plt.show() 939 | if Test == "V2V": 940 | real_distance, real_theta = evaluation.generate_input_v2v() 941 | elif Test == "V2I": 942 | real_distance, real_theta = evaluation.generate_input_v2i() 943 | 944 | random.seed(2) 945 | # combined = loss.Conversion2CSI(real_distance, real_theta)P 946 | combined = loss.Conversion2input_small(real_theta.T[:40], real_distance.T[:40]) 947 | 948 | combined = tf.expand_dims(combined, axis=3) 949 | #different_num_user(combined, mode="sumrate") 950 | comparison(combined, mode="sumrate") 951 | # comparison_between_crb_distance(combined) 952 | # comparison_between_crb_angle(combined) --------------------------------------------------------------------------------