Surface NMR processing and inversion GUI
選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

invertTA.py 26KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679
  1. from akvo.tressel.SlidesPlot import *
  2. import numpy as np
  3. import sys
  4. import matplotlib.pyplot as plt
  5. import cmocean
  6. from pylab import meshgrid
  7. from akvo.tressel.logbarrier import *
  8. import yaml,os
  9. import multiprocessing
  10. import itertools
  11. from scipy.linalg import svd
  12. from matplotlib.backends.backend_pdf import PdfPages
  13. from matplotlib.colors import LogNorm
  14. from matplotlib.colors import LightSource
  15. from matplotlib.ticker import ScalarFormatter
  16. from matplotlib.ticker import MaxNLocator
  17. from matplotlib.ticker import AutoMinorLocator
  18. from matplotlib.ticker import LogLocator
  19. from matplotlib.ticker import FormatStrFormatter
  20. from matplotlib.colors import Normalize
  21. import cmocean
  22. from akvo.tressel.lemma_yaml import *
  23. from akvo.tressel import nonlinearinv as nl
  24. import pandas as pd
  25. import matplotlib.colors as colors
  26. # From https://stackoverflow.com/questions/18926031/how-to-extract-a-subset-of-a-colormap-as-a-new-colormap-in-matplotlib
  27. def truncate_colormap(cmap, minval=0.0, maxval=1.0, n=100):
  28. new_cmap = colors.LinearSegmentedColormap.from_list(
  29. 'trunc({n},{a:.2f},{b:.2f})'.format(n=cmap.name, a=minval, b=maxval),
  30. cmap(np.linspace(minval, maxval, n)))
  31. return new_cmap
  32. def buildKQT(K0,tg,T2Bins):
  33. """
  34. Constructs a QT inversion kernel from an initial amplitude one.
  35. """
  36. nlay, nq = np.shape(K0)
  37. nt2 = len(T2Bins)
  38. nt = len(tg)
  39. KQT = np.zeros( ( nq*nt,nt2*nlay), dtype=np.complex128 )
  40. for iq in range(nq):
  41. for it in range(nt):
  42. for ilay in range(nlay):
  43. for it2 in range(nt2):
  44. #KQT[iq*nt + it,ilay*nt2+it2] = K0[ilay,iq]*np.exp(-((10+tg[it])*1e-3)/(1e-3*T2Bins[it2]))
  45. KQT[iq*nt + it,ilay*nt2+it2] = K0[ilay,iq]*np.exp(-((10+tg[it])*1e-3)/(1e-3*T2Bins[it2]))
  46. return KQT
  47. def loadAkvoData(fnamein, chan):
  48. """ Loads data from an Akvo YAML file. The 0.02 is hard coded as the pulse length. This needs to be
  49. corrected in future kernel calculations. The current was reported but not the pulse length.
  50. """
  51. fname = (os.path.splitext(fnamein)[0])
  52. with open(fnamein, 'r') as stream:
  53. try:
  54. AKVO = (yaml.load(stream, Loader=yaml.Loader))
  55. except yaml.YAMLError as exc:
  56. print(exc)
  57. exit()
  58. Z = np.zeros( (AKVO.nPulseMoments, AKVO.Gated["Pulse 1"]["abscissa"].size ) )
  59. ZS = np.zeros( (AKVO.nPulseMoments, AKVO.Gated["Pulse 1"]["abscissa"].size ) )
  60. for q in range(AKVO.nPulseMoments):
  61. Z[q] = AKVO.Gated["Pulse 1"][chan]["Q-"+str(q) + " CA"].data
  62. if chan == "Chan. 1":
  63. ZS[q] = AKVO.Gated["Pulse 1"][chan]["STD"].data
  64. elif chan == "Chan. 2":
  65. ZS[q] = AKVO.Gated["Pulse 1"][chan]["STD"].data
  66. elif chan == "Chan. 3":
  67. ZS[q] = AKVO.Gated["Pulse 1"][chan]["STD"].data
  68. elif chan == "Chan. 4":
  69. ZS[q] = AKVO.Gated["Pulse 1"][chan]["STD"].data
  70. else:
  71. print("DOOM!!!")
  72. exit()
  73. #Z *= 1e-9
  74. #ZS *= 1e-9
  75. J = AKVO.Pulses["Pulse 1"]["current"].data
  76. J = np.append(J,J[-1]+(J[-1]-J[-2]))
  77. Q = AKVO.pulseLength[0]*J
  78. return Z, ZS, AKVO.Gated["Pulse 1"]["abscissa"].data, Q
  79. def catLayers(K0):
  80. K = np.zeros( (len(K0.keys()), len(K0["layer-0"].data)) , dtype=complex )
  81. for lay in range(len(K0.keys())):
  82. #print(K0["layer-"+str(lay)].data) # print (lay)
  83. K[lay] =K0["layer-"+str(lay)].data # print (lay)
  84. return 1e9*K # invert in nV
  85. def loadK0(fname):
  86. """ Loads in initial amplitude kernel
  87. """
  88. print("loading K0", fname)
  89. with open(fname) as f:
  90. K0 = yaml.load(f, Loader=yaml.Loader)
  91. K = catLayers(K0.K0)
  92. ifaces = np.array(K0.Interfaces.data)
  93. return ifaces, K
  94. #return ifaces, np.abs(K)
  95. def invertDelta(G, V_n, T2Bins, sig, alphastar):
  96. """ helper function that simply calls logBarrier, simplfies parallel execution
  97. """
  98. model = logBarrier(G, V_n, T2Bins, "Single", MAXITER=1, sigma=sig, alpha=alphastar, smooth="Smallest")
  99. return model
  100. def main():
  101. if (len (sys.argv) < 2):
  102. print ("akvoQT invertParameters.yaml")
  103. exit()
  104. with open(sys.argv[1], 'r') as stream:
  105. try:
  106. cont = (yaml.load(stream, Loader=yaml.Loader))
  107. except yaml.YAMLError as exc:
  108. print(exc)
  109. exit(1)
  110. ###############################################
  111. # Load in data
  112. ###############################################
  113. V = []
  114. VS = []
  115. QQ = []
  116. tg = 0
  117. for dat in cont['data']:
  118. for ch in cont['data'][dat]['channels']:
  119. print("dat", dat, "ch", ch)
  120. v,vs,tg,Q = loadAkvoData(dat, ch)
  121. V.append(v)
  122. VS.append(vs)
  123. QQ.append(Q)
  124. for iv in range(1, len(V)):
  125. V[0] = np.concatenate( (V[0], V[iv]) )
  126. VS[0] = np.concatenate( (VS[0], VS[iv]) )
  127. V = V[0]
  128. VS = VS[0]
  129. ###############################################
  130. # Load in kernels
  131. ###############################################
  132. K0 = []
  133. for kern in cont["K0"]:
  134. ifaces,k0 = loadK0( kern )
  135. K0.append(k0)
  136. for ik in range(1, len(K0)):
  137. K0[0] = np.concatenate( (K0[0].T, K0[ik].T) ).T
  138. K0 = K0[0]
  139. #np.save("ifaces", ifaces)
  140. #exit()
  141. #plt.matshow(np.real(K0))
  142. #plt.show()
  143. #exit()
  144. ##############################################################
  145. # VERY Simple Sensitivity based calc. of noise per layer #
  146. # minimally useful, but retained for backwards compatibility #
  147. maxq = np.argmax(np.abs(K0), axis=1)
  148. maxK = .1 * np.abs(K0)[ np.arange(0,len(ifaces)-1), maxq ] # 10% water is arbitrary
  149. SNR = maxK / (VS[0][0])
  150. ###############################################
  151. # Build full kernel
  152. ###############################################
  153. T2Bins = np.logspace( np.log10(cont["T2Bins"]["low"]), np.log10(cont["T2Bins"]["high"]), cont["T2Bins"]["number"], endpoint=True, base=10)
  154. T2Bins2 = np.append( T2Bins, T2Bins[-1] + (T2Bins[-1]-T2Bins[-2]) )
  155. NT2 = len(T2Bins)
  156. KQT = np.real(buildKQT(np.abs(K0),tg,T2Bins))
  157. ###############################################
  158. # Linear Inversion
  159. ###############################################
  160. print("Calling inversion", flush=True)
  161. inv, ibreak, errn, phim, phid, mkappa, Wd, Wm, alphastar = logBarrier(KQT, np.ravel(V), T2Bins, "lcurve", MAXITER=150, sigma=np.ravel(VS), alpha=1e7, smooth="Smallest" )
  162. ################################
  163. # Summary plots, Data Space #
  164. ################################
  165. # 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
  166. # TODO, loop over channels
  167. ich = 0
  168. for ch in cont['data'][dat]['channels']:
  169. figx = plt.figure( figsize=(pc2in(42.0),pc2in(22.)) )
  170. ax1 = figx.add_axes([.100, .15, .200, .70])
  171. ax2 = figx.add_axes([.325, .15, .200, .70]) # shifted to make room for shared colourbar
  172. axc1= figx.add_axes([.550, .15, .025, .70]) # shifted to make room for shared colourbar
  173. ax3 = figx.add_axes([.670, .15, .200, .70])
  174. axc2= figx.add_axes([.895, .15, .025, .70]) # shifted to make room for shared colourbar
  175. ax3.set_yscale('log')
  176. ax2.set_yscale('log')
  177. ax1.set_yscale('log')
  178. ax2.yaxis.set_ticklabels([])
  179. ax3.yaxis.set_ticklabels([])
  180. ax3.set_xscale('log')
  181. ax2.set_xscale('log')
  182. ax1.set_xscale('log')
  183. ax1.set_ylabel("Q (A $\cdot$ s)")
  184. ax1.set_xlabel("time (s)")
  185. ax2.set_xlabel("time (s)")
  186. ax3.set_xlabel("time (s)")
  187. #TT, QQQ = np.meshgrid(tg, np.ravel(QQ))
  188. TT, QQQ = np.meshgrid(tg, np.ravel(QQ[ich]))
  189. nq = np.shape(QQ[ich])[0] - 1 # to account for padding in pcolor
  190. nt = np.shape(tg)[0]
  191. ntq = nt*nq
  192. VV = V[ich*nq:ich*nq+nq,:] # slice this channel
  193. VVS = VS[ich*nq:ich*nq+nq,:] # slice this channel
  194. mmax = np.max(np.abs(VV))
  195. mmin = np.min(VV)
  196. obs = ax1.pcolor(TT, QQQ, VV, cmap=cmocean.cm.curl_r, vmin=-mmax, vmax=mmax, shading='auto') # pcolor edge not defined
  197. ax1.set_title("observed")
  198. pre = np.dot(KQT[ich*ntq:(ich+1)*ntq,:], inv)
  199. PRE = np.reshape( pre, np.shape(VV) )
  200. prem = ax2.pcolor(TT, QQQ, PRE, cmap=cmocean.cm.curl_r, vmin=-mmax, vmax=mmax,shading='auto' )
  201. ax2.set_title("predicted")
  202. cbar = plt.colorbar(prem, axc1)
  203. axc1.set_ylim( [np.min(VV), np.max(VV)] )
  204. cbar.outline.set_edgecolor(None)
  205. cbar.set_label('$V_N$ (nV)')
  206. DIFF = (PRE-VV) / VVS
  207. md = np.max(np.abs(DIFF))
  208. dim = ax3.pcolor(TT, QQQ, DIFF, cmap=cmocean.cm.balance, vmin=-md, vmax=md, shading='auto')
  209. ax3.set_title("misfit / $\widehat{\sigma}$")
  210. cbar2 = plt.colorbar(dim, axc2)
  211. #axc1.set_ylim( [np.min(V), np.max(V)] )
  212. cbar2.outline.set_edgecolor(None)
  213. cbar2.set_label('$V_N$ (nV)')
  214. #plt.colorbar(dim, ax3)
  215. figx.suptitle(ch + " linear Inversion")
  216. plt.savefig(ch + "dataspace.pdf")
  217. ich += 1
  218. ###############################################
  219. # Non-linear refinement!
  220. ###############################################
  221. nonLinearRefinement = cont['NonLinearRefinement']
  222. if nonLinearRefinement:
  223. KQTc = buildKQT(K0, tg, T2Bins)
  224. prec = np.abs(np.dot(KQTc, inv))
  225. phidc = np.linalg.norm(np.dot(Wd,prec-np.ravel(V)))**2
  226. print("PHID forward linear=", errn, "PHID forward nonlinear=", phidc/len(np.ravel(V)))
  227. res = nl.nonlinearinversion(inv, Wd, KQTc, np.ravel(V), Wm, alphastar )
  228. if res.success == True:
  229. INVc = np.reshape(res.x, (len(ifaces)-1,cont["T2Bins"]["number"]) )
  230. prec = np.abs(np.dot(KQTc, res.x))
  231. phidc = np.linalg.norm(np.dot(Wd,prec-np.ravel(V)))**2
  232. PREc = np.reshape( prec, np.shape(V) )
  233. print("PHID linear=", errn, "PHID nonlinear=", phidc/len(np.ravel(V)))
  234. while phidc/len(np.ravel(V)) > errn:
  235. phidc_old = phidc/len(np.ravel(V))
  236. #alphastar *= .9
  237. res = nl.nonlinearinversion(res.x, Wd, KQTc, np.ravel(V), Wm, alphastar )
  238. if res.success == True:
  239. INVc = np.reshape(res.x, (len(ifaces)-1,cont["T2Bins"]["number"]) )
  240. prec = np.abs(np.dot(KQTc, res.x))
  241. phidc = np.linalg.norm(np.dot(Wd,prec-np.ravel(V)))**2
  242. PREc = np.reshape( prec, np.shape(V) )
  243. print("PHID linear=", errn, "PHID nonlinear=", phidc/len(np.ravel(V)))
  244. else:
  245. nonLinearRefinement = False
  246. print("Non-linear inversion failed, results will not be shown")
  247. break
  248. if phidc_old - phidc/len(np.ravel(V)) < 0.005:
  249. print("Not making progress reducing misfit in nonlinear refinement")
  250. break
  251. # Turn this into a nice figure w/ shared axes etc.
  252. # plt.matshow(PREc, cmap='Blues')
  253. # plt.gca().set_title("nonlinear predicted")
  254. # plt.colorbar()
  255. #
  256. # DIFFc = (PREc-V) / VS
  257. # md = np.max(np.abs(DIFF))
  258. # plt.matshow(DIFFc, cmap=cmocean.cm.balance, vmin=-md, vmax=md)
  259. # plt.gca().set_title("nonlinear misfit / $\widehat{\sigma}$")
  260. # plt.colorbar()
  261. ################################
  262. # Summary plots, Data Space #
  263. ################################
  264. ich = 0
  265. for ch in cont['data'][dat]['channels']:
  266. figx = plt.figure( figsize=(pc2in(42.0),pc2in(22.)) )
  267. ax1 = figx.add_axes([.100, .15, .200, .70])
  268. ax2 = figx.add_axes([.325, .15, .200, .70]) # shifted to make room for shared colourbar
  269. axc1= figx.add_axes([.550, .15, .025, .70]) # shifted to make room for shared colourbar
  270. ax3 = figx.add_axes([.670, .15, .200, .70])
  271. axc2= figx.add_axes([.895, .15, .025, .70]) # shifted to make room for shared colourbar
  272. ax3.set_yscale('log')
  273. ax2.set_yscale('log')
  274. ax1.set_yscale('log')
  275. ax2.yaxis.set_ticklabels([])
  276. ax3.yaxis.set_ticklabels([])
  277. ax3.set_xscale('log')
  278. ax2.set_xscale('log')
  279. ax1.set_xscale('log')
  280. ax1.set_ylabel("Q (A $\cdot$ s)")
  281. ax1.set_xlabel("time (s)")
  282. ax2.set_xlabel("time (s)")
  283. ax3.set_xlabel("time (s)")
  284. #TT, QQQ = np.meshgrid(tg, np.ravel(QQ))
  285. TT, QQQ = np.meshgrid(tg, np.ravel(QQ[ich]))
  286. nq = np.shape(QQ[ich])[0] - 1 # to account for padding in pcolor
  287. nt = np.shape(tg)[0]
  288. ntq = nt*nq
  289. VV = V[ich*nq:ich*nq+nq,:] # slice this channel
  290. VVS = VS[ich*nq:ich*nq+nq,:] # slice this channel
  291. mmax = np.max(np.abs(VV))
  292. mmin = np.min(VV)
  293. obs = ax1.pcolor(TT, QQQ, VV, cmap=cmocean.cm.curl_r, vmin=-mmax, vmax=mmax, shading='auto')
  294. ax1.set_title("observed")
  295. ## Here neds to change
  296. pre = np.abs(np.dot(KQTc[ich*ntq:(ich+1)*ntq,:], inv))
  297. PRE = np.reshape( pre, np.shape(VV) )
  298. prem = ax2.pcolor(TT, QQQ, PRE, cmap=cmocean.cm.curl_r, vmin=-mmax, vmax=mmax, shading='auto' )
  299. ax2.set_title("predicted")
  300. cbar = plt.colorbar(prem, axc1)
  301. axc1.set_ylim( [np.min(VV), np.max(VV)] )
  302. cbar.outline.set_edgecolor(None)
  303. cbar.set_label('$V_N$ (nV)')
  304. DIFF = (PRE-VV) / VVS
  305. md = np.max(np.abs(DIFF))
  306. dim = ax3.pcolor(TT, QQQ, DIFF, cmap=cmocean.cm.balance, vmin=-md, vmax=md, shading='auto')
  307. ax3.set_title("misfit / $\widehat{\sigma}$")
  308. cbar2 = plt.colorbar(dim, axc2)
  309. #axc1.set_ylim( [np.min(V), np.max(V)] )
  310. cbar2.outline.set_edgecolor(None)
  311. cbar2.set_label('$V_N$ (nV)')
  312. #plt.colorbar(dim, ax3)
  313. figx.suptitle(ch + " non-linear Inversion")
  314. plt.savefig(ch + "_NLdataspace.pdf")
  315. ich += 1
  316. ###############################################
  317. # Appraise DOI using simplified MRM
  318. ###############################################
  319. CalcDOI = cont['CalcDOI']
  320. if CalcDOI:
  321. pdf = PdfPages('resolution_analysis' + '.pdf' )
  322. MRM = np.zeros((len(ifaces)-1, len(ifaces)-1))
  323. # Build delta models
  324. DELTA = []
  325. for ilay in range(len(ifaces)-1):
  326. #for ilay in range(4):
  327. iDeltaT2 = len(T2Bins)//2
  328. deltaMod = np.zeros( (len(ifaces)-1, len(T2Bins)) )
  329. deltaMod[ilay][iDeltaT2] = 0.3
  330. dV = np.dot(KQT, np.ravel(deltaMod))
  331. #dinv, dibreak, derrn = logBarrier( KQT, dV, T2Bins, "single", MAXITER=1, sigma=np.ravel(VS), alpha=alphastar, smooth="Smallest" )
  332. #output = invertDelta(KQT, dV, T2Bins, np.ravel(VS), alphastar)
  333. DELTA.append(dV)
  334. print("Performing resolution analysis in parallel, printed output may not be inorder.", flush=True)
  335. with multiprocessing.Pool() as pool:
  336. invresults = pool.starmap(invertDelta, zip(itertools.repeat(KQT), DELTA, itertools.repeat(T2Bins), itertools.repeat(np.ravel(VS)), itertools.repeat(alphastar) ))
  337. # invresults = pool.starmap(logBarrier, zip(itertools.repeat(KQT), DELTA, itertools.repeat(T2Bins), itertools.repeat('single'), \
  338. # itertools.repeat('MAXITER=1'), itertools.repeat(np.ravel(VS)), itertools.repeat(alphastar))) #, itertools.repeat(u'smooth=\'Smallest\'')) )
  339. # This could be parallelized
  340. for ilay in range(len(ifaces)-1):
  341. # invert
  342. #dinv, dibreak, derrn = logBarrier(KQT, dV, T2Bins, "single", MAXITER=1, sigma=np.ravel(VS), alpha=alphastar, smooth="Smallest" )
  343. #print("Sum dinv from", str(ifaces[ilay]), "to", str(ifaces[ilay+1]), "=", np.sum(dinv))
  344. dinv, dibreak, derrn = invresults[ilay]
  345. DINV = np.reshape(dinv, (len(ifaces)-1,cont["T2Bins"]["number"]) )
  346. MRM[ilay,:] = np.sum(DINV, axis=1)
  347. Y,X = meshgrid( ifaces, T2Bins2 )
  348. fig = plt.figure( figsize=(pc2in(20.0),pc2in(22.)) )
  349. ax1 = fig.add_axes( [.2,.15,.6,.7] )
  350. im = ax1.pcolor(X, Y, DINV.T, cmap=cmocean.cm.tempo, shading='auto')
  351. ax1.plot( T2Bins[iDeltaT2], (ifaces[ilay]+ifaces[ilay+1])/2, 's', markersize=6, markeredgecolor='black') #, markerfacecolor=None )
  352. im.set_edgecolor('face')
  353. ax1.set_xlabel(u"$T_2^*$ (ms)")
  354. ax1.set_ylabel(u"depth (m)")
  355. ax1.set_xlim( T2Bins2[0], T2Bins2[-1] )
  356. ax1.set_ylim( ifaces[-1], ifaces[0] )
  357. ax2 = ax1.twiny()
  358. ax2.plot( np.sum(DINV, axis=1), (ifaces[1:]+ifaces[0:-1])/2 , color='mediumblue' )
  359. ax2.set_xlabel(u"total water (m$^3$/m$^3$)", color='mediumblue')
  360. ax2.set_ylim( ifaces[-1], ifaces[0] )
  361. ax2.xaxis.set_major_locator( MaxNLocator(nbins = 3) )
  362. ax2.get_xaxis().set_major_formatter(FormatStrFormatter('%0.2f'))
  363. pdf.savefig(facecolor=[0,0,0,0])
  364. plt.close(fig)
  365. np.save("MRM", MRM)
  366. centres = (ifaces[0:-1]+ifaces[1:])/2
  367. X,Y = np.meshgrid(ifaces,ifaces)
  368. fig = plt.figure( figsize=(pc2in(20.0),pc2in(22.)) )
  369. ax1 = fig.add_axes( [.2,.15,.6,.7] )
  370. ax1.pcolor(X,Y,MRM, cmap = cmocean.cm.ice)
  371. ax1.set_ylim(ifaces[-1], ifaces[0])
  372. maxDepth = np.argmax(MRM, axis=0)
  373. plt.plot(centres[maxDepth], centres, color='white')
  374. # Determine DOI
  375. DOIMetric = centres[maxDepth]/centres #> 0.9
  376. DOI = ifaces[ np.where(DOIMetric < 0.9 ) ][0]
  377. plt.axhline(y=DOI, color='white', linestyle='-.')
  378. ax1.set_ylim( ifaces[-1], ifaces[0] )
  379. ax1.set_xlim( ifaces[0], ifaces[-1] )
  380. ax1.set_xlabel(u"depth (m)")
  381. ax1.set_ylabel(u"depth (m)")
  382. plt.savefig("resolutionmatrix.pdf")
  383. pdf.close()
  384. INV = np.reshape(inv, (len(ifaces)-1,cont["T2Bins"]["number"]) )
  385. ############## LINEAR RESULT ##########################
  386. Y,X = meshgrid( ifaces, T2Bins2 )
  387. fig = plt.figure( figsize=(pc2in(20.0),pc2in(22.)) )
  388. ax1 = fig.add_axes( [.2,.15,.6,.7] )
  389. im = ax1.pcolor(X, Y, INV.T, cmap=cmocean.cm.tempo) #cmap='viridis')
  390. im.set_edgecolor('face')
  391. ax1.set_xlim( T2Bins[0], T2Bins[-1] )
  392. ax1.set_ylim( ifaces[-1], ifaces[0] )
  393. cb = plt.colorbar(im, label = u"PWC (m$^3$/m$^3$)") #, format='%1.1f')
  394. cb.locator = MaxNLocator( nbins = 4)
  395. cb.ax.yaxis.set_offset_position('left')
  396. cb.update_ticks()
  397. ax1.set_xlabel(u"$T_2^*$ (ms)")
  398. ax1.set_ylabel(u"depth (m)")
  399. ax1.get_xaxis().set_major_formatter(FormatStrFormatter('%1.0f'))
  400. ax1.get_yaxis().set_major_formatter(FormatStrFormatter('%1.0f'))
  401. ax1.xaxis.set_major_locator( MaxNLocator(nbins = 4) )
  402. ax2 = ax1.twiny()
  403. ax2.plot( np.sum(INV, axis=1), (ifaces[1:]+ifaces[0:-1])/2 , color='mediumblue' )
  404. ax2.set_xlabel(u"NMR total water (m$^3$/m$^3$)", color='mediumblue')
  405. ax2.set_ylim( ifaces[-1], ifaces[0] )
  406. ax2.xaxis.set_major_locator( MaxNLocator(nbins = 3) )
  407. ax2.get_xaxis().set_major_formatter(FormatStrFormatter('%0.2f'))
  408. #ax2.axhline( y=ifaces[SNRidx], xmin=0, xmax=1, color='black', linestyle='dashed' )
  409. if CalcDOI:
  410. ax2.axhline( y=DOI, xmin=0, xmax=1, color='black', linestyle='dashed' )
  411. ax2.tick_params(axis='x', colors='mediumblue')
  412. plt.setp(ax2.get_xticklabels(), color="mediumblue")
  413. plt.savefig("akvoInversion.pdf")
  414. #############
  415. # water plot#
  416. fig2 = plt.figure( figsize=(pc2in(20.0),pc2in(22.)) )
  417. ax = fig2.add_axes( [.2,.15,.6,.7] )
  418. # Bound water cutoff
  419. Bidx = T2Bins<33.0
  420. twater = np.sum(INV, axis=1)
  421. bwater = np.sum(INV[:,Bidx], axis=1)
  422. ax.plot( twater, (ifaces[0:-1]+ifaces[1::])/2, label="NMR total water", color='blue' )
  423. ax.plot( bwater, (ifaces[0:-1]+ifaces[1::])/2, label="NMR bound water", color='green' )
  424. ax.fill_betweenx((ifaces[0:-1]+ifaces[1::])/2 , twater, bwater, where=twater >= bwater, facecolor='blue', alpha=.5)
  425. ax.fill_betweenx((ifaces[0:-1]+ifaces[1::])/2 , bwater, 0, where=bwater >= 0, facecolor='green', alpha=.5)
  426. ax.set_xlabel(r"$\theta_N$ (m$^3$/m$^3$)")
  427. ax.set_ylabel(r"depth (m)")
  428. ax.set_ylim( ifaces[-1], ifaces[0] )
  429. ax.set_xlim( 0, ax.get_xlim()[1] )
  430. #ax.axhline( y=ifaces[SNRidx], xmin=0, xmax=1, color='black', linestyle='dashed' )
  431. if CalcDOI:
  432. ax.axhline( y=DOI, xmin=0, xmax=1, color='black', linestyle='dashed' )
  433. # Hide the right and top spines
  434. ax.spines['right'].set_visible(False)
  435. ax.spines['top'].set_visible(False)
  436. # Only show ticks on the left and bottom spines
  437. ax.yaxis.set_ticks_position('left')
  438. ax.xaxis.set_ticks_position('bottom')
  439. plt.legend()
  440. plt.savefig("akvoInversionWC.pdf")
  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. fr.to_csv("akvoInversion.csv", mode='w+')
  450. ############## NONLINEAR RESULT ##########################
  451. if nonLinearRefinement:
  452. Y,X = meshgrid( ifaces, T2Bins2 )
  453. fig = plt.figure( figsize=(pc2in(20.0),pc2in(22.)) )
  454. ax1 = fig.add_axes( [.2,.15,.6,.7] )
  455. im = ax1.pcolor(X, Y, INVc.T, cmap=cmocean.cm.tempo) #cmap='viridis')
  456. #im = ax1.pcolor(X[0:SNRidx,:], Y[0:SNRidx,:], INV.T[0:SNRidx,:], cmap=cmocean.cm.tempo) #cmap='viridis')
  457. #im = ax1.pcolor(X[SNRidx::,:], Y[SNRidx::,:], INV.T[SNRidx::,:], cmap=cmocean.cm.tempo, alpha=.5) #cmap='viridis')
  458. #im = ax1.pcolormesh(X, Y, INV.T, alpha=alphas) #, cmap=cmocean.cm.tempo) #cmap='viridis')
  459. #im = ax1.pcolormesh(X, Y, INV.T, alpha=alphas) #, cmap=cmocean.cm.tempo) #cmap='viridis')
  460. #ax1.axhline( y=ifaces[SNRidx], xmin=T2Bins[0], xmax=T2Bins[-1], color='black' )
  461. im.set_edgecolor('face')
  462. ax1.set_xlim( T2Bins[0], T2Bins[-1] )
  463. ax1.set_ylim( ifaces[-1], ifaces[0] )
  464. cb = plt.colorbar(im, label = u"PWC (m$^3$/m$^3$)") #, format='%1.1f')
  465. cb.locator = MaxNLocator( nbins = 4)
  466. cb.ax.yaxis.set_offset_position('left')
  467. cb.update_ticks()
  468. ax1.set_xlabel(u"$T_2^*$ (ms)")
  469. ax1.set_ylabel(u"depth (m)")
  470. ax1.get_xaxis().set_major_formatter(FormatStrFormatter('%1.0f'))
  471. ax1.get_yaxis().set_major_formatter(FormatStrFormatter('%1.0f'))
  472. ax1.xaxis.set_major_locator( MaxNLocator(nbins = 4) )
  473. #ax1.xaxis.set_label_position('top')
  474. ax2 = ax1.twiny()
  475. ax2.plot( np.sum(INVc, axis=1), (ifaces[1:]+ifaces[0:-1])/2 , color='mediumblue' )
  476. ax2.set_xlabel(u"NMR total water (m$^3$/m$^3$)", color='mediumblue')
  477. ax2.set_ylim( ifaces[-1], ifaces[0] )
  478. ax2.xaxis.set_major_locator( MaxNLocator(nbins = 3) )
  479. ax2.get_xaxis().set_major_formatter(FormatStrFormatter('%0.2f'))
  480. #ax2.axhline( y=ifaces[SNRidx], xmin=0, xmax=1, color='black', linestyle='dashed' )
  481. if CalcDOI:
  482. ax2.axhline( y=DOI, xmin=0, xmax=1, color='black', linestyle='dashed' )
  483. #ax2.xaxis.set_label_position('bottom')
  484. #fig.suptitle("Non linear inversion")
  485. ax2.tick_params(axis='x', colors='mediumblue')
  486. plt.setp(ax2.get_xticklabels(), color="mediumblue")
  487. plt.savefig("akvoInversionNL.pdf")
  488. #############
  489. # water plot#
  490. fig2 = plt.figure( figsize=(pc2in(20.0),pc2in(22.)) )
  491. ax = fig2.add_axes( [.2,.15,.6,.7] )
  492. # Bound water cutoff
  493. Bidx = T2Bins<33.0
  494. twater = np.sum(INVc, axis=1)
  495. bwater = np.sum(INVc[:,Bidx], axis=1)
  496. ax.plot( twater, (ifaces[0:-1]+ifaces[1::])/2, label="NMR total water", color='blue' )
  497. ax.plot( bwater, (ifaces[0:-1]+ifaces[1::])/2, label="NMR bound water", color='green' )
  498. ax.fill_betweenx((ifaces[0:-1]+ifaces[1::])/2 , twater, bwater, where=twater >= bwater, facecolor='blue', alpha=.5)
  499. ax.fill_betweenx((ifaces[0:-1]+ifaces[1::])/2 , bwater, 0, where=bwater >= 0, facecolor='green', alpha=.5)
  500. ax.set_xlabel(r"$\theta_N$ (m$^3$/m$^3$)")
  501. ax.set_ylabel(r"depth (m)")
  502. ax.set_ylim( ifaces[-1], ifaces[0] )
  503. ax.set_xlim( 0, ax.get_xlim()[1] )
  504. #ax.axhline( y=ifaces[SNRidx], xmin=0, xmax=1, color='black', linestyle='dashed' )
  505. if CalcDOI:
  506. ax.axhline( y=DOI, xmin=0, xmax=1, color='black', linestyle='dashed' )
  507. # Hide the right and top spines
  508. ax.spines['right'].set_visible(False)
  509. ax.spines['top'].set_visible(False)
  510. # Only show ticks on the left and bottom spines
  511. ax.yaxis.set_ticks_position('left')
  512. ax.xaxis.set_ticks_position('bottom')
  513. plt.savefig("akvoNLInversionWC.pdf")
  514. plt.legend()
  515. # Report results into a text file
  516. fr = pd.DataFrame( INVc, columns=T2Bins ) #[0:-1] )
  517. fr.insert(0, "layer top", ifaces[0:-1] )
  518. fr.insert(1, "layer bottom", ifaces[1::] )
  519. fr.insert(2, "NMR total water", np.sum(INVc, axis=1) )
  520. fr.insert(3, "NMR bound water", bwater )
  521. fr.insert(4, "Layer SNR", SNR )
  522. if CalcDOI:
  523. fr.insert(5, "Resolution", DOIMetric )
  524. fr.to_csv("akvoNLInversion.csv", mode='w+')
  525. #fr.to_excel("akvoInversion.xlsx")
  526. plt.show()
  527. if __name__ == "__main__":
  528. main()