TDIP class

Class managing time-domain induced polarisation (TDIP) field data.

Source code in tdip\tdip.py
  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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
class TDIP:
    """Class managing time-domain induced polarisation (TDIP) field data."""

    def __init__(self, filename=None, **kwargs):
        """Initialize with optional data load.

        Parameters
        ----------
        filename : str
            name of file to read in, allowed formats are:
                * Syscal Pro export file (*.txt)
                * ABEM TXT export file (*.txt or raw time series)
                * Syscal Pro binary file (*.bin)
                * GDD format (*.gdd)
                * Ares II format (*.2dm)
                * Aarhus Workbench processed data (*.tx2 and *.dip)
                * res2dinv data

        **kwargs:
            * paraGeometry : PLC (pygimli mesh holding geometry)
                plc for the 2d inversion domain
            * paraMesh : pygimli Mesh instance
                inversion mesh
            * verbose : bool
                Be verbose.
        """
        self.verbose = kwargs.get('verbose', False)
        self.basename = 'newfile'  # for saving results and images
        self.figs = {}  # figure container
        self.header = {}  # header for supplemental information
        self.t = np.array([])
        tt = kwargs.pop('t', None)  # save time vector temp
        self.data = kwargs.pop('data', None)  # data container
        self.rhoa = kwargs.pop('rhoa', None)  # app. resistivity matrix [Ohm m]
        self.MA = kwargs.pop('MA', None)  # app. chargeability matrix [mV/V]
        self.ERT = None  # Resistivity manager class instance
        self.sINV = None  # single inversion instance
        self.pd = None  # paraDomain
        self.res = None  # resistivity
        self.m = None  # single-time spectral chargeability
        self.M = None  # full-decay spectral chargeability
        self.modelDebye = None  # relaxation time distribution
        self.m0 = None  # Cole-Cole chargeability
        self.tau = None  # Cole-Cole time constant
        self.c = None  # Cole-Cole exponent
        self.customParaGeometry = kwargs.pop('paraGeometry', None)
        self.customParaMesh = kwargs.pop('paraMesh', None)

        if filename is not None:
            self.loadData(filename, **kwargs)
            if not self.data.exists('k'):
                self.data['k'] = ert.geometricFactors(self.data, dim=2)

        if tt is not None:
            self.t = tt

    def __repr__(self):  # for print function
        """Readable representation of the class."""
        out = ['TDIP data: ' + self.data.__str__()]
        out.append("MA shape = " + str(self.MA.shape))
        out[-1] += ' nt=' + str(len(self.t))
        out[-1] += f" (t={min(self.t):.3f}-{max(self.t):.3f}s)"
        if hasattr(self, 'header'):
            for key in self.header:
                val = self.header[key]
                if isinstance(val, str):
                    out.append(val)
                elif isinstance(val, (int, float)):
                    out.append(key+' = '+str(val))
                else:
                    out.append(key+' = array('+str(val.shape)+')')
        return "\n".join(out)

    def loadData(self, filename=None):  # , **kwargs):
        """Load data from any of the supported file types.

        Supported formats
        -----------------
        TXT - ABEM or Syscal Ascii (column) output
        BIN - Syscal binary format
        DAT - Res2dInv format
        GDD - GDD format (less tested)
        TX2 - Aarhus Workbench data
        DIP - AarhusInv (processed) data
        OHM - BERT format with ip1, ip2, ... fields
        OHM/MA - BERT format with scheme file and MA file
        """
        assert isinstance(filename, str), "Needs string to load files"
        self.basename = filename[:filename.rfind('.')]
        if Path(filename).is_file() and not filename.endswith(".shm"):
            self.data, self.MA, self.t, self.header = importTDIPdata(filename)
        elif (Path(self.basename+'.MA').is_file() and Path(self.basename+'.shm').is_file()):
            self.data = pg.DataContainerERT(self.basename+'.shm')
            MAT = np.genfromtxt(self.basename+'.MA').T
            self.t = MAT[:, 0]
            self.MA = MAT[:, 1:]
        else:
            raise ImportError("Could not read data")

        self.data.checkDataValidity(remove=False)
        try:
            self.MA = self.MA[:, np.array(self.data('valid'), dtype=bool)]
        except Exception:
            print("no valid apparent chargeability")

        self.data.removeInvalid()
        self.ensureRhoa()

        return

    def load(self, *args, **kwargs):
        """Load data. Use loadData instead."""
        pg.deprecated("use loadData instead")
        self.loadData(*args, **kwargs)

    def ensureRhoa(self):
        """Make sure apparent resistivity is present in file."""
        if not self.data.allNonZero('k'):
            self.data.set('k', ert.geometricFactors(self.data, 2))  # check dim
        if not self.data.allNonZero('rhoa'):
            if not self.data.allNonZero('r'):
                self.data.set('r', self.data('u')/self.data('i'))

            self.data.set('rhoa', self.data('r') * self.data('k'))
            # self.filter(rmin=1e-8)

    def filter(self, tmin=0, tmax=1e9, kmax=1e6, electrode=None, forward=False,
               a=None, b=None, m=None, n=None, ab=None, mn=None, corrSID=1,
               rmin=0, rmax=1e9, emax=1e9, fitmax=1e9, m0max=None, m0min=None,
               taumin=-9e99, taumax=9e99, umin=0, umax=9e9, nr=[], mask=False,
               verbose=True):
        """Filter data with respect to frequencies and geometric factor.

        Parameters
        ----------
        tmin, tmax : double
            minimum/maximum time (gate center) in s
        rmin, rmax : double
            minimum/maximum apparent resistivity in Ohmm
        kmax : double
            maximum (absolute) geometric factor in m
        emax : double
            maximum error in percent
        m0min, m0max : double
            minimum/maximum (fitted) initial chargeability
        taumin, taumax : double
            minimum/maximum (fitted) time constant
        fitmax : double
            maximum exponential fit
        electrode : int
            electrode to be removed completely
        a/b/m/n : int
            delete data with specific current or potential electrode
        ab/mn : int
            delete data with specific current or potential dipole lengths
        corrSID: int [1]
            correct sensor index (like in data files)
        nr : iterable of ints []
            data indices to delete
        forward : bool
            keep only forward-directed measurements
        """
        if verbose:
            print("filtering: nt={:d}, nd={:d}".format(*self.MA.shape))
        # time index
        ind = (self.t >= tmin) & (self.t <= tmax)
        self.MA = self.MA[ind, :]
        self.t = self.t[ind]
        if 'ipDT' in self.header:
            self.header['ipDT'] = self.header['ipDT'][ind]
        if 'ipGateT' in self.header:
            ind = np.append(ind, ind[-1])
            self.header['ipGateT'] = self.header['ipGateT'][ind]
        # data index
        ind = (np.abs(self.data('k')) <= kmax)  # maximum geometric factor
        ind[self.data['rhoa'] < rmin] = False
        ind[self.data['rhoa'] > rmax] = False
        if self.data.allNonZero('u'):
            ind[pg.abs(self.data['u']) >= umax] = False
            ind[pg.abs(self.data['u']) <= umin] = False

        ind[self.data['err'] > emax/100] = False
        if self.data.allNonZero('fit'):
            ind[self.data['fit'] > fitmax] = False
        if self.data.allNonZero('tau'):
            ind[self.data['tau'] > taumax] = False
            ind[self.data['tau'] < taumin] = False
        if self.data.allNonZero('m0'):
            if m0max is not None:
                ind[self.data['m0'] > m0max] = False
            if m0min is not None:
                ind[self.data['m0'] < m0min] = False

        ind[nr] = False  # individual numbers
        am = self.data("m") - self.data("a")
        if ab is not None:
            ind[np.isclose(np.abs(self.data["b"]-self.data["a"]), ab)] = False
        if mn is not None:
            ind[np.isclose(np.abs(self.data["n"]-self.data["m"]), mn)] = False
        if forward:
            ind[am < 0] = False  # reverse measurements
        for name in ['a', 'b', 'm', 'n']:
            u = list(np.atleast_1d(eval(name)))
            if electrode is not None:
                u.extend(list(np.atleast_1d(electrode)))
            for uu in u:
                ind = ind & np.not_equal(self.data(name) + corrSID, uu)

        if mask:  # do not delete the data but mask only the IP values
            fi = pg.find(ind)
            if isinstance(self.MA, np.ma.masked_array):
                revind = np.setxor1d(np.arange(self.data.size()), fi)
                pg.debug(revind)
                self.MA.mask[:, revind] = 1
            else:
                idx = np.ones_like(self.MA)
                idx[:, fi] = 0
                self.MA = np.ma.masked_array(self.MA, idx)
        else:
            self.data.set('valid', pg.Vector(self.data.size()))
            self.data.markValid(pg.find(ind))
            self.data.removeInvalid()
            self.MA = self.MA[:, ind]

        if electrode is not None:
            self.data.removeUnusedSensors()

        if verbose:
            print("filtered: nt={:d}, nd={:d}".format(*self.MA.shape))

    def mask(self, mamin=1e-6, mamax=10000, filter=False):
        """Mask out outliers.

        Parameters
        ----------
        The following filters will mask the whole decay (i.e. deactivate IP)

        mamin, mamax : double
            minimum/maximum chargeability
        """
        self.MA = np.ma.masked_outside(self.MA, mamin, mamax)
        if filter:
            print("Filtering after masking")
            self.filter(nr=np.nonzero(
                ~np.ma.any(self.MA, axis=0).data)[0])

    def showData(self, *args, **kwargs):
        """Show apparent resistivity pseudosection.

        Parameters
        ----------
        cMin, cMax : float
            minimum/maximum colorbar range (otherwise min/max data)
        cMap : string or colormap ['Spectral_r']
            colormap to be used
        **kwargs : plotting arguments (see ert.showData)
        """
        kwargs.setdefault('cMap', 'Spectral_r')
        kwargs.setdefault('logScale', True)
        return ert.showData(self.data, *args, **kwargs)

    def showRhoa(self, **kwargs):  # backward compatibility
        """Old function for showing apparent resistivity. Use showData."""
        pg.deprecated("Use showData.")
        return self.showData(**kwargs)

    def setGates(self, t=None, dt=None, delay=0.0):
        """Set time by specifying midpoints (t) or gate lengths dt & delay."""
        if t is None:
            assert dt is not None, "gate length and delay time must be set"
            if isinstance(dt, float):  # constant gate length
                self.dt = np.ones(len(self.t)) * dt
            else:
                self.dt = np.array(dt)

            t = np.cumsum(self.dt) - self.dt/2 + delay
            self.header['ipGateT'] = np.cumsum(np.hstack((0, self.dt))) + delay
            self.header['dt'] = self.dt
            self.header['delay'] = delay

        assert len(t) == self.MA.shape[0]
        self.t = t

    def integralChargeability(self, normalize=True, **kwargs):
        """Compute integral chargeability by summing up windows x dt.

        Parameters
        ----------
        normalize : bool [True]
            normalize such that mV/V is retrieved, otherwise msec
        start : int [0]
            first gate to take
        stop : int [self.MA.shape[1]]
            last gate to take

        Returns
        -------
            integral chargeability : numpy.array
        """
        start = kwargs.pop('start', 0)
        stop = kwargs.pop('stop', len(self.MA))
        mint = np.zeros(self.data.size())
        dt = self.header['ipDT']
        for i in range(start, stop):
            mint += self.MA[i] * dt[i]

        if normalize:
            mint /= sum(dt[start:stop])

        self.data['mint'] = mint

        return mint

    def showIntegralChargeability(self, **kwargs):
        """Show integral chargeability (kwargs forwarded to ert.show)."""
        if not self.data.haveData('mint'):
            self.data['mint'] = self.integralChargeability(**kwargs)

        kwargs.setdefault('cMap', 'plasma')
        kwargs.setdefault('logScale', True)

        return ert.showData(self.data, self.data('mint'), **kwargs)

    def showMa(self, nr=0, **kwargs):
        """Show apparent chargeability (kwargs forwarded to ert.showData).

        Parameters
        ----------
        nr : int [0]
            number of time gate to show
        **kwargs : any plotting arguments to be passed to ert.showData
        """
        kwargs.setdefault('cMap', 'plasma')
        kwargs.setdefault('logScale', True)
        kwargs.setdefault('label', 'chargeability (mV/V)')
        ax, cb = ert.showData(self.data, self.MA[nr], **kwargs)
        ax.set_title(f'$t$={self.t[nr]:.3f}')
        return ax, cb

    def fitDataDecays(self, show=False, tmin=0):
        """Fit (data) decays by exponential function.

        Linear regression of log(M) over t and stores the result in data:
            m0 - zero-time chargeability
            tau - characteristic decay time
            fit - RMS of difference between measured and modelled (log) M

        Parameters
        ----------
        tmin : float
            minimum time to be used for the fit
        show : bool
            show m0, tau and fit pseudosections
        """
        t = np.copy(self.t)
        fi = np.nonzero(t >= tmin)[0]
        G = np.ones((len(fi), 2))
        G[:, 1] = t[fi]
        Ginv = np.linalg.inv(G.T.dot(G)).dot(G.T)
        MAfi = self.MA[fi, :]
        lma = np.log(np.abs(MAfi.data)+0.0001)
        if isinstance(MAfi, np.ma.MaskedArray):
            lma[MAfi.mask] = 1

        ab = Ginv.dot(lma)
        self.data['m0'] = np.exp(ab[0])
        self.data['tau'] = -1./ab[1]
        fit = np.sqrt(np.mean((G.dot(ab)-lma)**2, axis=0))
        if isinstance(fit, np.ma.MaskedArray):
            self.data.set('fit', fit.data)
        else:
            self.data.set('fit', fit+1e-5)

        if show:
            ert.showData(self.data, 'm0', cMin=0, logScale=False,
                         label='M0 [mV/V]', markOutside=True)
            ert.showData(self.data, 'tau', label=r'$\tau$ [s]',
                         markOutside=True,
                         cMin=min(np.abs(self.data('tau'))), logScale=True)
            ert.showData(self.data, 'fit', label=r'fit rms [log]', logScale=0)

    def fitDecays(self, *args, **kwargs):
        """Fit data decays (old name). Use fitDataDecays instead."""
        pg.deprecated("Use fitDataDecays instead (or fitModelDecays)")
        self.fitDataDecays(*args, **kwargs)

    def generateDataPDF(self, rdict=None, mdict=None, **kwargs):
        """Generate multi-page pdf file with all data as pseudosections.

        Parameters
        ----------
        rdict : dict
            dictionary with plotting arguments for apparent resistivity
        mdict : dict
            dictionary with plotting arguments for apparent chargeability

        Any other keyword args are associated to mdict.
        """
        if rdict is None:
            rdict = dict(logScale=True)
        if mdict is None:
            posneg = kwargs.pop("posneg", None)
            if posneg:  #
                mdict = dict(cMin=-posneg, cMax=posneg, cMap='coolwarm')
            else:
                mdict = dict(cMin=1, cMax=np.max(self.MA), logScale=True)
        # set some default keywords
        mdict.update(**kwargs)
        rdict.setdefault('cMap', 'Spectral_r')  # default color scale
        rdict.setdefault('xlabel', 'x [m]')
        rdict.setdefault('label', r'$\rho_a$ [$\Omega$m]')
        mdict.setdefault('cMap', 'plasma')
        mdict.setdefault('xlabel', 'x [m]')
        mdict.setdefault('label', r'$m_a$ [mV/V]')
        fig, ax = plt.subplots()
        basename = kwargs.pop('basename', self.basename)
        with PdfPages(basename+'-alldata.pdf') as pdf:
            ert.showData(self.data, 'rhoa', ax=ax, **rdict, **kwargs)
            ax.set_title('apparent resistivity')
            fig.savefig(pdf, format='pdf')
            if max(self.data('err')) > 0:
                fig.clf()
                ax = fig.add_subplot(111)
                ert.showData(self.data, self.data('err')*100+0.01, ax=ax,
                             label=r'$\epsilon$ [%]', **kwargs)
                ax.set_title('error')
                fig.savefig(pdf, format='pdf')
            if self.data.allNonZero('stacks'):
                fig.clf()
                ax = fig.add_subplot(111)
                ert.showData(self.data, 'stacks', ax=ax, label='stacks',
                             logScale=False, **kwargs)
                ax.set_title('stacks')
                fig.savefig(pdf, format='pdf')
            if self.data.allNonZero('i'):
                fig.clf()
                ax = fig.add_subplot(111)
                ert.showData(self.data, self.data('i')*1000, ax=ax,
                             label=r'$I$ [mA]', **kwargs)
                ax.set_title('current')
                fig.savefig(pdf, format='pdf')
            if self.data.allNonZero('u'):
                fig.clf()
                ax = fig.add_subplot(111)
                ert.showData(self.data, self.data('u')*1000, ax=ax,
                             label=r'$U$ [mV]', **kwargs)
                ax.set_title('voltage')
                fig.savefig(pdf, format='pdf')
            if self.data.allNonZero('tau'):
                fig.clf()
                ax = fig.add_subplot(111)
                tau = np.abs(self.data('tau').array())
                cMin, cMax = np.nanquantile(tau, [0.03, 0.97])
                ert.showData(self.data, tau, ax=ax, label=r'$\tau$ [s]',
                             ind=(tau > 0), logScale=True,
                             cMin=cMin, cMax=cMax, **kwargs)
                ax.set_title('apparent relaxation time')
                fig.savefig(pdf, format='pdf')
            if self.data.allNonZero('fit'):
                fig.clf()
                ax = fig.add_subplot(111)
                ert.showData(self.data, 'fit', ax=ax, label='fit (log10)',
                             logScale=False, **kwargs)
                ax.set_title('fit')
                fig.savefig(pdf, format='pdf')
            if self.data.allNonZero('m0'):
                fig.clf()
                ax = fig.add_subplot(111)
                ert.showData(self.data, 'm0', ax=ax, **mdict)
                ax.set_title('fitted (t=0) chargeability')
                fig.savefig(pdf, format='pdf')
            for i, ma in enumerate(self.MA):
                fig.clf()
                ax = fig.add_subplot(111)
                ert.showData(self.data, ma, ax=ax, **mdict)
                tstr = f" (t={self.t[i]:.3f}s)"
                if 'ipGateT' in self.header:
                    tstr = ' (t={:g}-{:g}s)'.format(
                        *(self.header['ipGateT'][i:i+2]))
                ax.set_title('apparent chargeability gate ' + str(i+1) + tstr)
                fig.savefig(pdf, format='pdf')

    def showApparentChargeability(self, ax=None, nr=0, **kwargs):
        """Show apparent chargeability of a single Windows."""
        kwargs.setdefault('cMap', 'plasma')
        kwargs.setdefault('cMin', 0.1)
        kwargs.setdefault('cMax', 1000)
        if ax is None:
            fig, ax = plt.subplots()
            self.figs[f'MA{nr:02d}'] = fig

        ert.show(self.data, self.MA[nr-1], ax=ax, **kwargs)

    def getDataIndex(self, abmn=None):
        """Return data index for given ABMN combination.

        Parameters
        ----------
        abmn : list
            list of current (A,B) and potential (M,N) electrodes
            A/B and M/N can be interchanged (internally ordered)
        """
        a = np.minimum(self.data('a'), self.data('b'))
        b = np.maximum(self.data('a'), self.data('b'))
        m = np.minimum(self.data('m'), self.data('n'))
        n = np.maximum(self.data('m'), self.data('n'))
        nr = np.nonzero(np.isclose(a, min(abmn[:2])-1) &
                        np.isclose(b, max(abmn[:2])-1) &
                        np.isclose(m, min(abmn[2:4])-1) &
                        np.isclose(n, max(abmn[2:4])-1))[0][0]
        return nr

    def getDataDecay(self, abmn=None):
        """Return apparent chargeability decay for given ABMN combination.

        Parameters
        ----------
        abmn : list
            list of current (A,B) and potential (M,N) electrodes
            A/B and M/N can be interchanged (internally ordered)
        """
        nr = self.getDataIndex(abmn)
        if isinstance(nr, np.int64):
            return Decay(self.t, self.MA[:, nr] / 1000)
            # return self.MA[:, nr]
        else:
            print(abmn, nr, type(nr))
            raise KeyError("No such abmn combination found.")

    def showDecay(self, nr=[], ax=None, ab=None, mn=None, verbose=True, **kwargs):
        """Show decay curves for groups of data.

        Parameters
        ----------
        nr : iterable
            list of data indices to show, if not given ab/mn are analysed
        ab : [int, int]
            list of sensor numbers for current injection (counting from 1)
        mn : [int, int]
            list of sensor numbers for potential (counting from 1)

        Plotting Keywords
        -----------------
        showFit : bool [False]
            show fitted Debye or Cole-Cole curve
        label : str
            legend label for single data, otherwise generated from A,B,M,N
        basename : str
            string to prepend to automatically generated label
        marker : str ['x']
            marker to use for plotting
        xlim, ylim : [float, float]
            limits for x or y axis
        xscale : str ['linear']
            scaling of x axis
        yscale : str ['log']
            scaling of y axis
        xlabel : str [r'$t$ [s]']
            label for the x axis
        ylabel : str [r'$m_a$ [mV/V]']
            label for the y axis
        """
        data = self.data
        if "basename" in kwargs:
            bs = kwargs['basename']
        else:
            bs = 'abmn'
            if ab is not None:
                bs = "mn"
        if ab is not None:
            a = np.minimum(data('a'), data('b'))
            b = np.maximum(data('a'), data('b'))
            # nr.extend(pg.find((a == min(ab)-1) & (b == max(ab)-1)))
            nr = np.nonzero(np.isclose(a, min(ab)-1) &
                            np.isclose(b, max(ab)-1))[0]
        if mn is not None:
            m = np.minimum(data('m'), data('n'))
            n = np.maximum(data('m'), data('n'))
            # fi = pg.find((m == min(mn)-1) & (n == max(mn)-1))
            fi = np.nonzero(np.isclose(m, min(mn)-1) &
                            np.isclose(n, max(mn)-1))[0]
            if ab is not None:  # already chose AB dipole => select
                nr = np.intersect1d(nr, fi)
            else:
                nr.extend(fi)

        kwargs.setdefault('marker', 'x')
        kwargs.setdefault('xscale', 'log')
        kwargs.setdefault('yscale', 'log')
        shFit = (kwargs.pop('showFit', False) and self.data.haveData('m0') and
                 self.data.haveData('tau'))
        ls = "" if shFit else "-"
        kwargs.setdefault('ls', ls)
        if verbose:
            print("nr=", nr)
            if shFit:
                print("fit = " + np.array2string(np.array(self.data['fit'][nr])))

        outkeys = ['xlim', 'ylim', 'xlog', 'ylog', 'xscale', 'yscale']
        if isinstance(nr, int):
            nr = [nr]
        if len(nr) > 0:
            if ax is None:
                self.figs['decay'], ax = plt.subplots()

            for nn in nr:
                abmn = [int(self.data(t)[nn]+1) for t in ['a', 'b', 'm', 'n']]
                kw = kwargs.copy()
                for key in outkeys:
                    if key in kw:
                        kw.pop(key)

                ma = self.MA[:, nn]
                if kw.pop('invalid', False):
                    ax.plot(self.t, ma.data, color='gray', ms=2,
                            marker=kwargs["marker"], ls=ls)
                    ax.plot(self.t, -np.array(ma.data), ls='--',
                            color='lightgray', ms=2, marker=kwargs["marker"])
                if ab is not None:
                    kw.setdefault('label', (bs+': '+'{:d} '*2).format(
                        *abmn[2:]))
                    kw.setdefault('color', "C"+str(abmn[2] % 9))
                else:
                    kw.setdefault('label', (bs+': '+'{:d} '*4).format(*abmn))
                li = ax.plot(self.t, ma, **kw)[0]
                if shFit and np.ma.any(ma):
                    fit = self.data['m0'][nn] * \
                        np.exp(-np.array(self.t)/self.data['tau'][nn])
                    ax.plot(self.t, fit, color=li.get_color(), ls='--')

            ax.grid(True)
            ax.legend()
            if 'xlim' in kwargs:
                ax.set_xlim(kwargs['xlim'])
            if 'ylim' in kwargs:
                ax.set_ylim(kwargs['ylim'])
            if 'xscale' in kwargs:
                ax.set_xscale(kwargs['xscale'])
            if 'yscale' in kwargs:
                ax.set_yscale(kwargs['yscale'])
            ax.set_xlabel(kwargs.pop('xlabel', r'$t$ [s]'))
            ax.set_ylabel(kwargs.pop('ylabel', r'$m_a$ [mV/V]'))
            tit = ""
            if ab is not None:
                tit = "A-B = {:d}-{:d}".format(*abmn[:2])
            if mn is not None:
                tit += " , M-N = {:d}-{:d}".format(*abmn[2:])

            if len(tit) > 0 and len(ax.get_title()) == 0:
                ax.set_title(tit)

            return ax

    def generateDecayPDF(self, **kwargs):
        """Generate a pdf file with all decays sorted by current injections.

        Parameters
        ----------
        showFit : bool [False]
            show fitted Debye or Cole-Cole curve
        marker : str ['x']
            marker to use for plotting
        xlim, ylim : float [<automatic>]
            limits for x or y axis
        xscale : str ['linear']
            scaling of x axis
        yscale : str ['log']
            scaling of y axis
        xlabel : str [r'$t$ [s]']
            label for the x axis
        ylabel : str [r'$m_a$ [mV/V]']
            label for the y axis
        """
        from matplotlib.backends.backend_pdf import PdfPages

        ab = (self.data('a') + 1) * 1000 + self.data('b') + 1
        # ab = (self.data('a')) * 1000 + self.data('b')
        uab = np.array(np.unique(ab), dtype=int)
        # sort them according AB length (major) and A electrode (minor)
        dip = np.abs(uab // 1000 - (uab % 1000)) * 1000 + uab // 1000
        uab = uab[np.argsort(dip)]
        kwargs.setdefault("verbose", False)
        basename = kwargs.pop('basename', self.basename)
        with PdfPages(basename + '-decays.pdf') as pdf:
            fig, ax = plt.subplots()
            for u in uab:
                ab = [u // 1000, (u % 1000)]
                # ab = [u // 1000 + 1, (u % 1000) + 1]
                ax.cla()
                self.showDecay(ab=ab, ax=ax, **kwargs)
                fig.savefig(pdf, format='pdf')

    def saveData(self, basename=None, **kwargs):
        """Save all data as shm and accompagnying .MA (like FDIP) files."""
        basename = basename or self.basename
        self.data.save(basename+".shm", "a b m n k rhoa")
        MA = np.array(self.MA.data)
        if isinstance(self.MA, np.ma.masked_array):
            MA[self.MA.mask] = 999

        A = np.column_stack((self.t, MA))
        np.savetxt(basename+".MA", A.T, fmt="%6.3f", delimiter="\t")
        data = pg.DataContainerERT(self.data)
        tokens = "a b m n k rhoa"
        if self.data.haveData("m0"):
            tokens += " m0"

        for i in range(self.MA.shape[0]):
            tok = "ip"+str(i+1)
            data[tok] = MA[i, :]
            tokens += " " + tok

        data.save(basename+".ohm", tokens)

    def invertRhoa(self, **kwargs):
        """Invert apparent resistivity. kwargs forwarded to ERTManager."""
        if self.ERT is None:
            self.ERT = ert.ERTManager()

        self.ERT.fop.setData(self.data)
        if "mesh" in kwargs:
            self.ERT.fop.setMesh(kwargs["mesh"])

        show = kwargs.pop('show', False)
        if not self.data.haveData("err"):
            self.data["err"] = ert.estimateError(self.data)

        self.res = self.ERT.invert(data=self.data, **kwargs)
        self.response = self.ERT.inv.response
        self.coverage = self.ERT.coverage()
        self.pd = self.ERT.paraDomain
        self.pd["resistivity"] = self.res
        self.pd["coverage"] = self.coverage
        if show:
            return self.showResistivity()

    def invertMa(self, nr=0, ma=None, fop=None, mesh=None,
                 res=None, debug=False, reg=None, **kwargs):
        """Invert for chargeability.

        Directly invert apparent chargeability for intrinsic chargeability.
        As the Jacobian of the ERT forward operator is needed, the inversion of
        the DC data must be done before.

        Parameters
        ----------
        nr : int [0]
            gate to invert (counting from 1), 0 means fitted (zero-time) Ma
        error : float [0.002]
            error in apparent chargeability
        lam : float [100]
            regularization strength
        zWeight : float [1.0]
            vertical penalty
        robustData : bool [False]
            use L1 norm on data misfit
        blockyModel: bool [False]
            use L1 norm on model roughness
        regionFile : str
            load region file
        show : bool [False]
            show resulting chargeability distribution

        fop : pg.DC*MultiElectrodeModelling
            DC forward operator
        mesh : pg.Mesh
            inversion mesh
        res : iterable
            resistivity vector
        """
        show = kwargs.pop('show', False)
        if ma is None:
            if nr == 0 or nr == '0':
                if self.data.exists('m0'):
                    ma = self.data('m0') * 0.001
                else:
                    pg.info("fitted M0 not existing, taking first gate")
                    ma = self.MA[0] * 0.001
            else:
                if isinstance(nr, float):
                    pg.info("Using closest gate to time ", nr)
                    nr = np.argmin(np.abs(self.t-nr)) + 1
                    pg.info(" : ", nr)

                ma = self.MA[nr-1] * 0.001  # should MA be in V/V instead?

        errLevel = kwargs.pop('error', 0.002)
        if hasattr(errLevel, '__iter__') and len(errLevel) == len(ma):
            maerr = errLevel
        else:
            maerr = np.ones_like(ma) * errLevel

        # restrict values above 1
        if 0:
            maerr[ma > 1] = 1e5
            ma[ma > 1] = 0.99
        # restrict values below 1
        if 0:
            maerr[ma < 0] = 1e5
            ma[ma < 0] = 0.001

        if isinstance(ma, np.ma.MaskedArray):
            maerr[ma.mask] = 1e5
            ma = np.copy(ma.data)

        fIP = []
        verbose = kwargs.pop("verbose", False)
        if kwargs.pop("Seigel", False):
            fIP = DCIPSeigelModelling(self.ERT)
            res = self.res
        else:
            if fop is None:
                fop = self.ERT.fop
            if mesh is None:
                mesh = self.ERT.mesh
            if res is None:
                res = self.res  # self.ERT.model

            if hasattr(self, "response") and hasattr(self.response,
                                                     "__iter__"):
                fIP = DCIPMModelling(fop, mesh, res, verbose,
                                     response=self.response)
            else:
                fIP = DCIPMModelling(fop, mesh, res, verbose)

            if 'regionFile' in kwargs:
                fIP.regionManager().loadMap(kwargs.pop('regionFile'))
            else:
                if fop.regionManager().regionCount() > 1:
                    fIP.region(1).setBackground(True)
                    fIP.region(2).setConstraintType(1)

        fIP.regionManager().setZWeight(kwargs.pop('zWeight', 1.0))
        fIP.createRefinedForwardMesh(True)
        # tD, tM = pg.core.RTransLog(), pg.core.RTransLogLU(0, 0.99)
        self.invIP = pg.Inversion(fop=fIP, verbose=True, debug=debug)
        self.invIP.modelTrans = pg.trans.TransLogLU(0.0001, 0.999)
        mstart = pg.Vector(len(res), np.abs(pg.median(ma)))
        kwargs.setdefault('lam', 100)
        if reg:
            self.invIP.setRegularization(**reg)
        self.m = self.invIP.run(ma, maerr/ma, startModel=mstart, **kwargs)
        pg.info(f"chi^2={self.invIP.chi2():.1f} RMS={self.invIP.absrms()*1000:.1f}mV/V")
        if show:
            return self.showChargeability()
        else:
            return self.invIP

    def invertDebye(self, **kwargs):
        """Invert into Debye distribution model."""
        from pygimli.math.matrix import KroneckerMatrix
        self.tau = kwargs.pop("tau", np.logspace(-1, 1, 11))
        DD = pg.Matrix(len(self.t), len(self.tau))
        for i, ti in enumerate(self.t):
            DD.setRow(i, pg.exp(-ti/self.tau))

        JJ = pg.matrix.MultLeftRightMatrix(
            self.ERT.fop.jacobian(), 1/self.ERT.inv.response, self.ERT.model)
        K = KroneckerMatrix(DD, JJ)
        f = pg.frameworks.LinearModelling(K)
        f.setMesh(self.ERT.mesh, ignoreRegionManager=True)
        C1 = self.ERT.fop.constraints()
        C = pg.matrix.FrameConstraintMatrix(C1, len(self.tau))
        self.dinv = pg.Inversion(fop=f)
        self.dinv.modelTrans = pg.trans.TransLog()
        # inv.dataTrans = pg.trans.TransLog()
        f.setConstraints(C)
        MA = np.copy(self.MA.data) * 0.001
        absErr = kwargs.pop("absoluteError", 0.001)
        relErr = kwargs.pop("relativeError", 0.03)
        errMat = absErr / np.abs(MA) + relErr
        if isinstance(self.MA, np.ma.MaskedArray):
            errMat[self.MA.mask] = 1e5
            MA[self.MA.mask] = 0.001

        dataVec = MA.ravel()
        errVec = errMat.ravel()
        np.savetxt("dataerr.txt", np.column_stack([dataVec, errVec]))
        kwargs.setdefault("startModel", np.median(dataVec))
        showModel = kwargs.pop("showModel", False)
        showFit = kwargs.pop("showFit", False)
        model = self.dinv.run(dataVec, errMat.ravel(), **kwargs)
        self.modelDebye = np.reshape(model, [len(self.tau), -1])
        self.pd = self.ERT.paraDomain
        self.pd["TC"] = np.sum(self.modelDebye, axis=0)
        self.pd["logMeanTau"] = np.exp(np.sum(np.log(np.reshape(
            self.tau, [-1, 1]))*self.modelDebye, axis=0) / self.pd["TC"])
        if showModel:
            for mo in self.modelDebye:
                pg.show(self.pd, mo, cMin=0, cMax=0.05, logScale=False, cMap="magma_r")
        if showFit:
            RE = np.reshape(self.dinv.response, [len(self.t), -1])
            _, ax = plt.subplots(nrows=RE.shape[0], ncols=2, figsize=(5, 12),
                                 sharex=True, sharey=True)
            kw = dict(cMin=0, cMax=100, logScale=False, colorBar=0, cMap="magma")
            for i, re in enumerate(RE):
                ert.show(self.data, self.MA[i, :], ax=ax[i, 0], **kw)
                ert.show(self.data, re*1000, ax=ax[i, 1], **kw)

    def showResistivity(self, ax=None, **kwargs):
        """Show resistivity inversion result.

        Any kwargs (cMin, cMax, logScale) are forwarded to pg.show.
        """
        kwargs.setdefault('logScale', True)
        kwargs.setdefault('label', r'resistivity [$\Omega$m]')
        kwargs.setdefault('cMap', 'Spectral_r')
        kwargs.setdefault('coverage', self.ERT.coverage())
        if self.pd is None or len(self.res) != self.pd.cellCount():
            self.pd = self.ERT.paraDomain
        return pg.show(self.pd, self.res, ax=ax, **kwargs)

    def showChargeability(self, ax=None, **kwargs):
        """Show chargeability inversion result.

        Any kwargs (ax, cMin, cMax, logScale) are forwarded to pg.show.
        """
        kwargs.setdefault('label', 'chargeability [mV/V]')
        kwargs.setdefault('cMap', 'plasma')
        return pg.show(self.ERT.paraDomain, self.m*1e3, ax=ax, **kwargs)

    def showResults(self, rkw={}, mkw={}):
        """Show result (resistivity and chargeability in two subfigures).

        Parameters
        ----------
        rkw : dict
            dictionary for being passed to showResistivity
        mkw : dict
            dictionary for being passed to showChargeability
        """
        self.figs['result'], ax = plt.subplots(nrows=2)
        self.showResistivity(ax=ax[0], **rkw)
        self.showChargeability(ax=ax[1], **mkw)
        return ax

    def individualInversion(self, **kwargs):
        """Carry out individual inversion for spectral chargeability.

        Creates numpy array self.M storing chargeabilities for all gates

        Parameters
        ----------
        error : float [0.002]
            assumed error of apparent chargeability
        **kwargs : dict
            passed to self.invertMa
        """
        errLevel = kwargs.pop('error', 0.002)
        error = np.ones(self.MA.shape[1]) * errLevel
        if self.ERT is None or self.res is None:
            self.invertRhoa(**kwargs)

        self.M = np.zeros((len(self.MA), len(self.res)))
        for i, ma in enumerate(self.MA):
            pg.info(f'Inverting gate {i+1}')
            error[:] = errLevel
            if isinstance(ma, np.ma.MaskedArray):
                madata = np.copy(ma.data)
                error[ma.mask] = 1e8
                madata[ma.mask] = 0.1
                self.invertMa(ma=madata*0.001, absoluteError=error, **kwargs)
            else:
                self.invertMa(ma=ma*0.001, absoluteError=error, **kwargs)

            self.M[i] = self.m

    def simultaneousInversion(self, fop=None, res=None, **kwargs):
        """Carry out simultaneous inversion with smoothness along t axis."""
        errLevel = kwargs.pop('error', 0.002)
        if fop is None or res is None:
            if self.ERT is None:
                self.invertRhoa(**kwargs)  # rather check whether already done!

            fop = self.ERT.fop

        fop.setVerbose(False)
        error = np.ones_like(self.MA) * errLevel
        MA = np.copy(self.MA.data)  # make a copy as it will be changed
        if isinstance(self.MA, np.ma.MaskedArray):
            error[self.MA.mask] = 1e8
            MA[self.MA.mask] = 0.1

        fIP = DCIPMSmoothModelling(fop, self.pd, self.res,
                                   self.t)
        fIP.createRefinedForwardMesh(False)
        fIP.regionManager().setZWeight(kwargs.get('zWeight', 0.3))
        tD, tM = pg.trans.Trans(), pg.trans.TransLogLU(0, 0.99)
        INV = pg.Inversion(fop=fIP, verbose=True, debug=False)
        INV.dataTrans = tD
        INV.modelTrans = tM
        print(kwargs)
        mstart = pg.Vector(fIP.nc*fIP.nt, 0.1)
        dataVals = MA.ravel()*0.001
        INV.setRegularization(cType=2)
        kwargs.setdefault("lam", 100)
        mm = INV.run(dataVals, error.ravel()/dataVals,
                     startModel=mstart, **kwargs)
        self.M = np.reshape(mm, (-1, self.pd.cellCount()))
        self.MAfwd = np.reshape(INV.response, (len(self.t), -1))

    def getCellID(self, pos):
        """Return cell ID of nearest cell to position."""
        return self.pd.findCell(pos).id()

    def getModelDecay(self, cellID, return_index=False):
        """Return SIP spectrum for single cell (id or position)."""
        if hasattr(cellID, '__iter__'):  # tuple => position
            cellID = self.getCellID(cellID)

        if return_index:
            return self.M[:, cellID], cellID
        else:
            return self.M[:, cellID]

    def showModelDecay(self, cellID, **kwargs):
        """Show SIP spectrum for single cell (id or position)."""
        decay, idx = self.getModelDecay(cellID, return_index=True)
        shfit = kwargs.pop("showFit", False)
        if 'ax' in kwargs:
            ax = kwargs.pop('ax')
        else:
            self.figs['modelDecay'], ax = plt.subplots()
            # kwargs.setdefault('xLabel)

        kwargs.setdefault("label", 'inverted')
        ax.loglog(self.t, decay*1000, 'x-', **kwargs)
        if shfit:
            if hasattr(self, 'FWR'):
                ax.loglog(self.t, self.FWR[:, idx]*1000, label='fitted')
            else:

                pg.warn("No fwd!")

        ax.legend()
        ax.grid(True)
        return ax

    def showModelDecays(self, positions=None, **kwargs):
        """Show model spectra for a number of positions or IDs."""
        kwargs.setdefault("showFit", False)
        self.figs['modelDecays'], ax = plt.subplots()
        LABELS = []
        if positions is None:  # not given: check for x and z vectors
            x = kwargs.pop("x", None)
            z = kwargs.pop("z", None)
            if z is None:
                z = kwargs.pop("y", None)
            if x is None and z is None:
                raise NameError("Specify either position vector or x and z")
            if isinstance(x, (float, int)):
                x = np.ones_like(z) * x
            if isinstance(z, (float, int)):
                z = np.ones_like(x) * z

            positions = [[xi, zi] for xi, zi in zip(x, z, strict=False)]

        for pos in positions:
            label = 'x={:.1f} z={:.1f}'.format(*pos)
            LABELS.append(label)
            # kwargs['label'] = label
            self.showModelDecay(pos, ax=ax, **kwargs)

        ax.set_ylim(auto=True)
        # ax.set_xlim(min(self.freq), max(self.freq))
        ax.legend(LABELS, loc='best')

        return ax

    def fitModelDecays(self, show=False, useColeCole=False, **kwargs):
        """Fit model decays by exponential function or Cole-Cole model.

        Linear regression (Debye) of log(M) over t storing:
            m0 - zero-time (or Cole-Cole) chargeability
            tau - characteristic time constant
            c - Cole-Cole exponent (only if useColeCole=True)
            fit - RMS of difference between measured and modelled (log) M
        """
        G = np.ones((len(self.t), 2))
        G[:, 1] = self.t
        Ginv = np.linalg.inv(G.T.dot(G)).dot(G.T)
        lma = np.log(self.M)
        ab = Ginv.dot(lma)
        self.m0 = np.exp(ab[0])
        self.tau = np.minimum(np.maximum(-1./ab[1], 0.01), 10)
        self.c = np.ones(self.M.shape[1])
        self.fit = np.sqrt(np.mean((G.dot(ab)-lma)**2, axis=0))
        self.FWR = self.m0.reshape(1, -1) * np.exp(-self.t.reshape(-1, 1) *
                                                   self.tau.reshape(1, -1))
        mpar = kwargs.pop('mpar', (0.01, 0.0001, 1.))
        taupar = kwargs.pop('taupar', (1.0, 0.01, 10.0))
        cpar = kwargs.pop('cpar', (0.3, 0.0, 1.05))
        if useColeCole:
            f = CCTDModelling(self.t)
            f.region(0).setParameters(*mpar)  # M
            f.region(1).setParameters(*taupar)  # tau
            f.region(2).setParameters(*cpar)  # c
            # INV = pg.core.RInversion(self.M[:, 0], f, False)
            INV = pg.frameworks.MarquardtInversion(fop=f)
            # INV.setMarquardtScheme()
            error = kwargs.pop('error', 0.05)
            # pg.Vector(self.M.shape[0], 0.05))
            self.FWR = np.ones_like(self.M)
            # self.fit = np.ones(self.M.shape[1])
            print('Fitting model decays:')
            # medmodel = [np.median(self.m0), np.median(self.tau), 0.5]
            kwargs.setdefault('lam', 1000)
            for i in range(self.M.shape[1]):
                print('.', end='')
                # INV.setData(self.M[:, i])
                medmodel = [self.m0[i], self.tau[i], 0.5]
                dataVals = self.M[:, i]
                model = INV.run(dataVals, error/dataVals+0.01,
                                startModel=medmodel, **kwargs)
                self.m0[i] = model[0]
                self.tau[i] = model[1]
                self.c[i] = model[2]
                self.FWR[:, i] = INV.response
                self.fit[i] = INV.absrms()
            if show:
                pg.show(self.pd, self.fit, label='RMS fit')
                return self.showColeColeResults()
        else:  # only a Debye term
            if show:
                fig, ax = plt.subplots(nrows=3)
                pg.show(self.pd, self.m0*1000, ax=ax[0], label='M (mV/V)')
                pg.show(self.pd, self.tau, ax=ax[1], label=r'$\tau$ (s)')
                pg.show(self.pd, self.fit, ax=ax[2], label='RMS fit (log)',
                        logScale=0)
                return ax

    def showColeColeResults(self, rlim=(None, None), clim=(0, 0.5),
                            mlim=(None, None), tlim=(None, None), shFit=0):
        """Show resulting Cole-Cole models."""
        isCC = int(min(self.c) < 1)
        fig, ax = plt.subplots(nrows=3+isCC+int(shFit), figsize=(8, 12))
        pg.show(self.pd, self.res, ax=ax[0], label='resistivity (Ohmm)',
                cMap='Spectral_r', cMin=rlim[0], cMax=rlim[1], logScale=True)
        pg.show(self.pd, self.m0*1000, ax=ax[1], cMin=mlim[0], cMax=mlim[1],
                label='M (mV/V)', cMap='plasma', logScale=False)
        pg.show(self.pd, self.tau, ax=ax[2], cMin=tlim[0], cMax=tlim[1],
                label=r'$\tau$ (s)')
        if isCC:
            pg.show(self.pd, self.c, cMin=clim[0], cMax=clim[1],
                    logScale=False, ax=ax[3], label=r'$c$ (-)')
        if shFit:
            pg.show(self.pd, self.fit, cMin=clim[0], cMax=clim[1],
                    logScale=False, ax=ax[-1], label=r'fit (-)')

        fig.tight_layout()
        self.figs['resultCC'] = fig
        return ax

    def generateModelPDF(self, rdict=None, mdict=None, **kwargs):
        """Generate a multi-page pdf file with all data as pseudosections.

        Parameters
        ----------
        rdict : dict
            dictionary with plotting arguments for apparent resistivity
        mdict : dict
            dictionary with plotting arguments for apparent chargeability
        """
        if rdict is None:
            rdict = dict(logScale=True, cMap='Spectral_r',
                         label=r'$\rho_a$ [$\Omega$m]', xlabel='x [m]')
        if mdict is None:
            mdict = dict(cMin=1, cMax=np.max(self.M)*1000, logScale=True,
                         cMap='plasma', label=r'$m$ [mV/V]', xlabel='x [m]')
        mdict.update(**kwargs)
        rdict.setdefault('cMap', 'Spectral_r')  # default color scale
        mdict.setdefault('cMap', 'plasma')
        fig, ax = plt.subplots()
        basename = kwargs.pop('basename', self.basename)
        with PdfPages(basename+'-allmodel.pdf') as pdf:
            self.showResistivity(ax=ax, **rdict)
            fig.savefig(pdf, format='pdf')
            for i, t in enumerate(self.t):
                fig.clf()
                ax = fig.add_subplot(111)
                pg.show(self.pd, self.M[i, :]*1000, ax=ax, **mdict)
                ax.set_title(rf'$t({i:d})$={t:e}')
                fig.savefig(pdf, format='pdf')

    def saveFigures(self, ext='.pdf', **kwargs):
        """Save all figures in .figs to disk."""
        kwargs.setdefault('bbox_inches', 'tight')
        basename = kwargs.pop('basename', self.basename)
        for key in self.figs:
            self.figs[key].savefig(basename+'-'+key+ext, **kwargs)

    def saveResults(self, **kwargs):
        """Save inversion results to .rho and .M file plus mesh."""
        basename = kwargs.pop("basename", self.basename)
        self.pd.save(basename+'_pd.bms')  # better .bms only?
        self.pd["coverage"] = self.ERT.coverage()
        self.pd["resistivity"] = self.res
        self.pd.exportVTK(basename+".vtk")
        if self.res is not None:
            np.savetxt(basename+'.rho', self.res)
        if self.M is not None:
            np.savetxt(basename+'.M', self.M.T)
        if self.modelDebye is not None:
            A = np.hstack([self.tau.reshape(-1, 1), self.modelDebye])
            np.savetxt(basename+".rtd", A.T)

        self.saveFit()

    def loadResults(self, loadColeCole=False, **kwargs):
        """Load inversion results from file.

        Loads three (or four) files:
            - *_pd.bms : mesh file of inversion mesh
            - *.rho : resistivity vector (ascii column)
            - *.M : spectral chargeability (ascii columns for each gate)
            - *.rmtc : Cole-Cole/Debye results with rho, m, tau, c (and fit)
              (previously called .mtc without resistivity)

        Parameters
        ----------
        loadColeCole : bool [False]
            try loading Cole-Cole or Debye inversion results
        basename : str [self.basename]
            file base name (*) to load
        """
        basename = kwargs.pop("basename", self.basename)
        self.pd = pg.Mesh(basename+'_pd.bms')
        if Path(basename+'.rho').is_file():
            self.res = np.loadtxt(basename+'.rho')
        if Path(basename+'.M').is_file():
            self.M = np.loadtxt(basename+'.M').T
            if self.M.shape[0] == self.pd.cellCount():  # old style
                self.M = self.M.T
        if Path(basename+'.mtc').is_file() or Path(basename+'.rmtc').is_file():
            self.loadFit(basename=basename)
        if Path(basename+".rtd").is_file():
            B = np.loadtxt(basename+".rtd")
            self.tau = B[0]
            self.modelDebye = B[1:].T

    def loadResult(self, *args, **kwargs):
        """Load results (old name). Use load results."""
        pg.deprecated("use loadResults instead")
        self.loadResults(*args, **kwargs)

    def saveFit(self, **kwargs):
        """Save fitted chargeability, time constant & exponent to file."""
        basename = kwargs.pop("basename", self.basename)
        if kwargs.pop("noRes", False):  # old style
            if np.any(self.m0) and np.any(self.tau) and np.any(self.c):
                np.savetxt(self.basename+'.mtc', np.column_stack(
                    (self.m0, self.tau, self.c, self.fit)))
        else:
            if (np.any(self.res) and np.any(self.m0) and
                    np.any(self.tau) and np.any(self.c)):
                np.savetxt(basename+'.rmtc', np.column_stack(
                    (self.res, self.m0, self.tau, self.c, self.fit)))

    def loadFit(self, **kwargs):
        """Load fitted chargeability, time constant & exponent from file."""
        basename = kwargs.pop("basename", self.basename)
        if Path(basename+".rmtc").is_file():
            self.res, self.m0, self.tau, self.c, self.fit = np.loadtxt(
                basename+'.rmtc', unpack=1)
        elif Path(basename+".mtc").is_file():
            self.m0, self.tau, self.c, self.fit = np.loadtxt(
                basename+'.mtc', unpack=1)
            pg.info("Loading deprecated fit result (mtc) instead of rmtc")
        else:
            pg.warn("Could not find fit result " + basename + ".(r)mtc")

    def convertToFD(self, f=None, tau=None):
        """Convert whole data set to FDIP instance (requires FDIP package)."""
        from scipy.optimize import nnls
        from fdip import FDIP
        tau = tau or np.logspace(np.log10(min(self.t)),
                                 np.log10(max(self.t)), 31)
        if f is None:
            f =  np.logspace(-3, 3, 31)
        fdip = FDIP(f=f, data=self.data, basename=self.basename + "_TD2FD")
        fdip.RHOA = np.zeros([self.data.size(), len(f)])
        fdip.PHIA = np.zeros([self.data.size(), len(f)])
        T, W = np.meshgrid(tau, f * 2. * np.pi)
        A = 1 - 1. / (W*T * 1j + 1)
        G = np.zeros([len(self.t), len(tau)])
        for i, taui in enumerate(tau):
            G[:, i] = np.exp(-np.array(self.t)/taui)
        for i in range(self.data.size()):
            model, *_ = nnls(G, self.MA[:, i] / 1000)
            model[model > 1] = 0
            Z = (1. - A.dot(model))
            fdip.RHOA[i, :] = np.abs(Z) * self.data["rhoa"][i]
            fdip.PHIA[i, :] = -np.angle(Z)

        return fdip

    def simulate(self, **kwargs):
        """Synthetic simulation based on Cole-Cole model.

        Parameters
        ----------
        mesh : pg.Mesh
            mesh with regions to be mapped
        rhovec : array
            resistivities of the regions
        mvec : iterable
            chargeabilities
        tauvec : iterable
            time constants
        cvec : iterable
            relaxation exponents
        scheme : pg.DataContainerERT [self.data]
            protocol file
        fr : iterable [self.freq]
            frequency vector
        noiseLevel : float [0]
            relative error model
        noiseAbs : float [1e-5]
            absolute error model
        sr : bool [True]
            use singularity removal (secondary field)
        verbose : bool [False]
            some output
        """
        from fdip import FDIP

        if "scheme" in kwargs:
            self.data = kwargs.pop("scheme")

        if "t" in kwargs:
            self.t = kwargs.pop("t")

        fdip = FDIP(f=kwargs.pop("f", np.logspace(-3, 3, 41)),
                    data=self.data)
        fdip.simulate(**kwargs)
        self.data["rhoa"] = fdip.RHOA[:, 0]
        self.MA = np.zeros((len(self.t), self.data.size()))
        spec = SIPSpectrum(f=fdip.freq)
        tau = kwargs.pop("tau", np.logspace(-4, 1, 41))
        for i in range(fdip.data.size()):
            spec.amp = fdip.RHOA[i]
            spec.phi = fdip.PHIA[i]
            spec.fitDebyeModel(tau=tau, lam=1, verbose=False)
            self.MA[:, i] = spec.createDecay(t=self.t) * 1000 # mV/V

__init__(filename=None, **kwargs)

Initialize with optional data load.

Parameters:

Name Type Description Default
filename str

name of file to read in, allowed formats are: * Syscal Pro export file (.txt) * ABEM TXT export file (.txt or raw time series) * Syscal Pro binary file (.bin) * GDD format (.gdd) * Ares II format (.2dm) * Aarhus Workbench processed data (.tx2 and *.dip) * res2dinv data

None
**kwargs
  • paraGeometry : PLC (pygimli mesh holding geometry) plc for the 2d inversion domain
  • paraMesh : pygimli Mesh instance inversion mesh
  • verbose : bool Be verbose.
{}
Source code in tdip\tdip.py
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
def __init__(self, filename=None, **kwargs):
    """Initialize with optional data load.

    Parameters
    ----------
    filename : str
        name of file to read in, allowed formats are:
            * Syscal Pro export file (*.txt)
            * ABEM TXT export file (*.txt or raw time series)
            * Syscal Pro binary file (*.bin)
            * GDD format (*.gdd)
            * Ares II format (*.2dm)
            * Aarhus Workbench processed data (*.tx2 and *.dip)
            * res2dinv data

    **kwargs:
        * paraGeometry : PLC (pygimli mesh holding geometry)
            plc for the 2d inversion domain
        * paraMesh : pygimli Mesh instance
            inversion mesh
        * verbose : bool
            Be verbose.
    """
    self.verbose = kwargs.get('verbose', False)
    self.basename = 'newfile'  # for saving results and images
    self.figs = {}  # figure container
    self.header = {}  # header for supplemental information
    self.t = np.array([])
    tt = kwargs.pop('t', None)  # save time vector temp
    self.data = kwargs.pop('data', None)  # data container
    self.rhoa = kwargs.pop('rhoa', None)  # app. resistivity matrix [Ohm m]
    self.MA = kwargs.pop('MA', None)  # app. chargeability matrix [mV/V]
    self.ERT = None  # Resistivity manager class instance
    self.sINV = None  # single inversion instance
    self.pd = None  # paraDomain
    self.res = None  # resistivity
    self.m = None  # single-time spectral chargeability
    self.M = None  # full-decay spectral chargeability
    self.modelDebye = None  # relaxation time distribution
    self.m0 = None  # Cole-Cole chargeability
    self.tau = None  # Cole-Cole time constant
    self.c = None  # Cole-Cole exponent
    self.customParaGeometry = kwargs.pop('paraGeometry', None)
    self.customParaMesh = kwargs.pop('paraMesh', None)

    if filename is not None:
        self.loadData(filename, **kwargs)
        if not self.data.exists('k'):
            self.data['k'] = ert.geometricFactors(self.data, dim=2)

    if tt is not None:
        self.t = tt

__repr__()

Readable representation of the class.

Source code in tdip\tdip.py
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
def __repr__(self):  # for print function
    """Readable representation of the class."""
    out = ['TDIP data: ' + self.data.__str__()]
    out.append("MA shape = " + str(self.MA.shape))
    out[-1] += ' nt=' + str(len(self.t))
    out[-1] += f" (t={min(self.t):.3f}-{max(self.t):.3f}s)"
    if hasattr(self, 'header'):
        for key in self.header:
            val = self.header[key]
            if isinstance(val, str):
                out.append(val)
            elif isinstance(val, (int, float)):
                out.append(key+' = '+str(val))
            else:
                out.append(key+' = array('+str(val.shape)+')')
    return "\n".join(out)

convertToFD(f=None, tau=None)

Convert whole data set to FDIP instance (requires FDIP package).

Source code in tdip\tdip.py
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
def convertToFD(self, f=None, tau=None):
    """Convert whole data set to FDIP instance (requires FDIP package)."""
    from scipy.optimize import nnls
    from fdip import FDIP
    tau = tau or np.logspace(np.log10(min(self.t)),
                             np.log10(max(self.t)), 31)
    if f is None:
        f =  np.logspace(-3, 3, 31)
    fdip = FDIP(f=f, data=self.data, basename=self.basename + "_TD2FD")
    fdip.RHOA = np.zeros([self.data.size(), len(f)])
    fdip.PHIA = np.zeros([self.data.size(), len(f)])
    T, W = np.meshgrid(tau, f * 2. * np.pi)
    A = 1 - 1. / (W*T * 1j + 1)
    G = np.zeros([len(self.t), len(tau)])
    for i, taui in enumerate(tau):
        G[:, i] = np.exp(-np.array(self.t)/taui)
    for i in range(self.data.size()):
        model, *_ = nnls(G, self.MA[:, i] / 1000)
        model[model > 1] = 0
        Z = (1. - A.dot(model))
        fdip.RHOA[i, :] = np.abs(Z) * self.data["rhoa"][i]
        fdip.PHIA[i, :] = -np.angle(Z)

    return fdip

ensureRhoa()

Make sure apparent resistivity is present in file.

Source code in tdip\tdip.py
132
133
134
135
136
137
138
139
140
def ensureRhoa(self):
    """Make sure apparent resistivity is present in file."""
    if not self.data.allNonZero('k'):
        self.data.set('k', ert.geometricFactors(self.data, 2))  # check dim
    if not self.data.allNonZero('rhoa'):
        if not self.data.allNonZero('r'):
            self.data.set('r', self.data('u')/self.data('i'))

        self.data.set('rhoa', self.data('r') * self.data('k'))

filter(tmin=0, tmax=1000000000.0, kmax=1000000.0, electrode=None, forward=False, a=None, b=None, m=None, n=None, ab=None, mn=None, corrSID=1, rmin=0, rmax=1000000000.0, emax=1000000000.0, fitmax=1000000000.0, m0max=None, m0min=None, taumin=-9e+99, taumax=9e+99, umin=0, umax=9000000000.0, nr=[], mask=False, verbose=True)

Filter data with respect to frequencies and geometric factor.

Parameters:

Name Type Description Default
tmin double

minimum/maximum time (gate center) in s

0
tmax double

minimum/maximum time (gate center) in s

0
rmin double

minimum/maximum apparent resistivity in Ohmm

0
rmax double

minimum/maximum apparent resistivity in Ohmm

0
kmax double

maximum (absolute) geometric factor in m

1000000.0
emax double

maximum error in percent

1000000000.0
m0min double

minimum/maximum (fitted) initial chargeability

None
m0max double

minimum/maximum (fitted) initial chargeability

None
taumin double

minimum/maximum (fitted) time constant

-9e+99
taumax double

minimum/maximum (fitted) time constant

-9e+99
fitmax double

maximum exponential fit

1000000000.0
electrode int

electrode to be removed completely

None
a

delete data with specific current or potential electrode

None
ab

delete data with specific current or potential dipole lengths

None
corrSID

correct sensor index (like in data files)

1
nr iterable of ints []

data indices to delete

[]
forward bool

keep only forward-directed measurements

False
Source code in tdip\tdip.py
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
def filter(self, tmin=0, tmax=1e9, kmax=1e6, electrode=None, forward=False,
           a=None, b=None, m=None, n=None, ab=None, mn=None, corrSID=1,
           rmin=0, rmax=1e9, emax=1e9, fitmax=1e9, m0max=None, m0min=None,
           taumin=-9e99, taumax=9e99, umin=0, umax=9e9, nr=[], mask=False,
           verbose=True):
    """Filter data with respect to frequencies and geometric factor.

    Parameters
    ----------
    tmin, tmax : double
        minimum/maximum time (gate center) in s
    rmin, rmax : double
        minimum/maximum apparent resistivity in Ohmm
    kmax : double
        maximum (absolute) geometric factor in m
    emax : double
        maximum error in percent
    m0min, m0max : double
        minimum/maximum (fitted) initial chargeability
    taumin, taumax : double
        minimum/maximum (fitted) time constant
    fitmax : double
        maximum exponential fit
    electrode : int
        electrode to be removed completely
    a/b/m/n : int
        delete data with specific current or potential electrode
    ab/mn : int
        delete data with specific current or potential dipole lengths
    corrSID: int [1]
        correct sensor index (like in data files)
    nr : iterable of ints []
        data indices to delete
    forward : bool
        keep only forward-directed measurements
    """
    if verbose:
        print("filtering: nt={:d}, nd={:d}".format(*self.MA.shape))
    # time index
    ind = (self.t >= tmin) & (self.t <= tmax)
    self.MA = self.MA[ind, :]
    self.t = self.t[ind]
    if 'ipDT' in self.header:
        self.header['ipDT'] = self.header['ipDT'][ind]
    if 'ipGateT' in self.header:
        ind = np.append(ind, ind[-1])
        self.header['ipGateT'] = self.header['ipGateT'][ind]
    # data index
    ind = (np.abs(self.data('k')) <= kmax)  # maximum geometric factor
    ind[self.data['rhoa'] < rmin] = False
    ind[self.data['rhoa'] > rmax] = False
    if self.data.allNonZero('u'):
        ind[pg.abs(self.data['u']) >= umax] = False
        ind[pg.abs(self.data['u']) <= umin] = False

    ind[self.data['err'] > emax/100] = False
    if self.data.allNonZero('fit'):
        ind[self.data['fit'] > fitmax] = False
    if self.data.allNonZero('tau'):
        ind[self.data['tau'] > taumax] = False
        ind[self.data['tau'] < taumin] = False
    if self.data.allNonZero('m0'):
        if m0max is not None:
            ind[self.data['m0'] > m0max] = False
        if m0min is not None:
            ind[self.data['m0'] < m0min] = False

    ind[nr] = False  # individual numbers
    am = self.data("m") - self.data("a")
    if ab is not None:
        ind[np.isclose(np.abs(self.data["b"]-self.data["a"]), ab)] = False
    if mn is not None:
        ind[np.isclose(np.abs(self.data["n"]-self.data["m"]), mn)] = False
    if forward:
        ind[am < 0] = False  # reverse measurements
    for name in ['a', 'b', 'm', 'n']:
        u = list(np.atleast_1d(eval(name)))
        if electrode is not None:
            u.extend(list(np.atleast_1d(electrode)))
        for uu in u:
            ind = ind & np.not_equal(self.data(name) + corrSID, uu)

    if mask:  # do not delete the data but mask only the IP values
        fi = pg.find(ind)
        if isinstance(self.MA, np.ma.masked_array):
            revind = np.setxor1d(np.arange(self.data.size()), fi)
            pg.debug(revind)
            self.MA.mask[:, revind] = 1
        else:
            idx = np.ones_like(self.MA)
            idx[:, fi] = 0
            self.MA = np.ma.masked_array(self.MA, idx)
    else:
        self.data.set('valid', pg.Vector(self.data.size()))
        self.data.markValid(pg.find(ind))
        self.data.removeInvalid()
        self.MA = self.MA[:, ind]

    if electrode is not None:
        self.data.removeUnusedSensors()

    if verbose:
        print("filtered: nt={:d}, nd={:d}".format(*self.MA.shape))

fitDataDecays(show=False, tmin=0)

Fit (data) decays by exponential function.

Linear regression of log(M) over t and stores the result in data: m0 - zero-time chargeability tau - characteristic decay time fit - RMS of difference between measured and modelled (log) M

Parameters:

Name Type Description Default
tmin float

minimum time to be used for the fit

0
show bool

show m0, tau and fit pseudosections

False
Source code in tdip\tdip.py
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
def fitDataDecays(self, show=False, tmin=0):
    """Fit (data) decays by exponential function.

    Linear regression of log(M) over t and stores the result in data:
        m0 - zero-time chargeability
        tau - characteristic decay time
        fit - RMS of difference between measured and modelled (log) M

    Parameters
    ----------
    tmin : float
        minimum time to be used for the fit
    show : bool
        show m0, tau and fit pseudosections
    """
    t = np.copy(self.t)
    fi = np.nonzero(t >= tmin)[0]
    G = np.ones((len(fi), 2))
    G[:, 1] = t[fi]
    Ginv = np.linalg.inv(G.T.dot(G)).dot(G.T)
    MAfi = self.MA[fi, :]
    lma = np.log(np.abs(MAfi.data)+0.0001)
    if isinstance(MAfi, np.ma.MaskedArray):
        lma[MAfi.mask] = 1

    ab = Ginv.dot(lma)
    self.data['m0'] = np.exp(ab[0])
    self.data['tau'] = -1./ab[1]
    fit = np.sqrt(np.mean((G.dot(ab)-lma)**2, axis=0))
    if isinstance(fit, np.ma.MaskedArray):
        self.data.set('fit', fit.data)
    else:
        self.data.set('fit', fit+1e-5)

    if show:
        ert.showData(self.data, 'm0', cMin=0, logScale=False,
                     label='M0 [mV/V]', markOutside=True)
        ert.showData(self.data, 'tau', label=r'$\tau$ [s]',
                     markOutside=True,
                     cMin=min(np.abs(self.data('tau'))), logScale=True)
        ert.showData(self.data, 'fit', label=r'fit rms [log]', logScale=0)

fitDecays(*args, **kwargs)

Fit data decays (old name). Use fitDataDecays instead.

Source code in tdip\tdip.py
398
399
400
401
def fitDecays(self, *args, **kwargs):
    """Fit data decays (old name). Use fitDataDecays instead."""
    pg.deprecated("Use fitDataDecays instead (or fitModelDecays)")
    self.fitDataDecays(*args, **kwargs)

fitModelDecays(show=False, useColeCole=False, **kwargs)

Fit model decays by exponential function or Cole-Cole model.

Linear regression (Debye) of log(M) over t storing: m0 - zero-time (or Cole-Cole) chargeability tau - characteristic time constant c - Cole-Cole exponent (only if useColeCole=True) fit - RMS of difference between measured and modelled (log) M

Source code in tdip\tdip.py
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
def fitModelDecays(self, show=False, useColeCole=False, **kwargs):
    """Fit model decays by exponential function or Cole-Cole model.

    Linear regression (Debye) of log(M) over t storing:
        m0 - zero-time (or Cole-Cole) chargeability
        tau - characteristic time constant
        c - Cole-Cole exponent (only if useColeCole=True)
        fit - RMS of difference between measured and modelled (log) M
    """
    G = np.ones((len(self.t), 2))
    G[:, 1] = self.t
    Ginv = np.linalg.inv(G.T.dot(G)).dot(G.T)
    lma = np.log(self.M)
    ab = Ginv.dot(lma)
    self.m0 = np.exp(ab[0])
    self.tau = np.minimum(np.maximum(-1./ab[1], 0.01), 10)
    self.c = np.ones(self.M.shape[1])
    self.fit = np.sqrt(np.mean((G.dot(ab)-lma)**2, axis=0))
    self.FWR = self.m0.reshape(1, -1) * np.exp(-self.t.reshape(-1, 1) *
                                               self.tau.reshape(1, -1))
    mpar = kwargs.pop('mpar', (0.01, 0.0001, 1.))
    taupar = kwargs.pop('taupar', (1.0, 0.01, 10.0))
    cpar = kwargs.pop('cpar', (0.3, 0.0, 1.05))
    if useColeCole:
        f = CCTDModelling(self.t)
        f.region(0).setParameters(*mpar)  # M
        f.region(1).setParameters(*taupar)  # tau
        f.region(2).setParameters(*cpar)  # c
        # INV = pg.core.RInversion(self.M[:, 0], f, False)
        INV = pg.frameworks.MarquardtInversion(fop=f)
        # INV.setMarquardtScheme()
        error = kwargs.pop('error', 0.05)
        # pg.Vector(self.M.shape[0], 0.05))
        self.FWR = np.ones_like(self.M)
        # self.fit = np.ones(self.M.shape[1])
        print('Fitting model decays:')
        # medmodel = [np.median(self.m0), np.median(self.tau), 0.5]
        kwargs.setdefault('lam', 1000)
        for i in range(self.M.shape[1]):
            print('.', end='')
            # INV.setData(self.M[:, i])
            medmodel = [self.m0[i], self.tau[i], 0.5]
            dataVals = self.M[:, i]
            model = INV.run(dataVals, error/dataVals+0.01,
                            startModel=medmodel, **kwargs)
            self.m0[i] = model[0]
            self.tau[i] = model[1]
            self.c[i] = model[2]
            self.FWR[:, i] = INV.response
            self.fit[i] = INV.absrms()
        if show:
            pg.show(self.pd, self.fit, label='RMS fit')
            return self.showColeColeResults()
    else:  # only a Debye term
        if show:
            fig, ax = plt.subplots(nrows=3)
            pg.show(self.pd, self.m0*1000, ax=ax[0], label='M (mV/V)')
            pg.show(self.pd, self.tau, ax=ax[1], label=r'$\tau$ (s)')
            pg.show(self.pd, self.fit, ax=ax[2], label='RMS fit (log)',
                    logScale=0)
            return ax

generateDataPDF(rdict=None, mdict=None, **kwargs)

Generate multi-page pdf file with all data as pseudosections.

Parameters:

Name Type Description Default
rdict dict

dictionary with plotting arguments for apparent resistivity

None
mdict dict

dictionary with plotting arguments for apparent chargeability

None
Any
required
Source code in tdip\tdip.py
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
def generateDataPDF(self, rdict=None, mdict=None, **kwargs):
    """Generate multi-page pdf file with all data as pseudosections.

    Parameters
    ----------
    rdict : dict
        dictionary with plotting arguments for apparent resistivity
    mdict : dict
        dictionary with plotting arguments for apparent chargeability

    Any other keyword args are associated to mdict.
    """
    if rdict is None:
        rdict = dict(logScale=True)
    if mdict is None:
        posneg = kwargs.pop("posneg", None)
        if posneg:  #
            mdict = dict(cMin=-posneg, cMax=posneg, cMap='coolwarm')
        else:
            mdict = dict(cMin=1, cMax=np.max(self.MA), logScale=True)
    # set some default keywords
    mdict.update(**kwargs)
    rdict.setdefault('cMap', 'Spectral_r')  # default color scale
    rdict.setdefault('xlabel', 'x [m]')
    rdict.setdefault('label', r'$\rho_a$ [$\Omega$m]')
    mdict.setdefault('cMap', 'plasma')
    mdict.setdefault('xlabel', 'x [m]')
    mdict.setdefault('label', r'$m_a$ [mV/V]')
    fig, ax = plt.subplots()
    basename = kwargs.pop('basename', self.basename)
    with PdfPages(basename+'-alldata.pdf') as pdf:
        ert.showData(self.data, 'rhoa', ax=ax, **rdict, **kwargs)
        ax.set_title('apparent resistivity')
        fig.savefig(pdf, format='pdf')
        if max(self.data('err')) > 0:
            fig.clf()
            ax = fig.add_subplot(111)
            ert.showData(self.data, self.data('err')*100+0.01, ax=ax,
                         label=r'$\epsilon$ [%]', **kwargs)
            ax.set_title('error')
            fig.savefig(pdf, format='pdf')
        if self.data.allNonZero('stacks'):
            fig.clf()
            ax = fig.add_subplot(111)
            ert.showData(self.data, 'stacks', ax=ax, label='stacks',
                         logScale=False, **kwargs)
            ax.set_title('stacks')
            fig.savefig(pdf, format='pdf')
        if self.data.allNonZero('i'):
            fig.clf()
            ax = fig.add_subplot(111)
            ert.showData(self.data, self.data('i')*1000, ax=ax,
                         label=r'$I$ [mA]', **kwargs)
            ax.set_title('current')
            fig.savefig(pdf, format='pdf')
        if self.data.allNonZero('u'):
            fig.clf()
            ax = fig.add_subplot(111)
            ert.showData(self.data, self.data('u')*1000, ax=ax,
                         label=r'$U$ [mV]', **kwargs)
            ax.set_title('voltage')
            fig.savefig(pdf, format='pdf')
        if self.data.allNonZero('tau'):
            fig.clf()
            ax = fig.add_subplot(111)
            tau = np.abs(self.data('tau').array())
            cMin, cMax = np.nanquantile(tau, [0.03, 0.97])
            ert.showData(self.data, tau, ax=ax, label=r'$\tau$ [s]',
                         ind=(tau > 0), logScale=True,
                         cMin=cMin, cMax=cMax, **kwargs)
            ax.set_title('apparent relaxation time')
            fig.savefig(pdf, format='pdf')
        if self.data.allNonZero('fit'):
            fig.clf()
            ax = fig.add_subplot(111)
            ert.showData(self.data, 'fit', ax=ax, label='fit (log10)',
                         logScale=False, **kwargs)
            ax.set_title('fit')
            fig.savefig(pdf, format='pdf')
        if self.data.allNonZero('m0'):
            fig.clf()
            ax = fig.add_subplot(111)
            ert.showData(self.data, 'm0', ax=ax, **mdict)
            ax.set_title('fitted (t=0) chargeability')
            fig.savefig(pdf, format='pdf')
        for i, ma in enumerate(self.MA):
            fig.clf()
            ax = fig.add_subplot(111)
            ert.showData(self.data, ma, ax=ax, **mdict)
            tstr = f" (t={self.t[i]:.3f}s)"
            if 'ipGateT' in self.header:
                tstr = ' (t={:g}-{:g}s)'.format(
                    *(self.header['ipGateT'][i:i+2]))
            ax.set_title('apparent chargeability gate ' + str(i+1) + tstr)
            fig.savefig(pdf, format='pdf')

generateDecayPDF(**kwargs)

Generate a pdf file with all decays sorted by current injections.

Parameters:

Name Type Description Default
showFit bool[False]

show fitted Debye or Cole-Cole curve

required
marker str[x]

marker to use for plotting

required
xlim float [<automatic>]

limits for x or y axis

required
ylim float [<automatic>]

limits for x or y axis

required
xscale str[linear]

scaling of x axis

required
yscale str[log]

scaling of y axis

required
xlabel str['$t$ [s]']

label for the x axis

required
ylabel str['$m_a$ [mV/V]']

label for the y axis

required
Source code in tdip\tdip.py
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
def generateDecayPDF(self, **kwargs):
    """Generate a pdf file with all decays sorted by current injections.

    Parameters
    ----------
    showFit : bool [False]
        show fitted Debye or Cole-Cole curve
    marker : str ['x']
        marker to use for plotting
    xlim, ylim : float [<automatic>]
        limits for x or y axis
    xscale : str ['linear']
        scaling of x axis
    yscale : str ['log']
        scaling of y axis
    xlabel : str [r'$t$ [s]']
        label for the x axis
    ylabel : str [r'$m_a$ [mV/V]']
        label for the y axis
    """
    from matplotlib.backends.backend_pdf import PdfPages

    ab = (self.data('a') + 1) * 1000 + self.data('b') + 1
    # ab = (self.data('a')) * 1000 + self.data('b')
    uab = np.array(np.unique(ab), dtype=int)
    # sort them according AB length (major) and A electrode (minor)
    dip = np.abs(uab // 1000 - (uab % 1000)) * 1000 + uab // 1000
    uab = uab[np.argsort(dip)]
    kwargs.setdefault("verbose", False)
    basename = kwargs.pop('basename', self.basename)
    with PdfPages(basename + '-decays.pdf') as pdf:
        fig, ax = plt.subplots()
        for u in uab:
            ab = [u // 1000, (u % 1000)]
            # ab = [u // 1000 + 1, (u % 1000) + 1]
            ax.cla()
            self.showDecay(ab=ab, ax=ax, **kwargs)
            fig.savefig(pdf, format='pdf')

generateModelPDF(rdict=None, mdict=None, **kwargs)

Generate a multi-page pdf file with all data as pseudosections.

Parameters:

Name Type Description Default
rdict dict

dictionary with plotting arguments for apparent resistivity

None
mdict dict

dictionary with plotting arguments for apparent chargeability

None
Source code in tdip\tdip.py
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
def generateModelPDF(self, rdict=None, mdict=None, **kwargs):
    """Generate a multi-page pdf file with all data as pseudosections.

    Parameters
    ----------
    rdict : dict
        dictionary with plotting arguments for apparent resistivity
    mdict : dict
        dictionary with plotting arguments for apparent chargeability
    """
    if rdict is None:
        rdict = dict(logScale=True, cMap='Spectral_r',
                     label=r'$\rho_a$ [$\Omega$m]', xlabel='x [m]')
    if mdict is None:
        mdict = dict(cMin=1, cMax=np.max(self.M)*1000, logScale=True,
                     cMap='plasma', label=r'$m$ [mV/V]', xlabel='x [m]')
    mdict.update(**kwargs)
    rdict.setdefault('cMap', 'Spectral_r')  # default color scale
    mdict.setdefault('cMap', 'plasma')
    fig, ax = plt.subplots()
    basename = kwargs.pop('basename', self.basename)
    with PdfPages(basename+'-allmodel.pdf') as pdf:
        self.showResistivity(ax=ax, **rdict)
        fig.savefig(pdf, format='pdf')
        for i, t in enumerate(self.t):
            fig.clf()
            ax = fig.add_subplot(111)
            pg.show(self.pd, self.M[i, :]*1000, ax=ax, **mdict)
            ax.set_title(rf'$t({i:d})$={t:e}')
            fig.savefig(pdf, format='pdf')

getCellID(pos)

Return cell ID of nearest cell to position.

Source code in tdip\tdip.py
1018
1019
1020
def getCellID(self, pos):
    """Return cell ID of nearest cell to position."""
    return self.pd.findCell(pos).id()

getDataDecay(abmn=None)

Return apparent chargeability decay for given ABMN combination.

Parameters:

Name Type Description Default
abmn list

list of current (A,B) and potential (M,N) electrodes A/B and M/N can be interchanged (internally ordered)

None
Source code in tdip\tdip.py
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
def getDataDecay(self, abmn=None):
    """Return apparent chargeability decay for given ABMN combination.

    Parameters
    ----------
    abmn : list
        list of current (A,B) and potential (M,N) electrodes
        A/B and M/N can be interchanged (internally ordered)
    """
    nr = self.getDataIndex(abmn)
    if isinstance(nr, np.int64):
        return Decay(self.t, self.MA[:, nr] / 1000)
        # return self.MA[:, nr]
    else:
        print(abmn, nr, type(nr))
        raise KeyError("No such abmn combination found.")

getDataIndex(abmn=None)

Return data index for given ABMN combination.

Parameters:

Name Type Description Default
abmn list

list of current (A,B) and potential (M,N) electrodes A/B and M/N can be interchanged (internally ordered)

None
Source code in tdip\tdip.py
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
def getDataIndex(self, abmn=None):
    """Return data index for given ABMN combination.

    Parameters
    ----------
    abmn : list
        list of current (A,B) and potential (M,N) electrodes
        A/B and M/N can be interchanged (internally ordered)
    """
    a = np.minimum(self.data('a'), self.data('b'))
    b = np.maximum(self.data('a'), self.data('b'))
    m = np.minimum(self.data('m'), self.data('n'))
    n = np.maximum(self.data('m'), self.data('n'))
    nr = np.nonzero(np.isclose(a, min(abmn[:2])-1) &
                    np.isclose(b, max(abmn[:2])-1) &
                    np.isclose(m, min(abmn[2:4])-1) &
                    np.isclose(n, max(abmn[2:4])-1))[0][0]
    return nr

getModelDecay(cellID, return_index=False)

Return SIP spectrum for single cell (id or position).

Source code in tdip\tdip.py
1022
1023
1024
1025
1026
1027
1028
1029
1030
def getModelDecay(self, cellID, return_index=False):
    """Return SIP spectrum for single cell (id or position)."""
    if hasattr(cellID, '__iter__'):  # tuple => position
        cellID = self.getCellID(cellID)

    if return_index:
        return self.M[:, cellID], cellID
    else:
        return self.M[:, cellID]

individualInversion(**kwargs)

Carry out individual inversion for spectral chargeability.

Creates numpy array self.M storing chargeabilities for all gates

Parameters:

Name Type Description Default
error float[0.002]

assumed error of apparent chargeability

required
**kwargs dict

passed to self.invertMa

{}
Source code in tdip\tdip.py
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
def individualInversion(self, **kwargs):
    """Carry out individual inversion for spectral chargeability.

    Creates numpy array self.M storing chargeabilities for all gates

    Parameters
    ----------
    error : float [0.002]
        assumed error of apparent chargeability
    **kwargs : dict
        passed to self.invertMa
    """
    errLevel = kwargs.pop('error', 0.002)
    error = np.ones(self.MA.shape[1]) * errLevel
    if self.ERT is None or self.res is None:
        self.invertRhoa(**kwargs)

    self.M = np.zeros((len(self.MA), len(self.res)))
    for i, ma in enumerate(self.MA):
        pg.info(f'Inverting gate {i+1}')
        error[:] = errLevel
        if isinstance(ma, np.ma.MaskedArray):
            madata = np.copy(ma.data)
            error[ma.mask] = 1e8
            madata[ma.mask] = 0.1
            self.invertMa(ma=madata*0.001, absoluteError=error, **kwargs)
        else:
            self.invertMa(ma=ma*0.001, absoluteError=error, **kwargs)

        self.M[i] = self.m

integralChargeability(normalize=True, **kwargs)

Compute integral chargeability by summing up windows x dt.

Parameters:

Name Type Description Default
normalize bool[True]

normalize such that mV/V is retrieved, otherwise msec

True
start int[0]

first gate to take

required
stop int[shape[1]]

last gate to take

required

Returns:

Type Description
integral chargeability : numpy.array
Source code in tdip\tdip.py
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
def integralChargeability(self, normalize=True, **kwargs):
    """Compute integral chargeability by summing up windows x dt.

    Parameters
    ----------
    normalize : bool [True]
        normalize such that mV/V is retrieved, otherwise msec
    start : int [0]
        first gate to take
    stop : int [self.MA.shape[1]]
        last gate to take

    Returns
    -------
        integral chargeability : numpy.array
    """
    start = kwargs.pop('start', 0)
    stop = kwargs.pop('stop', len(self.MA))
    mint = np.zeros(self.data.size())
    dt = self.header['ipDT']
    for i in range(start, stop):
        mint += self.MA[i] * dt[i]

    if normalize:
        mint /= sum(dt[start:stop])

    self.data['mint'] = mint

    return mint

invertDebye(**kwargs)

Invert into Debye distribution model.

Source code in tdip\tdip.py
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
def invertDebye(self, **kwargs):
    """Invert into Debye distribution model."""
    from pygimli.math.matrix import KroneckerMatrix
    self.tau = kwargs.pop("tau", np.logspace(-1, 1, 11))
    DD = pg.Matrix(len(self.t), len(self.tau))
    for i, ti in enumerate(self.t):
        DD.setRow(i, pg.exp(-ti/self.tau))

    JJ = pg.matrix.MultLeftRightMatrix(
        self.ERT.fop.jacobian(), 1/self.ERT.inv.response, self.ERT.model)
    K = KroneckerMatrix(DD, JJ)
    f = pg.frameworks.LinearModelling(K)
    f.setMesh(self.ERT.mesh, ignoreRegionManager=True)
    C1 = self.ERT.fop.constraints()
    C = pg.matrix.FrameConstraintMatrix(C1, len(self.tau))
    self.dinv = pg.Inversion(fop=f)
    self.dinv.modelTrans = pg.trans.TransLog()
    # inv.dataTrans = pg.trans.TransLog()
    f.setConstraints(C)
    MA = np.copy(self.MA.data) * 0.001
    absErr = kwargs.pop("absoluteError", 0.001)
    relErr = kwargs.pop("relativeError", 0.03)
    errMat = absErr / np.abs(MA) + relErr
    if isinstance(self.MA, np.ma.MaskedArray):
        errMat[self.MA.mask] = 1e5
        MA[self.MA.mask] = 0.001

    dataVec = MA.ravel()
    errVec = errMat.ravel()
    np.savetxt("dataerr.txt", np.column_stack([dataVec, errVec]))
    kwargs.setdefault("startModel", np.median(dataVec))
    showModel = kwargs.pop("showModel", False)
    showFit = kwargs.pop("showFit", False)
    model = self.dinv.run(dataVec, errMat.ravel(), **kwargs)
    self.modelDebye = np.reshape(model, [len(self.tau), -1])
    self.pd = self.ERT.paraDomain
    self.pd["TC"] = np.sum(self.modelDebye, axis=0)
    self.pd["logMeanTau"] = np.exp(np.sum(np.log(np.reshape(
        self.tau, [-1, 1]))*self.modelDebye, axis=0) / self.pd["TC"])
    if showModel:
        for mo in self.modelDebye:
            pg.show(self.pd, mo, cMin=0, cMax=0.05, logScale=False, cMap="magma_r")
    if showFit:
        RE = np.reshape(self.dinv.response, [len(self.t), -1])
        _, ax = plt.subplots(nrows=RE.shape[0], ncols=2, figsize=(5, 12),
                             sharex=True, sharey=True)
        kw = dict(cMin=0, cMax=100, logScale=False, colorBar=0, cMap="magma")
        for i, re in enumerate(RE):
            ert.show(self.data, self.MA[i, :], ax=ax[i, 0], **kw)
            ert.show(self.data, re*1000, ax=ax[i, 1], **kw)

invertMa(nr=0, ma=None, fop=None, mesh=None, res=None, debug=False, reg=None, **kwargs)

Invert for chargeability.

Directly invert apparent chargeability for intrinsic chargeability. As the Jacobian of the ERT forward operator is needed, the inversion of the DC data must be done before.

Parameters:

Name Type Description Default
nr int[0]

gate to invert (counting from 1), 0 means fitted (zero-time) Ma

0
error float[0.002]

error in apparent chargeability

required
lam float[100]

regularization strength

required
zWeight float[1.0]

vertical penalty

required
robustData bool[False]

use L1 norm on data misfit

required
blockyModel

use L1 norm on model roughness

required
regionFile str

load region file

required
show bool[False]

show resulting chargeability distribution

required
fop DC * MultiElectrodeModelling

DC forward operator

None
mesh Mesh

inversion mesh

None
res iterable

resistivity vector

None
Source code in tdip\tdip.py
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
def invertMa(self, nr=0, ma=None, fop=None, mesh=None,
             res=None, debug=False, reg=None, **kwargs):
    """Invert for chargeability.

    Directly invert apparent chargeability for intrinsic chargeability.
    As the Jacobian of the ERT forward operator is needed, the inversion of
    the DC data must be done before.

    Parameters
    ----------
    nr : int [0]
        gate to invert (counting from 1), 0 means fitted (zero-time) Ma
    error : float [0.002]
        error in apparent chargeability
    lam : float [100]
        regularization strength
    zWeight : float [1.0]
        vertical penalty
    robustData : bool [False]
        use L1 norm on data misfit
    blockyModel: bool [False]
        use L1 norm on model roughness
    regionFile : str
        load region file
    show : bool [False]
        show resulting chargeability distribution

    fop : pg.DC*MultiElectrodeModelling
        DC forward operator
    mesh : pg.Mesh
        inversion mesh
    res : iterable
        resistivity vector
    """
    show = kwargs.pop('show', False)
    if ma is None:
        if nr == 0 or nr == '0':
            if self.data.exists('m0'):
                ma = self.data('m0') * 0.001
            else:
                pg.info("fitted M0 not existing, taking first gate")
                ma = self.MA[0] * 0.001
        else:
            if isinstance(nr, float):
                pg.info("Using closest gate to time ", nr)
                nr = np.argmin(np.abs(self.t-nr)) + 1
                pg.info(" : ", nr)

            ma = self.MA[nr-1] * 0.001  # should MA be in V/V instead?

    errLevel = kwargs.pop('error', 0.002)
    if hasattr(errLevel, '__iter__') and len(errLevel) == len(ma):
        maerr = errLevel
    else:
        maerr = np.ones_like(ma) * errLevel

    # restrict values above 1
    if 0:
        maerr[ma > 1] = 1e5
        ma[ma > 1] = 0.99
    # restrict values below 1
    if 0:
        maerr[ma < 0] = 1e5
        ma[ma < 0] = 0.001

    if isinstance(ma, np.ma.MaskedArray):
        maerr[ma.mask] = 1e5
        ma = np.copy(ma.data)

    fIP = []
    verbose = kwargs.pop("verbose", False)
    if kwargs.pop("Seigel", False):
        fIP = DCIPSeigelModelling(self.ERT)
        res = self.res
    else:
        if fop is None:
            fop = self.ERT.fop
        if mesh is None:
            mesh = self.ERT.mesh
        if res is None:
            res = self.res  # self.ERT.model

        if hasattr(self, "response") and hasattr(self.response,
                                                 "__iter__"):
            fIP = DCIPMModelling(fop, mesh, res, verbose,
                                 response=self.response)
        else:
            fIP = DCIPMModelling(fop, mesh, res, verbose)

        if 'regionFile' in kwargs:
            fIP.regionManager().loadMap(kwargs.pop('regionFile'))
        else:
            if fop.regionManager().regionCount() > 1:
                fIP.region(1).setBackground(True)
                fIP.region(2).setConstraintType(1)

    fIP.regionManager().setZWeight(kwargs.pop('zWeight', 1.0))
    fIP.createRefinedForwardMesh(True)
    # tD, tM = pg.core.RTransLog(), pg.core.RTransLogLU(0, 0.99)
    self.invIP = pg.Inversion(fop=fIP, verbose=True, debug=debug)
    self.invIP.modelTrans = pg.trans.TransLogLU(0.0001, 0.999)
    mstart = pg.Vector(len(res), np.abs(pg.median(ma)))
    kwargs.setdefault('lam', 100)
    if reg:
        self.invIP.setRegularization(**reg)
    self.m = self.invIP.run(ma, maerr/ma, startModel=mstart, **kwargs)
    pg.info(f"chi^2={self.invIP.chi2():.1f} RMS={self.invIP.absrms()*1000:.1f}mV/V")
    if show:
        return self.showChargeability()
    else:
        return self.invIP

invertRhoa(**kwargs)

Invert apparent resistivity. kwargs forwarded to ERTManager.

Source code in tdip\tdip.py
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
def invertRhoa(self, **kwargs):
    """Invert apparent resistivity. kwargs forwarded to ERTManager."""
    if self.ERT is None:
        self.ERT = ert.ERTManager()

    self.ERT.fop.setData(self.data)
    if "mesh" in kwargs:
        self.ERT.fop.setMesh(kwargs["mesh"])

    show = kwargs.pop('show', False)
    if not self.data.haveData("err"):
        self.data["err"] = ert.estimateError(self.data)

    self.res = self.ERT.invert(data=self.data, **kwargs)
    self.response = self.ERT.inv.response
    self.coverage = self.ERT.coverage()
    self.pd = self.ERT.paraDomain
    self.pd["resistivity"] = self.res
    self.pd["coverage"] = self.coverage
    if show:
        return self.showResistivity()

load(*args, **kwargs)

Load data. Use loadData instead.

Source code in tdip\tdip.py
127
128
129
130
def load(self, *args, **kwargs):
    """Load data. Use loadData instead."""
    pg.deprecated("use loadData instead")
    self.loadData(*args, **kwargs)

loadData(filename=None)

Load data from any of the supported file types.

Supported formats

TXT - ABEM or Syscal Ascii (column) output BIN - Syscal binary format DAT - Res2dInv format GDD - GDD format (less tested) TX2 - Aarhus Workbench data DIP - AarhusInv (processed) data OHM - BERT format with ip1, ip2, ... fields OHM/MA - BERT format with scheme file and MA file

Source code in tdip\tdip.py
 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
def loadData(self, filename=None):  # , **kwargs):
    """Load data from any of the supported file types.

    Supported formats
    -----------------
    TXT - ABEM or Syscal Ascii (column) output
    BIN - Syscal binary format
    DAT - Res2dInv format
    GDD - GDD format (less tested)
    TX2 - Aarhus Workbench data
    DIP - AarhusInv (processed) data
    OHM - BERT format with ip1, ip2, ... fields
    OHM/MA - BERT format with scheme file and MA file
    """
    assert isinstance(filename, str), "Needs string to load files"
    self.basename = filename[:filename.rfind('.')]
    if Path(filename).is_file() and not filename.endswith(".shm"):
        self.data, self.MA, self.t, self.header = importTDIPdata(filename)
    elif (Path(self.basename+'.MA').is_file() and Path(self.basename+'.shm').is_file()):
        self.data = pg.DataContainerERT(self.basename+'.shm')
        MAT = np.genfromtxt(self.basename+'.MA').T
        self.t = MAT[:, 0]
        self.MA = MAT[:, 1:]
    else:
        raise ImportError("Could not read data")

    self.data.checkDataValidity(remove=False)
    try:
        self.MA = self.MA[:, np.array(self.data('valid'), dtype=bool)]
    except Exception:
        print("no valid apparent chargeability")

    self.data.removeInvalid()
    self.ensureRhoa()

    return

loadFit(**kwargs)

Load fitted chargeability, time constant & exponent from file.

Source code in tdip\tdip.py
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
def loadFit(self, **kwargs):
    """Load fitted chargeability, time constant & exponent from file."""
    basename = kwargs.pop("basename", self.basename)
    if Path(basename+".rmtc").is_file():
        self.res, self.m0, self.tau, self.c, self.fit = np.loadtxt(
            basename+'.rmtc', unpack=1)
    elif Path(basename+".mtc").is_file():
        self.m0, self.tau, self.c, self.fit = np.loadtxt(
            basename+'.mtc', unpack=1)
        pg.info("Loading deprecated fit result (mtc) instead of rmtc")
    else:
        pg.warn("Could not find fit result " + basename + ".(r)mtc")

loadResult(*args, **kwargs)

Load results (old name). Use load results.

Source code in tdip\tdip.py
1257
1258
1259
1260
def loadResult(self, *args, **kwargs):
    """Load results (old name). Use load results."""
    pg.deprecated("use loadResults instead")
    self.loadResults(*args, **kwargs)

loadResults(loadColeCole=False, **kwargs)

Load inversion results from file.

Loads three (or four) files: - _pd.bms : mesh file of inversion mesh - .rho : resistivity vector (ascii column) - .M : spectral chargeability (ascii columns for each gate) - .rmtc : Cole-Cole/Debye results with rho, m, tau, c (and fit) (previously called .mtc without resistivity)

Parameters:

Name Type Description Default
loadColeCole bool[False]

try loading Cole-Cole or Debye inversion results

False
basename str[basename]

file base name (*) to load

required
Source code in tdip\tdip.py
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
def loadResults(self, loadColeCole=False, **kwargs):
    """Load inversion results from file.

    Loads three (or four) files:
        - *_pd.bms : mesh file of inversion mesh
        - *.rho : resistivity vector (ascii column)
        - *.M : spectral chargeability (ascii columns for each gate)
        - *.rmtc : Cole-Cole/Debye results with rho, m, tau, c (and fit)
          (previously called .mtc without resistivity)

    Parameters
    ----------
    loadColeCole : bool [False]
        try loading Cole-Cole or Debye inversion results
    basename : str [self.basename]
        file base name (*) to load
    """
    basename = kwargs.pop("basename", self.basename)
    self.pd = pg.Mesh(basename+'_pd.bms')
    if Path(basename+'.rho').is_file():
        self.res = np.loadtxt(basename+'.rho')
    if Path(basename+'.M').is_file():
        self.M = np.loadtxt(basename+'.M').T
        if self.M.shape[0] == self.pd.cellCount():  # old style
            self.M = self.M.T
    if Path(basename+'.mtc').is_file() or Path(basename+'.rmtc').is_file():
        self.loadFit(basename=basename)
    if Path(basename+".rtd").is_file():
        B = np.loadtxt(basename+".rtd")
        self.tau = B[0]
        self.modelDebye = B[1:].T

mask(mamin=1e-06, mamax=10000, filter=False)

Mask out outliers.

Parameters:

Name Type Description Default
The
required
mamin double

minimum/maximum chargeability

1e-06
mamax double

minimum/maximum chargeability

1e-06
Source code in tdip\tdip.py
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
def mask(self, mamin=1e-6, mamax=10000, filter=False):
    """Mask out outliers.

    Parameters
    ----------
    The following filters will mask the whole decay (i.e. deactivate IP)

    mamin, mamax : double
        minimum/maximum chargeability
    """
    self.MA = np.ma.masked_outside(self.MA, mamin, mamax)
    if filter:
        print("Filtering after masking")
        self.filter(nr=np.nonzero(
            ~np.ma.any(self.MA, axis=0).data)[0])

saveData(basename=None, **kwargs)

Save all data as shm and accompagnying .MA (like FDIP) files.

Source code in tdip\tdip.py
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
def saveData(self, basename=None, **kwargs):
    """Save all data as shm and accompagnying .MA (like FDIP) files."""
    basename = basename or self.basename
    self.data.save(basename+".shm", "a b m n k rhoa")
    MA = np.array(self.MA.data)
    if isinstance(self.MA, np.ma.masked_array):
        MA[self.MA.mask] = 999

    A = np.column_stack((self.t, MA))
    np.savetxt(basename+".MA", A.T, fmt="%6.3f", delimiter="\t")
    data = pg.DataContainerERT(self.data)
    tokens = "a b m n k rhoa"
    if self.data.haveData("m0"):
        tokens += " m0"

    for i in range(self.MA.shape[0]):
        tok = "ip"+str(i+1)
        data[tok] = MA[i, :]
        tokens += " " + tok

    data.save(basename+".ohm", tokens)

saveFigures(ext='.pdf', **kwargs)

Save all figures in .figs to disk.

Source code in tdip\tdip.py
1201
1202
1203
1204
1205
1206
def saveFigures(self, ext='.pdf', **kwargs):
    """Save all figures in .figs to disk."""
    kwargs.setdefault('bbox_inches', 'tight')
    basename = kwargs.pop('basename', self.basename)
    for key in self.figs:
        self.figs[key].savefig(basename+'-'+key+ext, **kwargs)

saveFit(**kwargs)

Save fitted chargeability, time constant & exponent to file.

Source code in tdip\tdip.py
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
def saveFit(self, **kwargs):
    """Save fitted chargeability, time constant & exponent to file."""
    basename = kwargs.pop("basename", self.basename)
    if kwargs.pop("noRes", False):  # old style
        if np.any(self.m0) and np.any(self.tau) and np.any(self.c):
            np.savetxt(self.basename+'.mtc', np.column_stack(
                (self.m0, self.tau, self.c, self.fit)))
    else:
        if (np.any(self.res) and np.any(self.m0) and
                np.any(self.tau) and np.any(self.c)):
            np.savetxt(basename+'.rmtc', np.column_stack(
                (self.res, self.m0, self.tau, self.c, self.fit)))

saveResults(**kwargs)

Save inversion results to .rho and .M file plus mesh.

Source code in tdip\tdip.py
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
def saveResults(self, **kwargs):
    """Save inversion results to .rho and .M file plus mesh."""
    basename = kwargs.pop("basename", self.basename)
    self.pd.save(basename+'_pd.bms')  # better .bms only?
    self.pd["coverage"] = self.ERT.coverage()
    self.pd["resistivity"] = self.res
    self.pd.exportVTK(basename+".vtk")
    if self.res is not None:
        np.savetxt(basename+'.rho', self.res)
    if self.M is not None:
        np.savetxt(basename+'.M', self.M.T)
    if self.modelDebye is not None:
        A = np.hstack([self.tau.reshape(-1, 1), self.modelDebye])
        np.savetxt(basename+".rtd", A.T)

    self.saveFit()

setGates(t=None, dt=None, delay=0.0)

Set time by specifying midpoints (t) or gate lengths dt & delay.

Source code in tdip\tdip.py
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
def setGates(self, t=None, dt=None, delay=0.0):
    """Set time by specifying midpoints (t) or gate lengths dt & delay."""
    if t is None:
        assert dt is not None, "gate length and delay time must be set"
        if isinstance(dt, float):  # constant gate length
            self.dt = np.ones(len(self.t)) * dt
        else:
            self.dt = np.array(dt)

        t = np.cumsum(self.dt) - self.dt/2 + delay
        self.header['ipGateT'] = np.cumsum(np.hstack((0, self.dt))) + delay
        self.header['dt'] = self.dt
        self.header['delay'] = delay

    assert len(t) == self.MA.shape[0]
    self.t = t

showApparentChargeability(ax=None, nr=0, **kwargs)

Show apparent chargeability of a single Windows.

Source code in tdip\tdip.py
499
500
501
502
503
504
505
506
507
508
def showApparentChargeability(self, ax=None, nr=0, **kwargs):
    """Show apparent chargeability of a single Windows."""
    kwargs.setdefault('cMap', 'plasma')
    kwargs.setdefault('cMin', 0.1)
    kwargs.setdefault('cMax', 1000)
    if ax is None:
        fig, ax = plt.subplots()
        self.figs[f'MA{nr:02d}'] = fig

    ert.show(self.data, self.MA[nr-1], ax=ax, **kwargs)

showChargeability(ax=None, **kwargs)

Show chargeability inversion result.

Any kwargs (ax, cMin, cMax, logScale) are forwarded to pg.show.

Source code in tdip\tdip.py
929
930
931
932
933
934
935
936
def showChargeability(self, ax=None, **kwargs):
    """Show chargeability inversion result.

    Any kwargs (ax, cMin, cMax, logScale) are forwarded to pg.show.
    """
    kwargs.setdefault('label', 'chargeability [mV/V]')
    kwargs.setdefault('cMap', 'plasma')
    return pg.show(self.ERT.paraDomain, self.m*1e3, ax=ax, **kwargs)

showColeColeResults(rlim=(None, None), clim=(0, 0.5), mlim=(None, None), tlim=(None, None), shFit=0)

Show resulting Cole-Cole models.

Source code in tdip\tdip.py
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
def showColeColeResults(self, rlim=(None, None), clim=(0, 0.5),
                        mlim=(None, None), tlim=(None, None), shFit=0):
    """Show resulting Cole-Cole models."""
    isCC = int(min(self.c) < 1)
    fig, ax = plt.subplots(nrows=3+isCC+int(shFit), figsize=(8, 12))
    pg.show(self.pd, self.res, ax=ax[0], label='resistivity (Ohmm)',
            cMap='Spectral_r', cMin=rlim[0], cMax=rlim[1], logScale=True)
    pg.show(self.pd, self.m0*1000, ax=ax[1], cMin=mlim[0], cMax=mlim[1],
            label='M (mV/V)', cMap='plasma', logScale=False)
    pg.show(self.pd, self.tau, ax=ax[2], cMin=tlim[0], cMax=tlim[1],
            label=r'$\tau$ (s)')
    if isCC:
        pg.show(self.pd, self.c, cMin=clim[0], cMax=clim[1],
                logScale=False, ax=ax[3], label=r'$c$ (-)')
    if shFit:
        pg.show(self.pd, self.fit, cMin=clim[0], cMax=clim[1],
                logScale=False, ax=ax[-1], label=r'fit (-)')

    fig.tight_layout()
    self.figs['resultCC'] = fig
    return ax

showData(*args, **kwargs)

Show apparent resistivity pseudosection.

Parameters:

Name Type Description Default
cMin float

minimum/maximum colorbar range (otherwise min/max data)

required
cMax float

minimum/maximum colorbar range (otherwise min/max data)

required
cMap string or colormap[Spectral_r]

colormap to be used

required
**kwargs plotting arguments (see ert.showData)
{}
Source code in tdip\tdip.py
263
264
265
266
267
268
269
270
271
272
273
274
275
276
def showData(self, *args, **kwargs):
    """Show apparent resistivity pseudosection.

    Parameters
    ----------
    cMin, cMax : float
        minimum/maximum colorbar range (otherwise min/max data)
    cMap : string or colormap ['Spectral_r']
        colormap to be used
    **kwargs : plotting arguments (see ert.showData)
    """
    kwargs.setdefault('cMap', 'Spectral_r')
    kwargs.setdefault('logScale', True)
    return ert.showData(self.data, *args, **kwargs)

showDecay(nr=[], ax=None, ab=None, mn=None, verbose=True, **kwargs)

Show decay curves for groups of data.

Parameters:

Name Type Description Default
nr iterable

list of data indices to show, if not given ab/mn are analysed

[]
ab [int, int]

list of sensor numbers for current injection (counting from 1)

None
mn [int, int]

list of sensor numbers for potential (counting from 1)

None
Plotting Keywords

showFit : bool [False] show fitted Debye or Cole-Cole curve label : str legend label for single data, otherwise generated from A,B,M,N basename : str string to prepend to automatically generated label marker : str ['x'] marker to use for plotting xlim, ylim : [float, float] limits for x or y axis xscale : str ['linear'] scaling of x axis yscale : str ['log'] scaling of y axis xlabel : str [r'$t$ [s]'] label for the x axis ylabel : str [r'$m_a$ [mV/V]'] label for the y axis

Source code in tdip\tdip.py
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
def showDecay(self, nr=[], ax=None, ab=None, mn=None, verbose=True, **kwargs):
    """Show decay curves for groups of data.

    Parameters
    ----------
    nr : iterable
        list of data indices to show, if not given ab/mn are analysed
    ab : [int, int]
        list of sensor numbers for current injection (counting from 1)
    mn : [int, int]
        list of sensor numbers for potential (counting from 1)

    Plotting Keywords
    -----------------
    showFit : bool [False]
        show fitted Debye or Cole-Cole curve
    label : str
        legend label for single data, otherwise generated from A,B,M,N
    basename : str
        string to prepend to automatically generated label
    marker : str ['x']
        marker to use for plotting
    xlim, ylim : [float, float]
        limits for x or y axis
    xscale : str ['linear']
        scaling of x axis
    yscale : str ['log']
        scaling of y axis
    xlabel : str [r'$t$ [s]']
        label for the x axis
    ylabel : str [r'$m_a$ [mV/V]']
        label for the y axis
    """
    data = self.data
    if "basename" in kwargs:
        bs = kwargs['basename']
    else:
        bs = 'abmn'
        if ab is not None:
            bs = "mn"
    if ab is not None:
        a = np.minimum(data('a'), data('b'))
        b = np.maximum(data('a'), data('b'))
        # nr.extend(pg.find((a == min(ab)-1) & (b == max(ab)-1)))
        nr = np.nonzero(np.isclose(a, min(ab)-1) &
                        np.isclose(b, max(ab)-1))[0]
    if mn is not None:
        m = np.minimum(data('m'), data('n'))
        n = np.maximum(data('m'), data('n'))
        # fi = pg.find((m == min(mn)-1) & (n == max(mn)-1))
        fi = np.nonzero(np.isclose(m, min(mn)-1) &
                        np.isclose(n, max(mn)-1))[0]
        if ab is not None:  # already chose AB dipole => select
            nr = np.intersect1d(nr, fi)
        else:
            nr.extend(fi)

    kwargs.setdefault('marker', 'x')
    kwargs.setdefault('xscale', 'log')
    kwargs.setdefault('yscale', 'log')
    shFit = (kwargs.pop('showFit', False) and self.data.haveData('m0') and
             self.data.haveData('tau'))
    ls = "" if shFit else "-"
    kwargs.setdefault('ls', ls)
    if verbose:
        print("nr=", nr)
        if shFit:
            print("fit = " + np.array2string(np.array(self.data['fit'][nr])))

    outkeys = ['xlim', 'ylim', 'xlog', 'ylog', 'xscale', 'yscale']
    if isinstance(nr, int):
        nr = [nr]
    if len(nr) > 0:
        if ax is None:
            self.figs['decay'], ax = plt.subplots()

        for nn in nr:
            abmn = [int(self.data(t)[nn]+1) for t in ['a', 'b', 'm', 'n']]
            kw = kwargs.copy()
            for key in outkeys:
                if key in kw:
                    kw.pop(key)

            ma = self.MA[:, nn]
            if kw.pop('invalid', False):
                ax.plot(self.t, ma.data, color='gray', ms=2,
                        marker=kwargs["marker"], ls=ls)
                ax.plot(self.t, -np.array(ma.data), ls='--',
                        color='lightgray', ms=2, marker=kwargs["marker"])
            if ab is not None:
                kw.setdefault('label', (bs+': '+'{:d} '*2).format(
                    *abmn[2:]))
                kw.setdefault('color', "C"+str(abmn[2] % 9))
            else:
                kw.setdefault('label', (bs+': '+'{:d} '*4).format(*abmn))
            li = ax.plot(self.t, ma, **kw)[0]
            if shFit and np.ma.any(ma):
                fit = self.data['m0'][nn] * \
                    np.exp(-np.array(self.t)/self.data['tau'][nn])
                ax.plot(self.t, fit, color=li.get_color(), ls='--')

        ax.grid(True)
        ax.legend()
        if 'xlim' in kwargs:
            ax.set_xlim(kwargs['xlim'])
        if 'ylim' in kwargs:
            ax.set_ylim(kwargs['ylim'])
        if 'xscale' in kwargs:
            ax.set_xscale(kwargs['xscale'])
        if 'yscale' in kwargs:
            ax.set_yscale(kwargs['yscale'])
        ax.set_xlabel(kwargs.pop('xlabel', r'$t$ [s]'))
        ax.set_ylabel(kwargs.pop('ylabel', r'$m_a$ [mV/V]'))
        tit = ""
        if ab is not None:
            tit = "A-B = {:d}-{:d}".format(*abmn[:2])
        if mn is not None:
            tit += " , M-N = {:d}-{:d}".format(*abmn[2:])

        if len(tit) > 0 and len(ax.get_title()) == 0:
            ax.set_title(tit)

        return ax

showIntegralChargeability(**kwargs)

Show integral chargeability (kwargs forwarded to ert.show).

Source code in tdip\tdip.py
330
331
332
333
334
335
336
337
338
def showIntegralChargeability(self, **kwargs):
    """Show integral chargeability (kwargs forwarded to ert.show)."""
    if not self.data.haveData('mint'):
        self.data['mint'] = self.integralChargeability(**kwargs)

    kwargs.setdefault('cMap', 'plasma')
    kwargs.setdefault('logScale', True)

    return ert.showData(self.data, self.data('mint'), **kwargs)

showMa(nr=0, **kwargs)

Show apparent chargeability (kwargs forwarded to ert.showData).

Parameters:

Name Type Description Default
nr int[0]

number of time gate to show

0
**kwargs any plotting arguments to be passed to ert.showData
{}
Source code in tdip\tdip.py
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
def showMa(self, nr=0, **kwargs):
    """Show apparent chargeability (kwargs forwarded to ert.showData).

    Parameters
    ----------
    nr : int [0]
        number of time gate to show
    **kwargs : any plotting arguments to be passed to ert.showData
    """
    kwargs.setdefault('cMap', 'plasma')
    kwargs.setdefault('logScale', True)
    kwargs.setdefault('label', 'chargeability (mV/V)')
    ax, cb = ert.showData(self.data, self.MA[nr], **kwargs)
    ax.set_title(f'$t$={self.t[nr]:.3f}')
    return ax, cb

showModelDecay(cellID, **kwargs)

Show SIP spectrum for single cell (id or position).

Source code in tdip\tdip.py
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
def showModelDecay(self, cellID, **kwargs):
    """Show SIP spectrum for single cell (id or position)."""
    decay, idx = self.getModelDecay(cellID, return_index=True)
    shfit = kwargs.pop("showFit", False)
    if 'ax' in kwargs:
        ax = kwargs.pop('ax')
    else:
        self.figs['modelDecay'], ax = plt.subplots()
        # kwargs.setdefault('xLabel)

    kwargs.setdefault("label", 'inverted')
    ax.loglog(self.t, decay*1000, 'x-', **kwargs)
    if shfit:
        if hasattr(self, 'FWR'):
            ax.loglog(self.t, self.FWR[:, idx]*1000, label='fitted')
        else:

            pg.warn("No fwd!")

    ax.legend()
    ax.grid(True)
    return ax

showModelDecays(positions=None, **kwargs)

Show model spectra for a number of positions or IDs.

Source code in tdip\tdip.py
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
def showModelDecays(self, positions=None, **kwargs):
    """Show model spectra for a number of positions or IDs."""
    kwargs.setdefault("showFit", False)
    self.figs['modelDecays'], ax = plt.subplots()
    LABELS = []
    if positions is None:  # not given: check for x and z vectors
        x = kwargs.pop("x", None)
        z = kwargs.pop("z", None)
        if z is None:
            z = kwargs.pop("y", None)
        if x is None and z is None:
            raise NameError("Specify either position vector or x and z")
        if isinstance(x, (float, int)):
            x = np.ones_like(z) * x
        if isinstance(z, (float, int)):
            z = np.ones_like(x) * z

        positions = [[xi, zi] for xi, zi in zip(x, z, strict=False)]

    for pos in positions:
        label = 'x={:.1f} z={:.1f}'.format(*pos)
        LABELS.append(label)
        # kwargs['label'] = label
        self.showModelDecay(pos, ax=ax, **kwargs)

    ax.set_ylim(auto=True)
    # ax.set_xlim(min(self.freq), max(self.freq))
    ax.legend(LABELS, loc='best')

    return ax

showResistivity(ax=None, **kwargs)

Show resistivity inversion result.

Any kwargs (cMin, cMax, logScale) are forwarded to pg.show.

Source code in tdip\tdip.py
916
917
918
919
920
921
922
923
924
925
926
927
def showResistivity(self, ax=None, **kwargs):
    """Show resistivity inversion result.

    Any kwargs (cMin, cMax, logScale) are forwarded to pg.show.
    """
    kwargs.setdefault('logScale', True)
    kwargs.setdefault('label', r'resistivity [$\Omega$m]')
    kwargs.setdefault('cMap', 'Spectral_r')
    kwargs.setdefault('coverage', self.ERT.coverage())
    if self.pd is None or len(self.res) != self.pd.cellCount():
        self.pd = self.ERT.paraDomain
    return pg.show(self.pd, self.res, ax=ax, **kwargs)

showResults(rkw={}, mkw={})

Show result (resistivity and chargeability in two subfigures).

Parameters:

Name Type Description Default
rkw dict

dictionary for being passed to showResistivity

{}
mkw dict

dictionary for being passed to showChargeability

{}
Source code in tdip\tdip.py
938
939
940
941
942
943
944
945
946
947
948
949
950
951
def showResults(self, rkw={}, mkw={}):
    """Show result (resistivity and chargeability in two subfigures).

    Parameters
    ----------
    rkw : dict
        dictionary for being passed to showResistivity
    mkw : dict
        dictionary for being passed to showChargeability
    """
    self.figs['result'], ax = plt.subplots(nrows=2)
    self.showResistivity(ax=ax[0], **rkw)
    self.showChargeability(ax=ax[1], **mkw)
    return ax

showRhoa(**kwargs)

Old function for showing apparent resistivity. Use showData.

Source code in tdip\tdip.py
278
279
280
281
def showRhoa(self, **kwargs):  # backward compatibility
    """Old function for showing apparent resistivity. Use showData."""
    pg.deprecated("Use showData.")
    return self.showData(**kwargs)

simulate(**kwargs)

Synthetic simulation based on Cole-Cole model.

Parameters:

Name Type Description Default
mesh Mesh

mesh with regions to be mapped

required
rhovec array

resistivities of the regions

required
mvec iterable

chargeabilities

required
tauvec iterable

time constants

required
cvec iterable

relaxation exponents

required
scheme DataContainerERT[data]

protocol file

required
fr iterable[freq]

frequency vector

required
noiseLevel float[0]

relative error model

required
noiseAbs float[1e-05]

absolute error model

required
sr bool[True]

use singularity removal (secondary field)

required
verbose bool[False]

some output

required
Source code in tdip\tdip.py
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
def simulate(self, **kwargs):
    """Synthetic simulation based on Cole-Cole model.

    Parameters
    ----------
    mesh : pg.Mesh
        mesh with regions to be mapped
    rhovec : array
        resistivities of the regions
    mvec : iterable
        chargeabilities
    tauvec : iterable
        time constants
    cvec : iterable
        relaxation exponents
    scheme : pg.DataContainerERT [self.data]
        protocol file
    fr : iterable [self.freq]
        frequency vector
    noiseLevel : float [0]
        relative error model
    noiseAbs : float [1e-5]
        absolute error model
    sr : bool [True]
        use singularity removal (secondary field)
    verbose : bool [False]
        some output
    """
    from fdip import FDIP

    if "scheme" in kwargs:
        self.data = kwargs.pop("scheme")

    if "t" in kwargs:
        self.t = kwargs.pop("t")

    fdip = FDIP(f=kwargs.pop("f", np.logspace(-3, 3, 41)),
                data=self.data)
    fdip.simulate(**kwargs)
    self.data["rhoa"] = fdip.RHOA[:, 0]
    self.MA = np.zeros((len(self.t), self.data.size()))
    spec = SIPSpectrum(f=fdip.freq)
    tau = kwargs.pop("tau", np.logspace(-4, 1, 41))
    for i in range(fdip.data.size()):
        spec.amp = fdip.RHOA[i]
        spec.phi = fdip.PHIA[i]
        spec.fitDebyeModel(tau=tau, lam=1, verbose=False)
        self.MA[:, i] = spec.createDecay(t=self.t) * 1000 # mV/V

simultaneousInversion(fop=None, res=None, **kwargs)

Carry out simultaneous inversion with smoothness along t axis.

Source code in tdip\tdip.py
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
def simultaneousInversion(self, fop=None, res=None, **kwargs):
    """Carry out simultaneous inversion with smoothness along t axis."""
    errLevel = kwargs.pop('error', 0.002)
    if fop is None or res is None:
        if self.ERT is None:
            self.invertRhoa(**kwargs)  # rather check whether already done!

        fop = self.ERT.fop

    fop.setVerbose(False)
    error = np.ones_like(self.MA) * errLevel
    MA = np.copy(self.MA.data)  # make a copy as it will be changed
    if isinstance(self.MA, np.ma.MaskedArray):
        error[self.MA.mask] = 1e8
        MA[self.MA.mask] = 0.1

    fIP = DCIPMSmoothModelling(fop, self.pd, self.res,
                               self.t)
    fIP.createRefinedForwardMesh(False)
    fIP.regionManager().setZWeight(kwargs.get('zWeight', 0.3))
    tD, tM = pg.trans.Trans(), pg.trans.TransLogLU(0, 0.99)
    INV = pg.Inversion(fop=fIP, verbose=True, debug=False)
    INV.dataTrans = tD
    INV.modelTrans = tM
    print(kwargs)
    mstart = pg.Vector(fIP.nc*fIP.nt, 0.1)
    dataVals = MA.ravel()*0.001
    INV.setRegularization(cType=2)
    kwargs.setdefault("lam", 100)
    mm = INV.run(dataVals, error.ravel()/dataVals,
                 startModel=mstart, **kwargs)
    self.M = np.reshape(mm, (-1, self.pd.cellCount()))
    self.MAfwd = np.reshape(INV.response, (len(self.t), -1))