Browse Source

Inversion data space plots are improved greatly from previous

tags/1.6.1
Trevor Irons 3 years ago
parent
commit
c279d06331
2 changed files with 285 additions and 91 deletions
  1. 280
    86
      akvo/tressel/invertTA.py
  2. 5
    5
      akvo/tressel/logbarrier.py

+ 280
- 86
akvo/tressel/invertTA.py View File

@@ -28,6 +28,16 @@ from akvo.tressel import nonlinearinv as nl
28 28
 
29 29
 import pandas as pd
30 30
 
31
+
32
+import matplotlib.colors as colors
33
+
34
+# From https://stackoverflow.com/questions/18926031/how-to-extract-a-subset-of-a-colormap-as-a-new-colormap-in-matplotlib
35
+def truncate_colormap(cmap, minval=0.0, maxval=1.0, n=100):
36
+    new_cmap = colors.LinearSegmentedColormap.from_list(
37
+        'trunc({n},{a:.2f},{b:.2f})'.format(n=cmap.name, a=minval, b=maxval),
38
+        cmap(np.linspace(minval, maxval, n)))
39
+    return new_cmap
40
+
31 41
 def buildKQT(K0,tg,T2Bins):
32 42
     """ 
33 43
         Constructs a QT inversion kernel from an initial amplitude one.  
@@ -77,7 +87,7 @@ def loadAkvoData(fnamein, chan):
77 87
     J = AKVO.Pulses["Pulse 1"]["current"].data 
78 88
     J = np.append(J,J[-1]+(J[-1]-J[-2]))
79 89
     Q = AKVO.pulseLength[0]*J
80
-    return Z, ZS, AKVO.Gated["Pulse 1"]["abscissa"].data  #, Q
90
+    return Z, ZS, AKVO.Gated["Pulse 1"]["abscissa"].data, Q
81 91
 
82 92
 def catLayers(K0):
83 93
     K = np.zeros( (len(K0.keys()), len(K0["layer-0"].data)) , dtype=complex )
@@ -97,6 +107,11 @@ def loadK0(fname):
97 107
     return ifaces, K
98 108
     #return ifaces, np.abs(K)
99 109
 
110
+def invertDelta(G, V_n, T2Bins, sig, alphastar):
111
+    """ helper function that simply calls logBarrier, simplfies parallel execution
112
+    """
113
+    model = logBarrier(G, V_n, T2Bins, "Single", MAXITER=1, sigma=sig, alpha=alphastar, smooth="Smallest") 
114
+    return model
100 115
 
101 116
 
102 117
 def main():
@@ -116,13 +131,15 @@ def main():
116 131
     ###############################################
117 132
     V = []
118 133
     VS = []
134
+    QQ = []
119 135
     tg = 0
120 136
     for dat in cont['data']:
121 137
         for ch in cont['data'][dat]['channels']:
122 138
             print("dat", dat, "ch", ch)
123
-            v,vs,tg = loadAkvoData(dat, ch)
139
+            v,vs,tg,Q = loadAkvoData(dat, ch)
124 140
             V.append(v)
125 141
             VS.append(vs)
142
+            QQ.append(Q)
126 143
     for iv in range(1, len(V)):
127 144
         V[0] = np.concatenate( (V[0], V[iv]) )
128 145
         VS[0] = np.concatenate( (VS[0], VS[iv]) )
@@ -147,8 +164,9 @@ def main():
147 164
     #plt.show()
148 165
     #exit()
149 166
 
150
-    ##########################################################    
151
-    # VERY Simple Sensitivity based calc. of noise per layer #
167
+    ##############################################################    
168
+    # VERY Simple Sensitivity based calc. of noise per layer     #
169
+    # minimally useful, but retained for backwards compatibility #
152 170
     maxq = np.argmax(np.abs(K0), axis=1)
153 171
     maxK = .1 *  np.abs(K0)[ np.arange(0,len(ifaces)-1), maxq ] # 10% water is arbitrary  
154 172
     SNR = maxK / (VS[0][0])
@@ -170,25 +188,80 @@ def main():
170 188
     inv, ibreak, errn, phim, phid, mkappa, Wd, Wm, alphastar = logBarrier(KQT, np.ravel(V), T2Bins, "lcurve", MAXITER=150, sigma=np.ravel(VS), alpha=1e6, smooth="Smallest" ) 
171 189
 
172 190
 
173
-    ####################
174
-    # Summary plots    #
175
-    ####################
191
+    ################################
192
+    # Summary plots, Data Space    #
193
+    ################################
194
+
195
+    # TODO, need to clean this up for the case of multiple channels! Each channel should be a new row. It will be ugly, but important 
196
+    # TODO, loop over channels 
197
+    
198
+    ich = 0     
199
+    for ch in cont['data'][dat]['channels']:
200
+
201
+        figx = plt.figure( figsize=(pc2in(42.0),pc2in(22.)) )
202
+        ax1 = figx.add_axes([.100, .15, .200, .70])    
203
+        ax2 = figx.add_axes([.325, .15, .200, .70])   # shifted to make room for shared colourbar 
204
+        axc1= figx.add_axes([.550, .15, .025, .70])   # shifted to make room for shared colourbar 
205
+        ax3 = figx.add_axes([.670, .15, .200, .70])    
206
+        axc2= figx.add_axes([.895, .15, .025, .70])   # shifted to make room for shared colourbar 
207
+
208
+        ax3.set_yscale('log')
209
+        ax2.set_yscale('log')
210
+        ax1.set_yscale('log')
176 211
     
177
-    pre = np.dot(KQT,inv) 
178
-    PRE = np.reshape( pre, np.shape(V)  )
179
-    plt.matshow(PRE, cmap='Blues')
180
-    plt.gca().set_title("linear predicted")
181
-    plt.colorbar()
182
-
183
-    DIFF = (PRE-V) / VS
184
-    md = np.max(np.abs(DIFF))
185
-    plt.matshow(DIFF, cmap=cmocean.cm.balance, vmin=-md, vmax=md)
186
-    plt.gca().set_title("linear misfit / $\widehat{\sigma}$")
187
-    plt.colorbar()
212
+        ax2.yaxis.set_ticklabels([])
213
+        ax3.yaxis.set_ticklabels([])
188 214
     
189
-    plt.matshow(V, cmap='Blues')
190
-    plt.gca().set_title("observed")
191
-    plt.colorbar()
215
+        ax3.set_xscale('log')
216
+        ax2.set_xscale('log')
217
+        ax1.set_xscale('log')
218
+
219
+        ax1.set_ylabel("Q (A $\cdot$ s)")
220
+        ax1.set_xlabel("time (s)")
221
+        ax2.set_xlabel("time (s)")
222
+        ax3.set_xlabel("time (s)")
223
+
224
+        #TT, QQQ = np.meshgrid(tg, np.ravel(QQ))
225
+        
226
+        TT, QQQ = np.meshgrid(tg, np.ravel(QQ[ich]))
227
+        nq = np.shape(QQ[ich])[0] - 1 # to account for padding in pcolor 
228
+        nt = np.shape(tg)[0]
229
+        ntq = nt*nq
230
+        
231
+        VV = V[ich*nq:ich*nq+nq,:]   # slice this channel
232
+        VVS = VS[ich*nq:ich*nq+nq,:] # slice this channel
233
+
234
+        mmax = np.max(np.abs(VV))
235
+        mmin = np.min(VV)
236
+
237
+        obs = ax1.pcolor(TT, QQQ, VV, cmap=cmocean.cm.curl_r, vmin=-mmax, vmax=mmax)
238
+        ax1.set_title("observed")
239
+ 
240
+        pre = np.dot(KQT[ich*ntq:(ich+1)*ntq,:], inv)
241
+ 
242
+        PRE = np.reshape( pre, np.shape(VV)  )
243
+        prem = ax2.pcolor(TT, QQQ, PRE, cmap=cmocean.cm.curl_r, vmin=-mmax, vmax=mmax )
244
+        ax2.set_title("predicted")
245
+
246
+        cbar = plt.colorbar(prem, axc1)
247
+        axc1.set_ylim( [np.min(VV), np.max(VV)] )
248
+        cbar.outline.set_edgecolor(None)
249
+        cbar.set_label('$V_N$ (nV)')
250
+
251
+        DIFF = (PRE-VV) / VVS
252
+        md = np.max(np.abs(DIFF))
253
+        dim = ax3.pcolor(TT, QQQ, DIFF, cmap=cmocean.cm.balance, vmin=-md, vmax=md)
254
+        ax3.set_title("misfit / $\widehat{\sigma}$")
255
+    
256
+        cbar2 = plt.colorbar(dim, axc2)
257
+        #axc1.set_ylim( [np.min(V), np.max(V)] )
258
+        cbar2.outline.set_edgecolor(None)
259
+        cbar2.set_label('$V_N$ (nV)')
260
+        #plt.colorbar(dim, ax3)
261
+    
262
+        figx.suptitle(ch + " linear Inversion")
263
+
264
+        ich += 1
192 265
 
193 266
     ###############################################
194 267
     # Non-linear refinement! 
@@ -226,16 +299,96 @@ def main():
226 299
             if phidc_old - phidc/len(np.ravel(V)) < 0.005:
227 300
                 print("Not making progress reducing misfit in nonlinear refinement")
228 301
                 break
302
+
303
+        # Turn this into a nice figure w/ shared axes etc.    
304
+ 
305
+#         plt.matshow(PREc, cmap='Blues')
306
+#         plt.gca().set_title("nonlinear predicted")
307
+#         plt.colorbar()
308
+# 
309
+#         DIFFc = (PREc-V) / VS
310
+#         md = np.max(np.abs(DIFF))
311
+#         plt.matshow(DIFFc, cmap=cmocean.cm.balance, vmin=-md, vmax=md)
312
+#         plt.gca().set_title("nonlinear misfit / $\widehat{\sigma}$")
313
+#         plt.colorbar()
314
+
315
+
316
+        ################################
317
+        # Summary plots, Data Space    #
318
+        ################################
319
+
229 320
     
230
-        plt.matshow(PREc, cmap='Blues')
231
-        plt.gca().set_title("nonlinear predicted")
232
-        plt.colorbar()
321
+        ich = 0     
322
+        for ch in cont['data'][dat]['channels']:
323
+
324
+            figx = plt.figure( figsize=(pc2in(42.0),pc2in(22.)) )
325
+            ax1 = figx.add_axes([.100, .15, .200, .70])    
326
+            ax2 = figx.add_axes([.325, .15, .200, .70])   # shifted to make room for shared colourbar 
327
+            axc1= figx.add_axes([.550, .15, .025, .70])   # shifted to make room for shared colourbar 
328
+            ax3 = figx.add_axes([.670, .15, .200, .70])    
329
+            axc2= figx.add_axes([.895, .15, .025, .70])   # shifted to make room for shared colourbar 
330
+
331
+            ax3.set_yscale('log')
332
+            ax2.set_yscale('log')
333
+            ax1.set_yscale('log')
334
+    
335
+            ax2.yaxis.set_ticklabels([])
336
+            ax3.yaxis.set_ticklabels([])
337
+    
338
+            ax3.set_xscale('log')
339
+            ax2.set_xscale('log')
340
+            ax1.set_xscale('log')
341
+
342
+            ax1.set_ylabel("Q (A $\cdot$ s)")
343
+            ax1.set_xlabel("time (s)")
344
+            ax2.set_xlabel("time (s)")
345
+            ax3.set_xlabel("time (s)")
346
+
347
+            #TT, QQQ = np.meshgrid(tg, np.ravel(QQ))
348
+        
349
+            TT, QQQ = np.meshgrid(tg, np.ravel(QQ[ich]))
350
+            nq = np.shape(QQ[ich])[0] - 1 # to account for padding in pcolor 
351
+            nt = np.shape(tg)[0]
352
+            ntq = nt*nq
353
+        
354
+            VV = V[ich*nq:ich*nq+nq,:]   # slice this channel
355
+            VVS = VS[ich*nq:ich*nq+nq,:] # slice this channel
356
+
357
+            mmax = np.max(np.abs(VV))
358
+            mmin = np.min(VV)
359
+
360
+            obs = ax1.pcolor(TT, QQQ, VV, cmap=cmocean.cm.curl_r, vmin=-mmax, vmax=mmax)
361
+            ax1.set_title("observed")
362
+
363
+            ## Here neds to change  
364
+            pre = np.abs(np.dot(KQTc[ich*ntq:(ich+1)*ntq,:], inv))
365
+ 
366
+            PRE = np.reshape( pre, np.shape(VV)  )
367
+            prem = ax2.pcolor(TT, QQQ, PRE, cmap=cmocean.cm.curl_r, vmin=-mmax, vmax=mmax )
368
+            ax2.set_title("predicted")
369
+
370
+            cbar = plt.colorbar(prem, axc1)
371
+            axc1.set_ylim( [np.min(VV), np.max(VV)] )
372
+            cbar.outline.set_edgecolor(None)
373
+            cbar.set_label('$V_N$ (nV)')
374
+
375
+            DIFF = (PRE-VV) / VVS
376
+            md = np.max(np.abs(DIFF))
377
+            dim = ax3.pcolor(TT, QQQ, DIFF, cmap=cmocean.cm.balance, vmin=-md, vmax=md)
378
+            ax3.set_title("misfit / $\widehat{\sigma}$")
379
+    
380
+            cbar2 = plt.colorbar(dim, axc2)
381
+            #axc1.set_ylim( [np.min(V), np.max(V)] )
382
+            cbar2.outline.set_edgecolor(None)
383
+            cbar2.set_label('$V_N$ (nV)')
384
+            #plt.colorbar(dim, ax3)
385
+    
386
+            figx.suptitle(ch + " non-linear Inversion")
387
+
388
+            ich += 1
389
+
390
+
233 391
 
234
-        DIFFc = (PREc-V) / VS
235
-        md = np.max(np.abs(DIFF))
236
-        plt.matshow(DIFFc, cmap=cmocean.cm.balance, vmin=-md, vmax=md)
237
-        plt.gca().set_title("nonlinear misfit / $\widehat{\sigma}$")
238
-        plt.colorbar()
239 392
  
240 393
     ###############################################
241 394
     # Appraise DOI using simplified MRM 
@@ -248,18 +401,33 @@ def main():
248 401
         pdf = PdfPages('resolution_analysis' + '.pdf' )
249 402
         MRM = np.zeros((len(ifaces)-1, len(ifaces)-1))
250 403
 
251
-    #with multiprocessing.Pool() as pool: 
252
-    #    invresults = pool.starmap(invert, zip(itertools.repeat(Time), GT[0:ni], GD[0:ni], SIG[0:ni], itertools.repeat(sys.argv[3]) )) 
253
- 
254
-        # This could be parallelized 
404
+        # Build delta models 
405
+        DELTA = []
406
+        
255 407
         for ilay in range(len(ifaces)-1):
408
+        #for ilay in range(4):
256 409
             iDeltaT2 = len(T2Bins)//2
257 410
             deltaMod = np.zeros( (len(ifaces)-1, len(T2Bins)) )
258 411
             deltaMod[ilay][iDeltaT2] = 0.3
259
-            dV = np.dot(KQT, np.ravel(deltaMod)) 
412
+            dV = np.dot(KQT, np.ravel(deltaMod))
413
+            #dinv, dibreak, derrn = logBarrier( KQT, dV, T2Bins, "single", MAXITER=1, sigma=np.ravel(VS), alpha=alphastar, smooth="Smallest" ) 
414
+            #output = invertDelta(KQT, dV, T2Bins, np.ravel(VS), alphastar)
415
+            DELTA.append(dV)
416
+
417
+        print("Performing resolution analysis in parallel, printed output may not be inorder.", flush=True) 
418
+        with multiprocessing.Pool() as pool: 
419
+            invresults = pool.starmap(invertDelta, zip(itertools.repeat(KQT), DELTA, itertools.repeat(T2Bins), itertools.repeat(np.ravel(VS)), itertools.repeat(alphastar) )) 
420
+        #    invresults = pool.starmap(logBarrier, zip(itertools.repeat(KQT), DELTA, itertools.repeat(T2Bins), itertools.repeat('single'), \
421
+        #        itertools.repeat('MAXITER=1'), itertools.repeat(np.ravel(VS)), itertools.repeat(alphastar))) #, itertools.repeat(u'smooth=\'Smallest\'')) ) 
422
+ 
423
+        # This could be parallelized 
424
+        for ilay in range(len(ifaces)-1):
425
+
260 426
             # invert 
261
-            dinv, dibreak, derrn = logBarrier(KQT, dV, T2Bins, "single", MAXITER=1, sigma=np.ravel(VS), alpha=alphastar, smooth="Smallest" ) 
262
-            print("Sum dinv from", str(ifaces[ilay]), "to", str(ifaces[ilay+1]), "=", np.sum(dinv))
427
+            #dinv, dibreak, derrn = logBarrier(KQT, dV, T2Bins, "single", MAXITER=1, sigma=np.ravel(VS), alpha=alphastar, smooth="Smallest" ) 
428
+            #print("Sum dinv from", str(ifaces[ilay]), "to", str(ifaces[ilay+1]), "=", np.sum(dinv))
429
+            dinv, dibreak, derrn = invresults[ilay] 
430
+
263 431
     
264 432
             DINV = np.reshape(dinv, (len(ifaces)-1,cont["T2Bins"]["number"]) )
265 433
             MRM[ilay,:] = np.sum(DINV, axis=1)
@@ -309,18 +477,8 @@ def main():
309 477
 
310 478
         pdf.close()
311 479
 
312
-
313
-
314 480
     INV = np.reshape(inv, (len(ifaces)-1,cont["T2Bins"]["number"]) )
315 481
 
316
-    #alphas = np.tile(SNR, (len(T2Bins)-1,1))
317
-    #colors = Normalize(1e-6, np.max(INV.T), clip=True)(INV.T)
318
-    #colors = cmocean.cm.tempo(colors)
319
-    ##colors[..., -1] = alphas
320
-    #print(np.shape(colors)) 
321
-    #print(np.shape(INV.T)) 
322
-
323
-    #greys = np.full((*(INV.T).shape, 3), 70, dtype=np.uint8)
324 482
 
325 483
     ##############  LINEAR RESULT   ##########################
326 484
 
@@ -328,11 +486,6 @@ def main():
328 486
     fig = plt.figure( figsize=(pc2in(20.0),pc2in(22.)) )
329 487
     ax1 = fig.add_axes( [.2,.15,.6,.7] )
330 488
     im = ax1.pcolor(X, Y, INV.T, cmap=cmocean.cm.tempo) #cmap='viridis')
331
-    #im = ax1.pcolor(X[0:SNRidx,:], Y[0:SNRidx,:], INV.T[0:SNRidx,:], cmap=cmocean.cm.tempo) #cmap='viridis')
332
-    #im = ax1.pcolor(X[SNRidx::,:], Y[SNRidx::,:], INV.T[SNRidx::,:], cmap=cmocean.cm.tempo, alpha=.5) #cmap='viridis')
333
-    #im = ax1.pcolormesh(X, Y, INV.T, alpha=alphas) #, cmap=cmocean.cm.tempo) #cmap='viridis')
334
-    #im = ax1.pcolormesh(X, Y, INV.T, alpha=alphas) #, cmap=cmocean.cm.tempo) #cmap='viridis')
335
-    #ax1.axhline( y=ifaces[SNRidx], xmin=T2Bins[0], xmax=T2Bins[-1], color='black'  )
336 489
     im.set_edgecolor('face')
337 490
     ax1.set_xlim( T2Bins[0], T2Bins2[-1] )
338 491
     ax1.set_ylim( ifaces[-1], ifaces[0] )
@@ -348,7 +501,6 @@ def main():
348 501
     ax1.get_yaxis().set_major_formatter(FormatStrFormatter('%1.0f'))
349 502
     ax1.xaxis.set_major_locator( MaxNLocator(nbins = 4) )   
350 503
 
351
-    #ax1.xaxis.set_label_position('top') 
352 504
 
353 505
     ax2 = ax1.twiny()
354 506
     ax2.plot( np.sum(INV, axis=1), (ifaces[1:]+ifaces[0:-1])/2 ,  color='red' )
@@ -359,10 +511,50 @@ def main():
359 511
     #ax2.axhline( y=ifaces[SNRidx], xmin=0, xmax=1, color='black', linestyle='dashed'  )
360 512
     if CalcDOI:
361 513
         ax2.axhline( y=DOI, xmin=0, xmax=1, color='black', linestyle='dashed'  )
362
-    #ax2.xaxis.set_label_position('bottom') 
363 514
 
364 515
     plt.savefig("akvoInversion.pdf")
365 516
 
517
+    #############
518
+    # water plot#
519
+
520
+    fig2 = plt.figure( figsize=(pc2in(20.0),pc2in(22.)) )
521
+    ax = fig2.add_axes( [.2,.15,.6,.7] )
522
+    
523
+    # Bound water cutoff 
524
+    Bidx = T2Bins<33.0
525
+    twater = np.sum(INV, axis=1)
526
+    bwater = np.sum(INV[:,Bidx], axis=1)
527
+    
528
+    ax.plot( twater, (ifaces[0:-1]+ifaces[1::])/2, label="NMR total water", color='blue' )
529
+    ax.plot( bwater, (ifaces[0:-1]+ifaces[1::])/2, label="NMR bound water", color='green' )
530
+    
531
+    ax.fill_betweenx((ifaces[0:-1]+ifaces[1::])/2 , twater, bwater, where=twater >= bwater, facecolor='blue', alpha=.5)
532
+    ax.fill_betweenx((ifaces[0:-1]+ifaces[1::])/2 , bwater, 0, where=bwater >= 0, facecolor='green', alpha=.5)
533
+    
534
+    ax.set_xlabel(r"$\theta_N$ (m$^3$/m$^3$)")
535
+    ax.set_ylabel(r"depth (m)")
536
+    
537
+    ax.set_ylim( ifaces[-1], ifaces[0] )
538
+    ax.set_xlim( 0, ax.get_xlim()[1] )
539
+    
540
+    #ax.axhline( y=ifaces[SNRidx], xmin=0, xmax=1, color='black', linestyle='dashed'  )
541
+    if CalcDOI:
542
+        ax.axhline( y=DOI, xmin=0, xmax=1, color='black', linestyle='dashed'  )
543
+    
544
+    plt.savefig("akvoInversionWC.pdf")
545
+    plt.legend()  
546
+    
547
+    fr = pd.DataFrame( INV, columns=T2Bins ) #[0:-1] )
548
+    fr.insert(0, "layer top", ifaces[0:-1] )
549
+    fr.insert(1, "layer bottom", ifaces[1::] )
550
+    fr.insert(2, "NMR total water", np.sum(INV, axis=1) )
551
+    fr.insert(3, "NMR bound water", bwater )
552
+    fr.insert(4, "Layer SNR", SNR )
553
+    if CalcDOI:
554
+        fr.insert(5, "Resolution", DOIMetric )
555
+
556
+    fr.to_csv("akvoInversion.csv", mode='w+')    
557
+
366 558
 
367 559
     ##############  NONLINEAR RESULT   ##########################
368 560
 
@@ -406,49 +598,51 @@ def main():
406 598
         fig.suptitle("Non linear inversion")
407 599
         plt.savefig("akvoInversionNL.pdf")
408 600
 
409
-    #############
410
-    # water plot#
411 601
 
412
-    fig2 = plt.figure( figsize=(pc2in(20.0),pc2in(22.)) )
413
-    ax = fig2.add_axes( [.2,.15,.6,.7] )
602
+
603
+        #############
604
+        # water plot#
605
+
606
+        fig2 = plt.figure( figsize=(pc2in(20.0),pc2in(22.)) )
607
+        ax = fig2.add_axes( [.2,.15,.6,.7] )
414 608
     
415
-    # Bound water cutoff 
416
-    Bidx = T2Bins<33.0
417
-    twater = np.sum(INV, axis=1)
418
-    bwater = np.sum(INV[:,Bidx], axis=1)
609
+        # Bound water cutoff 
610
+        Bidx = T2Bins<33.0
611
+        twater = np.sum(INVc, axis=1)
612
+        bwater = np.sum(INVc[:,Bidx], axis=1)
419 613
     
420
-    ax.plot( twater, (ifaces[0:-1]+ifaces[1::])/2, label="NMR total water", color='blue' )
421
-    ax.plot( bwater, (ifaces[0:-1]+ifaces[1::])/2, label="NMR bound water", color='green' )
614
+        ax.plot( twater, (ifaces[0:-1]+ifaces[1::])/2, label="NMR total water", color='blue' )
615
+        ax.plot( bwater, (ifaces[0:-1]+ifaces[1::])/2, label="NMR bound water", color='green' )
422 616
     
423
-    ax.fill_betweenx((ifaces[0:-1]+ifaces[1::])/2 , twater, bwater, where=twater >= bwater, facecolor='blue', alpha=.5)
424
-    ax.fill_betweenx((ifaces[0:-1]+ifaces[1::])/2 , bwater, 0, where=bwater >= 0, facecolor='green', alpha=.5)
617
+        ax.fill_betweenx((ifaces[0:-1]+ifaces[1::])/2 , twater, bwater, where=twater >= bwater, facecolor='blue', alpha=.5)
618
+        ax.fill_betweenx((ifaces[0:-1]+ifaces[1::])/2 , bwater, 0, where=bwater >= 0, facecolor='green', alpha=.5)
425 619
     
426
-    ax.set_xlabel(r"$\theta_N$ (m$^3$/m$^3$)")
427
-    ax.set_ylabel(r"depth (m)")
620
+        ax.set_xlabel(r"$\theta_N$ (m$^3$/m$^3$)")
621
+        ax.set_ylabel(r"depth (m)")
428 622
     
429
-    ax.set_ylim( ifaces[-1], ifaces[0] )
430
-    ax.set_xlim( 0, ax.get_xlim()[1] )
623
+        ax.set_ylim( ifaces[-1], ifaces[0] )
624
+        ax.set_xlim( 0, ax.get_xlim()[1] )
431 625
     
432
-    #ax.axhline( y=ifaces[SNRidx], xmin=0, xmax=1, color='black', linestyle='dashed'  )
433
-    if CalcDOI:
434
-        ax.axhline( y=DOI, xmin=0, xmax=1, color='black', linestyle='dashed'  )
626
+        #ax.axhline( y=ifaces[SNRidx], xmin=0, xmax=1, color='black', linestyle='dashed'  )
627
+        if CalcDOI:
628
+            ax.axhline( y=DOI, xmin=0, xmax=1, color='black', linestyle='dashed'  )
435 629
     
436
-    plt.savefig("akvoInversionWC.pdf")
437
-    plt.legend()  
438
- 
630
+        plt.savefig("akvoInversionWC.pdf")
631
+        plt.legend()  
439 632
 
440
-    # Report results into a text file 
441
-    fr = pd.DataFrame( INV, columns=T2Bins ) #[0:-1] )
442
-    fr.insert(0, "layer top", ifaces[0:-1] )
443
-    fr.insert(1, "layer bottom", ifaces[1::] )
444
-    fr.insert(2, "NMR total water", np.sum(INV, axis=1) )
445
-    fr.insert(3, "NMR bound water", bwater )
446
-    fr.insert(4, "Layer SNR", SNR )
447
-    if CalcDOI:
448
-        fr.insert(5, "Resolution", DOIMetric )
449 633
 
450
-    fr.to_csv("akvoInversion.csv")    
451
-    #fr.to_excel("akvoInversion.xlsx")    
634
+        # Report results into a text file 
635
+        fr = pd.DataFrame( INVc, columns=T2Bins ) #[0:-1] )
636
+        fr.insert(0, "layer top", ifaces[0:-1] )
637
+        fr.insert(1, "layer bottom", ifaces[1::] )
638
+        fr.insert(2, "NMR total water", np.sum(INVc, axis=1) )
639
+        fr.insert(3, "NMR bound water", bwater )
640
+        fr.insert(4, "Layer SNR", SNR )
641
+        if CalcDOI:
642
+            fr.insert(5, "Resolution", DOIMetric )
643
+
644
+        fr.to_csv("akvoNLInversion.csv", mode='w+')    
645
+        #fr.to_excel("akvoInversion.xlsx")    
452 646
 
453 647
  
454 648
     plt.show()

+ 5
- 5
akvo/tressel/logbarrier.py View File

@@ -30,7 +30,7 @@ def curvatureg(x, y):
30 30
     y2 = gaussian_filter1d(y1, sigma=1, order=1)#, mode='constant', cval=y1[-1])
31 31
     return np.abs(x1*y2 - y1*x2) / np.power(x1**2 + y1**2, 3./2)
32 32
 
33
-def logBarrier(A, b, T2Bins, lambdastar, x_0=0, xr=0, alpha=10, mu1=10, mu2=10, smooth=False, MAXITER=70, fignum=1000, sigma=1, callback=None):
33
+def logBarrier(A, b, T2Bins, lambdastar, x_0=0, xr=0, alpha=10, mu1=10, mu2=10, smooth="Smallest", MAXITER=70, fignum=1000, sigma=1, callback=None):
34 34
     """Impliments a log barrier Tikhonov solution to a linear system of equations 
35 35
         Ax = b  s.t.  x_min < x < x_max. A log-barrier term is used for the constraint
36 36
     """
@@ -128,8 +128,8 @@ def logBarrier(A, b, T2Bins, lambdastar, x_0=0, xr=0, alpha=10, mu1=10, mu2=10,
128 128
     ALPHA = []
129 129
     ALPHA.append(alpha)
130 130
     #ALPHA = np.linspace( alpha, 1, MAXITER  )
131
-    print ("{:^10} {:^15} {:^15} {:^15} {:^15} {:^10} {:^10}".format("iteration",  "lambda", "phi_d", "phi_m","phi","kappa","kappa dist."), flush=True) 
132
-    print ("{:^10} {:>15} {:<15} {:<15} {:<15} {:<10} {:<10}".format("----------", "---------------", "---------------","---------------","---------------","----------","----------"), flush=True) 
131
+    print ("{:^5} {:^15} {:^15} {:^15} {:^15} {:^10} {:^10}".format("iter.",  "lambda", "phi_d", "phi_m","phi","kappa","kappa dist."), flush=True) 
132
+    print ("{:^5} {:>15} {:<15} {:<15} {:<15} {:<10} {:<10}".format("-----", "---------------", "---------------","---------------","---------------","----------","----------"), flush=True) 
133 133
     for i in range(MAXITER):
134 134
         #alpha = ALPHA[i]
135 135
 
@@ -219,7 +219,7 @@ def logBarrier(A, b, T2Bins, lambdastar, x_0=0, xr=0, alpha=10, mu1=10, mu2=10,
219 219
         #print ("{:<8} {:<15} {:<10} {:<10}".format(i, alpha, np.sqrt(phid/len(b)), phim), flush=True) 
220 220
         
221 221
         if i < 4:        
222
-            print ("{:^10} {:>15.4f} {:>15.4f} {:>15.4f} {:>15.4f}".format(i, alpha, np.sqrt(phid/len(b)), phim, tphi ), flush=True) 
222
+            print ("{:^5} {:>15.4f} {:>15.4f} {:>15.4f} {:>15.4f}".format(i, alpha, np.sqrt(phid/len(b)), phim, tphi ), flush=True) 
223 223
 
224 224
 #         if np.sqrt(phid/len(b)) < 0.97: 
225 225
 #             ibreak = -1
@@ -242,7 +242,7 @@ def logBarrier(A, b, T2Bins, lambdastar, x_0=0, xr=0, alpha=10, mu1=10, mu2=10,
242 242
                 kappa = curvaturefd(np.log(np.array(PHIM)), np.log(np.array(PHID)), ALPHA[0:i+1])#ALPHA[0:-1])
243 243
                 #kappa = curvatureg(np.log(np.array(PHIM)), np.log(np.array(PHID)))
244 244
                 #print("max kappa", np.argmax(kappa), "distance from", i-np.argmax(kappa)) 
245
-                print ("{:^10} {:>15.4f} {:>15.4f} {:>15.4f} {:>15.4f} {:^10} {:^10}".format(i, alpha, np.sqrt(phid/len(b)), phim, tphi, np.argmax(kappa), i-np.argmax(kappa)), flush=True) 
245
+                print ("{:^5} {:>15.4f} {:>15.4f} {:>15.4f} {:>15.4f} {:^10} {:^10}".format(i, alpha, np.sqrt(phid/len(b)), phim, tphi, np.argmax(kappa), i-np.argmax(kappa)), flush=True) 
246 246
             if i > 4 and (i-np.argmax(kappa)) > 4: # ((np.sqrt(phid_old/len(b))-np.sqrt(phid/len(b))) < 1e-4) : 
247 247
             #if np.sqrt(phid/len(b)) < 3.0 and ((np.sqrt(phid_old/len(b))-np.sqrt(phid/len(b))) < 1e-3): 
248 248
                 ibreak = 1

Loading…
Cancel
Save