-
Notifications
You must be signed in to change notification settings - Fork 4
/
massive.py
1599 lines (1275 loc) · 52.4 KB
/
massive.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
'''
Class that deals with a massive TS inversion (all pixels at the same time).
Written by R. Jolivet 2017
License:
MPITS: Multi-Pixel InSAR Time Series
Copyright (C) 2018 <Romain Jolivet>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
'''
import numpy as np
import sys
import scipy.linalg as lm
import scipy.io as sio
import h5py
import datetime as dt
import tsinsar as ts
import os
import copy
import itertools
import matplotlib.pyplot as plt
from . import utils
class tsmassive(object):
def __init__(self, name, massiveObject=None):
'''
Initializes the class
Args:
* name : Name of the project.
'''
# Stores the name somewhere
self.name = name
# Store if the problem has been solved
self.solved = False
# Initialize stuffs
self.orbitMinWeight = None
if massiveObject is None:
# Import a bunch of stuff to initialize the mpi communicator
import mpi4py
from mpi4py import MPI
# Stores the communicator
self.MPI = MPI
self.Com = MPI.COMM_WORLD
# Initialize the rank
self.rank = self.Com.Get_rank()
# Import a bunch of stuff to initialize the petsc business
import petsc4py
petsc4py.init(sys.argv,comm=self.Com)
from petsc4py import PETSc
# Store PETSc into self
self.PETSc = PETSc
else:
self.PETSc = massiveObject.PETSc
self.MPI = massiveObject.MPI
self.Com = massiveObject.Com
self.rank = massiveObject.Com.Get_rank()
# Ignore zero entries in mat() and vec()
self.ZER = self.PETSc.Mat.Option.IGNORE_ZERO_ENTRIES
# Insert, rather than Add
self.INS = self.PETSc.InsertMode.INSERT_VALUES
# Add, rather than insert
self.ADD = self.PETSc.InsertMode.ADD_VALUES
# PETSc options
self.Opt = self.PETSc.Options()
# Print stuff to show it has been initialized
self.PETSc.Sys.Print('-------------------------------------------------------')
self.PETSc.Sys.Print('-------------------------------------------------------')
self.PETSc.Sys.Print(' ')
self.PETSc.Sys.Print(' Massive Time Series Inversion System ')
self.PETSc.Sys.Print(' ')
self.PETSc.Sys.Print('-------------------------------------------------------')
self.PETSc.Sys.Print('-------------------------------------------------------')
# Set masterindex to 0
self.masterind = 0
# All done
return
def Finalize(self):
'''
Finalize the MPI and PETSc dudes.
'''
# Finalize PETSc
self.PETSc._finalize()
# Finalize MPI
self.MPI.Finalize()
# All done
return
def Barrier(self):
'''
Implements a MPI Barrier.
'''
# Barrier
self.Com.Barrier()
# All done
return
def setMasterInd(self, masterind):
'''
Set the index of the master date.
Args:
* masterind : Index of the master date.
'''
# Set it
self.masterind = masterind
# Move the time vector
if hasattr(self, 'ti'):
self.masterTime = copy.deepcopy(self.ti[masterind])
self.ti -= self.ti[masterind]
# All done
return
def Limits(self, stay, endy, stax, endx, stey=1, stex=1, dx=1., dy=1.):
'''
Sets the limits for the domain to compute on the interferogram.
Args:
* stay : First line to include.
* endy : Last line to include.
* stax : First column to include.
* endx : Last column to include.
* dx : Size of the pixels along range (same unit as Lambda)
* dy : Size of the pixels along azimuth (same unit as Lambda)
'''
self.stay = stay
self.endy = endy
self.stax = stax
self.endx = endx
self.stey = stey
self.stex = stex
self.dx = dx*stex
self.dy = dy*stey
# All done
return
def HDF5open(self, inputname, outputname):
'''
Opens the input HDF5 file to read the data.
Args:
* inputname : Name of the hdf5 file to open.
* outputname: Name of the output hdf5 file.
'''
self.PETSc.Sys.Print('-------------------------------------------------------')
self.PETSc.Sys.Print(' ')
self.PETSc.Sys.Print(' Open input (%s) and output (%s) HDF5 files '%(inputname, outputname))
self.PETSc.Sys.Print(' ')
# Open the file
self.hdfin = h5py.File(inputname, 'r', driver='mpio', comm=self.Com)
self.hdfout = h5py.File(outputname, 'w', driver='mpio', comm=self.Com)
# All done
return
def buildTimeMatrix(self, representation, createh5repo=True):
'''
Build the constrain matrix for a full pixel.
Args:
* representation: Functional representation of the constrained matrix.
* createh5repo : Create the dataset in the h5 file for the parameters.
'''
# Get the time
time = self.ti
dates = self.da
# Transform the dates into time
referenceTime = dt.datetime.fromordinal(int(self.da[self.masterind]))
for f, func in enumerate(representation):
for a, args in enumerate(func):
for s, spec in enumerate(args):
if type(spec)==dt.datetime:
spec = (spec - referenceTime).days/365.25
representation[f][a][s] = spec
# Functional parametrization
self.rep = representation
tMatrix,mName,regF = ts.Timefn(representation,time)
Jmat = copy.deepcopy(self.Jmat)
if hasattr(self, 'masterind'):
Jmat[:,self.masterind] = 0.0
Gg = np.dot(Jmat, tMatrix)
# Size
self.nParams = tMatrix.shape[1]
# Store
self.tMatrix = tMatrix
self.Gg = Gg
self.mName = mName
# Store
if createh5repo:
self.hdfout.create_dataset('mName', data=self.mName)
#All done
return
def HDF5close(self):
'''
Close the 2 HDF5 files open.
'''
self.hdfin.close()
self.hdfout.close()
# All done
return
def LoadDataFromHDF5(self, referencePixel=None, dataStorage='igram'):
'''
Loads Stuffs from the Design Matrix
'''
self.PETSc.Sys.Print('-------------------------------------------------------')
self.PETSc.Sys.Print(' ')
self.PETSc.Sys.Print(' Get Design Matrix and Data From the h5file')
self.PETSc.Sys.Print(' ')
# Get the files
fin = self.hdfin
fout = self.hdfout
# Get the design matrix
self.Jmat = fin['Jmat'].value
# Get the numbers
self.Nifg = self.Jmat.shape[0]
self.Nsar = self.Jmat.shape[1]
# Get the dates
self.da = fin['dates'].value
self.ti = fin['tims'].value
fout.create_dataset('dates',data=self.da)
fout.create_dataset('tims',data=self.ti)
if hasattr(self, 'masterind'):
self.masterTime = copy.deepcopy(self.ti[self.masterind])
self.ti -= fin['tims'][self.masterind]
fout.create_dataset('masterind',data=self.masterind)
else:
self.masterTime = None
# Create sub data holder
igram = fin[dataStorage]
# Check something
assert igram.shape[1]>=self.endy, \
'More lines than available asked... {} / {}'.format(igram.shape[1],
self.endy)
assert igram.shape[2]>=self.endx, \
'More columns than available asked... {} / {}'.format(igram.shape[2],
self.endx)
# Some size things
lines = range(self.stay, self.endy, self.stey)
self.Ny = len(lines)
self.Nx = len(range(self.stax, self.endx, self.stex))
self.igramsub = fout.create_dataset('Data',(self.Nifg,self.Ny,self.Nx),'f')
# Read and copy sub data
isublines = utils._split_seq(lines, self.Com.Get_size())[self.Com.Get_rank()]
osublines = utils._split_seq(range(len(lines)), self.Com.Get_size())[self.Com.Get_rank()]
self.igramsub[:,osublines,:] = igram[:,isublines,self.stax:self.endx:self.stex]
# Wait until all has been copied
self.Barrier()
# Reference (only on a fraction of interfero)
if referencePixel is not None:
self.xRef, self.yRef = referencePixel
for i in utils._split_seq(range(self.igramsub.shape[0]), self.Com.Get_size())[self.Com.Get_rank()]:
assert np.isfinite(self.igramsub[i, self.yRef, self.xRef]), 'Reference is not finite on interferogram {}'.format(i)
self.igramsub[i,:,:] -= self.igramsub[i, self.yRef, self.xRef]
else:
self.xRef = None
self.yRef = None
# build arrays with that
self.da = np.array(self.da)
# All done
return
def makeMask(self, MinInt=None, MinIma=None, debug=False, minPix=10):
'''
Builds a list of x and y coordinates of the valid pixels,
together with the number of interferograms and images valid per pixel.
Args:
* MinInt : Minimum number of coherent Interferograms to accept pixel.
* MinIma : Minimum number of coherent Images to accept pixel.
* debug : If True, shows the minimum number of ifg and images requested
and the number ifg and image available per pixel
'''
self.PETSc.Sys.Print('-------------------------------------------------------')
self.PETSc.Sys.Print(' ')
self.PETSc.Sys.Print(' Determine the mask and the number of data')
self.PETSc.Sys.Print(' ')
# Limits
if MinInt is None:
Ndmin = self.Nifg
else:
Ndmin = MinInt
if MinIma is None:
Nimin = self.Nsar
else:
Nimin = MinIma
# Create a storage in the h5 file
images = self.hdfout.create_dataset('Number of Images', (self.Ny, self.Nx), dtype='f')
interferograms = self.hdfout.create_dataset('Number of Interferograms', (self.Ny, self.Nx), dtype='f')
# Allocate a list
PixList = []
IfgToDelete = []
ImagesToDelete = []
# Get the lines we are going to work on
me = self.Com.Get_rank()
size = self.Com.Get_size()
columns = utils._split_seq(range(self.Nx), size)[me]
# Loop on the pixels
for c in columns:
for l in range(self.Ny):
# Get the data
d = self.igramsub[:, l, c]
# Get the number of non-nan pixels (i.e. interferograms)
Nd = len(d[np.isfinite(d)])
# Check Number of interferos
J = np.delete(self.Jmat, np.where(np.isnan(d)), axis=0)
a = np.array([np.count_nonzero(J[:,i]) for i in range(self.Nsar)])
# Check Masterind things
if hasattr(self, 'masterind'):
if a[self.masterind] > 0:
a = np.delete(a, self.masterind)
# Number of parameters
Ni = self.Nsar-1
if hasattr(self, 'masterind'): Ni += 1
# Get the number of images
Nit = np.count_nonzero(a)
if hasattr(self, 'masterind'): Nit += 1
# Store that
images[l, c] = Nit
interferograms[l,c] = Nd
# Store these
if debug:
print('Col/Line: {}/{} Ndata, min: {}/{} Ni, min: {}/{}'.format(c,l,
Nd, Ndmin, Ni, Nimin))
if (Nd>=Ndmin) and (Nit>=Nimin):
ima = np.flatnonzero(a==0)
ifg = np.flatnonzero(np.isnan(d))
PixList.append([c, l, Nd, Ni])
IfgToDelete.append(ifg)
ImagesToDelete.append(ima)
# Reshape
PixList = np.array(PixList).reshape((len(PixList),4))
# Share lists to everyone
self.PixList = np.concatenate(self.Com.allgather(PixList)).astype(int)
self.IfgToDelete = list(itertools.chain.from_iterable(self.Com.allgather(IfgToDelete)))
self.ImagesToDelete = list(itertools.chain.from_iterable(self.Com.allgather(ImagesToDelete)))
# Number of pixels
self.Npix = self.PixList.shape[0]
assert self.Npix>minPix, 'Number of acceptable pixel is too low...'
# Compute the starting and ending lines of each pixel and the starting and ending column of Glocal
self.buildPixStartStop()
# All done
return
def fillG(self):
'''
Fill the G matrix with appropriate numbers.
'''
self.PETSc.Sys.Print('-------------------------------------------------------')
self.PETSc.Sys.Print(' ')
self.PETSc.Sys.Print(' Fill the G matrix')
self.PETSc.Sys.Print(' ')
# Get the ownerships
I = list(self.G.getOwnershipRange())
# Do not handle the last lines if minimizeorbit==True
if self.orbitMinWeight is not None and I[-1]==self.Nl:
I[-1] -= self.nOrb
# Do not handle the last line if orbitConstraints is not None
if self.orbitConstraints is not None and I[-1]==self.Nl:
I[-1] -= self.nOrb*len(self.orbitConstraints)
# Where do we start?
us, xs, ys, nis = self.line2pix(I[0])
# Where do we end?
ue, xe, ye, nie = self.line2pix(I[1]-1)
# First pixel
if nis>0: # If first pixel is incomplete, deal with its lines
nli = self.PixStartStop[us,1] - I[0]
for i in range(I[0],I[0]+nli):
# Get the pixel position and the number of the line we want
u, x, y, ni = self.line2pix(i)
# Get the corresponding line
dline, indc, oline, indo = self.getGline(u,ni)
# Fill G
self.G.setValues(i, indc, dline, self.INS)
if self.orbit and (oline is not None):
self.G.setValues(i, indo, oline, self.INS)
# Update the first pixel to deal with
us += 1
# Last pixel
if (nie<self.PixList[ue,2]-1): # If last pixel is incomplete, deal with its lines
# We deal line by line
for i in range(I[1]-(nie+1),I[1]):
# Get the pixel position and the number of the line we want
u, x, y, ni = self.line2pix(i)
# Get the corresponding line
dline, indc, oline, indo = self.getGline(u,ni)
# Fill G
self.G.setValues(i, indc, dline, self.INS)
if self.orbit and (oline is not None):
self.G.setValues(i, indo, oline, self.INS)
# Update the last pixel to deal with
ue -= 1
# Other complete pixels
for u in range(us,ue+1):
# Get G
G,iGr,iGc,O,iOr,iOc = self.getG(u)
if len(iGc)*len(iGr)!=np.prod(G.shape):
print('Soucis Worker {} Pixel {} {} \n\
iGc: {} - {} ({}) \n\
iGr: {} - {} ({})\n\
G: {}'.format(self.Com.Get_rank(), self.PixList[u,0],
self.PixList[u,1], iGc[0], iGc[-1], len(iGc),
iGr[0], iGr[-1], len(iGr), G.shape))
assert False, 'Die here'
# Set the values
self.G.setValues(iGr, iGc, G.flatten(), self.INS)
if self.orbit:
self.G.setValues(iOr, iOc, O.flatten(), self.INS)
# Minimize orbits?
if self.orbitMinWeight is not None:
line = self.orbitMinWeight*np.ones((self.OrbShape,))
for i in range(self.nOrb):
iOr = self.Nl-(i+1)
iOc = range(self.Nc-(i+1)*self.OrbShape, self.Nc-i*self.OrbShape)
self.G.setValues(iOr, iOc, line.tolist(), self.INS)
# Additional Constraints
if self.orbitConstraints is not None:
I = self.G.getOwnershipRange()
nl = self.Nl - self.nOrb*len(self.orbitConstraints) - 1
for orbit in self.orbitConstraints:
nl += 1
weight = self.orbitConstraints[orbit]['Weight']
if I[0]<=nl<I[1]: self.G.setValue(nl, self.Npar+orbit, weight, self.INS)
nl += 1
if I[0]<=nl<I[1]: self.G.setValue(nl, self.Npar+orbit+self.Nsar, weight, self.INS)
if self.nOrb>2:
nl += 1
if I[0]<=nl<I[1]: self.G.setValue(nl, self.Npar+orbit+2*self.Nsar, weight, self.INS)
# All done
return
def filld(self):
'''
Fill the vector d with the appropriate numbers.
'''
self.PETSc.Sys.Print('-------------------------------------------------------')
self.PETSc.Sys.Print(' ')
self.PETSc.Sys.Print(' Fill the data vector')
self.PETSc.Sys.Print(' ')
# Who am I
me = self.Com.Get_rank()
# Get the ownership range
Istart, Iend = self.d.getOwnershipRange()
# Do not handle last line orbitConstraints is not None
if self.orbitConstraints is not None and Iend==self.Nl:
Iend -= self.nOrb*len(self.orbitConstraints)
# Create a ifgsInG list
self.ifgsInG = [[],[],[],[]]
# Get ownerships
I = self.d.getOwnershipRanges()
# Do not handle last line orbitConstraints is not None
if self.orbitConstraints is not None and I[-1]==self.Nl:
I[-1] -= self.nOrb*len(self.orbitConstraints)
# Create a dictionary of data/worker and a dictionary of index/worker
d = {}
d['data'] = []
d['x'] = []
d['y'] = []
d['interfero'] = []
d['lines'] = []
# Store for each pixel into the appropriate data/worker vector
for pix, pss in zip(self.PixList, self.PixStartStop):
# Where do the data for this pixel start and stop
Pst = pss[0]
Ped = pss[1]
# On which worker are the starting and ending lines of this pixel
Wst = self.line2rank(Pst)
Wed = self.line2rank(Ped-1)
# Do something only if I own that pixel
if Wst==me or Wed==me:
# Get x and y
x = pix[0]
y = pix[1]
# Get the data
data = self.igramsub[:,y,x]
ilocal = np.where(np.isfinite(data))
dlocal = data[ilocal].tolist()
# Which interferograms are concerned
ifglocal = (np.arange(self.Nifg)[ilocal]).astype(int).tolist()
xlocal = (np.ones((len(ifglocal),))*x).astype(int).tolist()
ylocal = (np.ones((len(ifglocal),))*y).astype(int).tolist()
# 2 Cases:
if Wst==Wed==me: # Both start and end are on the same worker
assert len(dlocal)==Ped-Pst, 'Whhhooooaaaaa.... {} {} '.format(x,y)
d['data'].extend(dlocal)
d['x'].extend(xlocal)
d['y'].extend(ylocal)
d['interfero'].extend(ifglocal)
d['lines'].extend(range(Pst,Ped))
#print('Worker {:2d}: {:4d} {:4d} Full Pixel ({},{})'.format(me, len(dlocal), len(range(Pst,Ped)), x,y))
elif Wst==me: # I own the starting point
ed = I[Wed] - Pst
assert len(dlocal[:ed])==I[Wed]-Pst, 'Whhhooooaaaaaaa... {} {} Starting Error'.format(x,y)
d['data'].extend(dlocal[:ed])
d['x'].extend(xlocal[:ed])
d['y'].extend(ylocal[:ed])
d['interfero'].extend(ifglocal[:ed])
d['lines'].extend(range(Pst,I[Wed]))
#print('Worker {:2d}: {:4d} {:4d} Starting Point Owned'.format(me, len(dlocal[:ed]), len(range(Pst,I[Wed]))))
elif Wed==me: # I own the ending point
st = I[Wed] - Pst
assert len(dlocal[st:])==Ped-I[Wed], 'Whhhooooaaaaaaa... {} {} Starting Error'.format(x,y)
d['data'].extend(dlocal[st:])
d['x'].extend(xlocal[st:])
d['y'].extend(ylocal[st:])
d['interfero'].extend(ifglocal[st:])
d['lines'].extend(range(I[Wed],Ped))
#print('Worker {:2d}: {:4d} {:4d} Ending Point Owned'.format(me, len(dlocal[st:]), len(range(I[Wed],Ped))))
# Store values in d
self.d.setValues(d['lines'], d['data'], self.INS)
# Save x, y, ifg and lines in ifgsInG
self.ifgsInG = [d['x'], d['y'], d['interfero'], d['lines']]
# Finalize ifgsInG
self.ifgsInG = np.array(self.ifgsInG).T.astype(int)
# Add constraints if needed
if self.orbitConstraints is not None:
I = self.d.getOwnershipRange()
nl = self.Nl - self.nOrb*len(self.orbitConstraints) - 1
for orbit in self.orbitConstraints:
weight = self.orbitConstraints[orbit]['Weight']
x = self.orbitConstraints[orbit]['X ramp']
nl += 1
if I[0]<=nl<I[1]: self.d.setValue(nl, x*weight, self.INS)
y = self.orbitConstraints[orbit]['Y ramp']
nl += 1
if I[0]<=nl<I[1]: self.d.setValue(nl, y*weight, self.INS)
if self.nOrb>2:
c = self.orbitConstraints[orbit]['Constant']
nl += 1
if I[0]<=nl<I[1]: self.d.setValue(nl, c*weight, self.INS)
# All done
return
def buildOrbitMatrix(self, includeConstant=True, looseConstraints=None, strongConstraints=None):
'''
Create the Full Orbit Matrix.
The equation is orb = ax + by (+ c, if includeConstant is True).
This will also include the reference for all interferograms (they can be shifted)
orbits.
Args:
* includeConstant : Estimates a constant term
* looseConstraints : Adds constraints on the estimation of the orbits
This just adds lines to G
Default is None
example: {0: {'X ramp': 1.2,
'Y ramp': 2.0,
'Constant': 0.0,
'Weight': 100.0},
22: {'X ramp': 1.3,
'Y ramp': 2.4,
'Constant': 0.0,
'Weight': 100.0}}
* strongConstraints : Adds strong Constraints on the wanted parameters.
The parameters are taken out of the inversion (equal to 0)
Default is None
'''
# Stack them up
Orb = copy.deepcopy(self.Jmat)
# Strong Constraints
self.strongConstraints = strongConstraints
if strongConstraints is not None:
assert type(strongConstraints) in (int,list), 'strongConstraints should be of Type int or list...'
Orb = np.delete(Orb, strongConstraints, axis=1)
# Add the referencing term
refO = np.eye(self.Nifg)
# Save it
self.OrbShape = Orb.shape[1]
if includeConstant:
self.Orb = np.hstack((Orb,Orb,Orb,refO))
self.nOrb = 3
else:
self.Orb = np.hstack((Orb,Orb,refO))
self.nOrb = 2
# Save the orbital constraint
self.orbitConstraints = looseConstraints
self.strongConstraints = strongConstraints
# All done
return
def AllocateGmd(self, dryanddie=False, orbit=True, nonzerosfactor=10):
'''
Allocates the PETSc matrices.
'''
# Get the size of the matrix
self.getFullSize(orbit=orbit, nonzerosfactor=nonzerosfactor)
# Print some things
self.PETSc.Sys.Print('-------------------------------------------------------')
self.PETSc.Sys.Print(' ')
self.PETSc.Sys.Print(' Allocate G, m and d')
self.PETSc.Sys.Print(' ')
self.PETSc.Sys.Print(' Data vector size: {}'.format(self.Nl))
self.PETSc.Sys.Print(' Model parameter size: {}'.format(self.Nc))
self.PETSc.Sys.Print(' Non Zero values in the diagonal blocks: {}'.format(self.d_nz))
self.PETSc.Sys.Print(' Non Zero values in the off-diagonal part: {}'.format(self.o_nz))
if dryanddie:
self.PETSc.Sys.Print(' Dry run...')
self.Finalize()
self.HDF5close()
sys.exit()
# Data vector
self.Allocated()
# Model vector
self.Allocatem()
# Theory matrix
self.AllocateG()
# Wait
self.Barrier()
# All done
return
def Allocated(self):
'''
Allocates the data vector.
'''
# Check if it exists
if hasattr(self, 'd'):
self.d.destroy()
self.d = self.PETSc.Vec().createMPI(self.Nl, comm=self.Com)
self.d.setOption(self.ZER,1) # Ignore zero entries on d
# All done
return
def Allocatem(self):
'''
Allocates the model vector.
'''
# Check if it exists
if hasattr(self, 'm'):
self.m.destroy()
self.PETSc.Sys.Print(' ')
self.m = self.PETSc.Vec().createMPI(self.Nc, comm=self.Com)
# All done
return
def AllocateG(self):
'''
Allocate the design matrix.
'''
# Check if it exists
if hasattr(self, 'G'):
self.G.destroy()
self.G = self.PETSc.Mat().createAIJ([self.Nl, self.Nc], nnz = [self.d_nz, self.o_nz],
comm=self.Com)
self.G.setOption(self.ZER,1) # Ignore zero entrie on G
# All done
return
def AssembleGmd(self):
'''
Assembles the vector d, m and the matrix G for PETSc.
'''
self.PETSc.Sys.Print('-------------------------------------------------------')
self.PETSc.Sys.Print(' ')
self.PETSc.Sys.Print(' Assembles G, m and d')
self.PETSc.Sys.Print(' ')
# Assemble d
self.Assembled()
# Assemble m
self.Assemblem()
# Assemble G
self.AssembleG()
# All done
return
def Assemblem(self):
'''
Assembles the model vector.
'''
self.m.assemble()
# All done
return
def AssembleG(self):
'''
Assembles the Design matrix.
'''
self.G.assemble()
# All done
return
def Assembled(self):
'''
Assembles the data vector.
'''
self.d.assemble()
# All done
return
def line2rank(self, line):
'''
From the index of the line in the Global G, returns the
worker affected to that line.
Args:
* line : Line of the Global G.
'''
# Get ownerships
I = self.d.getOwnershipRanges()
# find the index of the lowest line number above line in I
up = np.flatnonzero(I>line)[0] - 1
# return
return up
def Phi2ImgPix(self, onmyown=True):
'''
Builds an array (self.imgsInPhi) with 4 columns:
[x, y, Img#, id] where id is the index of an element of self.Phi
Args:
* onmyown : If True, will only do that over the lines owned by the mpi worker
'''
# Initialize
imgsInPhi = []
# Loop over the columns
if onmyown:
I = self.Phi.getOwnershipRange()
indexes = range(I[0], I[1])
else:
indexes = range(self.Nc)
# Loop
for index in indexes:
p, x, y, ni = self.phiLine2pix(index)
if p is not None:
imgsInPhi.append([x, y, ni, index])
# Array-ize
self.imgsInPhi = np.array(imgsInPhi).astype(int)
# All done
return
def Glines2IfgPixels(self, onmyown=True):
'''
Creates an array (self.ifgsInG) with 4 columns:
[x, y, ifg#, line] where line is the number of the line in global G.
Args:
* onmyown : If True, will only do that over the lines owned by the mpi worker
'''
# Initialize a list
ifgsInG = []
# Loop over the lines of G (all or just what I own)
if onmyown:
I = self.d.getOwnershipRange()
Lines = range(I[0], I[1])
else:
Lines = range(self.Nl)
# Check minimize
if Lines[-1]==self.Nl and self.orbitMinWeight is not None:
Lines[-1] -= self.nOrb
# Loop
for l in Lines:
p, x, y, ni = self.line2pix(l, generalIfgNum=True)
if p is not None:
ifgsInG.append([x, y, ni, l])
# Array-ize
self.ifgsInG = np.array(ifgsInG).astype(int)
# All done
return
def mIndex2ParamsPixels(self, onmyown=True):
'''
Creates an array (self.parsInG) with 4 columns:
[x, y, par#, column], where line is the number of the line in Global G.
Args:
* onmyown : If True, will onle do that over the columns owned by the worker.
'''
# Initialize a list
parsInG = []
# Loop over the indexes of m
if onmyown:
I = self.m.getOwnershipRange()
Columns = range(I[0], I[1])
else:
Columns = range(self.Nc)
# Loop
for column in Columns:
u, p = self.col2pix(column)
if u is not None:
x, y = self.PixList[u,:2]
parsInG.append([x, y, p, column])
# Save
self.parsInG = np.array(parsInG)
# All done
return
def whereisXYTinPhi(self, x, y, i):
'''
From the position of a pixel (x,y) and the date index, i, get the line in self.Phi.
'''
# Which one is this pixel
u = np.where( (self.PixList[:,0] == x) & (self.PixList[:,1] == y) )[0]
# Check if the pixel is in the list
if len(u) == 0:
return None
# Find the position in Phi
pos = np.int(self.PixSSInc2Phi[u,0])
# All done
return pos
def getDataSpace(self, vector='d'):
'''
Get the vector from the self.vector PETSc vector and send them to workers.
Each worker will receive a number of residual image so they can work on them.
'''
# Which vector do I want
if type(vector) is str:
dataSpaceVector = self.__getattribute__(vector)
else:
dataSpaceVector = vector
# Who am I
me = self.Com.Get_rank()
# Create the list of which ifg goes on which worker
ifgsWanted = utils._split_seq(range(self.Nifg), self.Com.Get_size())
# 1. Send the residuals to the workers who are going to work on them
Packages = [] # In case nothing is sent here
# Iterate over the workers
for worker in range(self.Com.Get_size()):
# Create the list of things to send
ToSend = []
# Iterate over the ifgs this worker takes care of
for ifg in ifgsWanted[worker]:
# Find the lines corresponding to that interfero
ii = np.flatnonzero(self.ifgsInG[:,2] == ifg)
# Get the coordinates and lines
indx = self.ifgsInG[ii,0] # X coordinates of the pixels
indy = self.ifgsInG[ii,1] # Y coordinates of the pixels