-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathcovar_ui.py
1461 lines (1206 loc) · 66.2 KB
/
covar_ui.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# -*- coding: utf-8 -*-
"""
Copyright 2017 Bernard Giroux, Elie Dumas-Lefebvre, Jerome Simon
email: [email protected]
This file is part of BhTomoPy.
BhTomoPy 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 sys
from PyQt5 import QtGui, QtWidgets, QtCore
from model import Model
from mog import Mog
import covar
import database
import utils_ui
from utils_ui import lay, inv_lay, MyQLabel
from utils import ComputeThread
from copy import deepcopy
from math import ceil
from scipy.optimize import fmin
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg
from matplotlib.figure import Figure
import numpy as np
import unicodedata
xi = unicodedata.lookup("GREEK SMALL LETTER XI")
theta = unicodedata.lookup("GREEK SMALL LETTER THETA")
tau = unicodedata.lookup("GREEK SMALL LETTER TAU")
class CovarUI(QtWidgets.QFrame):
model = None # current model
temp_grid = None # the grid modified from covar_ui actually is only a temporary one. The
# original grid must not be modified.
updateHandler = False # selected model may seldom be modified twice. 'updateHandler' prevents
# functions from firing more than once. TODO: use a QValidator instead.
updateHandlerParameters = False
data = None # holds the model's data so that it does not need to be computed
# more than once
idata = None # idem.
L = None # ray matrix
Cd = None # experimental covariance
xc = None # grid's centers
triggerFctAdjustCov = QtCore.pyqtSignal() # Signal to update Popup while computing adjustCov
FuncCounter = 0 # Number of adjustCov call
def __init__(self, parent=None):
super(CovarUI, self).__init__()
self.setWindowTitle("BhTomoPy/Covariance")
self.triggerFctAdjustCov.connect(
self.handleAdjustCov) # Signal for computing popup, to follow the progress of adjust()
self.init_UI()
def show(self):
super(CovarUI, self).show()
# Gets initial geometry of the widget:
qr = self.frameGeometry()
# Shows it at the center of the screen
cp = QtWidgets.QDesktopWidget().availableGeometry().center()
# Moves the window's center at the center of the screen
qr.moveCenter(cp)
# Then moves it at the top left
translation = qr.topLeft()
self.move(translation)
self.update_model()
self.parameters_displayed_update()
self.update_velocity_display()
def openfile(self):
new_model = utils_ui.chooseModel(database)
if new_model is not None:
self.set_current_model(new_model)
self.mogs_list.clear()
self.mogs_list.addItems([item.name for item in self.model.mogs])
self.mogs_list.setCurrentRow(0)
self.update_model()
self.update_booleans()
self.parameters_displayed_update()
self.update_data()
def savefile(self):
self.apply_booleans()
return utils_ui.savefile(database)
def saveasfile(self):
self.apply_booleans()
return utils_ui.saveasfile(database)
def apply_booleans(self):
self.current_covar().use_xi = self.ellip_veloc_checkbox.isChecked()
self.current_covar().use_tilt = self.tilted_ellip_veloc_checkbox.isChecked()
self.current_covar().use_c0 = self.include_checkbox.isChecked()
self.flag_modified_covar()
def update_booleans(self):
covar_ = self.current_covar()
if covar_ is not None:
self.ellip_veloc_checkbox.setCheckState(covar_.use_xi)
self.tilted_ellip_veloc_checkbox.setCheckState(covar_.use_tilt)
self.include_checkbox.setCheckState(covar_.use_c0)
def set_current_model(self, model):
if self.updateHandler: # TODO unnecessary?
return
self.updateHandler = True
if self.model is not None:
if utils_ui.save_warning(database):
self.model = model
self.clear_figures()
if model.grid is not None:
self.update_temp_grid()
else:
self.model = model
self.clear_figures()
if model.grid is not None:
self.update_temp_grid()
self.updateHandler = False
def current_covar(self):
if self.model is not None and self.model.grid is not None:
if self.T_and_A_combo.currentIndex() == 0:
if self.model.tt_covar is None:
self.model.tt_covar = covar.CovarianceModel(self.model.grid.type)
covariance = self.model.tt_covar
else:
if self.model.amp_covar is None:
self.model.amp_covar = covar.CovarianceModel(self.model.grid.type)
covariance = self.model.amp_covar
return covariance
def current_mog(self):
if self.model is not None:
if self.mogs_list.currentIndex() != -1:
return database.session.query(Mog).filter(Mog.name == self.mogs_list.currentItem().text()).first()
def flag_modified_covar(self):
if self.model is not None:
self.model.modified = True
def parameters_displayed_update(self):
if self.updateHandler:
return
self.updateHandler = True
self.Sub_widget.setDisabled(True)
for item in (*self.slowness_widget, *self.xi_widget, *self.tilt_widget):
item.setHidden(True)
self.slowness_3D_widget.setHidden(True)
self.ellip_veloc_checkbox.setDisabled(True)
self.tilted_ellip_veloc_checkbox.setDisabled(True)
self.step_Y_edit.setDisabled(True)
self.covar_struct_combo.setDisabled(True)
self.btn_Add_Struct.setDisabled(True)
self.btn_Rem_Struct.setDisabled(True)
self.xi_label.setHidden(True)
self.xi_edit.setHidden(True)
self.xi_checkbox.setHidden(True)
self.tilt_label.setHidden(True)
self.tilt_edit.setHidden(True)
self.tilt_checkbox.setHidden(True)
self.Nug_groupbox.setDisabled(True)
self.auto_update_checkbox.setDisabled(True)
self.btn_compute.setDisabled(True)
self.Grid_groupbox.setDisabled(True)
self.Adjust_Model_groupbox.setDisabled(True)
if self.model is not None:
self.Sub_widget.setDisabled(False)
if self.model.grid is not None:
self.covar_struct_combo.setDisabled(False)
self.btn_Add_Struct.setDisabled(False)
self.Grid_groupbox.setDisabled(False)
if self.current_covar().covar:
self.btn_Rem_Struct.setDisabled(False)
self.Nug_groupbox.setDisabled(False)
self.auto_update_checkbox.setDisabled(False)
self.btn_compute.setDisabled(False)
self.Adjust_Model_groupbox.setDisabled(False)
if self.model.grid.type == '2D' or self.model.grid.type == '2D+':
for item in (*self.slowness_widget,):
item.setHidden(False)
self.ellip_veloc_checkbox.setDisabled(False)
if self.ellip_veloc_checkbox.isChecked():
for item in (*self.xi_widget,):
item.setHidden(False)
self.tilted_ellip_veloc_checkbox.setDisabled(False)
self.xi_label.setHidden(False)
self.xi_edit.setHidden(False)
self.xi_checkbox.setHidden(False)
if self.tilted_ellip_veloc_checkbox.isChecked():
for item in (*self.tilt_widget,):
item.setHidden(False)
self.tilt_label.setHidden(False)
self.tilt_edit.setHidden(False)
self.tilt_checkbox.setHidden(False)
else:
self.tilted_ellip_veloc_checkbox.setCheckState(False)
else:
self.tilted_ellip_veloc_checkbox.setCheckState(False)
self.ellip_veloc_checkbox.setCheckState(False)
elif self.model.grid.type == '3D':
self.slowness_3D_widget.setHidden(False)
self.step_Y_edit.setDisabled(False)
else:
self.ellip_veloc_checkbox.setCheckState(False)
self.tilted_ellip_veloc_checkbox.setCheckState(False)
else:
QtWidgets.QMessageBox.warning(self, "Warning", "This model has no grid.")
self.update_parameters()
else:
self.ellip_veloc_checkbox.setCheckState(False)
self.tilted_ellip_veloc_checkbox.setCheckState(False)
if self.T_and_A_combo.currentIndex() == 0:
self.slowness_param_edit.setText("Slowness")
self.slowness_3D_param_edit.setText("Slowness")
self.slowness_label.setText("Slowness")
self.tt_label.setText("Traveltime")
else:
self.slowness_param_edit.setText("Attenuation")
self.slowness_3D_param_edit.setText("Attenuation")
self.slowness_label.setText("Attenuation")
self.tt_label.setText(tau)
self.updateHandler = False
def auto_update(self):
if self.auto_update_checkbox.isChecked():
self.compute()
def update_model(self):
self.btn_Rem_Struct.setDisabled(True)
self.updateHandler = True
self.covar_struct_combo.clear()
self.updateHandler = False
if self.model is not None:
self.model_label.setText("Model : " + self.model.name)
if self.model.grid is not None:
self.update_structures()
if self.temp_grid is None:
ntraces = 0
for mog_ in database.session.query(Mog).all():
ntraces += mog_.data.ntrace
self.mogs_list.setCurrentRow(0)
self.cells_no_label.setText(str(self.model.grid.getNumberOfCells()))
self.reset_grid()
self.update_data()
else:
self.cells_no_label.setText('0')
self.rays_no_label.setText('0')
self.reset_grid()
else:
self.reset_grid()
def update_structures(self):
self.covar_struct_combo.clear()
current_list = self.current_covar().covar
if current_list is not None:
if not current_list:
self.add_struct()
self.covar_struct_combo.addItems(["Structure no " + str(i + 1) for i in range(len(current_list))])
self.covar_struct_combo.setCurrentIndex(0)
self.update_parameters()
self.btn_Rem_Struct.setDisabled(False)
def new_grid(self):
self.temp_grid = deepcopy(self.model.grid)
def reset_grid(self):
if self.model is None or self.model.grid is None:
self.X_min_label.setText('0')
self.X_max_label.setText('0')
self.Y_min_label.setText('0')
self.Y_max_label.setText('0')
self.Z_min_label.setText('0')
self.Z_max_label.setText('0')
self.step_X_edit.setText('0')
self.step_Y_edit.setText('0')
self.step_Z_edit.setText('0')
self.temp_grid = None
else:
self.new_grid()
self.X_min_label.setText(str(self.temp_grid.grx[0])[:7])
self.X_max_label.setText(str(self.temp_grid.grx[-1])[:7])
if self.temp_grid.gry: # TODO verify
self.Y_min_label.setText(str(self.temp_grid.gry[0])[:7])
self.Y_max_label.setText(str(self.temp_grid.gry[-1])[:7])
else:
self.Y_min_label.setText('0')
self.Y_max_label.setText('0')
self.Z_min_label.setText(str(self.temp_grid.grz[0])[:7])
self.Z_max_label.setText(str(self.temp_grid.grz[-1])[:7])
self.step_X_edit.setText(
str(2 * self.temp_grid.dx)) # by default, the step should be twice the size of the original
self.step_Y_edit.setText(
str(2 * self.temp_grid.dy)) # grid in order to make the computing less resources-expensive
self.step_Z_edit.setText(str(2 * self.temp_grid.dz))
self.update_temp_grid()
def update_temp_grid(self):
if self.temp_grid is not None and self.model.grid is not None:
if np.abs(self.temp_grid.dx - float(self.step_X_edit.text())) > 0.00001:
dx = float(self.step_X_edit.text())
nb_elements = ceil((self.model.grid.grx[-1] - self.model.grid.grx[0]) / dx)
self.temp_grid.grx = self.model.grid.grx[0] + dx * np.arange(0, nb_elements + 1)
elif np.abs(self.temp_grid.dy - float(self.step_Y_edit.text())) > 0.00001:
dy = float(self.step_Y_edit.text())
nb_elements = ceil((self.model.grid.gry[-1] - self.model.grid.gry[0]) / dy)
self.temp_grid.gry = self.model.grid.gry[0] + dy * np.arange(0, nb_elements + 1)
elif np.abs(self.temp_grid.dz - float(self.step_Z_edit.text())) > 0.00001:
dz = float(self.step_Z_edit.text())
nb_elements = ceil((self.model.grid.grz[-1] - self.model.grid.grz[0]) / dz)
self.temp_grid.grz = self.model.grid.grz[0] + dz * np.arange(0, nb_elements + 1)
self.cells_no_labeli.setText(str(self.temp_grid.getNumberOfCells()))
self.update_data()
def update_parameters(self):
self.updateHandlerParameters = True
covar_ = self.current_covar()
ind = self.covar_struct_combo.currentIndex()
if ind != -1:
if self.model.grid.type == '2D' or self.model.grid.type == '2D+':
self.slowness_type_combo.setCurrentIndex(covar_.covar[ind].type)
self.slowness_range_X_edit.setText(str(covar_.covar[ind].range[0]))
self.slowness_range_Z_edit.setText(str(covar_.covar[ind].range[1]))
self.slowness_theta_X_edit.setText(str(covar_.covar[ind].angle[0]))
self.slowness_sill_edit.setText(str(covar_.covar[ind].sill))
self.slowness_edit.setText(str(covar_.nugget_model))
self.tt_edit.setText(str(covar_.nugget_data))
if self.ellip_veloc_checkbox.isChecked():
if covar_.covar_xi[ind] is None:
covar_.covar_xi[ind] = covar.CovarianceFactory.detDefault2D()
self.xi_type_combo.setCurrentIndex(covar_.covar_xi[ind].type)
self.xi_range_X_edit.setText(str(covar_.covar_xi[ind].range[0]))
self.xi_range_Z_edit.setText(str(covar_.covar_xi[ind].range[1]))
self.xi_theta_X_edit.setText(str(covar_.covar_xi[ind].angle[0]))
self.xi_sill_edit.setText(str(covar_.covar_xi[ind].sill))
self.xi_edit.setText(str(covar_.nugget_xi))
if self.tilted_ellip_veloc_checkbox.isChecked():
if covar_.covar_tilt[ind] is None:
covar_.covar_tilt[ind] = covar.CovarianceFactory.detDefault2D()
self.tilt_type_combo.setCurrentIndex(covar_.covar_tilt[ind].type)
self.tilt_range_X_edit.setText(str(covar_.covar_tilt[ind].range[0]))
self.tilt_range_Z_edit.setText(str(covar_.covar_tilt[ind].range[1]))
self.tilt_theta_X_edit.setText(str(covar_.covar_tilt[ind].angle[0]))
self.tilt_sill_edit.setText(str(covar_.covar_tilt[ind].sill))
self.tilt_edit.setText(str(covar_.nugget_tilt))
elif self.model.grid.type == '3D':
self.slowness_3D_type_combo.setCurrentIndex(covar_.covar[ind].type)
self.slowness_3D_range_X_edit.setText(str(covar_.covar[ind].range[0]))
self.slowness_3D_range_Y_edit.setText(str(covar_.covar[ind].range[1]))
self.slowness_3D_range_Z_edit.setText(str(covar_.covar[ind].range[2]))
self.slowness_3D_theta_X_edit.setText(str(covar_.covar[ind].angle[0]))
self.slowness_3D_theta_Y_edit.setText(str(covar_.covar[ind].angle[1]))
self.slowness_3D_theta_Z_edit.setText(str(covar_.covar[ind].angle[2]))
self.slowness_3D_sill_edit.setText(str(covar_.covar[ind].sill))
self.slowness_edit.setText(str(covar_.nugget_model))
self.tt_edit.setText(str(covar_.nugget_data))
self.updateHandlerParameters = False
def apply_parameters_changes(self):
if self.updateHandlerParameters:
return
covar_ = self.current_covar()
ind = self.covar_struct_combo.currentIndex()
if self.model.grid.type == '2D' or self.model.grid.type == '2D+':
covar_.covar[ind].range[0] = float(self.slowness_range_X_edit.text())
covar_.covar[ind].range[1] = float(self.slowness_range_Z_edit.text())
covar_.covar[ind].angle[0] = float(self.slowness_theta_X_edit.text())
covar_.covar[ind].sill = float(self.slowness_sill_edit.text())
covar_.nugget_model = float(self.slowness_edit.text())
covar_.nugget_data = float(self.tt_edit.text())
if self.ellip_veloc_checkbox.isChecked():
self.loadRays()
self.computeCd()
if covar_.covar_xi[ind] is None:
covar_.covar_xi[ind] = covar.CovarianceFactory.detDefault2D()
covar_.covar_xi[ind].range[0] = float(self.xi_range_X_edit.text())
covar_.covar_xi[ind].range[1] = float(self.xi_range_Z_edit.text())
covar_.covar_xi[ind].angle[0] = float(self.xi_theta_X_edit.text())
covar_.covar_xi[ind].sill = float(self.xi_sill_edit.text())
covar_.nugget_xi = float(self.xi_edit.text())
if self.tilted_ellip_veloc_checkbox.isChecked():
if covar_.covar_tilt[ind] is None:
covar_.covar_tilt[ind] = covar.CovarianceFactory.detDefault2D()
covar_.covar_tilt[ind].range[0] = float(self.tilt_range_X_edit.text())
covar_.covar_tilt[ind].range[1] = float(self.tilt_range_Z_edit.text())
covar_.covar_tilt[ind].angle[0] = float(self.tilt_theta_X_edit.text())
covar_.covar_tilt[ind].sill = float(self.tilt_sill_edit.text())
covar_.nugget_tilt = float(self.tilt_edit.text())
elif self.model.grid.type == '3D':
covar_.covar[ind].range[0] = float(self.slowness_3D_range_X_edit.text())
covar_.covar[ind].range[1] = float(self.slowness_3D_range_Y_edit.text())
covar_.covar[ind].range[2] = float(self.slowness_3D_range_Z_edit.text())
covar_.covar[ind].angle[0] = float(self.slowness_3D_theta_X_edit.text())
covar_.covar[ind].angle[1] = float(self.slowness_3D_theta_Y_edit.text())
covar_.covar[ind].angle[2] = float(self.slowness_3D_theta_Z_edit.text())
covar_.covar[ind].sill = float(self.slowness_3D_sill_edit.text())
covar_.nugget_model = float(self.slowness_edit.text())
covar_.nugget_data = float(self.tt_edit.text())
self.flag_modified_covar()
database.modified = True
def change_covar_type_slowness(self, ctype):
if not self.updateHandler:
ind = self.covar_struct_combo.currentIndex()
cov = self.current_covar().covar[ind]
self.current_covar().covar[ind] = covar.CovarianceFactory.buildCov(ctype, cov.range, cov.angle, cov.sill)
self.flag_modified_covar()
database.modified = True
def change_covar_type_xi(self, ctype):
if not self.updateHandler:
ind = self.covar_struct_combo.currentIndex()
cov = self.current_covar().covar_xi[ind]
self.current_covar().covar_xi[ind] = covar.CovarianceFactory.buildCov(ctype, cov.range, cov.angle, cov.sill)
self.flag_modified_covar()
database.modified = True
def change_covar_type_tilt(self, ctype):
if not self.updateHandler:
ind = self.covar_struct_combo.currentIndex()
cov = self.current_covar().covar_tilt[ind]
self.current_covar().covar_tilt[ind] = covar.CovarianceFactory.buildCov(ctype, cov.range, cov.angle,
cov.sill)
self.flag_modified_covar()
database.modified = True
def add_struct(self):
if self.model.grid.type == '2D' or self.model.grid.type == '2D+':
new = covar.CovarianceFactory.detDefault2D()
elif self.model.grid.type == '3D':
new = covar.CovarianceFactory.detDefault3D()
self.current_covar().covar.append(new)
self.current_covar().covar_xi.append(None)
self.current_covar().covar_tilt.append(None)
count = self.covar_struct_combo.count()
self.covar_struct_combo.addItem('Structure no ' + str(count + 1))
self.covar_struct_combo.setCurrentIndex(count)
self.parameters_displayed_update()
self.update_parameters()
self.flag_modified_covar()
database.modified = True
def del_struct(self):
index = self.covar_struct_combo.currentIndex()
del self.current_covar().covar[index]
del self.current_covar().covar_xi[index]
del self.current_covar().covar_tilt[index]
self.covar_struct_combo.clear()
self.covar_struct_combo.addItems(["Structure no " + str(i + 1) for i in range(len(self.current_covar().covar))])
count = self.covar_struct_combo.count()
if count != 0:
if index == count:
self.covar_struct_combo.setCurrentIndex(index - 1)
else:
self.covar_struct_combo.setCurrentIndex(index)
self.parameters_displayed_update()
self.update_parameters()
self.flag_modified_covar()
database.modified = True
def handleAdjustCov(self):
self.FuncCounter += 1
self.progress_lbl.setText("Computing Iteration " + str(self.FuncCounter) + ".\nPlease wait...")
def refreshFigs(self):
"""
Refresh the Covariance and the comparaison figure
"""
g, gt = self.calculate()
n1 = range(0, len(gt))
n2 = range(0, len(g))
self.covariance_fig.plot(n2, g, n1, gt)
gmin = np.min(np.concatenate([g, gt]))
gmax = np.max(np.concatenate([g, gt]))
self.comparison_fig.plot(g, gt, gmin, gmax)
def adjustInThread(self):
try:
self.FuncCounter = 0
self.progress_lbl.setText("Computing Iteration " + "0" + ".\nPlease wait...")
self.computing_form.show()
# self.adjust()
# self.computing_form.hide()
self.compute_thread = ComputeThread(self.adjust)
self.compute_thread.finished.connect(self.adjustFinished)
self.compute_thread.start()
except Exception as ex:
print(type(ex))
print(ex.args)
print(ex)
def adjustFinished(self):
self.update_parameters()
self.refreshFigs()
self.flag_modified_covar()
database.modified = True
self.computing_form.hide()
def adjust(self):
cm = self.current_covar()
global ix
global x0
ix = 0
x0 = np.zeros(100)
ns = len(cm.covar)
def ifNotChekedAddToXi(checkbox, valueToAdd):
"""
Function to simplify the code below.
If the checkbox 'Fix' for the specify value isn't checked, add the value to the array.
"""
global ix
global x0
if not checkbox.isChecked():
x0[ix] = valueToAdd
ix += 1
for n in range(0, ns):
_covar = cm.covar[n]
if len(_covar.range) == 2:
ifNotChekedAddToXi(self.slowness_range_X_checkbox, _covar.range[0]) # Add Range X
ifNotChekedAddToXi(self.slowness_range_Z_checkbox, _covar.range[1]) # Add Range Z
ifNotChekedAddToXi(self.slowness_theta_X_checkbox, _covar.angle[0]) # Add Angle Theta X
ifNotChekedAddToXi(self.slowness_sill_checkbox, _covar.sill) # Add Sill
elif len(_covar.range) == 3:
ifNotChekedAddToXi(self.slowness_3D_range_X_checkbox, _covar.range[0]) # Add 3D Range X
ifNotChekedAddToXi(self.slowness_3D_range_Y_checkbox, _covar.range[1]) # Add 3D Range Y
ifNotChekedAddToXi(self.slowness_3D_range_Z_checkbox, _covar.range[2]) # Add 3D Range Z
ifNotChekedAddToXi(self.slowness_3D_theta_X_checkbox, _covar.angle[0]) # Add Angle Theta X
ifNotChekedAddToXi(self.slowness_3D_theta_Y_checkbox, _covar.angle[1]) # Add Angle Theta Y
ifNotChekedAddToXi(self.slowness_3D_theta_Z_checkbox, _covar.angle[2]) # Add Angle Theta Z
ifNotChekedAddToXi(self.slowness_3D_sill_checkbox, _covar.sill) # Add Sill
if self.ellip_veloc_checkbox.isChecked():
# TODO : add 3D support
_covar_xi = cm.covar_xi[n]
if len(_covar.range) == 2:
ifNotChekedAddToXi(self.xi_range_X_checkbox, _covar_xi.range[0]) # Add xi Range X
ifNotChekedAddToXi(self.xi_range_Z_checkbox, _covar_xi.range[1]) # Add xi Range Z
ifNotChekedAddToXi(self.xi_theta_X_checkbox, _covar_xi.angle[0]) # Add xi Angle Theta X
ifNotChekedAddToXi(self.xi_sill_checkbox, _covar_xi.sill) # Add xi Sill
if self.tilted_ellip_veloc_checkbox.isChecked():
_covar_tilt = cm.covar_tilt[n]
if len(_covar.range) == 2:
ifNotChekedAddToXi(self.tilt_range_X_checkbox, _covar_tilt.range[0]) # Add tilt Range X
ifNotChekedAddToXi(self.tilt_range_Z_checkbox, _covar_tilt.range[1]) # Add tilt Range Z
ifNotChekedAddToXi(self.tilt_theta_X_checkbox, _covar_tilt.angle[0]) # Add tilt Angle Theta X
ifNotChekedAddToXi(self.tilt_sill_checkbox, _covar_tilt.sill) # Add tilt Sill
# Adding nugget effect
ifNotChekedAddToXi(self.slowness_checkbox,
cm.nugget_model) # Add slowness for the slowness covariance / amplitude for the amplitude covariance
ifNotChekedAddToXi(self.tt_checkbox,
cm.nugget_data) # Add traveltime for the slowness covariance / tau for the amplitude covariance
if self.ellip_veloc_checkbox.isChecked():
ifNotChekedAddToXi(self.xi_checkbox, cm.nugget_xi) # Add nugget xi
if self.tilted_ellip_veloc_checkbox.isChecked():
ifNotChekedAddToXi(self.tilt_checkbox, cm.nugget_tilt) # Add nugget tilt
x0 = x0[:ix]
fmin(func=self.adjustCov, x0=x0, xtol=1e-12, ftol=1e-12, maxiter=int(self.Iter_edit.text()),
maxfun=int(self.Iter_edit.text()), disp=0)
def adjustCov(self, x0):
cm = self.current_covar()
global ix
ix = -1
ns = len(cm.covar)
def ifNotChekedChangeVariable(checkbox, VariableToChange):
"""
Function to simplify the code below.
If the checkbox 'Fix' for the specify value isn't checked, return the modified value.
"""
global ix
if not checkbox.isChecked():
ix += 1
return x0[ix]
else:
return VariableToChange
for n in range(0, ns):
_covar = cm.covar[n]
if len(_covar.range) == 2:
_covar.range[0] = ifNotChekedChangeVariable(self.slowness_range_X_checkbox,
_covar.range[0]) # Add Range X
_covar.range[1] = ifNotChekedChangeVariable(self.slowness_range_X_checkbox,
_covar.range[1]) # Add Range Z
_covar.angle[0] = ifNotChekedChangeVariable(self.slowness_theta_X_checkbox,
_covar.angle[0]) # Add Angle Theta X
_covar.sill = ifNotChekedChangeVariable(self.slowness_sill_checkbox, _covar.sill) # Add Sill
elif len(_covar.range) == 3:
_covar.range[0] = ifNotChekedChangeVariable(self.slowness_3D_range_X_checkbox,
_covar.range[0]) # Add 3D Range X
_covar.range[1] = ifNotChekedChangeVariable(self.slowness_3D_range_Y_checkbox,
_covar.range[1]) # Add 3D Range Y
_covar.range[2] = ifNotChekedChangeVariable(self.slowness_3D_range_Z_checkbox,
_covar.range[2]) # Add 3D Range Z
_covar.angle[0] = ifNotChekedChangeVariable(self.slowness_3D_theta_X_checkbox,
_covar.angle[0]) # Add Angle Theta X
_covar.angle[1] = ifNotChekedChangeVariable(self.slowness_3D_theta_Y_checkbox,
_covar.angle[1]) # Add Angle Theta Y
_covar.angle[2] = ifNotChekedChangeVariable(self.slowness_3D_theta_Z_checkbox,
_covar.angle[2]) # Add Angle Theta Z
_covar.sill = ifNotChekedChangeVariable(self.slowness_3D_sill_checkbox, _covar.sill) # Add Sill
if self.ellip_veloc_checkbox.isChecked():
# TODO : add 3D support
_covar_xi = cm.covar_xi[n]
if len(_covar.range) == 2:
_covar_xi.range[0] = ifNotChekedChangeVariable(self.xi_range_X_checkbox,
_covar_xi.range[0]) # Add xi Range X
_covar_xi.range[1] = ifNotChekedChangeVariable(self.xi_range_Z_checkbox,
_covar_xi.range[1]) # Add xi Range Z
_covar_xi.angle[0] = ifNotChekedChangeVariable(self.xi_theta_X_checkbox,
_covar_xi.angle[0]) # Add xi Angle Theta X
_covar_xi.sill = ifNotChekedChangeVariable(self.xi_sill_checkbox, _covar_xi.sill) # Add xi Sill
if self.tilted_ellip_veloc_checkbox.isChecked():
_covar_tilt = cm.covar_tilt[n]
if len(_covar.range) == 2:
_covar_tilt.range[0] = ifNotChekedChangeVariable(self.tilt_range_X_checkbox,
_covar_tilt.range[0]) # Add tilt Range X
_covar_tilt.range[1] = ifNotChekedChangeVariable(self.tilt_range_Z_checkbox,
_covar_tilt.range[1]) # Add tilt Range Z
_covar_tilt.angle[0] = ifNotChekedChangeVariable(self.tilt_theta_X_checkbox,
_covar_tilt.angle[0]) # Add tilt Angle Theta X
_covar_tilt.sill = ifNotChekedChangeVariable(self.tilt_sill_checkbox,
_covar_tilt.sill) # Add tilt Sill
# Adding nugget effect
cm.nugget_model = ifNotChekedChangeVariable(self.slowness_checkbox,
cm.nugget_model) # Add slowness for the slowness covariance / amplitude for the amplitude covariance
cm.nugget_data = ifNotChekedChangeVariable(self.tt_checkbox,
cm.nugget_data) # Add traveltime for the slowness covariance / tau for the amplitude covariance
if self.ellip_veloc_checkbox.isChecked():
cm.nugget_xi = ifNotChekedChangeVariable(self.xi_checkbox, cm.nugget_xi) # Add nugget xi
if self.tilted_ellip_veloc_checkbox.isChecked():
cm.nugget_tilt = ifNotChekedChangeVariable(self.tilt_checkbox, cm.nugget_tilt) # Add nugget tilt
g, gt = self.calculate()
_q = np.flip(np.arange(1, len(g) + 1) ** 2, axis=0)
_q = (_q / (np.max(_q))) + 1
g = g[:len(_q)]
gt = gt[:len(_q)]
self.triggerFctAdjustCov.emit()
return sum(((gt - g) * _q) ** 2)
def fix_verif(self):
if self.model.grid.type == '2D' or self.model.grid.type == '2D+':
items = [*self.slowness_checkboxes, *self.nugget_checkboxes]
if self.ellip_veloc_checkbox.isChecked():
items += [*self.xi_checkboxes, self.xi_checkbox]
if self.tilted_ellip_veloc_checkbox.isChecked():
items += [*self.tilt_checkboxes, self.tilt_checkbox]
elif self.model.grid.type == '3D':
items = [*self.slowness_3D_checkboxes]
if False in [item.isChecked() for item in items]:
self.btn_GO.setEnabled(True)
else:
self.btn_GO.setEnabled(False)
QtWidgets.QMessageBox.warning(self, "Warning",
"In order to adjust the model, at least one 'Fix' checkbox must be left unchecked.")
def update_velocity_display(self):
flag = self.Upper_limit_checkbox.isChecked()
self.velocity_edit.setEnabled(flag)
if flag:
self.velocity_edit.setText('0.15')
else:
self.velocity_edit.setText('')
def update_data(self):
selectedMogs = [i.row() for i in self.mogs_list.selectedIndexes()]
if self.Upper_limit_checkbox.isChecked() and self.T_and_A_combo.currentIndex() == 0:
vlim = float(self.velocity_edit.text())
else:
vlim = 0.0
type_dict = {0: 'tt', 1: 'amp', 2: 'fce'}
type_ = type_dict[self.T_and_A_combo.currentIndex()]
if self.mogs_list.currentRow() != -1:
self.data, self.idata = Model.getModelData(self.model, selectedMogs, type_, vlim=vlim)
self.rays_no_label.setText(str(self.data.shape[0]))
self.loadRays()
self.computeCd()
def loadRays(self):
aniso = self.ellip_veloc_checkbox.isChecked()
if self.curv_rays_combo.count() > 1: # TODO implement curved rays
# curved rays
# check if grid compatible
if self.model.grid.checkCenter(self.model.inv_res[self.curv_rays_combo.currentIndex() - 1].tomo.x,
# TODO -1's?
self.model.inv_res[self.curv_rays_combo.currentIndex() - 1].tomo.y,
self.model.inv_res[self.curv_rays_combo.currentIndex() - 1].tomo.z) == 0:
print('Grid Not Compatible With Ray Matrix. Using Straight Rays.')
self.curv_rays_combo.setCurrentIndex(0)
self.loadRays()
return
ndata = 0
ind = np.zeros(self.data.shape[0], 1)
for n in range(0, self.data.shape[0]):
ii = np.where(
self.model.inv_res[self.curv_rays_combo.currentIndex() - 1].tomo.no_trace == self.data[n, 2])
if np.all(ii == 0):
print('Ray No', str(self.data[n, 3]), 'Missing From Ray Matrix. Using Straight Rays.')
self.curv_rays_combo.setCurrentIndex(0)
self.loadRays()
return
else:
ndata += 1
ind[ndata] = ii
ind = ind[0:ndata]
self.L = self.model.inv_res[self.curv_rays_combo.currentIndex() - 1].tomo.L[ind, :]
else:
# straight rays
self.L = self.temp_grid.getForwardStraightRays(self.idata, aniso=aniso)
def computeCd(self):
# Computes experimental covariance
nt = self.L.shape[0]
if not self.ellip_veloc_checkbox.isChecked():
s0 = np.mean(self.data[:, 0] / np.sum(self.L.toarray(), 1))
mta = s0 * np.sum(self.L, 1).getA() # mean traveltime
else:
np_ = self.L.shape[1] / 2
l = np.sqrt(self.L[:, 0:np_].power(2) + self.L[:, np_:].power(2))
s0 = np.mean(self.data[:, 0] / np.sum(l, 1))
mta = s0 * np.sum(l, 1).getA()
dt = self.data[:, 0].reshape((-1, 1)) - mta
self.Cd = dt.dot(dt.T)
self.Cd = self.Cd.reshape((nt ** 2,), order='F')
def compute(self):
self.progress_lbl.setText("Computing.\nPlease wait...")
self.computing_form.show()
# self.refreshFigs()
# self.computing_form.hide()
self.compute_thread = ComputeThread(self.refreshFigs)
self.compute_thread.finished.connect(self.computing_form.hide)
self.compute_thread.start()
def calculate(self):
self.apply_booleans()
if self.model.grid.type == '2D' or self.model.grid.type == '2D+':
xc = self.temp_grid.getCellCenter()
cm = self.current_covar()
Cm = cm.compute(xc, xc)
s = (self.data[:, 0].reshape(-1) / np.sum(self.L, 1).reshape(-1)).T
s0 = np.mean(s)
if cm.use_xi:
if cm.use_tilt:
np_ = self.L.shape[1] / 2
l = np.sqrt(self.L[:, 0:np_].power(2) + self.L[:, (np_):].power(2))
s0 = np.mean(self.data[:, 0] / np.sum(l, 1)) + np.zeros([int(np_), 1])
xi0 = np.ones([int(np_), 1]) + 0.001 # add 1/1000 so that J_th != 0
theta0 = np.zeros([int(np_), 1]) + 0.0044 # add a quarter of a degree so that J_th != 0
J = covar.computeJ2(self.L, np.concatenate([s0, xi0, theta0]))
Cm = J.dot(np.dot(Cm.toarray(), J.T))
else:
np_ = self.L.shape[1] / 2
l = np.sqrt(self.L[:, 0:np_].power(2) + self.L[:, (np_):].power(2))
s0 = np.mean(self.data[:, 0] / np.sum(l, 1)) + np.zeros([int(np_), 1])
xi0 = np.ones([int(np_), 1])
J = covar.computeJ(self.L, np.concatenate([s0, xi0]))
Cm = J.dot(np.dot(Cm.toarray(), J.T))
else:
Cm = self.L.dot(Cm.dot(self.L.T.toarray()))
if cm.use_c0:
# use exp variance
c0 = self.data[:, 1] ** 2
Cm += cm.nugget_data * np.diag(c0)
else:
Cm += cm.nugget_data * np.eye(self.L.shape[0])
Cm = Cm.flatten()
ind = np.argsort(Cm)
ind = ind[::-1]
Cm = Cm[ind]
lclas = int(self.bin_edit.text())
afi = float(self.bin_frac_edit.text())
gt = covar.moy_bloc(Cm, lclas)
ind0 = np.where(gt < np.inf)
gt = gt[ind0].T
g = self.Cd[ind]
g = covar.moy_bloc(g, lclas)
g = g[ind0].T
N = int(np.round(len(g) * afi))
g = g[0:N]
gt = gt[0:N]
return g, gt
def show_stats(self):
if self.model is not None:
if self.mogs_list.selectedIndexes() != []:
L = self.temp_grid.getForwardStraightRays(ind=self.idata)
s = (self.data[:, 0].reshape(-1) / np.sum(L, 1).reshape(-1)).T
if self.T_and_A_combo.currentIndex() == 0:
s = 1 / s
data_type = 'tt'
else:
data_type = 'amp'
s0 = np.mean(s)
vs = np.var(s)
Tx = self.temp_grid.Tx[self.idata, :]
Rx = self.temp_grid.Rx[self.idata, :]
hyp = np.sqrt(np.sum((Tx - Rx) ** 2, 1))
dz = Tx[:, 2] - Rx[:, 2]
theta = 180 / np.pi * np.arcsin(dz / hyp)
self.statistics_fig.plot(data_type, s, hyp, theta, s0, vs)
self.statistics_form.show()
else:
QtWidgets.QMessageBox.warning(self, 'Warning', "No MOG selected.")
def clear_figures(self):
self.covariance_fig.clear_()
self.comparison_fig.clear_()
self.statistics_fig.clear_()
def init_UI(self):
# --- Color for the labels --- #
palette = QtGui.QPalette()
palette.setColor(QtGui.QPalette.Foreground, QtCore.Qt.red)
class MyLineEdit(QtWidgets.QLineEdit): # allows verifying if an edit's text has been modified
textModified = QtCore.pyqtSignal(str, str) # (before, after)
def __init__(self, contents='', parent=None):
super(MyLineEdit, self).__init__(contents, parent)
self.editingFinished.connect(self.checkText)
self.textChanged.connect(lambda: self.checkText())
self.returnPressed.connect(lambda: self.checkText(True))
self._before = contents
def checkText(self, _return=False):
if (not self.hasFocus() or _return) and self._before != self.text():
self._before = self.text()
self.textModified.emit(self._before, self.text())
# ------- Widgets Creation ------- #
# --- Menu Actions --- #
openAction = QtWidgets.QAction('Open', self)
openAction.setShortcut('Ctrl+O')
openAction.triggered.connect(self.openfile)
saveAction = QtWidgets.QAction('Save', self)
saveAction.setShortcut('Ctrl+S')
saveAction.triggered.connect(self.savefile)
saveasAction = QtWidgets.QAction('Save as', self)
saveasAction.setShortcut('Ctrl+A')
saveasAction.triggered.connect(self.saveasfile)
# --- Menubar --- #
self.menu = QtWidgets.QMenuBar()
filemenu = self.menu.addMenu('&File')
filemenu.addAction(openAction)
filemenu.addAction(saveAction)
filemenu.addAction(saveasAction)
# --- Buttons Sets --- #
self.btn_Show_Stats = QtWidgets.QPushButton("Show Stats")
self.btn_Add_Struct = QtWidgets.QPushButton("Add Structure")
self.btn_Rem_Struct = QtWidgets.QPushButton("Remove Structure")
self.btn_compute = QtWidgets.QPushButton("Compute")
self.btn_GO = QtWidgets.QPushButton("GO")
# --- Labels --- #
self.model_label = MyQLabel("Model :", ha='left')
cells_label = MyQLabel("Cells", ha='left')
cells_labeli = MyQLabel("Cells", ha='left')
rays_label = MyQLabel("Rays", ha='left')
self.cells_no_label = MyQLabel("0", ha='right')
self.cells_no_labeli = MyQLabel("0", ha='right')
self.rays_no_label = MyQLabel("0", ha='right')
curv_rays_label = MyQLabel("Curved Rays", ha='right')
X_label = MyQLabel("X", ha='center')
Y_label = MyQLabel("Y", ha='center')
Z_label = MyQLabel("Z", ha='center')
Xi_label = MyQLabel("X", ha='center')
Yi_label = MyQLabel("Y", ha='center')
Zi_label = MyQLabel("Z", ha='center')
self.X_min_label = MyQLabel("0", ha='center')
self.Y_min_label = MyQLabel("0", ha='center')
self.Z_min_label = MyQLabel("0", ha='center')
self.X_max_label = MyQLabel("0", ha='center')