-
Notifications
You must be signed in to change notification settings - Fork 1
/
cudavenant.py
2458 lines (2078 loc) · 80.6 KB
/
cudavenant.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
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Attemps to provide the covenant package with a GPU acceleration with CUDA.
Provides the essential functions for simulating nD discrete Radon measures
and reconstructing those measures w.r.t to a provided acquistion
Created on Mon Mar 22 08:49:01 2021
@author: Bastien (https://github.com/XeBasTeX,
https://gitlab.inria.fr/blaville)
"""
__normalis_PSF__ = True
import torch
import ot
import numpy as np
from matplotlib.animation import FuncAnimation
from mpl_toolkits.axes_grid1 import make_axes_locatable
import matplotlib.pyplot as plt
from tqdm import tqdm
#If you want to set the noise seed
# torch.manual_seed(90)
# GPU acceleration if needed, enable by default
device = "cuda" if torch.cuda.is_available() else "cpu"
# device = "cpu"
print("[Cudavenant] Using {} device".format(device))
def sum_normalis(X_domain, Y_domain, sigma_g):
r"""
Returns the sum of all the components of the discrete PSF, such that
the PSF can be normalised i.e. torch.sum(PSF) = 1
Parameters
----------
X_domain: Tensor
X coordinate grid (from meshgrid).
Y_domain: Tensor
Grid of Y coordinates (from meshgrid).
sigma_g: double
:math:`sigma` parameter of the Gaussian.
Returns
-------
double
Sum of all components of the PSF
"""
expo = torch.exp(-(torch.pow(X_domain, 2) +
torch.pow(Y_domain, 2))/(2*sigma_g**2))
normalis = sigma_g * (2*np.pi)
normalis = 1 / normalis
return torch.sum(normalis * expo)
def gaussienne_2D(X_domain, Y_domain, sigma_g, undivide=__normalis_PSF__):
r"""
2D normalised Gaussian bump centred in 0 .
Parameters
----------
X_domain: Tensor
X coordinate grid (from meshgrid).
Y_domain: Tensor
Grid of Y coordinates (from meshgrid).
sigma_g: double
:math:`sigma` parameter of the Gaussian.
undivide : boolean
Parameter to normalise by the components of the PSF
The default is True.
Returns
-------
Tensor
Discretisation of the gaussian :math:`h` on :math:`\mathcal{X}`.
"""
expo = torch.exp(-(torch.pow(X_domain, 2) + torch.pow(Y_domain, 2))
/ (2*sigma_g**2))
normalis = (sigma_g * (2*np.pi))
normalis = 1 / normalis
if undivide == True:
sumistan = torch.sum(expo * normalis)
return expo * normalis / sumistan
return expo * normalis
def grad_x_gaussienne_2D(X_domain, Y_domain, X_deriv, sigma_g, normalis=None):
r"""
2D normalised Gaussian bump centred in 0. Be aware of the chain rule
derivation
Parameters
----------
X_domain: Tensor
X coordinate grid (from meshgrid).
Y_domain: Tensor
Grid of Y coordinates (from meshgrid).
X_deriv : Tensor
Coordinate grid X to compute the :math:`x`-axis of the partial
derivative
sigma_g: double
:math:`sigma` parameter of the Gaussian.
Returns
-------
Tensor
Discretisation of the first partial derivative of the Gaussian
:math:`\partial_1 h` on :math:`\mathcal{X}`.
"""
expo = gaussienne_2D(X_domain, Y_domain, sigma_g, normalis)
cst_deriv = sigma_g**2
carre = - X_deriv
return carre * expo / cst_deriv
def grad_y_gaussienne_2D(X_domain, Y_domain, Y_deriv, sigma_g, normalis=None):
r"""
2D normalised Gaussian bump centred in 0. Be aware of the chain rule
derivation
Parameters
----------
X_domain: Tensor
X coordinate grid (from meshgrid).
Y_domain: Tensor
Grid of Y coordinates (from meshgrid).
Y_deriv : Tensor
Coordinate grid Y to compute the :math:`x`-axis of the partial
derivative
sigma_g: double
:math:`sigma` parameter of the Gaussian.
Returns
-------
Tensor
Discretisation of the first partial derivative of the Gaussian
:math:`\partial_2 h` on :math:`\mathcal{X}`.
"""
expo = gaussienne_2D(X_domain, Y_domain, sigma_g, normalis)
cst_deriv = sigma_g**2
carre = - Y_deriv
return carre * expo / cst_deriv
def grad_gaussienne(X_domain, Y_domain, sigma_g, normalis=None):
"""
Gradient of the Gaussian function centred in 0.
Parameters
----------
X_domain: Tensor
X coordinate grid (from meshgrid).
Y_domain: Tensor
Grid of Y coordinates (from meshgrid).
sigma_g: double
:math:`sigma` parameter of the Gaussian.
normalis : boolean, optional
Enables or not the normalisation of the gaussian PSF.
The default is None.
Returns
-------
Tensor
Discretisation of the gradient of the Gaussian bump :math:`h` on
:math:`\mathcal{X}`.
"""
gauss = gaussienne_2D(X_domain, Y_domain, sigma_g)
return((- (X_domain + Y_domain) / sigma_g**2) * gauss)
# def indicator_function_list(elements, X_domain, Y_domain, width):
# for x_coord in X_domain:
# for y_coord in Y_domain:
# if (x_coord - width <= element[0] <= x_coord + width and
# y_coord - width <= element[1] <= y_coord + width):
# return 1
class Domain2D:
def __init__(self, gauche, droit, ech, sigma_psf, dev='cpu'):
"""
Only implemented for square grid
Parameters
----------
gauche : double
Left limit of the square :math:`\mathcal{X}`.
droit : double
Right limit of the square :math:`\mathcal{X}`.
ech : int
Size number of the grid.
sigma_psf : double
:math:`sigma` parameter of the Gaussian
dev : str, optional
Device for computation (cpu, cuda:0, etc.). The default is 'cpu'.
Returns
-------
None.
"""
grille = torch.linspace(gauche, droit, ech)
X_domain, Y_domain = torch.meshgrid(grille, grille)
self.x_gauche = gauche
self.x_droit = droit
self.N_ech = ech
self.X_grid = grille.to(dev)
self.X = X_domain.to(dev)
self.Y = Y_domain.to(dev)
self.sigma = sigma_psf
self.dev = dev
def get_domain(self):
return(self.X, self.Y)
def size(self):
return self.N_ech
def compute_square_mesh(self):
r"""
Returns the meshgrid discretizing the domain :math:`\mathcal{X}` to
N_ech
Returns
-------
Tensor
The coordinate grids in `x` and `y` directions.
"""
return torch.meshgrid(self.X_grid)
def big(self):
r"""
Returns the meshgrid discretizing the domain :math:`\mathcal{X}` to
N_ech
Returns
-------
Tensor
The coordinate grids in `x` and `y` directions.
"""
grid_big = torch.linspace(self.x_gauche-self.x_droit, self.x_droit,
2*self.N_ech - 1).to(device)
X_big, Y_big = torch.meshgrid(grid_big, grid_big)
return(X_big, Y_big)
def biggy(self):
r"""
Returns the meshgrid discretizing the domain :math:`\mathcal{X}` to
N_ech
Returns
-------
Tensor
The coordinate grids in `x` and `y` directions.
"""
grid_big = torch.linspace(self.x_gauche-self.x_droit, self.x_droit,
2*self.N_ech)
X_big, Y_big = torch.meshgrid(grid_big, grid_big)
return(X_big, Y_big)
def reverse(self):
r"""
Returns the meshgrid discretizing the domain :math:`\mathcal{X}` to
N_ech
Returns
-------
Tensor
The coordinate grids in `x` and `y` directions.
"""
grid_big = torch.linspace(self.x_gauche-self.x_droit, self.x_droit,
self.N_ech)
X_big, Y_big = torch.meshgrid(grid_big, grid_big)
return(X_big, Y_big)
def to(self, dev):
"""
Sends the Domain2D object to the `device` component (the CPU or
the Nvidia GPU)
Parameters
----------
dev : str
Either `cpu`, `cuda` (default GPU) or `cuda:0`, `cuda:1`, etc.
Returns
-------
None.
"""
return Domain2D(self.x_gauche, self.x_droit, self.N_ech, self.sigma,
dev=dev)
def super_resolve(self, q=4, sigma=None):
"""
Generate the super-resolved domain by a super-resolution factor
:math:`q`.
Parameters
----------
q : int, optional
Super-resolution factor i.e. the coefficient from coarse to fine
grid. The default is 4.
sigma : double, optional
Custom sigma bound to the domain. It is used for the plot of
Radon measure: indeed, it can not be plotted until it is processed
into the forward operator. The common scheme consists in plotting
the measure through a Gaussian kernel with really small sigma.
The default is None: if choosen it will grab the sigma of the
current object domain `self`.
Returns
-------
Domain2D
Super-resolved domain i.e. domain with :math:`q^d` times more
points.
"""
super_N_ech = q * self.N_ech
if sigma == None:
super_sigma = self.sigma
else:
super_sigma = sigma
return Domain2D(self.x_gauche, self.x_droit, super_N_ech, super_sigma,
dev=self.dev)
class Bruits:
def __init__(self, fond, niveau, type_de_bruits):
self.fond = fond
self.niveau = niveau
self.type = type_de_bruits
def get_fond(self):
return self.fond
def get_nv(self):
return self.niveau
class Mesure2D:
def __init__(self, amplitude=None, position=None, dev='cpu'):
if amplitude is None or position is None:
amplitude = torch.Tensor().to(dev)
position = torch.Tensor().to(dev)
assert(len(amplitude) == len(position)
or len(amplitude) == len(position))
if isinstance(amplitude, torch.Tensor) and isinstance(position,
torch.Tensor):
self.a = amplitude.to(dev)
self.x = position.to(dev)
elif isinstance(amplitude, np.ndarray) and isinstance(position,
np.ndarray):
self.a = torch.from_numpy(amplitude).to(dev)
self.x = torch.from_numpy(position).to(dev)
elif isinstance(amplitude, list) and isinstance(position, list):
self.a = torch.tensor(amplitude).to(dev)
self.x = torch.tensor(position).to(dev)
else:
raise TypeError("Please check the format of your input")
self.N = len(amplitude)
def __add__(self, m):
a_new = torch.cat((self.a, m.a))
x_new = torch.cat((self.x, m.x))
return Mesure2D(a_new, x_new, dev=device)
def __eq__(self, m):
if m == 0 and (self.a == [] and self.x == []):
return True
if isinstance(m, self.__class__):
return self.__dict__ == m.__dict__
return False
def __ne__(self, m):
return not self.__eq__(m)
def __str__(self):
return(f"{self.N} δ-pics \nAmplitudes : {self.a}" +
f"\nPositions : {self.x}")
def to(self, dev):
"""
Sends the Measure2D object to the `device` component (the processor or
the Nvidia graphics card)
Parameters
----------
dev : str
Either `cpu`, `cuda` (default GPU) or `cuda:0`, `cuda:1`, etc.
Returns
-------
None.
"""
return Mesure2D(self.a, self.x, dev=dev)
def kernel(self, dom, noyau='gaussienne', dev=device):
r"""
Applies a kernel to the discrete measure :math:`m`.
Supported: convolution with Gaussian kernel.
Parameters
----------
dom: :py:class:`covenant.Domain2D`
Domain where the acquisition in :math:`\mathrm{L}^2(\mathcal{X})`
of :math:`m` lives.
kernel: str, optional
Class of the kernel applied to the measurement. Only the classes
'gaussienne' and 'fourier' are currently supported, the Laplace
kernel or the Laplace kernel or the Airy function will probably be
implemented in a future version. The default is 'gaussienne'.
Raises
------
TypeError
The kernel is not yet implemented.
NameError
The kernel is not recognised by the function.
Returns
-------
acquired: Tensor
Matrix discretizing :math:`\Phi(m)` .
"""
N = self.N
x = self.x
a = self.a
X_domain = dom.X
Y_domain = dom.Y
if dev == 'cuda':
acquis = torch.cuda.FloatTensor(X_domain.shape).fill_(0)
else:
acquis = torch.zeros(X_domain.shape)
if noyau == 'gaussienne':
sigma = dom.sigma
for i in range(0, N):
acquis += a[i] * gaussienne_2D(X_domain - x[i, 0],
Y_domain - x[i, 1],
sigma)
return acquis
if noyau == 'fourier':
f_c = dom.sigma
f_c_vec = torch.arange(- f_c, f_c + 1)
imag = torch.complex(torch.tensor(0), torch.tensor(1))
acquis = a * torch.exp(-2 * imag * np.pi * f_c_vec * x)
return acquis
if noyau == 'laplace':
raise TypeError("Pas implémenté.")
raise NameError("Unknown kernel.")
def cov_kernel(self, dom):
r"""
Covariance kernel associated with the measure :math:`m` on the domain
`dom`.
Parameters
----------
dom: :py:class:`covenant.Domain2D`
Domain where the acquisition in :math:`\mathrm{L}^2(\mathcal{X})`
of :math:`m` lives.
Returns
-------
acquired: Tensor
Matrix discretizing :math:`\Lambda(m)` .
"""
X_domain = dom.X
Y_domain = dom.Y
sigma = dom.sigma
N_ech = dom.N_ech
N = self.N
x = self.x
amp = self.a
if device == 'cuda':
acquis = torch.cuda.FloatTensor(N_ech**2, N_ech**2).fill_(0)
else:
acquis = torch.zeros(N_ech**2, N_ech**2)
for i in range(0, N):
noyau = gaussienne_2D(X_domain - x[i, 0],
Y_domain - x[i, 1],
sigma)
noyau_re = noyau.reshape(-1)
acquis += amp[i] * torch.outer(noyau_re, noyau_re)
return acquis
def acquisition(self, dom, echantillo, bru):
r"""
Simulates an acquisition for the measurement.
Parameters
----------
dom: :py:class:`covenant.Domain2D`
Domain where the acquisition in :math:`\mathrm{L}^2(\mathcal{X})`
of :math:`m` lives.
echantillo : double
Format of the square matrix of noises. Hierher to be expanded on
domains in rectangle.
bru: Noises
The object contains all the values defining the noise to
be simulated.
Raises
------
NameError
The specified noise type is not recognised by the function.
Returns
-------
acquired : Tensor
Vector discretizing acquisition :math:`\Phi(m)`.
"""
fond = bru.fond
nv = bru.niveau
type_de_bruits = bru.type
if type_de_bruits == 'unif':
w = (nv * torch.rand((echantillo, echantillo))).to(device)
simul = self.kernel(dom, noyau='gaussienne')
acquis = simul + w + fond
return acquis
if type_de_bruits == 'gauss':
simul = self.kernel(dom, noyau='gaussienne')
w = torch.normal(0, nv, size=(echantillo, echantillo)).to(device)
acquis = simul + w + fond
return acquis
if type_de_bruits == 'poisson':
w = nv * torch.poisson(dom.X)
simul = w * self.kernel(dom, noyau='gaussienne')
acquis = simul + fond
raise NameError("Unknown type of noise")
def graphe(self, dom, lvl=50, noyau='gaussienne'):
"""
Plot the functiun through the Gaussian kernel.
Parameters
----------
dom: :py:class:`covenant.Domain2D`
Domain where the acquisition in :math:`\mathrm{L}^2(\mathcal{X})`
of :math:`m` lives.
lvl : int, optional
Number of level lines. The default is 50.
Returns
-------
None.
"""
# f = plt.figure()
X_domain = dom.X
Y_domain = dom.Y
plt.contourf(X_domain, Y_domain, self.kernel(dom, noyau=noyau),
lvl, label='$y_0$', cmap='hot')
plt.xlabel('X', fontsize=18)
plt.ylabel('Y', fontsize=18)
plt.title('$\Phi y$', fontsize=18)
plt.colorbar()
plt.grid()
plt.show()
def tv(self):
r"""
TV norm of the measure.
Returns
-------
double
:math:`|m|(\mathcal{X})`, the TV-norm of :math:`m`.
"""
try:
return torch.linalg.norm(self.a, ord=1)
except ValueError:
return 0
def export(self, dom, obj='covar', dev=device, title=None, legend=False):
r"""
Export the measure plotted through a kernel
Parameters
----------
dom: :py:class:`covenant.Domain2D`
Domain where the acquisition in :math:`\mathrm{L}^2(\mathcal{X})`
of :math:`m` lives.
obj : str, optional
Either 'covar' to reconstruct wrt covariance either 'acquis'
to recostruct wrt to the temporal mean. The default is 'covar'.
dev: str
Either `cpu`, `cuda` (GPU par défaut) or `cuda:0`, `cuda:1`, etc.
title : str, optional
Title of the ouput image file. The default is None.
legend : boolean, optional
Boolean: should a legend be written. The default is True.
Raises
------
TypeError
The provided name for the plot file is not a string.
Returns
-------
None.
"""
result = self.kernel(dom, dev=dev) # Really fast if you have
# CUDA enabled
if dev != 'cpu':
result = result.to('cpu')
if title is None:
title = 'fig/reconstruction/experimentals.png'
elif isinstance(title, str):
title = 'fig/reconstruction/' + title + '.png'
else:
raise TypeError("You ought to give a str type name for the plot")
if legend == True:
if obj == 'covar':
plt.title(r'Reconstruction $\Phi(m_{M,x})$ ' +
f'with N = {m.N}', fontsize=20)
elif obj == 'acquis':
plt.title(r'Reconstruction $\Phi(m_{a,x})$ ' +
f'with N = {m.N}', fontsize=20)
plt.imshow(result, cmap='hot')
plt.colorbar()
plt.xlabel('X', fontsize=18)
plt.ylabel('Y', fontsize=18)
plt.colorbar()
plt.show()
plt.savefig(title, format='pdf', dpi=1000,
bbox_inches='tight', pad_inches=0.03)
else:
plt.imsave(title, result, cmap='hot', vmax=13)
print("[+] Measure saved")
def show(self, dom, acquis):
"""
Plot the Dirac measure as points with the acquisition in the
background.
Parameters
----------
dom: :py:class:`covenant.Domain2D`
Domain where the acquisition in :math:`\mathrm{L}^2(\mathcal{X})`
of :math:`m` lives.
acquis: Tensor
Vector of the observation, will be compared with the action of the
operator on the measure :math:`m`.
Returns
-------
None.
"""
plt.figure()
cont1 = plt.contourf(dom.X, dom.Y, acquis, 100, cmap='gray')
for c in cont1.collections:
c.set_edgecolor("face")
plt.colorbar()
plt.scatter(self.x[:, 0], self.x[:, 1], marker='+', c='orange',
label='Spikes', s=dom.N_ech*self.a)
plt.legend()
def energie(self, dom, acquis, regul, obj='covar', bruits='gauss'):
r"""
Energy of the measure for the Covenant problem
:math:`(\mathcal{Q}_\lambda (y))` or BLASSO on
the average acquisition :math:`(\mathcal{P}_\lambda (\overline{y}))`.
Parameters
----------
dom: :py:class:`covenant.Domain2D`
Domain where the acquisition in :math:`\mathrm{L}^2(\mathcal{X})`
of :math:`m` lives.
acquis: Tensor
Vector of the observation, will be compared with the action of the
operator on the measure :math:`m`.
regul : double, optional
Regularisation parameter `\lambda`.
obj : str, optional
Either 'covar' to reconstruct wrt covariance either 'acquis'
to recostruct wrt to the temporal mean. The default is 'covar'.
bruits: str, optional
The object contains all the values defining the noise to be
simulated.
Raises
------
NameError
The kernel is not recognised by the function.
Returns
-------
double
Evaluation of :math:`T_\lambda` energy for :math:`m` measurement.
"""
# normalis = torch.numel(acquis)
normalis = 1
if bruits == 'poisson':
if obj == 'covar':
R_nrj = self.cov_kernel(dom)
attache = 0.5 * torch.linalg.norm(acquis - R_nrj)**2 / normalis
parcimonie = regul*self.tv()
return attache + parcimonie
if obj == 'acquis':
simul = self.kernel(dom)
attache = 0.5 * torch.linalg.norm(acquis - simul)**2 / normalis
parcimonie = regul*self.tv()
return attache + parcimonie
elif bruits in ('gauss', 'unif'):
if obj == 'covar':
R_nrj = self.cov_kernel(dom)
attache = 0.5 * torch.linalg.norm(acquis - R_nrj)**2 / normalis
parcimonie = regul*self.tv()
return attache + parcimonie
if obj == 'acquis':
simul = self.kernel(dom)
attache = 0.5 * torch.linalg.norm(acquis - simul)**2 / normalis
parcimonie = regul*self.tv()
return attache + parcimonie
raise NameError("Unknown kernel")
raise NameError("Unknown noise")
def save(self, path='saved_objects/measure.pt'):
"""
Save the measure in the given `path` file
Parameters
----------
path : str, optional
Path and name of the saved measure object. The default is
'saved_objects/measure.pt'.
Returns
-------
None.
"""
torch.save(self, path)
def prune(self, tol=1e-4):
r"""
Discard the :math:`\delta`-peaks of very low amplitudes
(can be understood as numerical artifacts).
Parameters
----------
tol : double, optional
Tolerance below which Dirac measures are not kept. The default is
1e-3.
Returns
-------
m : Mesure2D
Discrete measures without the low-amplitudes :math:`\delta`-peaks.
"""
# nnz = np.count_nonzero(self.a)
nnz_a = self.a.clone().detach()
nnz = nnz_a > tol
nnz_a = nnz_a[nnz]
nnz_x = self.x.clone().detach()
nnz_x = nnz_x[nnz]
m = Mesure2D(nnz_a, nnz_x, dev=device)
return m
# def merge_spikes(mes, tol=1e-3):
# """
# Retire les :math:`\delta`-pic doublons, sans considération sur l'amplitude.
# Parameters
# ----------
# mes : Mesure2D
# Mesure dont on veut retirer les :math:`\delta`-pics doublons.
# tol : double, optional
# Tolérance pour la distance entre les points. The default is 1e-3.
# Returns
# -------
# new_mes : Mesure2D
# Mesure sans les :math:`\delta`-pics doublons.
# """
# mat_dist = cdist(mes.x, mes.x)
# idx_spurious = np.array([])
# list_x = np.array([])
# list_a = np.array([])
# for j in range(mes.N):
# for i in range(j):
# if mat_dist[i, j] < tol:
# coord = [int(i), int(j)]
# idx_spurious = np.append(idx_spurious, np.array(coord))
# idx_spurious = idx_spurious.reshape((int(len(idx_spurious)/2), 2))
# idx_spurious = idx_spurious.astype(int)
# if idx_spurious.size == 0:
# return mes
# else:
# cancelled = []
# for i in range(mes.N):
# if i in cancelled or i in idx_spurious[:, 0]:
# cancelled = np.append(cancelled, i)
# else:
# if list_x.size == 0:
# list_x = np.vstack([mes.x[i]])
# else:
# list_x = np.vstack([list_x, mes.x[i]])
# list_a = np.append(list_a, mes.a[i])
# return Mesure2D(list_a, list_x)
def mesure_aleatoire(N, dom):
r"""
Created a random measure of N :math:`\delta`-peaks with random amplitudes
between 0.5 and 1.5.
Parameters
----------
N : int
Number of :math:`\delta`-peaks to put in the discrete measure.
dom : Domain2D
Domain where the :math:`\delta`-peaks will be put.
Returns
-------
m : :class:`Mesure2D`
Discrete measure composed of N distinct :math:`\delta`-peaks.
"""
x = dom.x_gauche + torch.rand(N, 2) * (dom.x_droit - dom.x_gauche)
a = 0.5 + torch.rand(N)
return Mesure2D(a, x)
def phi(m, dom, obj='covar'):
r"""
Compute the output of an acquisition operator with measure :math:`m` as
an input
Parameters
----------
m : Mesure2D
Discrete measure on :math:`\mathcal{X}`.
dom : Domain2D
Domain :math:`\mathcal{X}` on which the acquisition of :math:`m`
is computed in :math:`\mathrm{L}^2(\mathcal{X})` if the objective is
acquisition or :math:`\mathrm{L}^2(\mathcal{X^2})` if the objective is
covariance.
obj : str, optional
Provide the objective of the operator. The default is 'covar'.
Raises
------
TypeError
The operator's objective (or rather its kernel) is not recognised.
Returns
-------
Tensor
Returns :math:`\Phi(m)` if the objective is acquisition, and
:math:`\Lambda(m)` if the objective is covariance.
"""
if obj == 'covar':
return m.cov_kernel(dom)
if obj == 'acquis':
return m.kernel(dom)
raise NameError('Unknown BLASSO target.')
def phi_vecteur(a, x, dom, obj='covar'):
r"""
Compute the output image of the forward operator evaluated on the discrete
measure :math:`m_{a,x}` with amplitude a and position x as an input.
Parameters
----------
a : array_like
Luminosity vector, ought to have the same number of elements as
:math:`x`.
x : array_like
Luminosity vector, ought to have the same number of elements as
:math:`a`.
dom : Domain2D
Domain :math:`\mathcal{X}` on which the acquisition of :math:`m`
is computed in :math:`\mathrm{L}^2(\mathcal{X})` if the objective is
acquisition or :math:`\mathrm{L}^2(\mathcal{X^2})` if the objective is
covariance.
obj : str, optional
Provide the objective of the operator. The default is 'covar'.
Raises
------
TypeError
The operator's objective (or rather its kernel) is not recognised.
Returns
-------
Tensor
Returns :math:`\Phi(m)` if the objective is acquisition, and
:math:`\Lambda(m)` if the objective is covariance.
"""
if obj == 'covar':
m_tmp = Mesure2D(a, x)
return m_tmp.cov_kernel(dom)
if obj == 'acquis':
m_tmp = Mesure2D(a, x)
return m_tmp.kernel(dom)
raise TypeError('Unknown BLASSO target.')
def phiAdjoint(acquis, dom, obj='covar'):
r"""
Compute the adjoint operator.
Parameters
----------
acquis : Tensor
Either the acquisition :math:`y` or the covariance :math:`R_y`.
dom : Domain2D
Domain :math:`\mathcal{X}` on which the acquisition of :math:`m`
is computed in :math:`\mathrm{L}^2(\mathcal{X})` if the objective is
acquisition or :math:`\mathrm{L}^2(\mathcal{X^2})` if the objective is
covariance.
obj : str, optional
Provide the objective of the operator. The default is 'covar'.
Raises
------
TypeError
The operator's objective (or rather its kernel) is not recognised.
Returns
-------
eta : Tensor
Continuous function, element of :math:`\mathscr{C}(\mathcal{X})`,
discretised. Useful to compute the discretisation of the certificate
:math:`\eta` associated to the measure.
"""
N_ech = dom.N_ech
sigma = dom.sigma
if obj == 'covar':
(X_big, Y_big) = dom.big()
h_vec = gaussienne_2D(X_big, Y_big, sigma, undivide=__normalis_PSF__)
h_vec2 = torch.pow(h_vec, 2)
h_ker = h_vec2.reshape(1, 1, N_ech*2-1, N_ech*2-1)
diacquis = torch.diag(torch.abs(acquis)).reshape(N_ech, N_ech)
y_arr = diacquis.reshape(1, 1, N_ech, N_ech)
eta = torch.nn.functional.conv2d(h_ker, y_arr, stride=1)
eta = torch.flip(torch.squeeze(eta), [1, 0])
return eta
if obj == 'acquis':
(X_big, Y_big) = dom.big()
h_vec = gaussienne_2D(X_big, Y_big, sigma, undivide=__normalis_PSF__)
h_ker = h_vec.reshape(1, 1, N_ech*2-1, N_ech*2-1)
y_arr = acquis.reshape(1, 1, N_ech, N_ech)
eta = torch.nn.functional.conv2d(h_ker, y_arr, stride=1)
eta = torch.flip(torch.squeeze(eta), [1, 0])