-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathalg_tools_2d.py
2021 lines (1803 loc) · 91.7 KB
/
alg_tools_2d.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
from __future__ import division
import numpy as np
import scipy as sp
from scipy import linalg
import scipy.optimize
import scipy.sparse as sps
import scipy.fftpack as sp_fft
from scipy.ndimage.filters import maximum_filter
from scipy.ndimage.morphology import generate_binary_structure, binary_erosion
from functools import partial
from joblib import Parallel, delayed, cpu_count
import os
# from matplotlib import rcParams
import matplotlib.pyplot as plt
from alg_tools_1d import distance
use_mkl_fft = True
try:
import mkl_fft
except ImportError:
use_mkl_fft = False
# for latex rendering
# os.environ['PATH'] = os.environ['PATH'] + ':/usr/texbin' + \
# ':/opt/local/bin' + ':/Library/TeX/texbin/'
# rcParams['text.usetex'] = True
# rcParams['text.latex.unicode'] = True
def distance_2d(x, y, x_ref, y_ref):
z = x + 1j * y
z_ref = x_ref + 1j * y_ref
ind = distance(z, z_ref)[1]
return np.sqrt(np.mean(np.abs(z[ind[:, 0]] - z_ref[ind[:, 1]]) ** 2))
def snr_normalised(data, data_ref, rescale=True):
"""
Compute a scale invariant SNR: SNR(alpha * data, data_ref).
Here alpha is a scalar that is computed by minimising the difference
between alpha * data and data_ref.
:param data: input data
:param data_ref: reference data
:param rescale: wether compute the scaling factor alpha or not. If not, then alpha = 1
:return:
"""
data = np.reshape(data, (-1, 1), order='F')
data_ref = np.reshape(data_ref, (-1, 1), order='F')
if rescale:
alpha = np.dot(data.conj().T, data_ref).squeeze() / np.dot(data.conj().T, data).squeeze()
else:
alpha = 1.
return 20 * np.log10(linalg.norm(data_ref) / linalg.norm(alpha * data - data_ref))
def std_normalised(data, data_ref):
"""
Compute a normalised standard deviation for the difference
between the data and the reference data_ref:
std(alpha * data - data_ref)
Here alpha is a scalar that is computed by minimising the
difference between alpha * data and data_ref.
:param data: input data
:param data_ref: reference data
:return:
"""
data = np.reshape(data, (-1, 1), order='F')
data_ref = np.reshape(data_ref, (-1, 1), order='F')
alpha = np.dot(data.conj().T, data_ref).squeeze() / np.dot(data.conj().T, data).squeeze()
return np.std(alpha * data - data_ref), alpha
def roots2(coef, plt_sz, tau_x, tau_y):
"""
Find the roots of a 2D polynomial with the coefficients specified by c_{k,l}
by utilizing the np.roots function along x/y-directions seperately. The mask
function is given as
mu(x,y) = sum_{k,l} c_{k,l} e^{2j*pi*k/tau_x * x + 2j*pi*l/tau_y * y}
:param coef: curve coefficients
:param plt_sz: size of the plot. plt_sz[0] corresponds to the vertical dimension, i.e., y-axis
:param tau_x: period along x-axis
:param tau_y: period along y-axis
:return:
"""
L, K = coef.shape
l_limit = np.int(np.floor(L / 2.))
k_limit = np.int(np.floor(K / 2.))
x_grid = np.linspace(0, tau_x, num=plt_sz[1], endpoint=False, dtype=float)
y_grid = np.linspace(0, tau_y, num=plt_sz[0], endpoint=False, dtype=float)
# evaluate the vertical direction roots
vec_K = np.arange(-k_limit, k_limit + 1, dtype=float)[:, np.newaxis]
j2pi_taux = 1j * 2 * np.pi / tau_x
j2pi_tauy = 1j * 2 * np.pi / tau_y
cords = np.empty((0, 2))
for loop in range(np.int(plt_sz[1])):
x_loop = x_grid[loop]
root_loop = np.roots((np.dot(coef,
np.exp(j2pi_taux * x_loop * vec_K)
))[::-1].squeeze())
pos_loop = np.log(root_loop) / j2pi_tauy
idx = np.abs(np.imag(pos_loop)) < 1e-10
y_cord = np.real(pos_loop[idx])
y_cord -= np.floor(y_cord / tau_y) * tau_y
cords = np.concatenate((cords, np.hstack((np.tile(x_loop, (y_cord.size, 1)),
y_cord[:, np.newaxis]
))
), axis=0)
# evaluate the horizontal direction roots
vec_L = np.arange(-l_limit, l_limit + 1, dtype=float)[:, np.newaxis]
coef_T = coef.T
for loop in range(np.int(plt_sz[0])):
y_loop = y_grid[loop]
root_loop = np.roots((np.dot(coef_T,
np.exp(j2pi_tauy * y_loop * vec_L)
))[::-1].squeeze())
pos_loop = np.log(root_loop) / j2pi_taux
idx = np.abs(np.imag(pos_loop)) < 1e-10
x_cord = np.real((pos_loop[idx]))
x_cord -= np.floor(x_cord / tau_x) * tau_x
cords = np.concatenate((cords, np.hstack((x_cord[:, np.newaxis],
np.tile(y_loop, (x_cord.size, 1))
))
), axis=0)
# normalize to the closet discrete grids speicified by [x_grid,y_grid]
Tx = tau_x / plt_sz[1]
Ty = tau_y / plt_sz[0]
# eps = np.spacing(1)
cords_normalise = np.hstack((np.floor(cords[:, 0] / Tx)[:, np.newaxis],
np.floor(cords[:, 1] / Ty)[:, np.newaxis]
))
curve_plt = np.zeros(np.int(plt_sz[0] * plt_sz[1]))
curve_plt[(cords_normalise[:, 0] * plt_sz[0] +
cords_normalise[:, 1]).astype(int)] = 1
curve_plt = np.reshape(curve_plt, tuple(plt_sz.astype(int)), order='F')
return curve_plt
def convmtx2(H, M, N):
"""
build 2d convolution matrix
:param H: 2d filter
:param M: input signal dimension is M x N
:param N: input signal dimension is M x N
:return:
"""
P, Q = H.shape
blockHeight = int(M + P - 1)
blockWidth = int(M)
blockNonZeros = int(P * M)
totalNonZeros = int(Q * N * blockNonZeros)
THeight = int((N + Q - 1) * blockHeight)
TWidth = int(N * blockWidth)
Tvals = np.zeros((totalNonZeros, 1), dtype=H.dtype)
Trows = np.zeros((totalNonZeros, 1))
Tcols = np.zeros((totalNonZeros, 1))
c = np.dot(np.diag(np.arange(1, M + 1)), np.ones((M, P), dtype=float))
r = np.repeat(np.reshape(c + np.arange(0, P)[np.newaxis], (-1, 1), order='F'), N, axis=1)
c = np.repeat(c.flatten('F')[:, np.newaxis], N, axis=1)
colOffsets = np.arange(N) * M
colOffsets = np.reshape(np.repeat(colOffsets[np.newaxis], M * P, axis=0) + c, (-1, 1), order='F') - 1
rowOffsets = np.arange(N) * blockHeight
rowOffsets = np.reshape(np.repeat(rowOffsets[np.newaxis], M * P, axis=0) + r, (-1, 1), order='F') - 1
for k in range(Q):
val = np.reshape(np.tile((H[:, k]).flatten(), (M, 1)), (-1, 1), order='F')
first = int(k * N * blockNonZeros)
last = int(first + N * blockNonZeros)
Trows[first:last] = rowOffsets
Tcols[first:last] = colOffsets
Tvals[first:last] = np.tile(val, (N, 1))
rowOffsets += blockHeight
T = sps.coo_matrix((Tvals.squeeze(), (Trows.squeeze(), Tcols.squeeze())),
shape=(THeight, TWidth)).toarray()
return T
def convmtx2_valid(H, M, N):
"""
2d convolution matrix with the boundary condition 'valid', i.e., only filter
within the given data block.
:param H: 2d filter
:param M: input signal dimension is M x N
:param N: input signal dimension is M x N
:return:
"""
T = convmtx2(H, M, N)
s_H0, s_H1 = H.shape
if M >= s_H0:
S = np.pad(np.ones((M - s_H0 + 1, N - s_H1 + 1), dtype=bool),
((s_H0 - 1, s_H0 - 1), (s_H1 - 1, s_H1 - 1)),
'constant', constant_values=False)
else:
S = np.pad(np.ones((s_H0 - M + 1, s_H1 - N + 1), dtype=bool),
((M - 1, M - 1), (N - 1, N - 1)),
'constant', constant_values=False)
T = T[S.flatten('F'), :]
return T
def create_fri_curve_mask(coef, len_x, len_y, tau_x, tau_y):
"""
Crete a mask function for FRI curve from the given curve coefficients:
mu(x,y) = sum_{k,l} c_{k,l} exp(jkx/tau_x + jly/tau_y)
The FRI curve is defined as the roots of the mask function: mu(x,y) = 0.
:param coef: a 2D array curve coefficients
:param len_x: length of the horizontal axis for the mask function
:param len_y: length of the vertical axis for the mask function
:param tau_x: period along x-axis
:param tau_y: period along y-axis
:return:
"""
# zero padding the coefficients to the same size of x and y
coef_pad = np.pad(coef, ((0, (len_y - coef.shape[0]).astype(int)),
(0, (len_x - coef.shape[1]).astype(int))),
mode='constant', constant_values=0)
# circular shift the origin to the upper-left corner
coef_shift = np.roll(np.roll(coef_pad, -np.int(np.floor(coef.shape[0] / 2.)), 0),
-np.int(np.floor(coef.shape[1] / 2.)), 1)
if use_mkl_fft:
mask_fn = mkl_fft.ifft2(coef_shift) * len_x * len_y / (tau_x * tau_y)
else:
mask_fn = sp_fft.fft2(coef_shift) * len_x * len_y / (tau_x * tau_y)
return mask_fn
def gen_samples_edge_img(coef, samp_size, B_x, B_y, tau_x, tau_y, amp_fn=lambda x, y: 1., over_samp_ratio=221):
"""
Generate the ideally lowpass filtered samples (with fft2) of an edge image,
which is discontinuous on the curve with the curve coefficients coef.
:param coef: curve coefficients that define the FRI curve
:param samp_size: 1 x 2 array, desired sample size
:param B_x: bandwidth of the ideal lowpass filter along x-axis
:param B_y: bandwidth of the ideal lowpass filter along y-axis
:param tau_x: period along x-axis
:param tau_y: period along y-axis
:param amp_fn: the amplitude function. The default is 1, i.e.,
the edge image is the indicator function
:param over_samp_ratio: the over sampling ratio used in fft. The higher the ratio,
the accurater the fft approximation is.
:return:
"""
len_x = samp_size[1] * over_samp_ratio
len_y = samp_size[0] * over_samp_ratio
xs = np.reshape(np.linspace(0, tau_x, len_x, endpoint=False), (1, -1), order='F')
ys = np.reshape(np.linspace(0, tau_y, len_y, endpoint=False), (-1, 1), order='F')
# number of frequency domain samples
freq_samp_sz_x = np.int(2 * np.floor(B_x * tau_x / 2) + 1)
freq_samp_sz_y = np.int(2 * np.floor(B_y * tau_y / 2) + 1)
# boundary width (assume that both samp_size and len_x are ODD numbers!!!
assert samp_size[0] % 2 == 1 and samp_size[1] % 2 == 1
wd0 = np.int((len_y - freq_samp_sz_y) / 2.)
wd1 = np.int((len_x - freq_samp_sz_x) / 2.)
mask_fn = np.real(create_fri_curve_mask(coef, len_x, len_y, tau_x, tau_y))
edge_img = np.double(mask_fn <= 0.) * amp_fn(xs, ys)
# ideal lowpass filtering and sampling (use fft2 for numerical implementation)
if use_mkl_fft:
fourier_trans_all = sp_fft.fftshift(mkl_fft.fft2(edge_img))
else:
fourier_trans_all = sp_fft.fftshift(sp_fft.fft2(edge_img))
# extracting the low frequency components based on the bandwidth
fourier_lowpass = fourier_trans_all[wd0:wd0 + freq_samp_sz_y,
wd1:wd1 + freq_samp_sz_x] / ((len_x * len_y) /
(freq_samp_sz_x * freq_samp_sz_y))
# pad zeros based on the size of the spatial domain samples
pad_sz_x = np.int((samp_size[1] - freq_samp_sz_x) / 2)
pad_sz_y = np.int((samp_size[0] - freq_samp_sz_y) / 2)
fourier_data = np.pad(fourier_lowpass,
((pad_sz_y, pad_sz_y), (pad_sz_x, pad_sz_x)),
mode='constant', constant_values=0)
if use_mkl_fft:
samples = mkl_fft.ifft2(sp_fft.ifftshift(fourier_data)) * \
(samp_size[0] * samp_size[1] / (freq_samp_sz_x * freq_samp_sz_y))
else:
samples = sp_fft.ifft2(sp_fft.ifftshift(fourier_data)) * \
(samp_size[0] * samp_size[1] / (freq_samp_sz_x * freq_samp_sz_y))
return samples, fourier_lowpass
def build_G_fri_curve(x_samp, y_samp, B_x, B_y, tau_x, tau_y):
"""
:param x_samp: sampling locations along x-axis
:param y_samp: sampling locations along y-axis
:param B_x: filter bandwidth along x-axis
:param B_y: filter bandwidth along y-axis
:param tau_x: period along x-axis
:param tau_y: period along y-axis
:return:
"""
k_limit = np.floor(B_x * tau_x / 2.)
l_limit = np.floor(B_y * tau_y / 2.)
k_grid, l_grid = np.meshgrid(np.arange(-k_limit, k_limit + 1),
np.arange(-l_limit, l_limit + 1))
x_grid, y_grid = np.meshgrid(x_samp, y_samp)
k_grid = np.reshape(k_grid, (1, -1), order='F')
l_grid = np.reshape(l_grid, (1, -1), order='F')
x_grid = np.reshape(x_grid, (-1, 1), order='F')
y_grid = np.reshape(y_grid, (-1, 1), order='F')
G = np.exp(1j * 2 * np.pi / tau_x * x_grid * k_grid +
1j * 2 * np.pi / tau_y * y_grid * l_grid) / (B_x * B_y * tau_x * tau_y)
return G
def Tmtx_curve(data, M, N, freq_factor):
return convmtx2_valid(data * np.reshape(freq_factor, data.shape, order='F'), M, N)
def Rmtx_curve(coef, M, N, freq_factor):
"""
build the right dual matrix for the FRI curve
:param coef: annihilating filter coefficients
:param M: input signal dimension is M x N
:param N: input signal dimension is M x N
:param freq_factor: the scaling factor in the annihilation constraint
:return:
"""
return convmtx2_valid(coef, M, N) * np.reshape(freq_factor, (1, -1), order='F')
def hermitian_expansion(len_c):
"""
create the expansion matrix such that we expand the vector that is Hermitian symmetric.
The input vector is the concatenation of the real part and imaginary part
of the vector in the first half.
:param len_c: length of the first half for the real part. Hence, it is 1 element more than
that for the imaginary part
:return: D1: expansion matrix for the real part
D2: expansion matrix for the imaginary part
"""
D0 = np.eye(len_c)
D1 = np.vstack((D0, D0[1::, ::-1]))
D2 = np.vstack((D0, -D0[1::, ::-1]))
D2 = D2[:, :-1]
return D1, D2
def recon_fri_curve(G, a, K, L, B_x, B_y, tau_x, tau_y, noise_level, max_ini=100, stop_cri='mse'):
"""
Reconstruction FRI curve from the given set of ideally lowpass filtered samples
:param G: the linear mapping between the measurements a and the unknown FIR sequence b
:param a: the given measurements
:param K: size of the curve coefficients along x-axis (2K_0 + 1)
:param L: size of the curve coefficients along y-axis (2L_0 + 1)
:param B_x: bandwidth of the lowpass filter along x-axis
:param B_y: bandwidth of the lowpass filter along y-axis
:param tau_x: period along x-axis
:param tau_y: period along y-axis
:param noise_level: level of noise in the given measurements
:param max_ini: maximum number of initialisations
:param stop_cri: stopping criteria: 1) mse; or 2) max_iter
:return:
"""
compute_mse = (stop_cri == 'mse')
k_limit = np.int(np.floor(B_x * tau_x / 2.))
l_limit = np.int(np.floor(B_y * tau_y / 2.))
sz_b0 = 2 * l_limit + 1
sz_b1 = 2 * k_limit + 1
sz_conv_out0 = sz_b0 - L + 1
sz_conv_out1 = sz_b1 - K + 1
numel_conv_out = sz_conv_out0 * sz_conv_out1
numel_coef = K * L
numel_b = sz_b0 * sz_b1
k_grid, l_grid = np.meshgrid(np.arange(-k_limit, k_limit + 1),
np.arange(-l_limit, l_limit + 1))
k_grid = np.reshape(k_grid, (-1, 1), order='F')
l_grid = np.reshape(l_grid, (-1, 1), order='F')
# the scaling factor in the annihilation constraint
freq_scaling = 2 * np.pi / tau_x * k_grid + 1j * 2 * np.pi / tau_y * l_grid
# reshape a as a column vector
a = np.reshape(a, (-1, 1), order='F')
GtG = np.dot(G.conj().T, G)
Gt_a = np.dot(G.conj().T, a)
max_iter = 50
min_error = float('inf')
beta = np.reshape(linalg.lstsq(G, a)[0], (sz_b0, sz_b1), order='F')
Tbeta = Tmtx_curve(beta, L, K, freq_scaling)
rhs = np.concatenate((np.zeros(numel_coef + numel_conv_out + numel_b), [1.]))
rhs_bl = np.concatenate((Gt_a, np.zeros((numel_conv_out, 1), dtype=Gt_a.dtype)))
for ini in range(max_ini):
c = np.random.randn(L, K) + 1j * np.random.randn(L, K)
c0 = np.reshape(c.copy(), (-1, 1), order='F')
error_seq = np.zeros(max_iter)
R_loop = Rmtx_curve(c, sz_b0, sz_b1, freq_scaling)
for loop in range(max_iter):
# update c
Mtx_loop = np.vstack((np.hstack((np.zeros((numel_coef, numel_coef)), Tbeta.conj().T,
np.zeros((numel_coef, numel_b)), c0)),
np.hstack((Tbeta, np.zeros((numel_conv_out, numel_conv_out)),
-R_loop, np.zeros((numel_conv_out, 1)))),
np.hstack((np.zeros((numel_b, numel_coef)), -R_loop.conj().T,
GtG, np.zeros((numel_b, 1)))),
np.hstack((c0.conj().T, np.zeros((1, numel_conv_out + numel_b + 1))))
))
# matrix should be Hermitian symmetric
Mtx_loop += Mtx_loop.conj().T
Mtx_loop *= 0.5
c = np.reshape(linalg.solve(Mtx_loop, rhs)[:numel_coef],
(L, K), order='F')
# update b
R_loop = Rmtx_curve(c, sz_b0, sz_b1, freq_scaling)
Mtx_brecon = np.vstack((np.hstack((GtG, R_loop.conj().T)),
np.hstack((R_loop, np.zeros((numel_conv_out, numel_conv_out))))
))
# matrix should be Hermitian symmetric
Mtx_brecon += Mtx_brecon.conj().T
Mtx_brecon *= 0.5
b_recon = linalg.solve(Mtx_brecon, rhs_bl)[:numel_b]
# calculate the objective function value
error_seq[loop] = linalg.norm(a - np.dot(G, b_recon))
if error_seq[loop] < min_error:
min_error = error_seq[loop]
b_opt = b_recon
c_opt = c
# check the stopping criterion
if min_error < noise_level and compute_mse:
break
if min_error < noise_level and compute_mse:
break
b_opt = np.reshape(b_opt, (sz_b0, sz_b1), order='F')
# apply least square to the denoised Fourier data
numel_coef_h = np.int(np.floor(K * L / 2.))
# take the Hermitian symmetry into account
D1, D2 = hermitian_expansion(numel_coef_h + 1)
# D =[D1, 0; 0, D2]
D = np.vstack((np.hstack((D1, np.zeros((2 * numel_coef_h + 1, numel_coef_h), dtype=float))),
np.hstack((np.zeros((2 * numel_coef_h + 1, numel_coef_h + 1), dtype=float), D2))
))
D1_jD2 = np.hstack((D1, 1j * D2))
fri_data = b_opt * np.reshape(freq_scaling, (sz_b0, sz_b1), order='F')
anni_mtx_r = convmtx2_valid(np.real(fri_data), L, K)
anni_mtx_i = convmtx2_valid(np.imag(fri_data), L, K)
anni_mtx_ri_D = np.dot(np.vstack((np.hstack((anni_mtx_r, -anni_mtx_i)),
np.hstack((anni_mtx_i, anni_mtx_r))
)), D)
Vh = linalg.svd(anni_mtx_ri_D, compute_uv=True)[2]
c_h_ri = Vh.conj().T[:, -1]
coef = np.reshape(np.dot(D1_jD2, c_h_ri), (L, K), order='F')
return b_opt, min_error, coef, ini
def plt_recon_fri_curve(coef, coef_ref, tau_x, tau_y, plt_size=(1e3, 1e3),
save_figure=False, file_name='fri_curve.pdf',
file_format='pdf', nargout=0):
"""
Plot the reconstructed FRI curve, which is specified by the coefficients.
:param coef: FRI curve coefficients
:param coef_ref: ground truth FRI curve coefficients
:param tau_x: period along x-axis
:param tau_y: period along y-axis
:param plt_size: size of the plot to draw the curve as a discrete image
:param save_figure: save the figure as pdf file or not
:param file_name: the file name used for saving the figure
:return:
"""
curve = 1 - roots2(coef, plt_size, tau_x, tau_y)
curve_ref = 1 - roots2(coef_ref, plt_size, tau_x, tau_y)
idx = np.argwhere(curve_ref == 0)
idx_y = idx[:, 0]
idx_x = idx[:, 1]
subset_idx = (np.round(np.linspace(0, idx_x.size - 1, np.int(0.1 * idx_x.size))
)).astype(int)
plt.figure(figsize=(3, 3), dpi=90)
plt.imshow(255 * curve, origin='upper', vmin=0, vmax=255, cmap='gray')
plt.scatter(idx_x[subset_idx], idx_y[subset_idx], s=1, edgecolor='none', c=[1, 0, 0], hold=True)
plt.axis('off')
if save_figure:
plt.savefig(file_name, format=file_format, dpi=300, transparent=True)
# plt.show()
if nargout == 0:
return None
else:
return curve, idx_x, idx_y, subset_idx
# == for structured low rank approximation (SLRA) method == #
def slra_fri_curve(G, a, K, L, K_alg, L_alg, B_x, B_y, tau_x, tau_y,
max_iter=100, weight_choice='1'):
"""
sturctured low rank approximation method by L. Condat:
http://www.gipsa-lab.grenoble-inp.fr/~laurent.condat/download/pulses_recovery.m
:param G: the linear mapping between the spatial domain samples and the Fourier samples.
Typically a truncated DFT transformation.
:param a: the spatial domain samples
:param K: size of the curve coefficients along x-axis (2K_0 + 1)
:param L: size of the curve coefficients along y-axis (2L_0 + 1)
:param K_cad: size of the assumed curve coefficients along x-axis,
which is used in the Cadzow iterative denoising. It should be at least K.
:param L_cad: size of the assumed curve coefficients along y-axis,
# which is used in the Cadzow iterative denoising. It should be at least L.
:param B_x: bandwidth of the lowpass filter along x-axis
:param B_y: bandwidth of the lowpass filter along y-axis
:param tau_x: period along x-axis
:param tau_y: period along y-axis
:param max_iter: maximum number of iterations
:return:
"""
mu = 0.1 # default parameter by the author. Must be in (0,2)
gamma = 0.51 * mu # default parameter by the author. Must be in (mu/2,1)
k_limit = np.int(np.floor(B_x * tau_x / 2.))
l_limit = np.int(np.floor(B_y * tau_y / 2.))
k_grid, l_grid = np.meshgrid(np.arange(-k_limit, k_limit + 1),
np.arange(-l_limit, l_limit + 1))
k_grid = np.reshape(k_grid, (-1, 1), order='F')
l_grid = np.reshape(l_grid, (-1, 1), order='F')
sz_b0 = 2 * l_limit + 1
sz_b1 = 2 * k_limit + 1
b = np.reshape(linalg.lstsq(G, np.reshape(a, (-1, 1), order='F'))[0],
(sz_b0, sz_b1), order='F')
# number of zeros of the annihilating filter matrix in the Cadzow iteration
num_zero = (K_alg - K + 1) * (L_alg - L + 1)
blk_sz0 = b.shape[0] - L_alg + 1
blk_sz1 = L_alg
num_blk0 = b.shape[1] - K_alg + 1
num_blk1 = K_alg
# the scaling factor in the annihilation constraint
freq_scaling = 2 * np.pi / tau_x * k_grid + 1j * 2 * np.pi / tau_y * l_grid
# take the Hermtian symmetry into account
numel_coef_h = np.int(np.floor(K * L / 2))
D1, D2 = hermitian_expansion(numel_coef_h + 1)
D = np.vstack((np.hstack((D1, np.zeros((2 * numel_coef_h + 1, numel_coef_h), dtype=float))),
np.hstack((np.zeros((2 * numel_coef_h + 1, numel_coef_h + 1), dtype=float), D2))
))
D1_jD2 = np.hstack((D1, 1j * D2))
I_hat = b * np.reshape(freq_scaling, b.shape, order='F')
anni_mtx_noisy = convmtx2_valid(I_hat, L_alg, K_alg)
if weight_choice == '1':
# weight matrix version I
weight_mtx = 1. / (blk_sum(np.ones(anni_mtx_noisy.shape),
blk_sz0, blk_sz1, num_blk0, num_blk1)
)
elif weight_choice == '2':
# weight matrix version II
freq_rescale_weights = np.abs(convmtx2_valid(np.reshape(freq_scaling, b.shape, order='F'), L_alg, K_alg))
freq_rescale_weights[freq_rescale_weights < 1e-10] += 1e-3 # avoid dividing by 0
weight_mtx = 1. / (freq_rescale_weights *
blk_sum(np.ones(anni_mtx_noisy.shape),
blk_sz0, blk_sz1, num_blk0, num_blk1)
)
else:
# weight matrix version III (equal weights)
weight_mtx = np.ones(anni_mtx_noisy.shape)
# initialise annihilation data matrix
anni_mtx_denoised = anni_mtx_noisy.copy()
mats = anni_mtx_denoised.copy() # auxiliary matrix
for loop in range(max_iter):
U_loop, s_loop, Vh_loop = \
linalg.svd(mats + gamma * (anni_mtx_denoised - mats) +
mu * (anni_mtx_noisy - anni_mtx_denoised) * weight_mtx,
full_matrices=False, compute_uv=True)
# thresholding singular values
s_loop[-1 - num_zero + 1::] = 0.
# re-synthesize the matrix
anni_mtx_denoised = np.dot(U_loop, np.dot(np.diag(s_loop), Vh_loop))
mats = mats - anni_mtx_denoised + \
blk_avg(2 * anni_mtx_denoised - mats,
blk_sz0, blk_sz1, num_blk0, num_blk1)
anni_mtx_denoised = blk_avg(anni_mtx_denoised, blk_sz0, blk_sz1, num_blk0, num_blk1)
# the denoised Fourier data
I_hat_denoised = get_mtx_entries(anni_mtx_denoised, blk_sz0, blk_sz1, num_blk0, num_blk1)
# build the associated convolution matrix from the denoised data
anni_mtx_denoised_r = convmtx2_valid(np.real(I_hat_denoised), L, K)
anni_mtx_denoised_i = convmtx2_valid(np.imag(I_hat_denoised), L, K)
anni_mtx_denoised_ri_D = np.dot(np.vstack((np.hstack((anni_mtx_denoised_r,
-anni_mtx_denoised_i)),
np.hstack((anni_mtx_denoised_i,
anni_mtx_denoised_r))
)),
D)
# take svd decomposition of the annihilating filter matrix and extract
# the singular vector that has the smallest singular value
Vh = linalg.svd(anni_mtx_denoised_ri_D, compute_uv=True)[2]
c_h_ri = Vh.conj().T[:, -1]
coef_recon = np.reshape(np.dot(D1_jD2, c_h_ri), (L, K), order='F')
return coef_recon
def blk_sum(mtx, blk_sz0, blk_sz1, num_blk0, num_blk1):
"""
average a matrix so that it satisfies the block Toeplitz structure
:param mtx: the matrix to be averaged
:param blk_sz0: block size (the vertical dimension)
:param blk_sz1: block size (the horizontal dimension)
:param num_blk0: number of blocks (the vertical dimension)
:param num_blk1: number of blocks (the horizontal dimension)
:return:
"""
# initialise the average matrix
mtx_avg = np.zeros(mtx.shape, dtype=mtx.dtype)
idx_h, idx_v = np.meshgrid(np.arange(num_blk1), np.arange(num_blk0))
# parse the blocks
for count in range(-num_blk0 + 1, num_blk1):
idx_h_count = np.diag(idx_h, count)
idx_v_count = np.diag(idx_v, count)
sum_mtx = np.zeros((blk_sz0, blk_sz1), dtype=mtx.dtype)
# first average block-wise
for inner in range(idx_h_count.size):
idx_h0 = idx_h_count[inner] * blk_sz1
idx_v0 = idx_v_count[inner] * blk_sz0
sum_mtx += mtx[idx_v0:idx_v0 + blk_sz0, idx_h0:idx_h0 + blk_sz1]
# now average the entries in the averaged block matrix
sum_blk = diag_sum(sum_mtx, blk_sz0, blk_sz1)
# assign the summed matrix to the output
for inner in range(idx_h_count.size):
idx_h0 = idx_h_count[inner] * blk_sz1
idx_v0 = idx_v_count[inner] * blk_sz0
mtx_avg[idx_v0:idx_v0 + blk_sz0, idx_h0:idx_h0 + blk_sz1] = sum_blk
return mtx_avg
def diag_sum(mtx, mtx_sz0, mtx_sz1):
"""
average a matrix so that it conforms to the Toeplitz structure
:param mtx: the matrix to be averaged
:param mtx_sz0: size of the matrix (vertical dimension)
:param mtx_sz1: size of the matrix (horizontal dimension)
:return:
"""
col = np.zeros(mtx_sz0, dtype=mtx.dtype)
row = np.zeros(mtx_sz1, dtype=mtx.dtype)
for count in range(0, -mtx_sz0, -1):
col[-count] = np.sum(np.diag(mtx, count))
for count in range(mtx_sz1):
row[count] = np.sum(np.diag(mtx, count))
return linalg.toeplitz(col, row)
# ============ for Cadzow denoising method ============= #
def cadzow_iter_fri_curve(G, a, K, L, K_cad, L_cad, B_x, B_y, tau_x, tau_y, max_iter=100):
"""
cadzow iterative denoising method for FRI curves.
:param G: the linear mapping between the spatial domain samples and the Fourier samples.
Typically a truncated DFT transformation.
:param a: the spatial domain samples
:param K: size of the curve coefficients along x-axis (2K_0 + 1)
:param L: size of the curve coefficients along y-axis (2L_0 + 1)
:param K_cad: size of the assumed curve coefficients along x-axis,
which is used in the Cadzow iterative denoising. It should be at least K.
:param L_cad: size of the assumed curve coefficients along y-axis,
# which is used in the Cadzow iterative denoising. It should be at least L.
:param B_x: bandwidth of the lowpass filter along x-axis
:param B_y: bandwidth of the lowpass filter along y-axis
:param tau_x: period along x-axis
:param tau_y: period along y-axis
:param max_iter: maximum number of iterations
:return:
"""
k_limit = np.int(np.floor(B_x * tau_x / 2.))
l_limit = np.int(np.floor(B_y * tau_y / 2.))
k_grid, l_grid = np.meshgrid(np.arange(-k_limit, k_limit + 1),
np.arange(-l_limit, l_limit + 1))
k_grid = np.reshape(k_grid, (-1, 1), order='F')
l_grid = np.reshape(l_grid, (-1, 1), order='F')
sz_b0 = 2 * l_limit + 1
sz_b1 = 2 * k_limit + 1
b = np.reshape(linalg.lstsq(G, np.reshape(a, (-1, 1), order='F'))[0],
(sz_b0, sz_b1), order='F')
# number of zeros of the annihilating filter matrix in the Cadzow iteration
num_zero = (K_cad - K + 1) * (L_cad - L + 1)
blk_sz0 = b.shape[0] - L_cad + 1
blk_sz1 = L_cad
num_blk0 = b.shape[1] - K_cad + 1
num_blk1 = K_cad
# the scaling factor in the annihilation constraint
freq_scaling = 2 * np.pi / tau_x * k_grid + 1j * 2 * np.pi / tau_y * l_grid
# take the Hermtian symmetry into account
numel_coef_h = np.int(np.floor(K * L / 2))
D1, D2 = hermitian_expansion(numel_coef_h + 1)
D = np.vstack((np.hstack((D1, np.zeros((2 * numel_coef_h + 1, numel_coef_h), dtype=float))),
np.hstack((np.zeros((2 * numel_coef_h + 1, numel_coef_h + 1), dtype=float), D2))
))
D1_jD2 = np.hstack((D1, 1j * D2))
I_hat = b * np.reshape(freq_scaling, b.shape, order='F')
anni_mtx = convmtx2_valid(I_hat, L_cad, K_cad)
for loop in range(max_iter):
U_loop, s_loop, Vh_loop = linalg.svd(anni_mtx, full_matrices=False, compute_uv=True)
if s_loop[-1 - num_zero] / s_loop[-1 - num_zero + 1] > 1e12:
break
# thresholding singular values
s_loop[-1 - num_zero + 1::] = 0.
# re-synthesize the matrix
anni_mtx_threshold = np.dot(U_loop, np.dot(np.diag(s_loop), Vh_loop))
anni_mtx = blk_avg(anni_mtx_threshold, blk_sz0, blk_sz1, num_blk0, num_blk1)
# the denoised Fourier data
I_hat_denoised = get_mtx_entries(anni_mtx, blk_sz0, blk_sz1, num_blk0, num_blk1)
# build the associated convolution matrix from the denoised data
anni_mtx_denoised_r = convmtx2_valid(np.real(I_hat_denoised), L, K)
anni_mtx_denoised_i = convmtx2_valid(np.imag(I_hat_denoised), L, K)
anni_mtx_denoised_ri_D = np.dot(np.vstack((np.hstack((anni_mtx_denoised_r,
-anni_mtx_denoised_i)),
np.hstack((anni_mtx_denoised_i,
anni_mtx_denoised_r))
)),
D)
# take svd decomposition of the annihilating filter matrix and extract
# the singular vector that has the smallest singular value
Vh = linalg.svd(anni_mtx_denoised_ri_D, compute_uv=True)[2]
c_h_ri = Vh.conj().T[:, -1]
coef_recon = np.reshape(np.dot(D1_jD2, c_h_ri), (L, K), order='F')
return coef_recon
def blk_avg(mtx, blk_sz0, blk_sz1, num_blk0, num_blk1):
"""
average a matrix so that it satisfies the block Toeplitz structure
:param mtx: the matrix to be averaged
:param blk_sz0: block size (the vertical dimension)
:param blk_sz1: block size (the horizontal dimension)
:param num_blk0: number of blocks (the vertical dimension)
:param num_blk1: number of blocks (the horizontal dimension)
:return:
"""
# initialise the average matrix
mtx_avg = np.zeros(mtx.shape, dtype=mtx.dtype)
idx_h, idx_v = np.meshgrid(np.arange(num_blk1), np.arange(num_blk0))
# parse the blocks
for count in range(-num_blk0 + 1, num_blk1):
idx_h_count = np.diag(idx_h, count)
idx_v_count = np.diag(idx_v, count)
sum_mtx = np.zeros((blk_sz0, blk_sz1), dtype=mtx.dtype)
# first average block-wise
for inner in range(idx_h_count.size):
idx_h0 = idx_h_count[inner] * blk_sz1
idx_v0 = idx_v_count[inner] * blk_sz0
sum_mtx += mtx[idx_v0:idx_v0 + blk_sz0, idx_h0:idx_h0 + blk_sz1]
avg_blk = sum_mtx / idx_h_count.size
# now average the entries in the averaged block matrix
avg_blk = diag_avg(avg_blk, blk_sz0, blk_sz1)
# assign the averaged matrix to the output
for inner in range(idx_h_count.size):
idx_h0 = idx_h_count[inner] * blk_sz1
idx_v0 = idx_v_count[inner] * blk_sz0
mtx_avg[idx_v0:idx_v0 + blk_sz0, idx_h0:idx_h0 + blk_sz1] = avg_blk
return mtx_avg
def diag_avg(mtx, mtx_sz0, mtx_sz1):
"""
average a matrix so that it conforms to the Toeplitz structure
:param mtx: the matrix to be averaged
:param mtx_sz0: size of the matrix (vertical dimension)
:param mtx_sz1: size of the matrix (horizontal dimension)
:return:
"""
col = np.zeros(mtx_sz0, dtype=mtx.dtype)
row = np.zeros(mtx_sz1, dtype=mtx.dtype)
for count in range(0, -mtx_sz0, -1):
col[-count] = np.mean(np.diag(mtx, count))
for count in range(mtx_sz1):
row[count] = np.mean(np.diag(mtx, count))
return linalg.toeplitz(col, row)
def get_mtx_entries(mtx, blk_sz0, blk_sz1, num_blk0, num_blk1):
"""
get the entries of the block-Toeplitz matrix
:param mtx: the block-Toeplitz matrix
:param blk_sz0: block size (the vertical dimension)
:param blk_sz1: block size (the horizontal dimension)
:param num_blk0: number of blocks (the vertical dimension)
:param num_blk1: number of blocks (the horizontal dimension)
:return:
"""
data = np.zeros((blk_sz0 + blk_sz1 - 1,
num_blk0 + num_blk1 - 1), dtype=mtx.dtype)
for count in range(num_blk1 - 1, -1, -1):
mtx_count = mtx[0:blk_sz0, count * blk_sz1:(count + 1) * blk_sz1]
data[:, -count + num_blk1 - 1] = np.concatenate((mtx_count[0, -1::-1],
mtx_count[1::, 0]))
for count in range(1, num_blk0):
mtx_count = mtx[count * blk_sz0:(count + 1) * blk_sz0, 0:blk_sz1]
data[:, count + num_blk1 - 1] = np.concatenate((mtx_count[0, -1::-1],
mtx_count[1::, 0]))
return data
def lsq_fri_curve(G, a, K, L, B_x, B_y, tau_x, tau_y):
k_limit = np.int(np.floor(B_x * tau_x / 2.))
l_limit = np.int(np.floor(B_y * tau_y / 2.))
k_grid, l_grid = np.meshgrid(np.arange(-k_limit, k_limit + 1),
np.arange(-l_limit, l_limit + 1))
k_grid = np.reshape(k_grid, (-1, 1), order='F')
l_grid = np.reshape(l_grid, (-1, 1), order='F')
sz_b0 = 2 * l_limit + 1
sz_b1 = 2 * k_limit + 1
b = np.reshape(linalg.lstsq(G, np.reshape(a, (-1, 1), order='F'))[0],
(sz_b0, sz_b1), order='F')
# the scaling factor in the annihilation constraint
freq_scaling = 2 * np.pi / tau_x * k_grid + 1j * 2 * np.pi / tau_y * l_grid
numel_coef_h = np.int(np.floor(K * L / 2))
D1, D2 = hermitian_expansion(numel_coef_h + 1)
D = np.vstack((np.hstack((D1, np.zeros((2 * numel_coef_h + 1, numel_coef_h), dtype=float))),
np.hstack((np.zeros((2 * numel_coef_h + 1, numel_coef_h + 1), dtype=float), D2))
))
D1_jD2 = np.hstack((D1, 1j * D2))
I_hat = b * np.reshape(freq_scaling, b.shape, order='F')
anni_mtx_r = convmtx2_valid(np.real(I_hat), L, K)
anni_mtx_i = convmtx2_valid(np.imag(I_hat), L, K)
anni_mtx_ri_D = np.dot(np.vstack((np.hstack((anni_mtx_r, -anni_mtx_i)),
np.hstack((anni_mtx_i, anni_mtx_r))
)), D)
Vh = linalg.svd(anni_mtx_ri_D, compute_uv=True)[2]
c_h_ri = Vh.conj().T[:, -1]
coef = np.reshape(np.dot(D1_jD2, c_h_ri), (L, K), order='F')
return coef
# ============= for batch run ============== #
def run_algs(coef, G, samples_noiseless, P, K, L, K_cad, L_cad, B_x, B_y, tau_x, tau_y,
max_iter_cadzow=1000, max_iter_srla=1000, max_ini=50):
"""
run both the Cadzow method and the proposed method with the same set of samples
:param coef: the ground truth curve coefficients (used for comparison)
:param G: linear mapping between the spatial domain samples and the FRI sequence
:param samples_noiseless: the noiseless samples
:param P: the noise level (SNR in dB)
:param K: the dimension of the curve coeffiicents are L x K
:param L: the dimension of the curve coeffiicents are L x K
:param K_cad: size of the assumed curve coefficients along x-axis,
which is used in the Cadzow iterative denoising. It should be at least K.
:param L_cad: size of the assumed curve coefficients along y-axis,
# which is used in the Cadzow iterative denoising. It should be at least L.
:param B_x: bandwidth of the lowpass filter along x-axis
:param B_y: bandwidth of the lowpass filter along y-axis
:param tau_x: period along x-axis
:param tau_y: period along y-axis
:param max_iter_cadzow: maximum number of iterations for Cadzow's method
:param max_ini: maximum number of initialisations for the proposed method
:return:
"""
sp.random.seed() # so that each subprocess has a different random states
samples_size = samples_noiseless.shape
# check whether we are in the case with real-valued samples or not
real_valued = np.max(np.abs(np.imag(samples_noiseless))) < 1e-12
# add Gaussian white noise
if real_valued:
noise = np.random.randn(samples_size[0], samples_size[1])
samples_noiseless = np.real(samples_noiseless)
else:
noise = np.random.randn(samples_size[0], samples_size[1]) + \
1j * np.random.randn(samples_size[0], samples_size[1])
noise = noise / linalg.norm(noise, 'fro') * \
linalg.norm(samples_noiseless, 'fro') * 10 ** (-P / 20.)
samples_noisy = samples_noiseless + noise
# noise energy, in the noiseless case 1e-10 is considered as 0
noise_level = np.max([1e-10, linalg.norm(noise, 'fro')])
# least square minimisation
coef_recon_lsq = lsq_fri_curve(G, samples_noisy, K, L, B_x, B_y, tau_x, tau_y)
std_lsq = std_normalised(coef_recon_lsq, coef)[0]
snr_lsq = snr_normalised(coef_recon_lsq, coef)
# cadzow iterative denoising
coef_recon_cadzow = cadzow_iter_fri_curve(G, samples_noisy, K, L, K_cad,
L_cad, B_x, B_y, tau_x, tau_y,
max_iter=max_iter_cadzow)
std_cadzow = std_normalised(coef_recon_cadzow, coef)[0]
snr_cadzow = snr_normalised(coef_recon_cadzow, coef)
# structured low rank approximation (SLRA)
# weight_choice: '1': the default one based on number of the repetition of entries
# in the block Toeplitz matrix
# weight_choice: '2': based on the number of repetition of entries in the block
# Toeplitz matrix and the frequency re-scaling factor in hat_partial_I
# weight_choice: '3': equal weights for all entries in the block Toeplitz matrix
coef_recon_slra1 = slra_fri_curve(G, samples_noisy, K, L, K_cad, L_cad,
B_x, B_y, tau_x, tau_y,
max_iter=max_iter_srla,
weight_choice='1')
std_slra = std_normalised(coef_recon_slra1, coef)[0]
snr_slra = snr_normalised(coef_recon_slra1, coef)
# the proposed approach
xhat_recon, min_error, coef_recon, ini = \
recon_fri_curve(G, samples_noisy, K, L,
B_x, B_y, tau_x, tau_y, noise_level,
max_ini, stop_cri='max_iter')
std_proposed = std_normalised(coef_recon, coef)[0]
snr_proposed = snr_normalised(coef_recon, coef)
return std_lsq, snr_lsq, std_cadzow, snr_cadzow, \
std_slra, snr_slra, \
std_proposed, snr_proposed
# ============= for radio astronomy problem =========== #
def dirac_2d_v_and_h(direction, G_row, vec_len_row, num_vec_row,
G_col, vec_len_col, num_vec_col,
a, K, noise_level, max_ini, stop_cri):
"""
used to run the reconstructions along horizontal and vertical directions in parallel.
"""
if direction == 0: # row reconstruction
c_recon, min_error, b_recon, ini = \
recon_2d_dirac_vertical(G_row, vec_len_row, num_vec_row,
a, K, noise_level, max_ini, stop_cri)
else: # column reconstruction
c_recon, min_error, b_recon, ini = \
recon_2d_dirac_vertical(G_col, vec_len_col, num_vec_col,
a, K, noise_level, max_ini, stop_cri)
return c_recon, min_error, b_recon, ini
def recon_2d_dirac(FourierData, K, tau_x, tau_y,
tau_inter_x, tau_inter_y, omega_ell, M, N,
noise_level, max_ini=100, stop_cri='mse',
num_rotation=6):
"""
:param FourierData: Noisy Fourier transforms of the Diracs at some frequencies
:param K: number of Dirac
:param taus: [tau_x, tau_y] space support of the Dirac is [-tau_x/2,tau_x/2] x [-tau_y/2,tau_y/2]
:param omega_ell: frequencies where the FourierData is taken
:param M_N: [M,N] the equivalence of "bandwidth" in time domain (because of duality)
:param noise_level: noise level in the given Fourier data
:param max_ini: maximum number of random initialisation allowed in the IQML algorithm
:param stop_cri: stopping criteria: 1) 'mse' (default) or 2) 'maxiter'
:param exhaustive_search: whether or not to use exhaustive search to determine the correct (x,y) combinations
:return: xk_recon: reconstructed horizontal position of the Dirac
yk_recon: reconstructed vertical position of the Dirac
ak_recon: reconstructed amplitudes of the Dirac
"""
# omega_ell is an L by 2 matrix. The FIRST column corresponds to the HORIZONTAL (x-axis) frequencies where the
# Fourier measurements are taken; while the SECOND column corresponds to the VERTICAL (y-axis) frequencies.
omega_ell_x = omega_ell[:, 0]
omega_ell_y = omega_ell[:, 1]
# verify input parameters
# interpolation points cannot be too far apart
assert tau_inter_x >= tau_x and tau_inter_y >= tau_y
# M*tau is an odd number
assert M * tau_inter_x % 2 == 1 and N * tau_inter_y % 2 == 1
# G is a tall matrix
assert M * tau_inter_x * N * tau_inter_y <= omega_ell_x.size
# minimum number of annihilation equations compared with