forked from pog2/python_estimation_PolInSAR
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtomosar_synth.py
More file actions
2099 lines (1745 loc) · 78.1 KB
/
Copy pathtomosar_synth.py
File metadata and controls
2099 lines (1745 loc) · 78.1 KB
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 -*-
""" Classe TomoSARDataSet_synth et routines associées"""
from __future__ import division
import plot_tomo as pt
import sys
import numpy as np
import numpy.linalg as npl
import matplotlib.mlab as mat
import matplotlib.pyplot as plt
import stat_SAR as st
import RVoG_MB as mb
import basic_lib as bl
import os
import pdb
plt.ion()
class TomoSARDataSet_synth:
""" Classe TomoSARDataSet_synth permettant de stocker/analyser
des données mutlibaseline-polarimetrique."""
def __init__(self,param):
"""Initialisation de la classe à l'aide d'un object type param_rvog."""
self.k_z = param.k_z
self.theta = param.theta
self.T_vol = param.T_vol
self.T_ground = param.T_ground
self.h_v = param.h_v
self.z_g = param.z_g
self.extinction = param.sigma_v
#Na nombre d'antennes
self.Na = param.Na
#Données
self.imgMhh = [None]*self.Na
self.imgMhv = [None]*self.Na
self.imgMvh = [None]*self.Na
self.imgMvv = [None]*self.Na
self.Ha = [None]*self.Na
def get_data_teb_rect(self, nb_echant):
"""Récupère un tableau de dimension *(Nax3)xnb_echant* contenant
les valeurs des pixels associés aux données dans la base MPMB.
Les données sont exprimées dans la base MPMB:\n
y = (hh1,hh2,..,hhNa,hv1,hv2,..,hvNa,vv1,vv2,..,vvNa)\n
**Entrée** : - nb_echant : taille de l'echantillon \n
**Sortie** : - data : matrice (3*Na,nb_echant) contenant les données
"""
Na = self.Na
taille = nb_echant
data = np.zeros((3*Na,taille), 'complex64')
for j in range(Na):
data[j,:] = self.imgMhh[j][0:taille]
data[j+Na,:] = self.imgMhv[j][0:taille]
data[j+2*Na,:] = self.imgMvv[j][0:taille]
return data
def get_data_rect(self, nb_echant):
"""Récupère un tableau de dimension *(3xNa)xnb_echant* contenant
les valeurs des pixels associes aux données en base lexicographique.
Les données sont exprimées dans la base lexicographique:
y = (hh1,hv1,vv1,hh2,hv2,vv2,...,hhNa,hvNa,vvNa)
**Entrée** : - nb_echant : taille de l'echantillon \n
**Sortie** : - data : matrice (3*Na,nb_echant) contenant les données
"""
Na = self.Na
taille = nb_echant
data = np.zeros((3*Na,taille), 'complex64')
if (taille > self.N):
print "Taille d'echantillon trop grande!!"
#cas monostatique : hv = vh
for j in range(Na):
data[3*j,:] = self.imgMhh[j][0:taille]
data[3*j+1,:] = self.imgMhv[j][0:taille]
data[3*j+2,:] = self.imgMvv[j][0:taille]
return data
def get_ha_single_rect(self,ant1,ant2):
"""Renvoie la hauteur d'ambigüité entre les antennes *ant1* et *ant2*.
**Entrées**: -*anti* : indice de l'antenne *i* (doit appartenir à *[0,Na-1]*)\n
**Sortie**: -*ha_single* : hauteur d'ambiguité
"""
H=self.Ha
sign=0
if (ant1>ant2):
ant1,ant2 = (ant2,ant1)
sign = -1
elif (ant1<ant2):
sign = 1
else:
print 'Dans get_ha_single_rect'
print "Attention! : Même valeur! ant1=",ant1,"ant2=",ant2
ha_single= sign*1/((-1/H[ant1]+1/H[ant2]))
return ha_single
def get_k_z(self,ant1,ant2):
"""Renvoie la sensibilité interferometrique
k_z entre les anntennes *ant1* et *ant2*.
**Entrées**: -*anti*: indice de l'antenne *i* (doit appartenir à [0,Na-1])
**Sortie**: -*k_z_ant1_ant2*: sensibilité interfométrique entre *ant1* et *ant2*
"""
k_z = self.k_z
k_z_ant1_ant2 = -k_z[ant1]+k_z[ant2]
return k_z_ant1_ant2
def get_W_k_rect(self,param,nb_echant):
"""Renvoie la matrice de covariance en coordonnées MPMB.
**Entrées**
* *param* : classe de paramètre rvog
* *nb_echant* : taille d'echantillon
**Sortie**:
* *covar* : matrice de covariance
"""
Ups = param.get_upsilon_gt()
k = st.generate_PolInSAR(Ups,nb_echant)
covar_lexi = k.dot(k.T.conj())/nb_echant
covar_mpmb = UPS_to_MPMB(covar_lexi)
return covar_mpmb
def get_W_k_norm_rect(self,param,nb_echant,type_norm='ps+tebald'):
"""Renvoie la matrice de covariance normalisée en coordonnées MPMB.
**Entrées**:
* *param*: classe de paramètre rvog
* *nb_echant*: taille d'echantillon
* *type_norm*: type de normalisation
* *mat+ps*: Application d'une normalisation+egalisation des rep polarmietrique
* *mat+ps+tebald*: precedent + normalisation selon chque recepteur et polar
* *ps+tebald*: egalisation des reps polar+tebald
**Sortie**:
* *covar* : matrice de covariance
"""
Na = self.Na
covar_mpmb = self.get_W_k_rect(param,nb_echant,Na)
if type_norm =='mat+ps':
covar_norm = normalize_MPMB_mat_PS(covar_mpmb,Na)
elif type_norm =='ps+tebald':
covar_norm = normalize_MPMB_PS_Tebald(covar_mpmb,Na)
elif type_norm == 'mat+ps+tebald':
covar_norm = normalize_MPMB_mat_PS_Tebald(covar_mpmb,Na)
else:
print 'Attention Type de normalisation inconnu ! '
return covar_norm
def get_covar_rect(self,param,nb_echant):
#Na = self.Na
covar_mpmb = self.get_W_k_rect(param,nb_echant)
covar_lexico = MPMB_to_UPS(covar_mpmb)
"""
data = self.get_data_rect(nb_echant,Na)
covar = data.dot(data.T.conj())/nb_echant
"""
return covar_lexico
def normalize_MPMB_mat_PS(W,Na):
"""Normalisation de la matrice de covariance pour imposer
la stationnarité polarimétrique (PS)
(hh1=hh2=..=hhNa; hv1=hv2...=hvNa et vv1=vv2=...=vvNa)
Version inspirée de la méthode de Pascale:\n
#. Passage dans la base lexicographie
#. Normalisation (operation matricielle)
#. Passage base MPMB (operation matricielle)
**Entrées**:
* *W* : matrice de covariace (base MPMB)
* *Na* : nombre d'antennes
**Sortie**:
* *W_cal* : matrice de covariance normalisée (base MPMB)
"""
Cal = np.zeros((3*Na,3*Na),'float')
Ups_cal = np.zeros((3*Na,3*Na),'complex64')
Ups_cal2 = np.zeros((3*Na,3*Na),'complex64')
cal_hh = np.zeros((Na-1,1),'float')
cal_hv = np.zeros((Na-1,1),'float')
cal_vv = np.zeros((Na-1,1),'float')
T = np.zeros((Na,3,3),'complex64')
Ups = MPMB_to_UPS(W,Na)
for i in range(Na-1):
cal_hh[i]=np.sqrt(np.real(Ups[0,0]/Ups[3*(i+1),3*(i+1)]))
cal_hv[i]=np.sqrt(np.real(Ups[1,1]/Ups[3*(i+1)+1,3*(i+1)+1]))
cal_vv[i]=np.sqrt(np.real(Ups[2,2]/Ups[3*(i+1)+2,3*(i+1)+2]))
vec_diag_cal = np.vstack((np.vstack((cal_hh,cal_hv)),cal_vv))
Cal[0:3,0:3] = np.eye(3)
Cal[3:,3:] = np.diagflat(vec_diag_cal)
Ups_cal = Cal.dot(Ups.dot(Cal))
Ups_cal2 = Ups_cal.copy()
for i in range(Na):
T[i][:,:] = Ups_cal[i*3:i*3+3,i*3:i*3+3].copy()
mean_T = T.mean(0)
for i in range(Na):
Ups_cal2[i*3:i*3+3,i*3:i*3+3] = mean_T
W_cal = UPS_to_MPMB(Ups_cal2)
return W_cal
def normalize_MPMB_mat_PS_Tebald(W,Na):
"""Applique la normalisation \'mat+ps\' puis celle de Tebaldini.
Normalisation tebaldini: normalisation selon chaquee canal et recepteur
Gamma = (E-1/2 Ups E-1/2 avec E=diag(Ups))
**Entrées**:
* *W* : matrice de covariace (base MPMB)
* *Na* : nombre d'antennes
**Sortie**:
* *Gamma* : matrice de covariance normalisée (base MPMB)
"""
W_norm = normalize_MPMB_mat_PS(W,Na)
E = power(np.diag(np.diag(W_norm.copy())),-0.5)
Gamma = E.dot(W_norm.dot(E))
return Gamma
def normalize_MPMB_PS_Tebald(W,Na):
"""Normalisation de la matrice de covariance exprimée dans la base MPMB.
La normalisation s\'effectue deux étapes:
#. Stationnarité polarimetrique: *T1 = T2 = ... = 1/N sum Ti*
#. Normalisation selon chaquee canal et recepteur (tebaldini) : Ups_norm=(E-1/2 Ups E-1/2 avec E=diag(Ups))
**Entrées**:
* *W* : matrice de covariance (base MPMB)
* *Na* : nombre d'antennes
**Sortie** :
* *W_norm* : matrice de covariance normalisée (base MPMB)
* *E* : diag(W_PS) avec W_PS, Ups_PS exprimé dans la base MPMB
"""
T = np.zeros((Na,3,3),'complex64')
Ups_PS = np.zeros((3*Na,3*Na),'complex64')
Ups_norm = np.zeros((3*Na,3*Na),'complex64')
Ups = MPMB_to_UPS(W)
for i in range(Na):
T[i][:,:] = Ups[i*3:i*3+3,i*3:i*3+3].copy()
mean_T = T.mean(0)
Ups_PS = Ups.copy()
for i in range(Na):
Ups_PS[i*3:i*3+3,i*3:i*3+3] = mean_T
E = power(np.diag(np.diag(Ups_PS.copy())),-0.5)
Ups_norm,E = blanch(Ups_PS)
#Passage dans base MPMB
W_norm = UPS_to_MPMB(Ups_norm)
E = UPS_to_MPMB(E)
return W_norm,E
def blanch(A):
"""Blanchiement de la matrice A
A_blanc=(E-1/2 A E-1/2 avec E=diag(A))\n
**Entrée** : A matrice à blanchir\n
**Sorties**
* *A_blanc* : matrice blanchie
* *EE* : EE=E^-1/2
"""
EE = power(np.diag(np.diag(A)),-0.5)
A_blanc = EE.dot(A.dot(EE))
return A_blanc,EE
def deblanch(W_blanc,E):
"""Deblanchi la matrice W_blanc
E etant la mat diagonale contenant les
coeff diagonoaux (puissance -1/2) de la matrice
non blanchie"""
F = npl.inv(E)
return F.dot(W_blanc.dot(F))
def retranch_phig(zg,R_t,vec_kz):
"""Retranche la phase du sol aux matrices R_t.
**Entrées** :
* *zg* : altitude du sol
* *R_t* : liste de matrices matrices structures (decomposition SKP).
Contient les réponses interferométrique de chaque baseline
* *vec_kz* : vecteur contenant les kz dans l'ordre i<j
ex en dual-baseline vec_kz=kz12,kz13,kz23
**Sortie** :
* *R_t* : liste des matrices de structures avec phase du sol retranchée.
"""
Na=mb.get_Na_from_Nb(len(vec_kz))
print Na
for p in range(len(R_t)):
for i in range(len(vec_kz)):
idx=mb.get_idx_dble_from_idx_mono(i,Na)
R_t[p][idx[0],idx[1]] = R_t[p][idx[0],idx[1]]*np.exp(-1j*vec_kz[i]*zg)
R_t[p][idx[1],idx[0]] = R_t[p][idx[1],idx[0]]*np.exp(+1j*vec_kz[i]*zg)
return R_t
def retranch_phig_W(zg,W,vec_kz):
"""Retranche la phase du sol
au niveau de la matrice de covariance (base MPMB)
**Entrées** :
* *zg* : altitude du sol
* *W* : mat de covariance (base MPMB)
* *vec_kz* : vecteur contenant les kz dans l'ordre i<j\n
ex en dual-baseline vec_kz=kz12,kz13,kz23
"""
Na=mb.get_Na_from_Nb(len(vec_kz))
Ups = MPMB_to_UPS(W)
mat_rot = np.ones(Ups.shape,dtype='complex')
p=0
for i in range(Na-1):
for j in range(i+1,Na):
mat_rot[3*i:3*(i+1),3*j:3*(j+1)] = np.ones((3,3))*np.exp(-1j*vec_kz[p]*zg)
mat_rot[3*j:3*(j+1),3*i:3*(i+1)] = np.ones((3,3))*np.exp(+1j*vec_kz[p]*zg)
p = p+1
Ups_rot = Ups*mat_rot #multip terme à terme
W_rot = UPS_to_MPMB(Ups_rot)
return W_rot
def sqrt_inverse(covar):
"""Retourne atemp verifiant atemp.dot(a_temp))=inv(covar)"""
w,v=npl.eig(covar)
atemp=np.sqrt(np.diag(1/w.real))
atemp=v.dot(atemp.dot(v.T.conj()))
return atemp
def sqrt_matrix(covar):
w,v=npl.eig(covar)
atemp=np.diag(np.sqrt(w.real))
atemp=v.dot(atemp.dot(v.T.conj()))
return atemp
def covar_inverse(covar):
w,v=npl.eig(covar)
atemp=(np.diag(1/w.real))
atemp=v.dot(atemp.dot(v.T.conj()))
return atemp
def polinsar_compute_omega12blanchi_basic(covar):
"""Calcule la matrice omega blanchi au sens de FF
Attention la matrice doit être une 6x6
**Entrée** : covar : matrice de covariance (base lexico)\n
**Sortie** : covar : matrice de covariance normalisée (base lexico)\n
"""
t11=covar[0:3,0:3]
t22=covar[3:6,3:6]
omega=covar[0:3,3:6]
omega_blanchi=sqrt_inverse(t11).dot(omega.dot(sqrt_inverse(t22)))
return omega_blanchi
def polinsar_compute_omega12blanchi(covar):
"""Calcule la matrice omega blanchi au sens de FF
cela devrait marcher aussi pour la CP.\n
Attention la matrice doit être une 6x6.
**Entrée** : covar : matrice de covariance (base lexico)\n
**Sortie** : covar : matrice de covariance normalisée (base lexico)\n
"""
temp=np.vsplit(covar,2)
bloc=[np.hsplit(temp[0],2),np.hsplit(temp[1],2)]
omega_blanchi=sqrt_inverse(bloc[0][0]).dot(bloc[0][1].dot(sqrt_inverse(bloc[1][1])))
return omega_blanchi
def polinsar_estime_droite(omega):
"""Estimation des paramètres de la droite de cohérence
par la Méthode FF améliorée \n
**Entrée** : omega : matrice de réponse interférométrique\n
**Sorties** :
* *theta* : angle d\'inclinaison par rapport à l\'axe horizontal
* *d* : distance à l'origine
"""
j=complex(0.,1.)
pi_delta=omega-omega.T.conj()
pi_sigma=omega+omega.T.conj()
k_delta=pi_delta - pi_delta.trace()/3.*np.eye(3)
k_sigma=pi_sigma - pi_sigma.trace()/3.*np.eye(3)
#calcul des droites
vc= -2*j*k_delta.dot(k_sigma).trace() + (j*(k_delta.dot(k_delta)+k_sigma.dot(k_sigma))).trace()
theta1 = 0.5* np.arctan2(np.imag(j*vc), np.real(j*vc))
theta2 = 0.5* np.arctan2(np.imag(-j*vc), np.real(-j*vc))
d1 = (np.sin(theta1)*pi_sigma.trace() - j*np.cos(theta1)*pi_delta.trace())/6
d2 = (np.sin(theta2)*pi_sigma.trace() - j*np.cos(theta2)*pi_delta.trace())/6
#Calcl des critères 1 et 2
n1 = np.cos(theta1)*pi_delta+j*np.sin(theta1)*pi_sigma-2*j*d1*np.eye(3)
c1 = ((n1.dot(n1.T.conj())).trace()).real
n2 = np.cos(theta2)*pi_delta + j*np.sin(theta2)*pi_sigma -2*j*d2*np.eye(3)
c2=((n2.dot(n2.T.conj())).trace()).real
d1=d1.real
d2=d2.real
if (c1 < c2):
theta1,theta2=theta2,theta1
d1,d2=d2,d1
return theta2,d2
def polinsar_ground_selection(covar,phi1,phi2,critere):
"""Suivant le critère choisi, on sélectionne la phase du sol entre phi1 et phi2
Les critètres possibles sont hh-hv, hh-vv, hhmvv-hv"""
j=complex(0,1)
vect_droite=np.exp(j*phi2)-np.exp(j*phi1)
if critere == 'hh-hv':
canop = covar[1,4]/np.sqrt(covar[1,1]*covar[4,4]) # le hv est proche du haut de la canopee
groun = covar[0,3]/np.sqrt(covar[0,0]*covar[3,3]) # le hh est proche du bas de la canopee
elif critere == 'hh-vv':
canop = covar[2,5]/np.sqrt(covar[2,2]*covar[5,5]) # le vv est proche du haut de la canopee
groun = covar[0,3]/np.sqrt(covar[0,0]*covar[3,3]) # le hh est proche du bas de la canopee
elif critere == 'hhmvv-hv':
canop = covar[1,4]/np.sqrt(covar[1,1]*covar[4,4]) # le hv est proche du haut de la canopee
temp=np.eye(6)
temp[0,2] = -1
temp[2,0] = 1
temp[3,5] = -1
temp[5,3] = 1
covart=temp.dot(covar.dot(temp.T))
groun = covart[0,3]/np.sqrt(covart[0,0]*covart[3,3]) # le hhmvv est proche du bas de la canopee
vect_coh=canop-groun
c1=(vect_droite*np.conj(vect_coh)).real
if c1 < 0:
phi1,phi2 = phi2,phi1
return phi1,phi2
def polinsar_phase_intersection_cu(covar,theta2,d2,critere):
#phi1,phi2 deux angles possible pour le sol
phi1=np.pi/2-theta2+np.arccos(d2)
phi2=np.pi/2-theta2-np.arccos(d2)
if phi1 < 0:
phi1 += 2*np.pi
if (phi2 < 0):
phi2=phi2+2*np.pi
phi1,phi2=polinsar_ground_selection(covar,phi1,phi2,critere)
return phi1,phi2
def polinsar_calcul_phig_psi(covar,critere='hh-hv'):
"""Effectue le calcul de la phase du sol et de ouverture angulaire
à partir de la matrice de covariance
Le critere est hh-hv,hh-vv,hhmvv-hv. Cette function retourne la
phase du sol et le psi (phi2-phi)"""
omega = polinsar_compute_omega12blanchi(covar)
theta2,d2 = polinsar_estime_droite(omega)
phi1,phi2 = polinsar_phase_intersection_cu(covar,theta2,d2,critere)
return phi1,phi2-phi1
def polinsar_gamav(costeta,kz,extinction,hv):
"""Calcul la cohérence interférométrique du volume seul à partir de
du costeta (cosinus de l'angle d'incidence, du kz, de l'extinction et du hv"""
alpha=2*extinction/costeta
a=np.exp(-alpha*hv)
I1=(1-a)/alpha
I2=(np.exp(complex(0.,1.)*kz*hv)-a)/(complex(0,1)*kz+alpha)
return I2/I1
def polinsar_plot_cu(covar,title =' CU'):
"""Plot the cohérence region associated with the 6x6 covariance matrix
covar"""
covarn = covar
plt.figure(1)
plt.axes(polar=True)
#plt.title='test'
T1=covarn[:3,:3]
omega = covarn[:3,3:]
#tracer plusieurs cohérences obtenues de manière alléatoire
k=np.random.randn(20000,3) + 1j*np.random.randn(20000,3)
power = ((k.dot(T1))*(np.conj(k))).sum(axis=1)
interf = ((k.dot(omega))*(np.conj(k))).sum(axis=1)/power
plt.plot(np.angle(interf),abs(interf),'c.')
# tracer la droite de cohérence
phig,psi = polinsar_calcul_phig_psi(covarn,'hh-hv')
plt.plot([phig,phig+psi],[1.,1.])
# tracer quelques points remarquables HH, HV, VV, phiG
ghh = omega[0,0]/T1[0,0]
plt.plot(np.angle(ghh),abs(ghh),'ro')
ghv = omega[1,1]/T1[1,1]
plt.plot(np.angle(ghv),abs(ghv),'go')
gvv = omega[2,2]/T1[2,2]
plt.plot(np.angle(gvv),abs(gvv),'bo')
plt.plot(phig,1.,'ko')
plt.text(1.,1.2,title)
def polinsar_plot_cu_orientation(covar,title=' CU'):
"""Plot the cohérence region associated with the 6x6 covariance matrix
covar - explore the orientation effect"""
covarn = normalize_T1T2(covar)
#plt.figure(num)
p1=plt.figure()
plt.axes(polar=True)
T1=covarn[:3,:3]
omega = covarn[:3,3:]
# tracer plusieurs cohérences obtenues de manière alléatoire
ia=[0,0,2,2]
ib=[0,2,0,2]
T2=covarn[ia,ib]
T2.shape=(2,2)
omega2=omega[ia,ib]
omega2.shape=(2,2)
k=np.random.randn(500,2) + 1j*np.random.randn(500,2)
power = ((k.dot(T2))*(np.conj(k))).sum(axis=1)
interf = ((k.dot(omega2))*(np.conj(k))).sum(axis=1)/power
plt.plot(np.angle(interf),abs(interf),'y.')
T2=covarn[:2,:2]
omega2=omega[:2,:2]
k=np.random.randn(500,2) + 1j*np.random.randn(500,2)
power = ((k.dot(T2))*(np.conj(k))).sum(axis=1)
interf = ((k.dot(omega2))*(np.conj(k))).sum(axis=1)/power
plt.plot(np.angle(interf),abs(interf),'c.')
T2=covarn[1:3,1:3]
omega2=omega[1:3,1:3]
k=np.random.randn(500,2) + 1j*np.random.randn(500,2)
power = ((k.dot(T2))*(np.conj(k))).sum(axis=1)
interf = ((k.dot(omega2))*(np.conj(k))).sum(axis=1)/power
plt.plot(np.angle(interf),abs(interf),'m.')
# tracer la droite de cohérence
phig,psi = polinsar_calcul_phig_psi(covarn,'hh-hv')
plt.plot([phig,phig+psi],[1.,1.])
# tracer quelques points remarquables HH, HV, VV, phiG
ghh = omega[0,0]/T1[0,0]
plt.plot(np.angle(ghh),abs(ghh),'ro')
ghv = omega[1,1]/T1[1,1]
plt.plot(np.angle(ghv),abs(ghv),'go')
gvv = omega[2,2]/T1[2,2]
plt.plot(np.angle(gvv),abs(gvv),'bo')
omegab=polinsar_compute_omega12blanchi(covarn)
plt.plot(phig,1.,'ko')
plt.text(1.,1.2,title)
#pylab.show()
return
def display_inversion_result(result):
plt.figure()
plt.imshow(result[0])
plt.colorbar()
plt.figure()
plt.imshow(result[1])
plt.colorbar()
return
def calcul_matrix_derive(a,b,I1,I2,alpha,kz,hv,tvol,tground,omega):
matrix_derive=np.zeros((6,6,20),dtype='complex')
# dérivation par rapport à Tvol
AA=[[1,0,0],[0,0,0],[0,0,0]]
AA1=np.dot(I1,AA)
AA2=np.dot(I2*b,AA)
matrix_derive[:,:,0]=np.vstack( (np.hstack( (AA1,AA2) ),
np.hstack( (np.conj(AA2.transpose()),AA1) ) ))
AA=[[0,0,0],[0,1,0],[0,0,0]]
AA1=np.dot(I1,AA)
AA2=np.dot(I2*b,AA)
matrix_derive[:,:,1]=np.vstack( (np.hstack( (AA1,AA2) ),
np.hstack( (np.conj(AA2.transpose()),AA1) ) ))
AA=[[0,0,0],[0,0,0],[0,0,1]]
AA1=np.dot(I1,AA)
AA2=np.dot(I2*b,AA)
matrix_derive[:,:,2]=np.vstack( (np.hstack( (AA1,AA2) ),
np.hstack( (np.conj(AA2.transpose()),AA1) ) ))
AA=[[0,1,0],[1,0,0],[0,0,0]]
AA1=np.dot(I1,AA)
AA2=np.dot(I2*b,AA)
matrix_derive[:,:,3]=np.vstack( (np.hstack( (AA1,AA2) ),
np.hstack( (np.conj(AA2.transpose()),AA1) ) ))
AA=[[0,1j,0],[-1j,0,0],[0,0,0]]
AA1=np.dot(I1,AA)
AA2=np.dot(I2*b,AA)
matrix_derive[:,:,4]=np.vstack( (np.hstack( (AA1,AA2) ),
np.hstack( (np.conj(AA2.transpose()),AA1) ) ))
AA=[[0,0,1],[0,0,0],[1,0,0]]
AA1=np.dot(I1,AA)
AA2=np.dot(I2*b,AA)
matrix_derive[:,:,5]=np.vstack( (np.hstack( (AA1,AA2) ),
np.hstack( (np.conj(AA2.transpose()),AA1) ) ))
AA=[[0,0,1j],[0,0,0],[-1j,0,0]]
AA1=np.dot(I1,AA)
AA2=np.dot(I2*b,AA)
matrix_derive[:,:,6]=np.vstack( (np.hstack( (AA1,AA2) ),
np.hstack( (np.conj(AA2.transpose()),AA1) ) ))
AA=[[0,0,0],[0,0,1],[0,1,0]]
AA1=np.dot(I1,AA)
AA2=np.dot(I2*b,AA)
matrix_derive[:,:,7]=np.vstack( (np.hstack( (AA1,AA2) ),
np.hstack( (np.conj(AA2.transpose()),AA1) ) ))
AA=[[0,0,0],[0,0,1j],[0,-1j,0]]
AA1=np.dot(I1,AA)
AA2=np.dot(I2*b,AA)
matrix_derive[:,:,8]=np.vstack( (np.hstack( (AA1,AA2) ),
np.hstack( (np.conj(AA2.transpose()),AA1) ) ))
# dérivation par rapport à Tground
AA=[[1,0,0],[0,0,0],[0,0,0]]
AA1=np.dot(a,AA)
AA2=np.dot(a*b,AA)
matrix_derive[:,:,9]=np.vstack( (np.hstack( (AA1,AA2) ),
np.hstack( (np.conj(AA2.transpose()),AA1) ) ))
AA=[[0,0,0],[0,1,0],[0,0,0]]
AA1=np.dot(a,AA)
AA2=np.dot(a*b,AA)
matrix_derive[:,:,10]=np.vstack( (np.hstack( (AA1,AA2) ),
np.hstack( (np.conj(AA2.transpose()),AA1) ) ))
AA=[[0,0,0],[0,0,0],[0,0,1]]
AA1=np.dot(a,AA)
AA2=np.dot(a*b,AA)
matrix_derive[:,:,11]=np.vstack( (np.hstack( (AA1,AA2) ),
np.hstack( (np.conj(AA2.transpose()),AA1) ) ))
AA=[[0,1,0],[1,0,0],[0,0,0]]
AA1=np.dot(a,AA)
AA2=np.dot(a*b,AA)
matrix_derive[:,:,12]=np.vstack( (np.hstack( (AA1,AA2) ),
np.hstack( (np.conj(AA2.transpose()),AA1) ) ))
AA=[[0,1j,0],[-1j,0,0],[0,0,0]]
AA1=np.dot(a,AA)
AA2=np.dot(a*b,AA)
matrix_derive[:,:,13]=np.vstack( (np.hstack( (AA1,AA2) ),
np.hstack( (np.conj(AA2.transpose()),AA1) ) ))
AA=[[0,0,1],[0,0,0],[1,0,0]]
AA1=np.dot(a,AA)
AA2=np.dot(a*b,AA)
matrix_derive[:,:,14]=np.vstack( (np.hstack( (AA1,AA2) ),
np.hstack( (np.conj(AA2.transpose()),AA1) ) ))
AA=[[0,0,1j],[0,0,0],[-1j,0,0]]
AA1=np.dot(a,AA)
AA2=np.dot(a*b,AA)
matrix_derive[:,:,15]=np.vstack( (np.hstack( (AA1,AA2) ),
np.hstack( (np.conj(AA2.transpose()),AA1) ) ))
AA=[[0,0,0],[0,0,1],[0,1,0]]
AA1=np.dot(a,AA)
AA2=np.dot(a*b,AA)
matrix_derive[:,:,16]=np.vstack( (np.hstack( (AA1,AA2) ),
np.hstack( (np.conj(AA2.transpose()),AA1) ) ))
AA=[[0,0,0],[0,0,1j],[0,-1j,0]]
AA1=np.dot(a,AA)
AA2=np.dot(a*b,AA)
matrix_derive[:,:,17]=np.vstack( (np.hstack( (AA1,AA2) ),
np.hstack( (np.conj(AA2.transpose()),AA1) ) ))
#Dérivation par rapport à zg
AA1=np.zeros((3,3))
AA2=np.dot(1j*kz,omega)
matrix_derive[:,:,18]=np.vstack( (np.hstack( (AA1,AA2) ),
np.hstack( (np.conj(AA2.transpose()),AA1) ) ))
AA1 = np.dot(-alpha*a,tground)+np.dot(-a,tvol)
xtamp = (1j*kz*np.exp(1j*kz*hv)+alpha*a) / (1j*kz+alpha)
AA2 = np.dot(b*xtamp,tvol)+np.dot(-alpha*a*b,tground)
matrix_derive[:,:,19]=np.vstack( (np.hstack( (AA1,AA2) ),
np.hstack( (np.conj(AA2.transpose()),AA1) ) ))
return matrix_derive
def sm_separation(W,Np,Na,Ki=2):
"""Separation de plusieurs mecanismes de diffusion à partir de la matrice
de covariance (base MPMB)
Implémentation de la méthode de Telbaldini.
**Entrées** :
* *W* : matrice de covariance des données (base MPMB) normalisée .
* *Ki* : nombre de mécanismes de rétro-diff (SM)
* *Np* : nombre de polarisation (3 en FullPol)
* *Na* : nombre d'antennes
**Sorties** :
* *R_t* : liste de matrices. Contient les matrices de strctures
* *C_t* : liste de matrices. Contient les matrices de reponse polarimetriques
* *G* : matrice de covariance des données (base MPMB)
"""
G = W.copy()#Sans normalisation. Normalisation censée être faite avant)"
P_G = p_rearg(G,Np,Na)
"""Attention : la fonction SVD renvoie
A = U S V.H
Donc pour acceder aux vecteurs singuliers droits
il faut prendre le .H de la sortie si on veut
que les vecteurs soit stockés en colonnes
"""
mat_u,lmbda,mat_v_H = npl.svd(P_G)
mat_v = mat_v_H.T.conj()
#extraction des 2 premiers termes de la svd
mat_u = mat_u[:,0:Ki]#Conserver les Ki premiers colonnnes
mat_v = mat_v[:,0:Ki]#Conserver les Ki premiers colonnnes
lmbda = lmbda[0:Ki]
U=[np.zeros((Np,Np))]*Ki
V=[np.zeros((Na,Na))]*Ki
C_t=[np.zeros((Np,Np))]*Ki
R_t=[np.zeros((Na,Na))]*Ki
#extraction des C_tilde et R_tilde
for k in range(Ki):
U[k] = vec2mat(mat_u[:,k],3)#selection des Ki premiers vec sing gauche
V[k] = vec2mat(mat_v[:,k],Na)#selection des Ki premiers vec sing droits
C_t[k] = lmbda[k]*U[k]
R_t[k] = V[k].conj()
R_t_00 = R_t[k][0,0]
R_t[k] = R_t[k]/R_t_00#normalisation
C_t[k] = C_t[k]*R_t_00
return R_t,C_t,G
def ground_selection_MB(R_t,interv_a,interv_b):
"""Selection du sol selon le criètre : \|coherence\| la plus elevée
**Entrées** :
* *R_t* : liste de matrice contenant les matrices de structures
du sol et du volume
* *interv_a* : intervale de valuer possible pour a (cohérence du sol)
* *interv_b* : intervale de valuer possible pour b (cohérence du volume)
NB : un critère de def-positivité de matrice R_k et C_k permet d\'obtenir
les valeurs de a (resp. de b) possibles pour calculer la matrice
de structure du sol (resp. du volume) à partir de la décomposition SKP
(cf Algebraic synthesis of forest scenarios[...]
Attention : ne fonctionne seuleement qu'en MB
(en SB \|gammav\|=1 possible pour le sol ET le volume)"""
vec_gamma = np.zeros((4,1),dtype='complex')
amin = interv_a[0][0]
amax = interv_a[0][1]
bmin = interv_b[0][0]
bmax = interv_b[0][1]
val = np.array([amin,amax,bmin,bmax])
for i in range(4):
vec_gamma[i] = val[i]*R_t[0][0,1]+(1-val[i])*R_t[1][0,1]
idx_gmax = np.argmax(np.abs(vec_gamma))
gmax =np.max(np.abs(vec_gamma))
if idx_gmax == 0 or idx_gmax == 1:
#la cohé max (signature du sol) est atteint pr des val de l'interv_a
# a <=> sol donc on ne change rien
interv_a_good =interv_a
interv_b_good =interv_b
elif idx_gmax == 2 or idx_gmax == 3:
#la cohé max est atteint pr des val de l'interv_b
# b <=> vol Donc on inverse interva et interv b
#pour que la branche b coresp au vol et branche a au sol
print 'grd selection : inversion interval'
interv_a_good = interv_b
interv_b_good = interv_a
return interv_a_good,interv_b_good
def value_R_C(R_t,C_t,a,b):
"""Calcul des matrices de structures (R_t) et de réponses polarimétriques
C_k à partir des valeurs a et b
Attention : R_t,C_t doivent être sous forme diagonale. Voir
Tebaldini, Algebraic synthesis of forest scenarios[...]
N.B : W = R_t[0]oC_t[0] + R_t[1]oC_t[1] (o : prod de kronecker)
**Entrées** :
* *R_t* : liste des matrices de structure
* *C_t* : liste des réponses polarimétrique
* *a,b* : scalaires fixant la cohérence du sol (resp. du volume)
**Sorties** :
* *vap* : valeurs diagonales de R1,R2,C1 et C2 dans un seul vecteur
* *R1*, *R2* : matrice de struce du sol et du volume
* *C1*,*C2* : reponse polarimétique du sol et du volume
"""
R1 = a*R_t[0]+(1-a)*R_t[1]
R2 = b*R_t[0]+(1-b)*R_t[1]
C1 = 1/(a-b)*((1-b)*C_t[0]-b*C_t[1])
C2 = 1/(a-b)*(-(1-a)*C_t[0]+a*C_t[1])
#Renvoi des valeurs diagonales dans un seul vecteur
vap_a = np.hstack((np.diag(R1),np.diag(C2)))
vap_b = np.hstack((np.diag(R2),np.diag(C1)))
vap = np.hstack((vap_a,vap_b))
return vap,R1,R2,C1,C2
def taille_intervb(R_t,interv_b):
"""Renvoie la taille de l'intervalle des gammav possibles
Si le nbre de baseline est superieur à 1 interv size
est un vecteur contenant la taille de l'intervalle sur
chaque baseline.
**Entrées** :
* *R_t* : liste des matrices de structure
* *interv_b* : liste contenant les bornes inf et sup de l'interval de
*b* possibles (cohérence du volume)
**Sorties** :
* *interv_size* : taille des intervalles de cohérences possibles
"""
Na = R_t[0].shape[0]
interv_size = np.zeros(Na)
Rv0= interv_b[0][0]*R_t[0]+(1-interv_b[0][0])*R_t[1]
Rv1= interv_b[0][1]*R_t[0]+(1-interv_b[0][1])*R_t[1]
vec_gamma0 = gamma_from_Rv(Rv0) #ensemble des cohé b=bmin
vec_gamma1 = gamma_from_Rv(Rv1) #ensemble de cohéb=bmax
interv_size=np.abs(vec_gamma0-vec_gamma1)
return interv_size
def gamma_a_b(R_t,a,b,ant1=0,ant2=1):
"""Renvoie la coherence de chaque R_k pour une valeur du couple
(a,b) (Ki=2)"""
gamma1 = a*R_t[0][ant1,ant2]+(1-a)*R_t[1][ant1,ant2]
gamma2 = b*R_t[0][ant1,ant2]+(1-b)*R_t[1][ant1,ant2]
return gamma1,gamma2
def rac_def_pos(R_t,a,b):
"""Calcul les racines du polyme pdp pour
une valeur de gamma_v définie par b"""
Na = R_t[0].shape[0]
Nb_baseline = int(Na*(Na-1)/2)
gamma_Rv = np.zeros(Nb_baseline,dtype='complex')
idx_g=0
for i in range(Na-1):
for j in range(i+1,Na):
#print i,j,idx_g,b*R_t[0][i,j]+(1-b)*R_t[1][i,j] #debug
gamma_Rv[idx_g] = b*R_t[0][i,j]+(1-b)*R_t[1][i,j]
idx_g +=1
ratio = gamma_Rv[1]/(gamma_Rv[0]**2) #g13/g12^2
z,alpha,beta,r1,r2,coeffa = pol_pdp(ratio)
return gamma_Rv,ratio,r1,r2,a
def pol_pdp(ratio):
"""Renvoie les racine du polynomes verfié par \|gamma12\|²
dans le cas de 3 Baselines et
les hypothèses *g12 = g12g12*alpha*exp(i*beta)*
et *g23 = g12* """
z= 1-ratio
alpha = np.abs(ratio)
beta = np.angle(ratio)
r1 = (np.abs(z)-1)/(alpha*(alpha-2*np.cos(beta)))
r2 = -(np.abs(z)+1)/(alpha*(alpha-2*np.cos(beta)))
coeffa = -alpha*(alpha-2*np.cos(beta))
return z,alpha,beta,r1,r2,coeffa
def interv_possible(alpha,mat_cond,Na):
"""Renvoi les intervalles pour a et b dont les valeurs donnent des
matrices R_t et C_t définies positives
**Entrées**
* *alpha* : racines des equations de positivité
* *mat_cond* : matrice binaire dont l'état correspond à la validation
de la condition de positivité (1 si vraie 0 sinon)
**Sorties** :
* *interv_a*, *interv_b* : intervalles possibles pour a et b
"""
index = zip(*np.where(mat_cond==1))
#Construction de la matrice contenant les valeurs des intervales
#on a (Na + 3) 'alpha' (Na par les mat R_k, 3 par les mat C_k)
#interv possible ]-oo;a0],[a0,a1],..,[a_Na+1,a_Na+2],[a_Na+2,+oo]
# soit Na+4 intervalle
"""Préferons la redondance à l'errance"""
mat_interv = np.ndarray((Na+4,Na+4),dtype=object) #array contenant des tuples
interv_a=[]
interv_b=[]
#les quatres coins particulier
mat_interv[0,0] = ((-np.inf,alpha[0]),(-np.inf,alpha[0]))
mat_interv[0,-1] = ((-np.inf,alpha[0]),(alpha[-1],np.inf))
mat_interv[-1,0] = ((alpha[-1],np.inf),(-np.inf,alpha[0]))
mat_interv[-1,-1] = ((alpha[-1],np.inf),(alpha[-1],np.inf))
#Remplissage des lignes et colonnes exterieures
for i in range(1,Na+3):# indice de 1 à Na+2 =>Na+2 elements
#parcours des lignes exterieures
mat_interv[i,0] = ((alpha[i-1],alpha[i]),(-np.inf,alpha[0]))
mat_interv[i,-1] = ((alpha[i-1],alpha[i]),(alpha[-1],np.inf))
#parcours des colonnes exterieures
mat_interv[0,i] = ((-np.inf,alpha[0]),(alpha[i-1],alpha[i]))
mat_interv[-1,i] = ((alpha[-1],np.inf,),(alpha[i-1],alpha[i]))
#Carré interieur
for i in range(1,Na+3):
for j in range(1,Na+3):
mat_interv[i,j]=((alpha[i-1],alpha[i]),(alpha[j-1],alpha[j]))
#SUGGESTIONS DE MODIF : AU LIEUR DE PRENDRE LA MOITIE ARBITRAITEMENT
# PRENDRE LES a>b ou a<b
if len(index)%2==0 and len(index)>1:
for i in range(len(index)//2): #On en la moitié (mat_interv symetrique)
interv_a.append(mat_interv[index[i]][0])
interv_b.append(mat_interv[index[i]][1])
elif len(index)==1:
interv_a.append(mat_interv[index[0]][0])
interv_b.append(mat_interv[index[0]][1])
return interv_a,interv_b
def search_space_definition(R_t,C_t,Na):
"""Permet de déterminer l'interval des valeurs possibles de a et b
en fonction des valeurs des valeurs propres R_t_diag et C_t_diag.
**Entrées** :
* *R_t* : liste des matrices de structure
* *C_t* : liste des réponses polarimétrique
* *Na* : nombre d'antennes
**Sorties** :
* *interv_a,interv_b* : intervals possibles pour les val. de a et b
* *mat_cond* : matrice contenant 1 si la condition de positivité est
vérifiée, 0 sinon.
* *alpha* : liste des valeurs ou les équations de positivité s'annulent
"""
#Nombre de SM
Ki=2
R_t_diag=[None]*Ki # Ki vecteurs (de dimensiosn Na) contenant les vap
C_t_diag=[None]*Ki
alpha_C = np.zeros((3,1))
alpha_R = np.zeros((Na,1))
# 'Diagonalisation 'commun
R_t_diag[0],R_t_diag[1],_,_ = ejd(R_t[0],R_t[1]) #ndice ~ k ~ num du SM
C_t_diag[0],C_t_diag[1],_,_ = ejd(C_t[0],C_t[1])
#definition des bords des intervalles possibles
for i in range(Na):
alpha_R[i]=np.real(R_t_diag[1][i,i]\
/(R_t_diag[1][i,i]-R_t_diag[0][i,i]))
for i in range(3):
alpha_C[i] = np.real(C_t_diag[0][i,i]\
/(C_t_diag[0][i,i]+C_t_diag[1][i,i]))
#on classe les alpha relatif à a et b (ce sont les même pour a ou b)
alpha = np.vstack((alpha_R,alpha_C))
alpha= np.real(alpha)
alpha.sort(0) #0 pour classer selon la premier dimension c.a.d les lignes
interv_a = [] #contient les intervales où les contraintes de positiv sont
interv_b = [] #valides. (a_min,a_max)
Sa=1 #seuil
a_test_debut= [alpha[0]-Sa]
a_test_mil = [(alpha[i]+alpha[i+1])/2 for i in range(alpha.size-1)]
a_test_fin = [alpha[-1]+Sa]
a_test = a_test_debut+a_test_mil+a_test_fin
beta = 0.75
Sb = 2 #seuil
b_test_debut= [alpha[0]-Sb]
b_test_mil = [(beta*alpha[i]+(1-beta)*alpha[i+1]) for i in range(alpha.size-1)]
b_test_fin = [alpha[-1]+Sb]
b_test = b_test_debut+b_test_mil+b_test_fin
mat_cond = np.zeros((len(a_test),len(b_test)))
mat_cond_vap = np.zeros((len(a_test),len(b_test)))
for i,a in enumerate(a_test):
for j,b in enumerate(b_test):
mat_cond[i,j] = positivity_condition(R_t_diag,C_t_diag,a,b)
#Verification: mat_cond doit être symetrique
if np.sum(mat_cond-mat_cond.T != 0):
print 'Attention matrice de conditions non symetrique !!'
else:
index = zip(*np.where(mat_cond==1))
#Construction de la matrice contenant les valeurs des intervales
#on a (Na + 3) 'alpha' (Na par les mat R_k, 3 par les mat C_k)