-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathxcorrRoutines.py
2245 lines (1867 loc) · 83.9 KB
/
xcorrRoutines.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 Sat Mar 7 17:03:53 2020
@author: Seo
"""
from intelHelpers import include_ipp
import os
import numpy as np
import scipy as sp
import scipy.signal as sps
import time
from spectralRoutines import czt, CZTCached
from signalCreationRoutines import makeFreq
from musicRoutines import MUSIC
# from numba import jit
from concurrent.futures import ThreadPoolExecutor, as_completed
import concurrent.futures
from tqdm import tqdm
try:
import cupy as cp
from cupyExtensions import *
from spectralRoutines import CZTCachedGPU
from filterRoutines import cupyMovingAverage
def cp_fastXcorr(
cutout,
rx,
freqsearch=True,
outputCAF=False,
shifts=None,
absResult=True,
BATCH=1024,
copyToCpu=True,
):
"""
Equivalent to fastXcorr, designed to run on gpu.
It is important to note that this function is sensitive to the memory requirements;
this means that for different cutout sizes, the batch size should be tuned to get maximum performance.
Otherwise, if using too small or too large batch sizes, the speed of this function may be
slower than a compiled, threaded xcorr function (see CyIppXcorrFFT).
"""
# Query the ram of the device, but we need extra space for the ffts to work, so use 1/4 to estimate
if cutout.nbytes * BATCH > cp.cuda.device.Device().mem_info[1] / 4:
raise MemoryError(
"Not enough memory with this batch. Try lowering the batch value."
)
# need both to be same type, maintain the type throughout
if cutout.dtype != rx.dtype:
raise Exception(
"Cutout and Rx must be same type, please cast one of them manually."
)
if shifts is None:
shifts = np.arange(len(rx) - len(cutout) + 1)
# common numbers in all consequent methods
cutoutNorm = np.linalg.norm(cutout)
cutoutNormSq = cutoutNorm**2.0
if not freqsearch:
print("Not implemented.")
elif not outputCAF:
if absResult is True:
# print('Frequency scanning, but no CAF output (flattened to time)..')
# h_freqlist = np.zeros(len(shifts),dtype=np.uint32)
d_freqlist = cp.zeros(len(shifts), dtype=cp.uint32)
# print('Returning normalized QF^2 real values..')
# h_result = np.zeros(len(shifts),dtype=np.float64)
d_result = cp.zeros(len(shifts), dtype=cp.float64)
# first copy the data in
d_cutout_conj = cp.asarray(cutout).conj()
d_rx = cp.asarray(rx)
numIter = int(np.ceil(len(shifts) / BATCH))
# allocate data arrays on gpu
d_pdt_batch = cp.zeros(
(BATCH, len(cutout)), dtype=rx.dtype
) # let's try using it in place all the way
d_rxNormPartSq_batch = cp.zeros((BATCH), dtype=cp.float64)
# new copy method allocs
yStarts = cp.arange(BATCH, dtype=cp.int32) * len(cutout)
lengths = cp.zeros(BATCH, dtype=cp.int32) + len(cutout)
# now iterate over the number of iterations required
# print("Starting cupy loop")
for i in tqdm(range(numIter)):
if i == numIter - 1: # on the last iteration, may have to clip
# print("FINAL BATCH")
TOTAL_THIS_BATCH = len(shifts) - BATCH * (numIter - 1)
else:
TOTAL_THIS_BATCH = BATCH
# print(i)
# print (TOTAL_THIS_BATCH)
# Slice shifts for the batch
xStarts = cp.asarray(
shifts[i * BATCH : i * BATCH + TOTAL_THIS_BATCH], dtype=cp.int32
)
# Copy groups
# cupyCopyGroups32fc(d_rx, d_pdt_batch, xStarts, yStarts[:TOTAL_THIS_BATCH], lengths[:TOTAL_THIS_BATCH])
# cupyCopyEqualSlicesToMatrix_32fc(d_rx, xStarts, len(cutout), d_pdt_batch[:TOTAL_THIS_BATCH,:])
cupyCopyIncrementalEqualSlicesToMatrix_32fc(
d_rx,
shifts[i * BATCH],
shifts[1]
- shifts[
0
], # assume constant increment # shifts[i*BATCH+1]-shifts[i*BATCH],
len(cutout),
TOTAL_THIS_BATCH,
d_pdt_batch[:TOTAL_THIS_BATCH, :],
) # very minimal improvement of ~10%
# Calculate norms
d_rxNormPartSq_batch = cp.linalg.norm(d_pdt_batch, axis=1) ** 2
# Perform the multiply
cp.multiply(d_pdt_batch, d_cutout_conj, out=d_pdt_batch)
# Then the ffts
# d_pdtfft_batch = cp.abs(cp.fft.fft(d_pdt_batch))**2 # already row-wise by default
# imax = cp.argmax(d_pdtfft_batch, axis=-1) # take the arg max for each row
imax, d_max = cupyArgmaxAbsRows_complex64(
cp.fft.fft(d_pdt_batch[:TOTAL_THIS_BATCH, :]),
d_argmax=d_freqlist[i * BATCH : i * BATCH + TOTAL_THIS_BATCH],
returnMaxValues=True,
THREADS_PER_BLOCK=1024,
)
# assign to d_freqlist output by slice
# d_freqlist[i*BATCH : i*BATCH + TOTAL_THIS_BATCH] = imax[:TOTAL_THIS_BATCH]
# assign to d_result
# for k in range(TOTAL_THIS_BATCH):
# d_result[i*BATCH + k] = d_pdtfft_batch[k, imax[k]] / d_rxNormPartSq_batch[k] / cutoutNormSq
d_result[i * BATCH : i * BATCH + TOTAL_THIS_BATCH] = (
d_max[:TOTAL_THIS_BATCH] ** 2
/ d_rxNormPartSq_batch[:TOTAL_THIS_BATCH]
/ cutoutNormSq
)
if copyToCpu:
# copy all results back
h_result = cp.asnumpy(d_result)
h_freqlist = cp.asnumpy(d_freqlist)
return h_result, h_freqlist
else:
return d_result, d_freqlist
else:
print("Not implemented.")
else:
print("Not implemented.")
def cp_fastXcorr_v2(
cutout: cp.ndarray,
rx: cp.ndarray,
startIdx: int = 0,
idxlen: int = None,
THREADS_PER_BLOCK: int = 32,
numSlidesPerBlk: int = None,
cztObj: CZTCachedGPU = None,
flattenCAF: bool = False,
BATCH: int = None,
):
"""
This function uses an optimised custom kernel for 'short' cutouts.
Short cutouts are defined as those that can occupy a small fraction of a CUDA block's shared memory.
As such, this function should perform the best when there is a large search range,
but a short cutout.
Parameters
----------
cutout : cp.ndarray, cp.complex64
The cutout/template to be correlated.
rx : cp.ndarray, cp.complex64
The signal to be correlated.
startIdx : int, optional
The starting index of rx to start correlation. The default is 0.
idxlen : int, optional
The number of indices to correlate over; the correlation index step size
is implicitly 1, and cannot be changed.
The default is None, which will default to maximum search range of rx.
cztObj : CZTCachedGPU (see spectralRoutines)
GPU-based CZT object. The xcorr will default to using FFTs if this is not supplied.
flattenCAF : bool, optional
Defaults to False, which returns the 2D ambiguity function.
Otherwise it flattens to the QF2 vs time, and the corresponding
maximum frequency index for each time.
BATCH : int, optional
Runs multiples of BATCH size to cover the xcorr indices.
Defaults to None, which will cover all of it in 1 go; this may cause OutOfMemoryErrors
if it is large.
"""
if idxlen is None:
idxlen = rx.size - cutout.size - startIdx + 1
if cztObj is not None and cztObj.m != cutout.size:
raise ValueError(
"CZT object input length doesn't match the cutout array size"
)
if BATCH is None:
BATCH = idxlen
# Allocate outputs
if flattenCAF:
d_freqIdx = cp.empty(idxlen, dtype=cp.uint32)
d_qf2 = cp.empty(idxlen, dtype=cp.float32)
else:
d_out = cp.empty((idxlen, cutout.size), dtype=cp.float32)
# Track the finished index
fi = 0
while fi < idxlen:
# How many to calculate this batch?
THIS_BATCH_LEN = BATCH if fi + BATCH < idxlen else idxlen - fi
# print("Processing %d:%d / %d" % (fi, fi+THIS_BATCH_LEN, idxlen))
# Call the optimised kernel (this will perform type checking for us already)
d_pdts = multiplySlidesNormalised(
cutout,
rx,
startIdx + fi,
THIS_BATCH_LEN,
THREADS_PER_BLOCK=THREADS_PER_BLOCK,
numSlidesPerBlk=numSlidesPerBlk,
)
if cztObj is None:
# Perform the FFT on each row
d_pdtsfft = cp.fft.fft(d_pdts, axis=1)
else:
# Use the czt on each row
d_pdtsfft = cztObj.runMany(d_pdts)
# We now have fft(x*y)/norm(y)/norm(x), so we take abs squared
if flattenCAF:
cupyArgmaxAbsRows_complex64(
d_pdtsfft,
d_argmax=d_freqIdx[fi : fi + THIS_BATCH_LEN],
d_max=d_qf2[fi : fi + THIS_BATCH_LEN],
returnMaxValues=True,
THREADS_PER_BLOCK=THREADS_PER_BLOCK,
useNormSqInstead=True,
)
else:
d_out[fi : fi + THIS_BATCH_LEN, :] = cupyComplexMagnSq(
d_pdtsfft[fi : fi + THIS_BATCH_LEN, :], out_dtype=cp.float32
) # Is faster now due to combined kernel!
# Increment index
fi += THIS_BATCH_LEN
# Return
if flattenCAF:
return d_freqIdx, d_qf2
else:
return d_out
#####################################
class TemplateCrossCorrelator:
"""
This is designed specifically to search for multiple templates,
but without frequency scanning.
As such it will pre-compute the (conjugate) FFTs of the templates,
and then store them so they can be reused later.
This method returns QF, not QF^2, unlike the defaults in other
classes and functions. It does the normalisation for QF in the
expected way, dividing by both the template energy and the input energy.
"""
def __init__(self, templates: cp.ndarray, inputSize: int):
self._inputSize = inputSize
# Verify type and shape
requireCupyArray(templates)
if not templates.ndim == 2:
raise ValueError("Templates must be a 2D array; 1 row for 1 template.")
# Save the original template length
self._templateOrigLength = templates.shape[1]
# Calculate original template normalisations
self._templateNorms = cp.linalg.norm(templates, axis=1)
# print(self._templateNorms)
# Pad the templates to input size
padded = cp.pad(
templates,
((0, 0), (0, inputSize-templates.shape[1]))
)
self._templatefftsconj = cp.fft.fft(padded, axis=1).conj() # Row-wise FFTs
def correlate(
self,
x: cp.ndarray,
returnMax: bool = False
):
"""
Main runtime method.
Parameters
---------
x : cp.ndarray
Complex-valued input array to correlate against.
Must be of the input size used to instantiate this class.
returnMax : bool
Returns a 2D full complex-valued matrix if False (default).
Returns 2 separate 1D arrays if True:
1) The real-valued QF values.
2) The associated template index for the maximised QF.
"""
# Check cupy array
requireCupyArray(x)
# Check dimension
if x.ndim != 1 or x.size != self._inputSize:
raise ValueError("x must be 1D of length %d" % self._inputSize)
# Compute FFT of input
xfft = cp.fft.fft(x)
# Compute rolling sum over the input
xpower = cupyComplexMagnSq(x, out_dtype=cp.float32)
xmovingEnergy = cupyMovingAverage(
xpower,
self._templateOrigLength,
sumInstead=True
)
xmovingNorms = xmovingEnergy**0.5
# print(xmovingNorms[self._templateOrigLength-1:])
# Perform correlation for each template in 1 op
out = cp.fft.ifft(xfft * self._templatefftsconj, axis=1)
# Normalise final output by rolling input norms
nout = out[:, :-self._templateOrigLength+1] / xmovingNorms[self._templateOrigLength-1:]
# Then normalise each row by associated template norms
nout = nout / self._templateNorms.reshape((-1, 1))
# Diverge depending on whether we want maximised 1D
# or the full 'CAF-like' output
if not returnMax:
return nout
else:
# Take the maximums down each column
nout = cp.abs(nout)
templateIdx = cp.argmax(nout, axis=0, keepdims=True)
# Use the indices to extract out of each column, then flatten
nout = cp.take_along_axis(nout, templateIdx, 0).reshape(-1)
return nout, templateIdx.reshape(-1)
except ModuleNotFoundError:
print("Failed to load cupy?")
def musicXcorr(cutout, rx, f_search, ftap, fs, dsr, plist, musicrows=130, shifts=None):
# Preconjugate
cutoutconj = cutout.conj()
# First create the music object
music = MUSIC(musicrows, snapshotJump=1, fwdBwd=True)
# Calculate the downsampled fs
fs_ds = fs / dsr
# Loop over shifts as usual
if shifts is None:
shifts = np.arange(len(rx) - len(cutout) + 1)
resultsgrid = {p: np.zeros((len(shifts), len(f_search))) for p in plist}
for i in range(len(shifts)):
s = shifts[i]
rxslice = rx[s : s + len(cutout)]
pdt = rxslice * cutoutconj
# Filter the product
pdtfilt = sps.lfilter(ftap, 1, pdt)
# Create a dictionary of the downsampled arrays for all phases
pdtfiltdsdict = {k: pdtfilt[int(len(ftap) / 2) + k :: dsr] for k in range(dsr)}
# Run the music algo on it
f, u, s, vh, Rx = music.run(
pdtfiltdsdict, f_search / fs_ds, plist, useSignalAsNumerator=True
)
for k in range(len(plist)):
p = plist[k]
resultsgrid[p][i, :] = f[
k, :
] # results dictionary is labelled by p-val as key, with 'CAF'-like matrix as value
return resultsgrid
def cztXcorr(
cutout, rx, f_searchMin, f_searchMax, fs, cztStep=0.1, outputCAF=False, shifts=None
):
cztobj = CZTCached(cutout.size, f_searchMin, f_searchMax, cztStep, fs)
# Create the freq array
f_search = cztobj.getFreq() # np.arange(f_searchMin, f_searchMax, cztStep)
if shifts is None:
shifts = np.arange(len(rx) - len(cutout) + 1)
# common numbers in all consequent methods
cutoutNorm = np.linalg.norm(cutout)
cutoutNormSq = cutoutNorm**2.0
if outputCAF:
result = np.zeros((len(shifts), f_search.size))
cutoutconj = cutout.conj()
for i in np.arange(len(shifts)):
s = shifts[i]
rxslice = rx[s : s + len(cutout)]
rxNormPartSq = np.linalg.norm(rxslice) ** 2
pdt = rxslice * cutoutconj
# pdtczt = czt(pdt, f_search[0],f_search[-1]+cztStep/2, cztStep, fs)
pdtczt = cztobj.run(pdt)
result[i, :] = np.abs(pdtczt) ** 2.0 / rxNormPartSq / cutoutNormSq
return result, f_search
else:
result = np.zeros(shifts.size, dtype=rx.dtype)
freqs = np.zeros(shifts.size, dtype=np.float64)
cutoutconj = cutout.conj()
for i in np.arange(len(shifts)):
s = shifts[i]
rxslice = rx[s : s + len(cutout)]
rxNorm = np.linalg.norm(rxslice)
pdt = rxslice * cutoutconj
# pdtczt = czt(pdt, f_search[0], f_search[-1]+cztStep/2, cztStep, fs)
pdtczt = cztobj.run(pdt)
abspdtczt = np.abs(pdtczt)
mi = np.argmax(abspdtczt)
result[i] = pdtczt[mi] / rxNorm / cutoutNorm
freqs[i] = f_search[mi]
return result, freqs
def fastXcorr(
cutout, rx, freqsearch=False, outputCAF=False, shifts=None, absResult=True
):
"""
Optional frequency scanning xcorr.
When absResult is set to False, the result is not absoluted, and is also not given as a
QF^2 value. It is left as a complex value, scaled only by the norm (not norm-squared!)
of the two corresponding array slices.
Consequently, when absResult is True (default), then the returned values are QF^2
normalized values.
"""
if shifts is None:
shifts = np.arange(len(rx) - len(cutout) + 1)
# common numbers in all consequent methods
cutoutNorm = np.linalg.norm(cutout)
cutoutNormSq = cutoutNorm**2.0
if not freqsearch:
# print('No frequency scanning xcorr..')
if absResult is True:
# print('Returning normalized QF^2 real values..')
result = np.zeros(len(shifts), dtype=np.float64)
for i in range(len(shifts)):
s = shifts[i]
result[i] = (
np.abs(np.vdot(rx[s : s + len(cutout)], cutout)) ** 2.0
) # vdot already takes conj of first arg
rxNormPartSq = np.linalg.norm(rx[s : s + len(cutout)]) ** 2.0
result[i] = result[i] / cutoutNormSq / rxNormPartSq
return result
else:
print("Returning normalized QF complex values..")
result = np.zeros(len(shifts), dtype=np.complex128)
for i in range(len(shifts)):
s = shifts[i]
result[i] = np.vdot(
rx[s : s + len(cutout)], cutout
) # vdot already takes conj of first arg
rxNormPart = np.linalg.norm(rx[s : s + len(cutout)])
result[i] = result[i] / cutoutNorm / rxNormPart
return result
elif not outputCAF:
# print('Frequency scanning, but no CAF output (flattened to time)..')
freqlist = np.zeros(len(shifts), dtype=np.uint32)
if absResult is True:
# print('Returning normalized QF^2 real values..')
result = np.zeros(len(shifts), dtype=np.float64)
for i in range(len(shifts)):
s = shifts[i]
pdt = rx[s : s + len(cutout)] * cutout.conj()
pdtfft = sp.fft.fft(pdt)
pdtfftsq = pdtfft**2.0
imax = np.argmax(np.abs(pdtfftsq))
freqlist[i] = imax
pmax = np.abs(pdtfftsq[imax])
rxNormPartSq = np.linalg.norm(rx[s : s + len(cutout)]) ** 2.0
result[i] = pmax / cutoutNormSq / rxNormPartSq
return result, freqlist
else:
# print('Returning normalized QF complex values..')
result = np.zeros(len(shifts), dtype=np.complex128)
for i in range(len(shifts)):
s = shifts[i]
pdt = rx[s : s + len(cutout)] * cutout.conj()
pdtfft = sp.fft.fft(pdt)
imax = np.argmax(np.abs(pdtfft))
freqlist[i] = imax
pmax = pdtfft[imax]
rxNormPart = np.linalg.norm(rx[s : s + len(cutout)])
result[i] = pmax / cutoutNorm / rxNormPart
return result, freqlist
else:
# print('Frequency scanning, outputting raw CAF...')
if absResult is True:
# print('Returning normalized QF^2 real values..')
result = np.zeros((len(shifts), len(cutout)), dtype=np.float64)
for i in range(len(shifts)):
s = shifts[i]
pdt = rx[s : s + len(cutout)] * cutout.conj()
pdtfft = sp.fft.fft(pdt)
pdtfftsq = np.abs(pdtfft**2.0)
rxNormPartSq = np.linalg.norm(rx[s : s + len(cutout)]) ** 2.0
result[i] = pdtfftsq / cutoutNormSq / rxNormPartSq
return result
else:
# print('Returning normalized QF complex values..')
result = np.zeros((len(shifts), len(cutout)), dtype=np.complex128)
for i in range(len(shifts)):
s = shifts[i]
pdt = rx[s : s + len(cutout)] * cutout.conj()
pdtfft = np.fft.fft(pdt)
rxNormPart = np.linalg.norm(rx[s : s + len(cutout)])
result[i] = pdtfft / cutoutNorm / rxNormPart
return result
def fineFreqTimeSearch(
x_aligned,
y_aligned,
fineRes,
freqfound,
freqRes,
fs,
td_scan_range,
steeringvec=None,
td_scan_freqBounds=None,
):
"""
Performs a finer search to align frequency and time, in two separate processes.
As such, this function may not result in the global minimum for TDOA/FDOA in 2-D, but will perform much
faster, since it only searches one index in both dimensions, rather than the full 2-D space.
The best fine frequency will be searched first (assumes that the sample-aligned arrays are correctly time-aligned).
Then, using the new value for the fine frequency alignment, the two arrays are then sub-sample time aligned.
Convention is for positive values to mean that y_aligned to be LATER than x_aligned i.e. timediff = tau_y - tau_x
Example:
for positive tau, x_aligned = x(t), y_aligned = x(t-tau), then timediff will return tau.
for positive tau, x_aligned = x(t), y_aligned = x(t+tau), then timediff will return -tau.
Usually coupled with a standard sample-wise xcorr from fastXcorr functions above. In that scenario, a selected signal
named 'cutout' will have a certain (sample period * num samples) delay against another 'rx' array. After selecting
y_aligned from the 'rx' array and using this function, the total time difference should be 'delay + timediff'.
Example pseudocode:
result = fastXcorr(...)
td = np.argmax(result) * T
td = td + timediff
"""
if len(fineRes) > 0:
# compute best freq
for i in range(len(fineRes)):
fineFreq = np.arange(freqfound - freqRes, freqfound + freqRes, fineRes[i])
precomputed = y_aligned.conj() * x_aligned
pp = np.zeros(len(fineFreq), dtype=np.complex128)
fineshifts = np.zeros((len(fineFreq), len(x_aligned)), dtype=np.complex128)
for j in range(len(fineFreq)):
fineshifts[j] = np.exp(
1j * 2 * np.pi * -fineFreq[j] * np.arange(len(x_aligned)) / fs
)
pp[j] = np.vdot(precomputed, fineshifts[j])
fineFreq_ind = np.argmax(np.abs(pp))
freqfound = fineFreq[fineFreq_ind]
finefreqfound = freqfound
x_aligned = x_aligned * fineshifts[fineFreq_ind]
else:
finefreqfound = None
# compute best time alignment
if steeringvec is None:
steeringvec = makeTimeScanSteervec(td_scan_range, fs, len(x_aligned))
x_fft = np.fft.fft(x_aligned)
y_fft = np.fft.fft(y_aligned)
rx_vec = x_fft * y_fft.conj()
if td_scan_freqBounds is not None:
freqvec = makeFreq(y_fft.size, fs)
rx_vec[
np.argwhere(
np.logical_or(
freqvec < td_scan_freqBounds[0], freqvec >= td_scan_freqBounds[1]
)
).reshape(-1)
] = 0
cost_vec = (
np.dot(rx_vec, steeringvec.conj().T)
/ np.linalg.norm(x_fft)
/ np.linalg.norm(y_fft)
)
idx_td = np.argmax(np.abs(cost_vec))
timediff = td_scan_range[idx_td]
return finefreqfound, timediff, cost_vec
def makeTimeScanSteervec(td_scan_range, fs, siglen):
sigFreq = makeFreq(siglen, fs)
mat = np.exp(1j * 2 * np.pi * sigFreq * td_scan_range.reshape((-1, 1)))
return mat
# %% TODO: refactor , add docstrings
class GenXcorr:
def __init__(self, td_scan_range, fs, siglen):
self.td_scan_range = td_scan_range
self.fs = fs
self.sigFreq = makeFreq(siglen, fs)
self.steeringvec = self._makeTimeScanSteervec()
self.td_scan_freqBounds = None
def _makeTimeScanSteervec(self):
mat = np.exp(
1j * 2 * np.pi * self.sigFreq * self.td_scan_range.reshape((-1, 1))
)
return mat
def setTDscan_freqBounds(self, td_scan_freqBounds: np.ndarray):
self.td_scan_freqBounds = td_scan_freqBounds
def xcorr(self, x: np.ndarray, y: np.ndarray):
x_fft = np.fft.fft(x)
y_fft = np.fft.fft(y)
rx_vec = x_fft * y_fft.conj()
if self.td_scan_freqBounds is not None:
rx_vec[
np.argwhere(
np.logical_or(
self.sigFreq < self.td_scan_freqBounds[0],
self.sigFreq >= self.td_scan_freqBounds[1],
)
).reshape(-1)
] = 0
cost_vec = (
np.dot(rx_vec, self.steeringvec.conj().T)
/ np.linalg.norm(x_fft)
/ np.linalg.norm(y_fft)
)
idx_td = np.argmax(np.abs(cost_vec))
timediff = self.td_scan_range[idx_td]
return timediff, cost_vec
# %%
def convertQF2toSNR(qf2):
"""For xcorr against pure signal."""
return qf2 / (1.0 - qf2)
def convertQF2toEffSNR(qf2):
"""For xcorr of two noisy signals."""
return 2.0 * qf2 / (1.0 - qf2)
def convertEffSNRtoQF2(effSNR):
"""For back-conversion."""
return effSNR / (2 + effSNR)
def expectedEffSNR(snr1, snr2=np.inf, OSR=1):
"""
Effective SNR is defined as 1/(0.5 * (1/y1 + 1/y2 + 1/y1y2)),
where y1 and y2 are the respective SNRs, with respect to the noise BW.
Example:
10 dB, in-band SNR signal.
Pure signal. (inf SNR)
OSR = 2
Effective SNR = 20.0/2 = 10.0
Taken from Algorithms for Ambiguity Function Processing. SEYMOUR STEIN.
"""
y = 1.0 / (0.5 * (1 / snr1 + 1 / snr2 + 1 / snr1 / snr2))
y = y / OSR # Scale by OSR
return y
def sigmaDTO(signalBW, noiseBW, integTime, effSNR):
"""
Taken from Algorithms for Ambiguity Function Processing. SEYMOUR STEIN.
"""
beta = np.pi / np.sqrt(3) * signalBW
s = 1.0 / beta / np.sqrt(noiseBW * integTime * effSNR)
return s
def sigmaDFO(noiseBW, integTime, effSNR):
"""
Taken from Algorithms for Ambiguity Function Processing. SEYMOUR STEIN.
"""
s = 0.55 / integTime / np.sqrt(noiseBW * integTime * effSNR)
return s
def theoreticalMultiPeak(startIdx1, startIdx2, snr_linear_1=None, snr_linear_2=None):
"""
Calculates parameters resulting from cross-correlation of multiple copies of a signal in two receivers.
Works with both indices and floating-point, but of course floating-point may result in 'unique' values being repeated.
"""
# if no snr supplied, just return the indices
if snr_linear_1 is None and snr_linear_2 is None:
mat = np.zeros((len(startIdx1), len(startIdx1))) # expected same length anyway
for i in range(len(mat)):
mat[i] = startIdx2[i] - startIdx1
mat = mat.flatten()
return np.unique(mat)
else:
mat = np.zeros((len(startIdx1), len(startIdx1))) # expected same length anyway
matEffSNR = np.zeros(
(len(startIdx1), len(startIdx1))
) # expected same length anyway
for i in range(len(mat)):
mat[i] = startIdx2[i] - startIdx1
tmp = 0.5 * (
(1 / snr_linear_1)
+ (1 / snr_linear_2[i])
+ (1 / snr_linear_1 / snr_linear_2[i])
)
matEffSNR[i] = 1 / tmp
mat = mat.flatten()
matEffSNR = matEffSNR.flatten()
u, indices = np.unique(mat, return_index=True)
return u, matEffSNR[indices]
def argmax2d(m: np.ndarray):
"""
Returns the 2-D indices that mark the maximum value in the matrix m.
Parameters
----------
m : np.ndarray
Input array.
Returns
-------
maxind: tuple
Indices of the max value. m[maxind[0],maxind[1]] should be the value.
"""
return np.unravel_index(np.argmax(m), m.shape)
def calcQF2(x: np.ndarray, y: np.ndarray):
"""
Simple one-line function to calculate QF2 for two equal length arrays (already aligned).
"""
if x.ndim == 1 and y.ndim == 1:
x_energy = np.linalg.norm(x) ** 2
y_energy = np.linalg.norm(y) ** 2
qf2 = np.abs(np.vdot(x, y)) ** 2 / x_energy / y_energy
return qf2
elif x.ndim == 2 and y.ndim == 2:
# Assume row-wise
x_energy = np.linalg.norm(x, axis=1) ** 2
y_energy = np.linalg.norm(y, axis=1) ** 2
qf2 = np.abs(np.sum(x * y.conj(), axis=1)) ** 2 / x_energy / y_energy
return qf2
# %%
class GroupXcorr:
def __init__(
self,
y: np.ndarray,
starts: np.ndarray,
lengths: np.ndarray,
freqs: np.ndarray,
fs: int,
autoConj: bool = True,
autoZeroStarts: bool = True,
):
"""
Parameters
----------
y : np.ndarray
Full length array which would usually be used for correlation.
starts : np.ndarray
(Sorted) Start indices for each group.
lengths : np.ndarray
Corresponding lengths for each group (in samples).
freqs : np.ndarray
Frequencies to scan over.
fs : int
Sampling rate of y.
autoConj : bool
Conjugates the y array for use in xcorr. Default is True.
autoZeroStarts : bool
Automatically zeros the 'starts' array based on the first start
(to ensure that the signal 'starts from 0'). Default is True.
"""
assert starts.size == lengths.size # this is the number of groups
self.starts = starts
if autoZeroStarts:
self.starts = self.starts - self.starts[0]
self.lengths = lengths
self.numGroups = self.starts.size # easy referencing
self.freqs = freqs
self.fs = fs
# Generate the stitched groups of y
if autoConj:
self.yconcat = np.hstack(
[
y.conj()[starts[i] : starts[i] + lengths[i]]
for i in range(self.numGroups)
]
)
else:
self.yconcat = np.hstack(
[y[starts[i] : starts[i] + lengths[i]] for i in range(self.numGroups)]
)
self.yconcatNormSq = np.linalg.norm(self.yconcat) ** 2
# Generate the frequency matrix
maxfreqMat = np.exp(
-1j * 2 * np.pi * freqs.reshape((-1, 1)) * np.arange(y.size) / fs
) # minus sign is FFT convention
self.freqMat = np.hstack(
[
maxfreqMat[:, starts[i] : starts[i] + lengths[i]]
for i in range(self.numGroups)
]
)
def xcorr(self, rx: np.ndarray, shifts: np.ndarray = None):
if shifts is None:
shifts = np.arange(len(rx) - (self.starts[-1] + self.lengths[-1]) + 1)
else:
assert (
shifts[-1] + self.starts[-1] + self.lengths[-1] < rx.size
) # make sure it can access it
xc = np.zeros(shifts.size)
freqpeaks = np.zeros(shifts.size)
for i in np.arange(shifts.size):
shift = shifts[i]
# Perform slicing of rx
rxconcat = np.hstack(
[
rx[
shift
+ self.starts[g] : shift
+ self.starts[g]
+ self.lengths[g]
]
for g in np.arange(self.numGroups)
]
)
rxconcatNormSq = np.linalg.norm(rxconcat) ** 2
# Now multiply by y
p = rxconcat * self.yconcat
# And the freqmat
pf = self.freqMat @ p
# Pick the max value
pfabs = np.abs(pf)
pmaxind = np.argmax(pfabs)
# Save output (with normalisations)
xc[i] = pfabs[pmaxind] ** 2 / rxconcatNormSq / self.yconcatNormSq
freqpeaks[i] = self.freqs[pmaxind]
return xc, freqpeaks
class GroupXcorrCZT:
def __init__(
self,
y: np.ndarray,
starts: np.ndarray,
lengths: np.ndarray,
f1: float,
f2: float,
binWidth: float,
fs: int,
autoConj: bool = True,
autoZeroStarts: bool = True,
):
assert starts.size == lengths.size
self.starts = starts
if autoZeroStarts:
self.starts = self.starts - self.starts[0]
self.lengths = lengths
self.numGroups = self.starts.size # easy referencing
self.fs = fs
# CZT parameters
self.f1 = f1
self.f2 = f2
self.binWidth = binWidth
# Generate the stacked matrix of groups of y, padded to longest length
self.maxLength = np.max(self.lengths)
self.ystack = np.zeros((self.numGroups, self.maxLength), y.dtype)
for i in range(self.numGroups):
self.ystack[i, : self.lengths[i]] = y[starts[i] : starts[i] + lengths[i]]
if autoConj:
self.ystack = self.ystack.conj()
self.ystackNormSq = np.linalg.norm(self.ystack.flatten()) ** 2
# Create a CZT object for some optimization
self.cztc = CZTCached(self.maxLength, f1, f2, binWidth, fs)
def xcorr(self, rx: np.ndarray, shifts: np.ndarray = None):
# We are returning CAF for this (for now?)
if shifts is None:
shifts = np.arange(len(rx) - (self.starts[-1] + self.lengths[-1]) + 1)
else: