-
Notifications
You must be signed in to change notification settings - Fork 3
/
demodulationRoutines.py
1619 lines (1324 loc) · 55.3 KB
/
demodulationRoutines.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
# -*- coding: utf-8 -*-
"""
Created on Fri Jun 19 16:21:35 2020
@author: Seo
"""
import numpy as np
from timingRoutines import Timer
# from numba import njit, jit
from xcorrRoutines import *
import warnings
import matplotlib.pyplot as plt
from cython_ext.compareIntPreambles import compareIntPreambles
try:
import cupy as cp
def cupyDemodulateCP2FSK(syms: cp.ndarray, h: float, up: int):
m = cp.array([[-1], [+1]])
tones = cp.exp(1j * np.pi * h * cp.arange(up) / up * m)
numSyms = int(np.floor(len(syms) / up))
bitCost = cp.zeros((2, numSyms))
demodBits = cp.zeros(numSyms, dtype=np.uint8)
for i in range(numSyms):
symbol = syms[i * up : (i + 1) * up]
for k in range(2):
bitCost[k, i] = cp.abs(cp.vdot(symbol, tones[k]))
demodBits[i] = cp.argmax(bitCost[:, i])
return demodBits, bitCost, tones
except:
print("Cupy not found.")
# %% Generic simple demodulators
class SimpleDemodulatorPSK:
"""
Generic demodulator implementation for BPSK/QPSK/8PSK.
This uses a dot product method to detect which symbol in the constellation is present.
The default constellation-bit mappings are provided as gray-mapped bits,
but this can be changed.
"""
# These default psk constellations are provided only for the basic class.
# The specialised classes use their own constellations which are optimised for demodulation.
pskdicts = { # This is a monotonically increasing index for each increase in angle
2: np.array([1.0, -1.0], dtype=np.complex128),
4: np.array([1.0, 1.0j, -1.0, -1.0j], dtype=np.complex128),
8: np.array(
[
1.0,
np.sqrt(2) / 2 * (1 + 1j),
1.0j,
np.sqrt(2) / 2 * (-1 + 1j),
-1.0,
np.sqrt(2) / 2 * (-1 - 1j),
-1.0j,
np.sqrt(2) / 2 * (1 - 1j),
],
dtype=np.complex128,
),
}
# This is a specific bit mapping for each corresponding index i.e. each angle, in increasing order
# E.g. QPSK/8PSK are gray mapped.
pskbitmaps = {
2: np.array([0b1, 0b0], dtype=np.uint8),
4: np.array([0b11, 0b01, 0b00, 0b10], dtype=np.uint8),
8: np.array(
[0b000, 0b001, 0b011, 0b010, 0b110, 0b111, 0b101, 0b100], dtype=np.uint8
),
}
def __init__(
self, m: int, bitmap: np.ndarray = None, cluster_threshold: float = 0.1
):
self.m = m
self.const = self.pskdicts[self.m]
self.normVecs = self.const.view(np.float64).reshape((-1, 2))
self.bitmap = self.pskbitmaps[self.m] if bitmap is None else bitmap
self.cluster_threshold = cluster_threshold
# Interrim output
self.xeo = None # Selected eye-opening resample points
self.xeo_i = None # Index of eye-opening
self.eo_metric = None # Metrics of eye-opening
self.reimc = None # Phase-locked to constellation (complex array)
self.svd_metric = None # SVD metric for phase lock
self.angleCorrection = None # Angle correction used in phase lock
self.syms = None # Output mapping to each symbol (0 to M-1)
self.matches = None # Output from amble rotation search
def getEyeOpening(self, x: np.ndarray, osr: int, abs_x: np.ndarray = None):
if abs_x is None:
abs_x = np.abs(
x
) # Provide option for pre-computed (often used elsewhere anyway)
x_rs_abs = abs_x.reshape((-1, osr))
self.eo_metric = np.mean(x_rs_abs, axis=0)
i = np.argmax(self.eo_metric)
x_rs = x.reshape((-1, osr))
return x_rs[:, i], i
def mapSyms(self, reimc: np.ndarray):
"""
Maps symbols to values from 0 to m-1. Note that this may not correspond to the
bit values desired e.g. gray mapping. In such scenarios, the bitmap should be amended.
This method does not need to be called directly; it is called as part of demod().
See symsToBits() for actual bit mapping.
Parameters
----------
reimc : np.ndarray
Correct eye-opening, frequency corrected and phase-locked complex-valued input.
Returns
-------
syms : np.ndarray
Output array corresponding to the symbol values 0 to m-1.
"""
reimcr = reimc.view(np.float32).reshape((-1, 2)).T
constmetric = self.normVecs @ reimcr
# Pick the arg max for each column
syms = np.argmax(constmetric, axis=0).astype(np.uint8)
return syms
def lockPhase(self, reim: np.ndarray):
# Power into BPSK
powerup = self.m // 2
reimp = reim**powerup
# Form the square product
reimpr = reimp.view(np.float32).reshape((-1, 2)).T
reimsq = reimpr @ reimpr.T
# SVD
u, s, vh = np.linalg.svd(reimsq) # Don't need vh technically
# Check the svd metrics
svd_metric = (
s[-1] / s[:-1]
) # Deal with this later when there is residual frequency
if np.any(svd_metric > self.cluster_threshold):
warnings.warn(
"Constellation not well clustered. There may be residual frequency shifts."
)
# Angle correction
angleCorrection = np.arctan2(u[1, 0], u[0, 0])
reimc = self.correctPhase(reim, -angleCorrection / powerup)
return reimc, svd_metric, angleCorrection
def correctPhase(self, reim: np.ndarray, phase: float):
return reim * np.exp(1j * phase)
def demod(
self, x: np.ndarray, osr: int, abs_x: np.ndarray = None, verb: bool = True
):
if x.dtype != np.complex64:
raise TypeError("Input array must be complex64.")
timer = Timer()
timer.start()
# Get eye-opening first
xeo, xeo_i = self.getEyeOpening(x, osr, abs_x)
timer.evt("Eye-opening")
# Correct the global phase first
reim = np.ascontiguousarray(xeo)
self.reimc, self.svd_metric, self.angleCorrection = self.lockPhase(reim)
timer.evt("lockPhase")
# Generic method: dot product with the normalised vectors
self.syms = self.mapSyms(self.reimc)
timer.evt("mapSyms")
if verb:
timer.rpt()
return self.syms
def ambleRotate(
self, amble: np.ndarray, search: np.ndarray = None, syms: np.ndarray = None
):
if syms is None:
syms = self.syms
if search is None:
search = np.arange(syms.size - amble.size + 1)
# Naive loop
length = amble.size
# Custom dll
self.matches = compareIntPreambles(
amble, syms, self.m, search[0], search[-1] + 1
)
s, rotation = argmax2d(self.matches)
sample = search[s] # Remember to reference the searched indices
rotatedsyms = (syms + rotation) % self.m # We rotate and return this!
bestMatches = self.matches[s, rotation]
return rotatedsyms, sample, rotation, bestMatches
@staticmethod
# @njit('uint32[:,:](uint8[:], int32[:], intc, uint8[:], intc)', cache=True, nogil=True)
def _ambleSearch(m_amble, search, m, syms, length):
matches = np.zeros((search.size, m), dtype=np.uint32)
for i in np.arange(search.size): # Use np.arange instead of range
mi = search[i]
diff = np.mod((m_amble - syms[mi : mi + length]), m)
# One-pass loop
for k in np.arange(diff.size):
matches[i, diff[k]] += 1
return matches
# @staticmethod
# @njit(cache=True, nogil=True) # not well tested yet
# def _ambleSearchv2(m_amble, search, m, syms, length):
# matches = np.zeros((search.size, m), dtype=np.uint32)
# for i in np.arange(search.size): # Use np.arange instead of range
# mi = search[i]
# diff = np.bitwise_xor(amble, syms[mi:mi+length])
# # One-pass loop
# for k in np.arange(diff.size):
# matches[i, -1-diff[k]] += 1
# return matches
def symsToBits(self, syms: np.ndarray = None, phaseSymShift: int = 0):
"""
Maps each symbol (integer array denoting the angle) to its own bit sequence,
as specified by the bitmap.
Parameters
----------
syms : np.ndarray, uint8, optional
Input symbol sequence. The default is None, which will use the last internally saved
syms array output.
phaseSymShift : int
Number of symbols to rotate the bit mapping by.
Example: m = 4.
Current bitmap is [3,1,0,2].
Rotating by 2 symbols equates to a phase shift of pi
(or equivalently, phase shift of syms by -pi).
Returns
-------
bits : np.ndarray
Bit sequence stored as individual bytes i.e. length of this array = length of syms.
"""
if syms is None:
syms = self.syms
return np.roll(self.bitmap, phaseSymShift)[syms]
def unpackToBinaryBytes(self, packed: np.ndarray):
"""
Turns an integer valued output from mapSyms()/demod()/symsToBits() into
a binary-valued array with each row corresponding to the binary value
of the integer.
Specifically, that means that each bit now occupies one byte in memory,
hence the name of the method. Contrast this with the packBinaryBytesToBits()
method which tends to follow.
Example:
m = 4.
Input array [0,1,2,3].
Output is [[0,0],
[0,1],
[1,0],
[1,1]].
Parameters
----------
packed : np.ndarray
Integer valued array.
Returns
-------
unpacked : np.ndarray
Matrix of N x k binary values, where N is the original length of 'packed',
and k is the number of bits used to represent each value of 'packed',
given by log2(m).
"""
bitsPerVal = int(np.log2(self.m))
# Unpack as usual
unpacked = np.unpackbits(packed).reshape((-1, 8))
# Slice the ending bits (default is big-endian)
unpacked = unpacked[:, -bitsPerVal:]
return unpacked
def packBinaryBytesToBits(self, unpacked: np.ndarray):
"""
This is a simple wrapper around numpy's packbits().
In this context, it takes the unpacked matrix from unpackToBinaryBytes()
and then compresses it to occupy the minimum requirement of bytes storage.
Example:
Input (QPSK) array [[0,0],
[0,1],
[1,0],
[1,1]].
This is compressed to a single byte corresponding to
[0,0,0,1,1,0,1,1], which is then returned as array([27]).
Parameters
----------
unpacked : np.ndarray
Input unpacked bits, usually from unpackToBinaryBytes().
Returns
-------
packed : np.ndarray
Packed bits storage of the input.
"""
return np.packbits(unpacked.reshape(-1))
def findPlainText(self, syms: np.ndarray = None, phaseSymShift: int = 0):
"""
For fixed symbols input and phaseSymShift mapping,
attempts to find an appropriate number of symbols to skip to maximise
the number of readable characters in UTF-8 encoding.
UTF-8 characters lie within 0x21 to 0x7E. For blind demodulation,
it may not be clear where the start of a byte is.
E.g. QPSK has 2 bits per symbol.
Hence there are 4 possible 'alignments' to read the start of a byte.
This method will attempt to search the possible alignments and return the best one.
Parameters
----------
syms : np.ndarray
Input array, usually from demod() output. Defaults to None,
which uses the internally saved output from the last demod().
phaseSymShift : int
Bitmap rotation, similar to symsToBits(). Defaults to 0.
Returns
-------
iSkip : int
The maximised alignment. The text can be read by then using
syms[iSkip:].
utf8chars : np.ndarray
Number of readable characters for the particular alignment.
"""
if syms is None:
syms = self.syms
# BPSK: 8 symbols
# QPSK: 4 symbols
# 8PSK: 24 symbols (due to 3x8)
symbolSkips = np.arange(np.lcm(self.m, 8), dtype=np.uint32)
# Search for the best one
utf8chars = np.zeros(symbolSkips.size, dtype=np.uint32)
for i, symbolSkip in enumerate(symbolSkips):
mapped = self.symsToBits(syms[symbolSkip:], phaseSymShift)
packedbytes = self.packBinaryBytesToBits(self.unpackToBinaryBytes(mapped))
# Characters in UTF-8 start at 0x21, end at 0x7E
utf8chars[i] = np.intersect1d(
np.argwhere(packedbytes >= 0x21).reshape(-1),
np.argwhere(packedbytes <= 0x7E).reshape(-1),
).size
# Maximise the skip with most readable characters
iSkip = np.argmax(utf8chars)
return iSkip, utf8chars
@staticmethod
def detect_B_or_Q(reim: np.ndarray, threshold: float = 0.5):
"""
Detects if a complex array is BPSK or QPSK, by comparing
the eigenvalues of an SVD decomposition.
BPSK eigenvalues are likely to be very different, whereas
QPSK eigenvalues are likely to be roughly equal.
The ratio of the eigenvalues is compared to the threshold;
QPSK is thus likely to be near 1.0 and BPSK is likely to be near 0.0.
Parameters
----------
reim : np.ndarray
Input complex array(s) at baudrate.
For 2-D arrays, each row is processed.
This is usually the output after
eye opening detection. No phase rotation is necessary.
threshold : float, optional
Threshold for BPSK/QPSK detection. The default is 0.5.
Returns
-------
m : np.ndarray
2 if BPSK, 4 if QPSK, for each row of the input array.
"""
# Check type
if reim.dtype != np.complex64 and reim.dtype != np.complex128:
raise TypeError("Input array must be complex.")
# Check shape
if reim.ndim == 1:
reim = reim.reshape((1, -1)) # Reshape to 1xN
# Allocate output
m = np.zeros(reim.shape[0], dtype=np.uint8)
yl = np.zeros(reim.shape[0])
# Iterate over every row
for i, row in enumerate(reim):
# Collapse to Nx2 real
x = row.astype(np.complex128).view(np.float64).reshape((-1, 2))
# Perform the svd on the self-dot-product
_, s, _ = np.linalg.svd(x.T @ x) # 2x2
# Determine if B or Q based on eigenvalues
y = s[1] / s[0]
yl[i] = y
if y < threshold:
m[i] = 2
else:
m[i] = 4
return m, yl
###############
class SimpleDemodulatorBPSK(SimpleDemodulatorPSK):
"""
Faster demodulator implementation specifically for BPSK.
"""
def __init__(self, bitmap: np.ndarray = None, cluster_threshold: float = 0.1):
super().__init__(2, bitmap, cluster_threshold)
@staticmethod
def mapSyms(reimc: np.ndarray):
# Simply get the real
re = np.real(reimc)
# And check sign
syms = (re < 0).astype(np.uint8)
return syms
###############
class SimpleDemodulatorQPSK(SimpleDemodulatorPSK):
"""
Faster demodulator implementation specifically for QPSK.
"""
gray4 = np.array([[2, 1], [3, 0]], dtype=np.uint8)
def __init__(self, bitmap: np.ndarray = None, cluster_threshold: float = 0.1):
super().__init__(4, bitmap, cluster_threshold)
# self.gray4 = np.zeros((2,2), dtype=np.uint8)
# self.gray4[1,1] = 0
# self.gray4[0,1] = 1
# self.gray4[0,0] = 2
# self.gray4[1,0] = 3
# This is X,Y > 0 gray encoded
@staticmethod
def mapSyms(reimc: np.ndarray):
if reimc.dtype != np.complex64:
raise TypeError("Input array must be complex64.")
# Reshape
reimd = reimc.view(np.float32).reshape((-1, 2))
# # Compute comparators
# xp = (reimd[:,0] > 0).astype(np.uint8)
# yp = (reimd[:,1] > 0).astype(np.uint8)
# # Now map
# idx = np.vstack((xp,yp))
# # Convert to constellation integers
# syms = self.gray4[tuple(idx)]
# New one-liner, prevents multiple comparator calls hence faster?
syms = SimpleDemodulatorQPSK.gray4[tuple((reimd > 0).T.astype(np.uint8))]
return syms
def correctPhase(self, reim: np.ndarray, phase: float):
# For gray-coding comparators, we move to the box
return reim * np.exp(1j * (phase + np.pi / 4))
################
class SimpleDemodulator8PSK(SimpleDemodulatorPSK):
"""
Faster demodulator implementation specifically for 8PSK.
"""
def __init__(self, bitmap: np.ndarray = None, cluster_threshold: float = 0.1):
super().__init__(8, bitmap, cluster_threshold)
# For the custom constellation, we don't map to a number but rather to the N-D index,
# mirroring the actual bits.
self.map8 = np.zeros((2, 2, 2), dtype=np.uint8)
self.map8[1, 1, 1] = 0
self.map8[0, 1, 1] = 1
self.map8[1, 0, 1] = 2
self.map8[0, 0, 1] = 3
self.map8[1, 1, 0] = 4
self.map8[0, 0, 0] = 5
self.map8[1, 0, 0] = 6
self.map8[0, 1, 0] = 7
def mapSyms(self, reimc: np.ndarray):
# 8PSK specific, add dimensions
reimd = reimc.view(np.float32).reshape((-1, 2))
scaling = np.max(self.eo_metric) # Assumes eye-opening has been done
reim_thresh = np.abs(
np.abs(np.cos(np.pi / 8) * scaling) - np.abs(np.sin(np.pi / 8) * scaling)
)
# Compute |X| - |Y|
xmy = np.abs(reimd[:, 0]) - np.abs(reimd[:, 1])
# And then | |X| - |Y| | + c, this transforms into QPSK box below XY plane
# with the new QPSK diamond above XY plane
z = (
np.abs(xmy) - reim_thresh
) # Do not stack into single array, no difference anyway
# C1: Check Z > 0; if + check even (diamond), if - check odd (QPSK, box)
c1z = z > 0
# C2: Z+ check XY and end, Z- check |X|-|Y| and C3
cx2 = reimd[:, 0] > 0
cy2 = reimd[:, 1] > 0
cxmy2 = xmy > 0
# C3: + check X, - check Y
cx3 = np.logical_and(cxmy2, cx2)
cy3 = np.logical_and(np.logical_not(cxmy2), cy2)
# Build backwards
idx1 = cxmy2
idx2 = np.logical_or(cx3, cy3)
idx1 = np.logical_or(
np.logical_and(c1z, idx1), np.logical_and(np.logical_not(c1z), cx2)
)
idx2 = np.logical_or(
np.logical_and(c1z, idx2), np.logical_and(np.logical_not(c1z), cy2)
)
idx0 = c1z
# Now map
idx = np.vstack(
(idx0.astype(np.uint8), idx1.astype(np.uint8), idx2.astype(np.uint8))
)
# Converts to the default demodulator constellation integers
syms = self.map8[
tuple(idx)
] # Needs to be vstack, and need the tuple(); need each value to be a column of indices
return syms
try:
import cupy as cp
import os
from cupyExtensions import cupyModuleToKernelsLoader, cupyRequireDtype
# Raw kernel to get many eye openings at once as a batch
with open(
os.path.join(
os.path.dirname(__file__), "custom_kernels", "eyeOpeningKernel.cu"
),
"r",
) as fid:
eyeOpeningBatchKernel = cp.RawKernel(fid.read(), """getEyeOpening_batch""")
(
lockPhase_mapSyms_singleBlkKernel_qpsk,
demod_qpsk_kernel,
compareIntegerPreambles_kernel,
cutAndRotate_gray_kernel,
detectBPSKorQPSK_kernel,
demod_b_or_q_psk_kernel,
), _ = cupyModuleToKernelsLoader(
"demodulation.cu",
[
"lockPhase_mapSyms_singleBlkKernel_qpsk",
"demod_qpsk",
"compareIntegerPreambles",
"cutAndRotatePSKSymbolsFromPossiblePreambles_Gray",
"detectBPSKorQPSK",
"demod_b_or_q_psk",
],
)
# Classes
class CupyDemodulatorPSK:
def __init__(self, m: int):
self.m = m
# Interrim output
self.xeo = None # Selected eye-opening resample points
self.xeo_i = None # Index of eye-opening
self.eo_metric = None # Metrics of eye-opening
self.reimc = None # Phase-locked to constellation (complex array)
self.svd_metric = None # SVD metric for phase lock
self.angleCorrection = None # Angle correction used in phase lock
self.syms = None # Output mapping to each symbol (0 to M-1)
self.matches = None # Output from amble rotation search
@staticmethod
def demod_b_or_q_psk(
d_xbatch: cp.ndarray, d_m: cp.ndarray, THREADS_PER_BLOCK: int = 128
):
# Turn into a 2-D if necessary
if d_xbatch.ndim == 1:
d_xbatch = d_xbatch.reshape((1, -1))
# Check dimensions match
if d_m.ndim != 1:
raise ValueError("d_m must be 1D.")
if d_xbatch.shape[0] != d_m.size:
raise ValueError("d_xbatch must have rows == d_m.size")
# Check types
cupyRequireDtype(cp.complex64, d_xbatch)
cupyRequireDtype(cp.uint8, d_m)
numSignals, xlength = d_xbatch.shape
NUM_BLKS = numSignals
# Allocate shared mem
smReq = xlength * 8 + THREADS_PER_BLOCK * 8
cupyCheckExceedsSharedMem(smReq)
# Allocate output
d_syms = cp.zeros(d_xbatch.shape, dtype=cp.uint8)
# Invoke kernel
demod_b_or_q_psk_kernel(
(NUM_BLKS,),
(THREADS_PER_BLOCK,),
(d_xbatch, xlength, numSignals, d_m, d_syms),
shared_mem=smReq,
)
return d_syms
@staticmethod
def _checkEigResults(d_x: cp.ndarray):
"""
Just meant for debugging purposes for the inner device function.
Results per row are:
0-3 : 2x2 row-major matrix from inner product
4-5 : Bigger eigenvalue then smaller eigenvalue
6-9 : 2x2 row-major matrix of eigenvectors (6&8) is one column eigenvector, (7&9) is another column eigenvector
"""
d_eigresults = cp.zeros((d_x.shape[0], 10), dtype=cp.float32)
THREADS_PER_BLOCK = 128
NUM_BLKS = d_x.shape[0]
smReq = THREADS_PER_BLOCK * 16 + d_x.shape[1] * 8
detectBPSKorQPSK_kernel(
(NUM_BLKS,),
(THREADS_PER_BLOCK,),
(d_x, int(d_x.shape[1]), int(d_x.shape[0]), d_eigresults),
shared_mem=smReq,
)
return d_eigresults
def getEyeOpening(self, x: cp.ndarray, osr: int, abs_x: cp.ndarray = None):
if abs_x is None:
abs_x = cp.abs(
x
) # Provide option for pre-computed (often used elsewhere anyway)
x_rs_abs = abs_x.reshape((-1, osr))
self.eo_metric = cp.mean(x_rs_abs, axis=0)
i = cp.argmax(self.eo_metric)
x_rs = x.reshape((-1, osr))
return x_rs[:, i], i
def getEyeOpeningBatch(
self, xbatch: cp.ndarray, osr: int, abs_xbatch: cp.ndarray
):
pass
@staticmethod
def prepareIntPreambles(integerPreamblesDict: dict):
ordering = []
lengths = []
amalg = []
for k, v in integerPreamblesDict.items():
ordering.append(k)
lengths.append(v.size)
amalg.append(v)
# Convert to gpu arrays
d_amalg = cp.asarray(np.hstack(amalg), dtype=cp.uint8)
return ordering, lengths, d_amalg
@staticmethod
def compareIntPreambles(
d_syms: cp.ndarray,
lengths: np.ndarray,
d_preamble_concat: cp.ndarray,
m: int,
psk_m: cp.ndarray = None,
searchStart: int = 0,
searchEnd: int = 128,
THREADS_PER_BLOCK: int = 128,
):
# Ensure m is reasonable
if m not in [2, 4, 8]:
raise ValueError("m must be 2/4/8.")
# Check that the psk_m mask is reasonable if it is specified
if psk_m is not None:
cupyRequireDtype(cp.uint8, psk_m)
if psk_m.shape != (d_syms.shape[0],):
raise ValueError("psk_m shape doesn't match d_syms rows.")
else:
psk_m = 0 # Set to null pointer
# Check types and lengths
symsLength = d_syms.shape[1]
numSignals = d_syms.shape[0]
if np.sum(lengths) != d_preamble_concat.size:
raise ValueError("Concatenated length is not equal to sum of lengths!")
if d_preamble_concat.dtype != cp.uint8:
raise TypeError("Concatenated preamble should be type uint8.")
if d_syms.dtype != cp.uint8:
raise TypeError("Symbols matrix should be type uint8.")
if searchEnd + np.max(lengths) >= symsLength:
raise ValueError(
"Search will extend past the syms length. Shorten the searchEnd."
)
# Convert lengths to gpu array
d_lengths = cp.asarray(lengths, dtype=np.int32)
# Allocate output
d_matches = cp.zeros(
numSignals * len(lengths) * (searchEnd - searchStart) * m,
dtype=np.uint32,
)
# Allocate shared memory
smReq = (
d_lengths.nbytes
+ symsLength * 1
+ d_preamble_concat.nbytes
+ (searchEnd - searchStart) * m * 4
)
# Invoke kernel
NUM_BLKS = numSignals
compareIntegerPreambles_kernel(
(NUM_BLKS,),
(THREADS_PER_BLOCK,),
(
d_syms,
numSignals,
symsLength,
searchStart,
searchEnd,
d_preamble_concat,
d_lengths.size,
d_lengths,
m,
d_matches,
psk_m,
),
shared_mem=smReq,
)
# Reshape matches for viewability
d_matches = d_matches.reshape(
(numSignals, d_lengths.size, searchEnd - searchStart, m)
)
return d_matches
@staticmethod
def cutAndRotateFromPreambles(
d_argmaxMatches: cp.ndarray,
d_syms: cp.ndarray,
d_preambleLengths: cp.ndarray,
d_sampleStops: cp.ndarray,
m: int,
d_psk_m: cp.ndarray = 0,
outLength: int = None,
d_out: cp.ndarray = None,
d_count: cp.ndarray = None,
THREADS_PER_BLK: int = 128,
alsoReturnWrittenCounts: bool = False,
):
if isinstance(d_psk_m, cp.ndarray):
cupyRequireDtype(cp.uint8, d_psk_m)
if d_psk_m.shape != (d_syms.shape[0],):
raise ValueError("d_psk_m must match d_syms rows")
# Performing checks
cupyRequireDtype(cp.uint32, d_argmaxMatches)
cupyRequireDtype(cp.uint32, d_preambleLengths)
cupyRequireDtype(cp.uint32, d_sampleStops)
cupyRequireDtype(cp.uint8, d_syms)
# Get dimensions and check
numRows, symsLength = d_syms.shape
if d_argmaxMatches.shape[0] != numRows or d_argmaxMatches.shape[1] != 3:
raise ValueError("d_argmaxMatches must be %d x 3" % (numRows))
if d_sampleStops.size != numRows:
raise ValueError("d_sampleStops must be length %d" % (numRows))
# Allocate shared mem
smReq = 3 * 4
# Allocate output
if outLength is None:
outLength = symsLength
# print("Using outLength = %d" % (outLength))
if d_out is None:
d_out = cp.zeros((numRows, outLength), dtype=cp.uint8)
# print("Allocated output size %d, %d" % (numRows, outLength))
# Invoke kernel
NUM_BLKS = numRows
# print("numRows = %d" % (NUM_BLKS))
if alsoReturnWrittenCounts:
if d_count is None:
d_count = cp.zeros(numRows, dtype=cp.uint32)
# print("outLength = %d" % (outLength))
cutAndRotate_gray_kernel(
(NUM_BLKS,),
(THREADS_PER_BLK,),
(
d_argmaxMatches,
numRows,
d_syms,
symsLength,
d_preambleLengths,
d_sampleStops,
np.uint8(m),
outLength,
d_out,
d_count,
d_psk_m,
),
shared_mem=smReq,
)
return d_out, d_count
else:
cutAndRotate_gray_kernel(
(NUM_BLKS,),
(THREADS_PER_BLK,),
(
d_argmaxMatches,
numRows,
d_syms,
symsLength,
d_preambleLengths,
d_sampleStops,
np.uint8(m),
outLength,
d_out,
0,
d_psk_m,
),
shared_mem=smReq,
)
return d_out
class CupyDemodulatorQPSK:
def __init__(
self,
batchLength: int,
numBitsPerBurst: int,
cluster_threshold: float = 0.1,
batch_size: int = 4096,
):
self.m = 4
self.cluster_threshold = cluster_threshold
self.batch_size = batch_size
self.batchLength = batchLength
self.numBitsPerBurst = numBitsPerBurst # Note that this number is twice the number of symbols used, since QPSK
# One-time pre-allocation
self.d_reim_batch = cp.zeros((batch_size, batchLength), dtype=cp.complex64)
self.d_reimc_batch = cp.zeros((batch_size, batchLength), dtype=cp.complex64)
self.d_syms_batch = cp.zeros((batch_size, batchLength), dtype=cp.uint32)
self.d_bestMatches = cp.zeros((batch_size), dtype=cp.int32)
self.d_bestRotations = cp.zeros((batch_size), dtype=cp.int32)
self.d_bestMatchIdx = cp.zeros((batch_size), dtype=cp.int32)
self.d_bits_batch = cp.zeros((batch_size, numBitsPerBurst), dtype=cp.uint8)
# Counter for batching
# self.actr = 0 # Batching for eye-opening
self.bctr = 0 # Batching for demodulation
# Note that they should be the same at the end
# # Interrim output
# self.xeo = None # Selected eye-opening resample points
# self.xeo_i = None # Index of eye-opening
# self.eo_metric = None # Metrics of eye-opening
# self.reimc = None # Phase-locked to constellation (complex array)
# self.svd_metric = None # SVD metric for phase lock
# self.angleCorrection = None # Angle correction used in phase lock
# self.syms = None # Output mapping to each symbol (0 to M-1)
# self.matches = None # Output from amble rotation search
@staticmethod
def demod(d_xbatch: cp.ndarray, THREADS_PER_BLOCK: int = 128):
if d_xbatch.ndim == 2:
numSignals, xlength = d_xbatch.shape
elif d_xbatch.ndim == 1:
numSignals = 1
xlength = d_xbatch.size
else:
raise ValueError("Input must be 1D or 2D array.")
NUM_BLKS = numSignals
# Allocate shared mem
smReq = xlength * 8 + THREADS_PER_BLOCK * 8
if smReq > 48000:
raise MemoryError("Requested shared mem exceeds 48kB: %d bytes" % smReq)
# Allocate output
d_syms = cp.zeros(d_xbatch.shape, dtype=cp.uint8)
# Invoke kernel
demod_qpsk_kernel(
(NUM_BLKS,),
(THREADS_PER_BLOCK,),
(d_xbatch, xlength, numSignals, d_syms),
shared_mem=smReq,
)
return d_syms
@staticmethod
def _getEyeOpeningBatch(
xbatch: cp.ndarray,
osr: int,
abs_xbatch: cp.ndarray,
d_xeo: cp.ndarray = None,
count: int = None,
THREADS_PER_BLOCK: int = 128,
):
"""
This is the static method version of the other method.
Useful if done standalone.
"""
# Blocks match the number of signals present in the batch, but you can
# specify the number of rows if the matrix has unused rows
NUM_BLOCKS = count if count is not None else xbatch.shape[0]
# simple shared memory requirements