This repository has been archived by the owner on Oct 21, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsls.py
2222 lines (1669 loc) · 79.1 KB
/
sls.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# System-Level Simulator functions
import utils as ut
import numpy as np
import numpy.linalg
import scipy.io
import scipy.interpolate
import application_traffic as at
def id_tti(tti, n_slots_per_frame, UL_DL_split):
"""
Based on the TDD split, figure if a tti is meant for UL or DL,
and return a string accordingly ('UL' or 'DL').
'F' (Flexible) options are not enabled currently.
"""
return 'DL'
if (tti % n_slots_per_frame + 1) > round(n_slots_per_frame * UL_DL_split):
return 'UL'
else:
return 'DL'
""" Functions for the Scheduling process part 1"""
def compute_avg_bitrate(previous_avg, curr_bitrate, tc=100):
""" Returns the average throughput experienced in the last tc time
intervals
"""
alphaPF = 1 / tc
return previous_avg * (1 - alphaPF) + curr_bitrate * alphaPF
def pf_scheduler(avg_thrput, curr_expected_bitrate):
"""
Returns the well known proportional fairness ratio, the ratio between the
passible to being achieved instantaneous bitrate and the average
experienced bitrate.
"""
# Only to cope with the initialisation possibility and avoid crashes
if avg_thrput == 0:
return 1e20
return curr_expected_bitrate / avg_thrput
def MLWDF_scheduler(avg_thrput, curr_expected_bitrate,
curr_delay, delay_threshold, delta=0.1):
"""
Parameters
----------
avg_thrput : weighted over many ttis
curr_expected_bitrate : bitrate estimated as achievable for the curr tti
lat : current delay of the packet at the head of the queue
delta : upper limit of packet loss rate
(0: NO PACKET CAN BE LOST!, 1: who cares)
Note: it was made to differentiate between several QoS.
So, if all users have the same priority, there's no weight from
it, and can be considered a constant.
Returns
-------
Returns the priority for a given user computed with the Maximum-Largest
Weighted Delay First Scheduler.
"""
# Is it natural log or log10?
a = -np.log(delta) / delay_threshold
return a * curr_delay * pf_scheduler(avg_thrput, curr_expected_bitrate)
def exp_pf_scheduler(avg_thrput, curr_expected_bitrate,
curr_delay, c, delay_threshold, all_delays,
kappa=100, epsilon=0.1):
"""
Parameters
----------
avg_thrput : average experienced throughput
curr_expected_bitrate : estimated achievable throughput
curr_delay : current delay of the head of the queue
c : constant, for prioritising traffic flows.
delay_threshold : maximum delay
all_delays : delay of each queue's head
n_rt : Number of real-time traffic flows (equivalent to the number of
buffers to be served)
Returns
-------
Double: A priority measure.
"""
print('This NEEDS testing!!!!')
a = c / delay_threshold
n_rt = len(all_delays)
aW_avg = sum(a * all_delays) / n_rt
return np.exp((a * curr_delay - aW_avg) / (1 + np.sqrt(aW_avg)) *
pf_scheduler(avg_thrput, curr_expected_bitrate))
def scheduler(scheduler_choice, avg_throughput_ue, estimated_bitrate,
buffer_head_of_queue_delay, delay_threshold,
scheduler_param_delta, scheduler_param_c, all_delays):
if scheduler_choice == 'PF':
priority = pf_scheduler(avg_throughput_ue,
estimated_bitrate)
elif scheduler_choice == 'M-LWDF':
priority = MLWDF_scheduler(avg_throughput_ue,
estimated_bitrate,
buffer_head_of_queue_delay,
delay_threshold,
scheduler_param_delta)
elif scheduler_choice == 'EXP/PF':
priority = exp_pf_scheduler(avg_throughput_ue,
estimated_bitrate,
buffer_head_of_queue_delay,
scheduler_param_c,
delay_threshold,
all_delays)
else:
raise Exception("The only available schedulers are 'PF', 'M-LWDF'"
" and 'EXP/PF'.")
return priority
"""
MCS table implemented in the functions below:
Table 5.2.2.1-3 from 38.214
For maximum BLER of 0.1 and up to 256 QAM.
CQI index | modulation | code rate x 1024 | efficiency | Bit Rate [kbps]
1 QPSK 78 0.1523 25,59375
2 QPSK 193 0.3770 63,328125
3 QPSK 449 0.8770 147,328125
4 16QAM 378 1.4766 248,0625
5 16QAM 490 1.9141 321,5625
6 16QAM 616 2.4063 404,25
7 64QAM 466 2.7305 458,71875
8 64QAM 567 3.3223 558,140625
9 64QAM 666 3.9023 655,59375
10 64QAM 772 4.5234 759,9375
11 64QAM 873 5.1152 859,359375
12 256QAM 711 5.5547 933,1875
13 256QAM 797 6.2266 1046,0625
14 256QAM 885 6.9141 1161,5625
15 256QAM 948 7.4063 1244,25
"""
def calc_CQI(sinr):
"""
Uses BLER(SINR) curves fitted for several tables of MCSs.
Here is implemented Table 5.2.2.1-3 from 38.214.
For maximum BLER of 0.1 and up to 256 QAM.
CQI index | modulation | code rate x 1024 efficiency | Bit Rate [kbps]
1 QPSK 78 0.1523 25,59375
2 QPSK 193 0.3770 63,328125
3 QPSK 449 0.8770 147,328125
4 16QAM 378 1.4766 248,0625
5 16QAM 490 1.9141 321,5625
6 16QAM 616 2.4063 404,25
7 64QAM 466 2.7305 458,71875
8 64QAM 567 3.3223 558,140625
9 64QAM 666 3.9023 655,59375
10 64QAM 772 4.5234 759,9375
11 64QAM 873 5.1152 859,359375
12 256QAM 711 5.5547 933,1875
13 256QAM 797 6.2266 1046,0625
14 256QAM 885 6.9141 1161,5625
15 256QAM 948 7.4063 1244,25
Parameters
----------
sinr : estimated achievable SINR.
Return
----------
mcs_idx : the index of the MCS to be used.
"""
#
for cqi_idx in range(15, 0, -1):
bler = get_BLER_from_fitted_MCS_curves(cqi_idx, sinr)
if bler < 0.1:
return (cqi_idx, bler)
# if not even the lowest modulation could cope with it, return
# the cqi for 'no_signal/out of range', at 100% BLER.
return (0, 1)
def get_BLER_from_fitted_MCS_curves(cqi, sinr):
"""
Parameters
----------
cqi : index for the MCS to be used
sinr : wanna guess this one?
Returns
-------
A tuple with
- CQI
- The Block Error Rate for a given SINR (expected or realised)
"""
x = sinr
ut.parse_input(cqi, [i for i in range(1, 15 + 1)])
if cqi >= 15 and sinr < 23.7:
bler = 1
elif cqi >= 14 and sinr < 22:
bler = 1
elif cqi >= 13 and sinr < 20:
bler = 1
elif cqi >= 12 and sinr < 18.3:
bler = 1
elif cqi >= 11 and sinr < 16.6:
bler = 1
elif cqi >= 10 and sinr < 14.8:
bler = 1
elif cqi >= 9 and sinr < 12.5:
bler = 1
elif cqi >= 8 and sinr < 10.7:
bler = 1
elif cqi >= 7 and sinr < 9:
bler = 1
elif cqi >= 6 and sinr < 6.7:
bler = 1
elif cqi >= 5 and sinr < 4.8:
bler = 1
elif cqi >= 4 and sinr < 3.4:
bler = 1
elif cqi >= 3 and sinr < -1.1:
bler = 1
elif cqi >= 2 and sinr < -6:
bler = 1
elif cqi >= 1 and sinr < -9.6:
bler = 1
else:
# Fitted curves
bler = {
1: (0.8942 * np.exp(-((x + 10.05) / 1.28)**2) +
0.5795 * np.exp(-((x + 8.602) / 0.9784)**2)),
2: 1 - (9.182 / (np.exp(-4.293 * x - 16.31) + 9.171)),
3: 1 - (0.7106 / (np.exp(-6.388 * x) + 0.7106)),
4: 1 - (1 / (np.exp(-6.138 * x + 28.19) + 0.9996)),
5: 1 - (1 / (np.exp(-7.502 * x + 44.68) + 0.9985)),
6: 1 - (1 / (np.exp(-8.279 * x + 64.07) + 0.9996)),
7: 1 - (1 / (np.exp(-7.981 * x + 79.61) + 0.9998)),
8: 1 - (1 / (np.exp(-8.217 * x + 96.46) + 0.9995)),
9: 1 - (1 / (np.exp(-9.292 * x + 124.6) + 0.9989)),
10: (0.6046 * np.exp(-((x - 15.1) / 0.3454)**2) +
0.9940 * np.exp(-((x - 13.47) / 0.969)**2) +
0.6544 * np.exp(-((x - 14.56) / 0.5685)**2)),
11: (0.6768 * np.exp(-((x - 16.3) / 0.6109)**2) +
0.9575 * np.exp(-((x - 15.24) / 0.895)**2) +
0.5245 * np.exp(-((x - 17.08) / 0.2716)**2) +
0.4280 * np.exp(-((x - 16.73) / 0.3344)**2)),
12: 1 - (1 / (np.exp(-10.22 * x + 196.7) + 0.9999)),
13: 1 - (1 / (np.exp(-9.939 * x + 208.5) + 0.9988)),
14: 1 - (1 / (np.exp(-10.23 * x + 234.7) + 0.9995)),
15: 1 - (1 / (np.exp(-9.504 * x + 235.7) + 0.9997))}[cqi]
# Limit non-sensical values
if bler < 0:
bler = 0
if bler > 1:
bler = 1
return bler
def bits_per_PRB(cqi):
"""
Returns the an (inflated) estimate of number of bits that can be sent
given a MCS and #PRBs.
This is 100% copy from the bits per PRB column.
From the implemented table, efficiency x 168 resource elements, each
containing a symbol.
V2 may implement something like this:
https://www.sharetechnote.com/html/5G/5G_MaxThroughputEstimation.html
"""
if cqi < 1:
return 0
if cqi > 15:
cqi = 15
bits_per_prb = {1: 25.5864,
2: 63.3360,
3: 147.3360,
4: 248.0688,
5: 321.5688,
6: 404.2584,
7: 458.7240,
8: 558.1464,
9: 655.5864,
10: 759.9312,
11: 859.3536,
12: 933.1896,
13: 1046.0688,
14: 1161.5688,
15: 1244.2584}[cqi]
return bits_per_prb
def estimate_bits_to_be_sent(cqi, n_prbs, freq_compression_ratio=1):
"""
The number of bits sent per PRB is constant for all numerologies, for
a given MCS (we use 'cqi' here). This happens because as a PRB gets larger
in frequency due to increase in numerology, it gets proportionally
shorter in time, and the bits we can send with more Hz but in a smaller
interval stay the same.
This mean that from the number of PRBs we can tell right away how many
bits can be sent.
(THE IMPORTANT PART NOW)
Furthermore, this function takes into account the possibility of less
frequency granularity. Basically, we can have PRBs that are larger
in frequency than expected, without scalling their duration. For such
inflated PRBs, this function scales the bits to be sent accordingly.
The frequency compression ratio corresponds to the number of PRBs
that each sample in frequency represents.
"""
bits_per_prb = bits_per_PRB(cqi) * freq_compression_ratio
return int(np.floor(bits_per_prb * n_prbs))
def bits_per_symb_from_cqi(cqi):
"""
Derived by visual inspection from the table above.
"""
if cqi < 1:
bits_per_symbol = 0
elif 1 <= cqi <= 3:
bits_per_symbol = 2
elif 4 <= cqi <= 6:
bits_per_symbol = 4
elif 7 <= cqi <= 11:
bits_per_symbol = 6
elif 12 <= cqi <= 15:
bits_per_symbol = 8
else:
raise Exception('No other CQIs are supported in a transmission. '
'Only from 1 to 15')
return bits_per_symbol
"""
Transport Blocks' Logic
"""
class Transport_Block():
def __init__(self, size, start_idx):
# Number of bits of the TB
self.size = size
# This Transport Block has assigned some bits in a certain part of
# the buffer. This will be used to remove these bits from the buffer
# afterwards if the block is transported successfully
self.start_idx = start_idx
def print_tb(self):
print(f'TB start: {self.start_idx}; Size: {self.size} bits.')
def get_TB_size(bits_to_be_sent, tbs_divisor, n_layers=0, v='v1'):
"""
Objective: returns the transport block size.
Currently V1:
Returns the a TBS which equals all bits estimated to get across given a
certain MCS and #PBRs.
Therefore, only one transport block is used. (more eggs in the same basket)
V2 Implements:
https://5g-tools.com/5g-nr-tbs-transport-block-size-calculator/
Described more carefully here:
https://www.sharetechnote.com/html/5G/5G_MCS_TBS_CodeRate.html#PDSCH_TBS
See also:
https://www.resurchify.com/5G-tutorial/5G-NR-Throughput-Calculator.php
Note before implementing v2: for the uplink is too complicated to do
the same. So, either do the same as for the DL, or stick with v1.
"""
if v == 'v1':
# here we estimate the bits a priori
pass
else:
# here we apply a complicated process to estimate the bits to be sent
# (decide about this!!!!!!!!!)
# Number of resource elements
# n_re_dmrs = 0
# Number of useful resource elements
# n_re =
bits_to_be_sent = 0 # V2 still to implement.
return np.ceil(bits_to_be_sent / tbs_divisor)
"""
Convenient Formulas
"""
def calc_SINR(tx_pow, ch_pow_gain, interference, noise_power):
"""
Compute the SINR.
"""
sig_pow = tx_pow * ch_pow_gain
sinr_linear = sig_pow / (noise_power + interference)
return 10 * np.log10(sinr_linear)
def get_curr_time_div(tti, time_div_ttis):
return int(np.floor(tti / time_div_ttis))
"""
SINR precise formula
"""
def calc_rx_power_lin(tx_pow, tx_precoder, rx_precoder, ch_coeffs):
"""
Receives channel coefficients, and precoders for the scheduled users
"""
ch_power_gain_before_combining = np.dot(ch_coeffs, tx_precoder)
ch_power_gain_after_combining = np.dot(ch_power_gain_before_combining,
rx_precoder)
return tx_pow * (abs(ch_power_gain_after_combining) ** 2)
"""
Functions to index the table of Information bits
Assumes the table has been written with an interval of 0.5 between SINRs.
"""
def load_info_bits_table(table_path):
"""
Loads to memory the complete table required for MIESM
"""
return np.genfromtxt(table_path, delimiter=',')
def get_information_bits(sinr, k, table, low_extreme=-10, step=0.5):
"""
Rounds the sinr and sees which index is that SINR belongs to.
"""
sinr_rounded = ut.round_to_value(sinr, step)
idx_of_sinr = int((sinr_rounded - low_extreme) / step)
k_idx = int(k / 2)
return table[idx_of_sinr, k_idx]
def get_sinr_from_info_bits_closest(info_bits, k, table):
"""
Returns the SINR that is closer to a certain number of information bits
of the table. Search along the column of that modulation is required.
"""
k_idx = int(k / 2)
idx_of_closest = (np.abs(table[:, k_idx] - info_bits)).argmin()
return table[idx_of_closest, 0]
def get_sinr_from_info_bits_interpolated(info_bits, k, table):
"""
Returns the SINR that is closer to a certain number of information bits
of the table. Search along the column of that modulation is required.
"""
k_idx = int(k / 2)
for i in range(table.shape[0]):
if table[i, k_idx] - info_bits > 0:
break
idx_of_previous = i - 1
idx_of_next = i
info_bits_diff = (table[idx_of_next, k_idx] -
table[idx_of_previous, k_idx])
if info_bits_diff == 0:
return get_sinr_from_info_bits_closest(info_bits, k, table)
# Manual interpolation
sinr_diff = (table[idx_of_next, 0] - table[idx_of_previous, 0])
slope = sinr_diff / info_bits_diff
diff = info_bits - table[idx_of_previous, k_idx]
sinr = table[idx_of_previous, 0] + slope * diff
return sinr
def avg_SINRs_MIESM(sinrs, table, k):
"""
Compute the SINR that each PRB would have to need to have in order to
transmit the average number of information bits each PRB can transmit.
k is the number of bits enconded in each symbol. E.g. In QPSK and 4-QAM,
there are 4 symbols, thus each enconding the value of 2 bits.
With an avergae number of information bits <=k, we search the table
Note: if the table is changed from [-10, 32] dB with steps of 0.5, the
indexing/search functions should have their arguments changed here.
"""
# The low extreme of the table
low_ext = -10
# The high extreme of the table
high_ext = 32
# Step between SINRs
step = 0.1
n_subcarriers = len(sinrs)
total_i_bits = 0
for i in range(n_subcarriers):
if sinrs[i] > high_ext:
total_i_bits += k
elif sinrs[i] < low_ext:
total_i_bits += 0
else:
total_i_bits += get_information_bits(sinrs[i], k, table,
low_ext, step)
# per symbol
avg_information_bits = total_i_bits / n_subcarriers
eff_sinr = get_sinr_from_info_bits_interpolated(avg_information_bits,
k, table)
return eff_sinr
##########################################################################################
"""
Functions around channel coefficients loading and handling/managing.
"""
def load_coeffs_part(fname):
fname_real = fname + '_r.bin'
fname_imag = fname + '_i.bin'
# Read coeffs in binary
with open(fname_real) as fp:
real_part = np.fromfile(fp, dtype=np.single)
with open(fname_imag) as fp:
imag_part = np.fromfile(fp, dtype=np.single)
# Merge them into a complex numbers and attribute the values to coeffs
coeffs_part = np.complex64(real_part + 1j * imag_part)
return coeffs_part
def get_coeff_part_idx(time_div_idx, freq_idx, bs_idx, ue_idx,
n_freq, n_bs, n_ue):
"""
Given the time division, it computes which parts (coefficients files)
should be loaded next in order to give continuity to the simulation.
"""
if freq_idx >= n_freq or bs_idx >= n_bs or ue_idx >= n_ue:
print('Wront index required!')
print(f"There are {n_freq} freqs, {n_bs} BSs and {n_ue} UEs."
f"The (zero-indexed!!!) index required was "
f"({freq_idx, bs_idx, ue_idx})")
raise Exception()
part_idx = (time_div_idx * (n_ue * n_bs * n_freq) +
freq_idx * (n_ue * n_bs) +
bs_idx * (n_ue) +
ue_idx * 1) + 1
return int(part_idx)
""" Coefficient Loading functions"""
def interp1d(xx, yy, kind='linear', ax=-1):
if kind == 'linear':
return scipy.interpolate.interp1d(xx, yy, 'linear', axis=ax)
elif kind == 'log':
logx = np.log10(xx)
logy = np.log10(yy)
lin_interp = scipy.interpolate.interp1d(logx, logy, 'linear',
axis=ax)
log_interp = lambda zz: np.power(10.0, lin_interp(np.log10(zz)))
return log_interp
else:
raise Exception("Only 'linear' and 'log' interpolation types "
"are available.")
def get_time_interpolation_ttis(target_interpolation_ttis,
time_compression_ratio):
# Compressed TTIs
ttis_c = np.arange(0, target_interpolation_ttis+1, time_compression_ratio)
# Non-compressed TTIs
ttis = np.arange(0, target_interpolation_ttis)
return ttis, ttis_c
def time_interpolation(ttis, ttis_c, coeffs_c, mode='fast'):
"""
Make an interpolation in the complex domain. For each coefficient, more
many TTIs are generated. Namely, time_compression_ratio of them.
We interpolate amplitude and phase linearly, through linear interpolations
of the real and imaginary parts.
"""
# Compressed real and imaginary parts
real_c = np.real(coeffs_c)
imag_c = np.imag(coeffs_c)
# Interpolated functions
real_i = interp1d(ttis_c, real_c, kind='linear')
imag_i = interp1d(ttis_c, imag_c, kind='linear')
if mode == 'fast':
interpolated_coeffs = np.complex64(real_i(ttis) + 1j * imag_i(ttis))
else:
mag_c = np.abs(coeffs_c)
mag_i = interp1d(ttis_c, mag_c, kind='linear')
interpolated_coeffs = np.complex64( \
mag_i(ttis) * np.exp(1j * np.angle(real_i(ttis) + 1j * imag_i(ttis))))
# Interpolate and reassemble
return interpolated_coeffs
def load_coeffs(tti, time_div_idx, n_time_divs, ttis_per_time_div,
time_compression_ratio, f_idx, n_freq, n_bs_gen, n_ue_gen,
specific_bss, specific_ues, coeff_file_prefix,
coeff_file_suffix, n_ue_coeffs, n_bs_coeffs, ae_ue, ae_bs,
prbs, ttis_per_batch):
"""
Loads coefficients from the respective time division:
In order to have generation and simulation decoupled, we may
generate with the number of time divisions we desire, and have a proper
amount of coefficients loaded, adjusted to their size. E.g. in 26 GHz
there are 16x more antennas than in 3.5 GHz, so it is less likely that
all users can be simulated simulatenously.
Samples are generated and we want to end up with TTIs. There can be a TTI
per sample, when time_compression_ratio = 1, but that is the minimum.
"""
if time_div_idx >= n_time_divs:
raise Exception('More time divisions than the ones the simulation '
'has, are not supported yet.')
coeffs = {}
if time_compression_ratio != 1:
ttis, ttis_c = get_time_interpolation_ttis(ttis_per_batch,
time_compression_ratio)
# The +1 is there for interpolation. It is actually the first
# sample of the next time division.
if time_compression_ratio == 1:
extra_sample = 0
else:
extra_sample = 1
samples_per_time_div = int(ttis_per_time_div /
time_compression_ratio) + extra_sample
samples_per_batch = int(ttis_per_batch /
time_compression_ratio) + extra_sample
if samples_per_batch < samples_per_time_div:
offset_in_ttis = int(tti - (time_div_idx) * ttis_per_time_div)
# offset in samples
offset = int(offset_in_ttis / time_compression_ratio)
print('Loading: ')
for bs in specific_bss:
for ue in specific_ues:
# Given the indices, figure what part should be loaded.
part_idx = get_coeff_part_idx(time_div_idx,
f_idx, bs, ue,
n_freq, n_bs_gen, n_ue_gen)
name_to_load = (coeff_file_prefix +
str(part_idx) +
coeff_file_suffix)
coeff_shape = (n_ue_coeffs[ue], n_bs_coeffs[bs],
prbs, samples_per_time_div)
print(f'\rLoading for UE {ue}, BS {bs}...', end='')
coeffs_aux = \
load_coeffs_part(name_to_load).reshape(coeff_shape, order='F')
# Trim to fit the batch size
if samples_per_batch < samples_per_time_div:
coeffs_aux = coeffs_aux[:,:,:,
offset:offset + samples_per_batch]
bs_idx = specific_bss.index(bs)
ue_idx = specific_ues.index(ue)
if time_compression_ratio == 1:
# When there were as many samples generated as TTIs needed
# no interpolation is needed
coeffs[(bs_idx, ue_idx)] = coeffs_aux
else:
# interpolate!
if time_compression_ratio > 10:
interp_mode = 'accurate'
else:
interp_mode = 'fast'
coeffs[(bs_idx, ue_idx)] = \
time_interpolation(ttis, ttis_c, coeffs_aux, interp_mode)
# In addition, return the last tti to which these coefficients apply
last_coeff_tti = tti + ttis_per_batch - 1
return coeffs, last_coeff_tti
def update_channel_vars(tti, TTIs_per_batch, n_ue, coeffs, channel,
channel_per_prb, save_prb_channel):
"""
Aggregate channel responses across antenna elements per ue. Assumes BS 0.
"""
ttis = np.arange(tti, tti + TTIs_per_batch)
for ue in range(n_ue):
# coeffs is a dictionary with the channel betwee BS-UE
c = coeffs[(0, ue)] # c is [n_rx, n_tx, n_prb, n_tti]
# a) take the power between any two elements
# b) get the average per prb (is not )
# c)
for t_idx in range(len(ttis)):
# channel is [n_ue,tti]
channel[ttis[t_idx]][ue] = \
10 * np.log10(np.sum(np.mean(np.abs(c[:,:,:,t_idx]) ** 2, 2)))
# channel_per_prb is [n_ue, tti, n_prb]
# The second check is to prevent this to run before it is properly
# implemented and tested. The save_prb_vars should be enough.
# PS: actually, separate in channel and sig_pow vars to be specific
if save_prb_channel and channel_per_prb != []:
channel_per_prb[ttis[t_idx]][ue] = 10 * \
np.log10(np.sum(np.sum(np.abs(c[:,:,:,t_idx]) ** 2, 0), 0))
def copy_last_coeffs(coeffs, last_x):
"""
Given a dictionary of coefficients, copy the last x coefficients to a new
dictionary with the same keys, but much smaller.
"""
# For initialisation purposes
if coeffs == '':
return ''
new_coeffs = {}
for key, coeff_vals in coeffs.items():
new_coeffs[key] = coeff_vals[:,:,:,-last_x:]
return new_coeffs
"""
Form channel matrix functions
"""
def channel_matrix(coeffs, ue, bs, prb, tti_relative, pol=-1):
if pol == -1:
c = coeffs[(bs, ue)][:,:,prb,tti_relative]
elif pol in [0, 1]:
c = coeffs[(bs, ue)][:,pol::2,prb,tti_relative]
else:
raise Exception('Only polarisations 0 and 1 are supported.')
return c
"""
Precoder related functions.
"""
def load_precoders(precoders_paths, vectorize_GoB):
"""
Creates a dictionary of base stations and angles, based on the precoder
files.
The precoder is for an array of a certain size that spans a certain
angular domain with a given resolution. This information will be read from
the precoder file.
"""
precoders_dict = {}
for bs in range(len(precoders_paths)):
precoder_file = scipy.io.loadmat(precoders_paths[bs])
precoders_dict[(bs, 'matrix')] = \
precoder_file['precoders_matrix'].astype(np.complex64)
precoders_dict[(bs, 'directions')] = \
precoder_file['precoders_directions']
precoders_dict[(bs, 'N1')] = precoder_file['N1'][0][0]
precoders_dict[(bs, 'N2')] = precoder_file['N2'][0][0]
precoders_dict[(bs, 'O1')] = precoder_file['O1'][0][0]
precoders_dict[(bs, 'O2')] = precoder_file['O2'][0][0]
n_azi_beams = precoders_dict[(bs, 'N1')] * precoders_dict[(bs, 'O1')]
n_ele_beams = precoders_dict[(bs, 'N2')] * precoders_dict[(bs, 'O2')]
n_directions = precoders_dict[(bs, 'directions')].shape[1]
# Store angle information along with the precoders
# Size = [# of precoders with very similar azimuths,
# # of precoders with very similar elevations]
# for a square GoBs, it is the square root of the total # of precoders
precoders_dict[(bs, 'size')] = [n_azi_beams, n_ele_beams]
precoders_dict[(bs, 'n_directions')] = n_directions
return precoders_dict
def print_precoders_dict(precoders_dict, bs_idx, print_directions=False,
print_precoders=False):
try:
size = precoders_dict[(bs_idx, 'size')]
n_directions = precoders_dict[(bs_idx, 'n_directions')]
print(f'Codebook for BS {bs_idx} has size {size} '
f'-> {n_directions} directions')
if print_directions or print_precoders:
for dir_idx in range(n_directions):
if print_directions:
ang = precoders_dict[(bs_idx, 'directions')][:,dir_idx]
print(f'Ang: [{ang[0]:2},{ang[1]:2}];')
if print_precoders:
p = precoders_dict[(bs_idx, 'matrix')][:,dir_idx]
print(p)
except KeyError:
print('KEY ERROR!!')
class Beam_pair():
"""
This class holds a beam pair between one BS polarisation and all
UE antennas. For organisational purposes, we divide the UE's antennas in
two, having a set of antenas (and a beamformer) per polarisation.
pol 0 means -45? antennas
pol 1 means +45? antennas
"""
def __init__(self):
# Grid of Beams specific: direction at which the BS beam is pointing
self.ang = [0, 0]
self.ang_idx = [0, 0]
self.beam_idx = -1
# The correct polarisation combination must be saved, because this
# determines the coefficients to be used when using that beam pair.
# pol = -1 -> both polarisations jointly
# pol = 0 -> pol 0 on bs, both polarisations on the ue
# (pol_comb = 0 + pol_comb = 2)
# pol = 1 -> pol 1 on bs, both polarisations on the ue
# (pol_comb = 1 + pol_comb = 3)
# For other combinations, change channel_matrix() to create the
# appropriate channel matrix. For now, all transmissions use all
# antennas.
self.pol = -1 # Note: this is not used anymore, but
# the channel_matrix() function still supports it.
# Notice that polarisation and polarisation combination are different
# things. When talking about combinations, we are referring to a
# combination of polarisations one at the UE, and one at the BS.
# If we just mention ONE polarisation, it is ALWAYS on the BS side,
# because, remember, the UE uses all antennas always
# The normalised precoders/combiners:
# Precoder used at BS side (for TX and RX)
self.bs_weights = []
# UE RX/TX precoders
# Derived with MRC/MRT from channel and BS precoder
# one per polarisation
self.ue_weights = []
# The linear power channel gain
self.ch_power_gain = 0
# When the precoder list was last updated (absolute tti)
# (In this TTI, the most up-to-date CSI was used)
self.last_updated = -1
def print_pair(self):
print(f'Ang: [{self.ang[0]:2},{self.ang[1]:2}]; '
f'Gain: {self.ch_power_gain:.2e}')
def print_curr_beam_pairs(curr_beam_pairs, n_bs, n_ue, n_layers):
for bs in range(n_bs):
for ue in range(n_ue):
# layers are updated at the same time, so we can use the time of
# update of just one of them.
print(f'BS {bs}, UE {ue}, All layers [Last updated in '
f'TTI {curr_beam_pairs[(bs, ue, 0)].last_updated}]:')
for l in range(n_layers):
curr_beam_pairs[(bs, ue, l)].print_list()
def interleave(arrays, axis=0, out=None):
"""
From user 'clwainwright' in https://stackoverflow.com/questions/5347065