Surface NMR processing and inversion GUI
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

invertTA.py 14KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381
  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. from matplotlib.colors import LogNorm
  10. from matplotlib.colors import LightSource
  11. from matplotlib.ticker import ScalarFormatter
  12. from matplotlib.ticker import MaxNLocator
  13. from matplotlib.ticker import AutoMinorLocator
  14. from matplotlib.ticker import LogLocator
  15. from matplotlib.ticker import FormatStrFormatter
  16. from matplotlib.colors import Normalize
  17. import cmocean
  18. from akvo.tressel.lemma_yaml import *
  19. from akvo.tressel import nonlinearinv as nl
  20. import pandas as pd
  21. def buildKQT(K0,tg,T2Bins):
  22. """
  23. Constructs a QT inversion kernel from an initial amplitude one.
  24. """
  25. nlay, nq = np.shape(K0)
  26. nt2 = len(T2Bins)
  27. nt = len(tg)
  28. KQT = np.zeros( ( nq*nt,nt2*nlay), dtype=np.complex128 )
  29. for iq in range(nq):
  30. for it in range(nt):
  31. for ilay in range(nlay):
  32. for it2 in range(nt2):
  33. #KQT[iq*nt + it,ilay*nt2+it2] = K0[ilay,iq]*np.exp(-((10+tg[it])*1e-3)/(1e-3*T2Bins[it2]))
  34. KQT[iq*nt + it,ilay*nt2+it2] = K0[ilay,iq]*np.exp(-((10+tg[it])*1e-3)/(1e-3*T2Bins[it2]))
  35. return KQT
  36. def loadAkvoData(fnamein, chan):
  37. """ Loads data from an Akvo YAML file. The 0.02 is hard coded as the pulse length. This needs to be
  38. corrected in future kernel calculations. The current was reported but not the pulse length.
  39. """
  40. fname = (os.path.splitext(fnamein)[0])
  41. with open(fnamein, 'r') as stream:
  42. try:
  43. AKVO = (yaml.load(stream, Loader=yaml.Loader))
  44. except yaml.YAMLError as exc:
  45. print(exc)
  46. exit()
  47. Z = np.zeros( (AKVO.nPulseMoments, AKVO.Gated["Pulse 1"]["abscissa"].size ) )
  48. ZS = np.zeros( (AKVO.nPulseMoments, AKVO.Gated["Pulse 1"]["abscissa"].size ) )
  49. for q in range(AKVO.nPulseMoments):
  50. Z[q] = AKVO.Gated["Pulse 1"][chan]["Q-"+str(q) + " CA"].data
  51. if chan == "Chan. 1":
  52. ZS[q] = AKVO.Gated["Pulse 1"][chan]["STD"].data
  53. elif chan == "Chan. 2":
  54. ZS[q] = AKVO.Gated["Pulse 1"][chan]["STD"].data
  55. elif chan == "Chan. 3":
  56. ZS[q] = AKVO.Gated["Pulse 1"][chan]["STD"].data
  57. elif chan == "Chan. 4":
  58. ZS[q] = AKVO.Gated["Pulse 1"][chan]["STD"].data
  59. else:
  60. print("DOOM!!!")
  61. exit()
  62. #Z *= 1e-9
  63. #ZS *= 1e-9
  64. J = AKVO.Pulses["Pulse 1"]["current"].data
  65. J = np.append(J,J[-1]+(J[-1]-J[-2]))
  66. Q = AKVO.pulseLength[0]*J
  67. return Z, ZS, AKVO.Gated["Pulse 1"]["abscissa"].data #, Q
  68. def catLayers(K0):
  69. K = np.zeros( (len(K0.keys()), len(K0["layer-0"].data)) , dtype=complex )
  70. for lay in range(len(K0.keys())):
  71. #print(K0["layer-"+str(lay)].data) # print (lay)
  72. K[lay] =K0["layer-"+str(lay)].data # print (lay)
  73. return 1e9*K # invert in nV
  74. def loadK0(fname):
  75. """ Loads in initial amplitude kernel
  76. """
  77. print("loading K0", fname)
  78. with open(fname) as f:
  79. K0 = yaml.load(f, Loader=yaml.Loader)
  80. K = catLayers(K0.K0)
  81. ifaces = np.array(K0.Interfaces.data)
  82. return ifaces, K
  83. #return ifaces, np.abs(K)
  84. def main():
  85. if (len (sys.argv) < 2):
  86. print ("akvoQT invertParameters.yaml")
  87. exit()
  88. with open(sys.argv[1], 'r') as stream:
  89. try:
  90. cont = (yaml.load(stream, Loader=yaml.Loader))
  91. except yaml.YAMLError as exc:
  92. print(exc)
  93. ###############################################
  94. # Load in data
  95. ###############################################
  96. V = []
  97. VS = []
  98. tg = 0
  99. for dat in cont['data']:
  100. for ch in cont['data'][dat]['channels']:
  101. print("dat", dat, "ch", ch)
  102. v,vs,tg = loadAkvoData(dat, ch)
  103. V.append(v)
  104. VS.append(vs)
  105. for iv in range(1, len(V)):
  106. V[0] = np.concatenate( (V[0], V[iv]) )
  107. VS[0] = np.concatenate( (VS[0], VS[iv]) )
  108. V = V[0]
  109. VS = VS[0]
  110. ###############################################
  111. # Load in kernels
  112. ###############################################
  113. K0 = []
  114. for kern in cont["K0"]:
  115. ifaces,k0 = loadK0( kern )
  116. K0.append(k0)
  117. for ik in range(1, len(K0)):
  118. K0[0] = np.concatenate( (K0[0].T, K0[ik].T) ).T
  119. K0 = K0[0]
  120. #plt.matshow(np.real(K0))
  121. #plt.show()
  122. #exit()
  123. ###################
  124. # VERY Simple DOI #
  125. maxq = np.argmax(np.abs(K0), axis=1)
  126. maxK = .1 * np.abs(K0)[ np.arange(0,len(ifaces)-1), maxq ] # 10% water is arbitrary
  127. SNR = maxK / (VS[0][0])
  128. #SNR[SNR>1] = 1
  129. SNRidx = len(ifaces)-3
  130. while SNR[SNRidx] > SNR[SNRidx+1] and SNRidx > 2:
  131. SNRidx -= 1
  132. #print("IDX", SNRidx)
  133. #plt.plot(ifaces[0:-1], SNR)
  134. #plt.plot(ifaces[0:-1][SNRidx], SNR[SNRidx], '.',markersize=12)
  135. #plt.gca().axhline(y=VS[0][0], xmin=0, xmax=ifaces[-1], color='r')
  136. #plt.gca().axhline(y=1, xmin=0, xmax=ifaces[-1], color='r')
  137. #K0T = np.dot(K0, K0.T)
  138. #K0T = np.dot(K0, np.dot( VS[0][0]* np.eye(len(ifaces)-1,1), K0.T) )
  139. #K0T = np.dot(K0, np.dot( 1/(VS[0][0]**2) * np.eye(np.shape(K0)[1]), K0.T) )
  140. #plt.matshow(0.05 * np.sqrt(K0T))
  141. #plt.colorbar()
  142. #plt.plot(ifaces[0:-1], np.diag( 0.01* np.sqrt(K0T)))
  143. #print(np.shape(K0T), len(ifaces)-1)
  144. #plt.show()
  145. #exit()
  146. ###############################################
  147. # Build full kernel
  148. ###############################################
  149. T2Bins = np.logspace( np.log10(cont["T2Bins"]["low"]), np.log10(cont["T2Bins"]["high"]), cont["T2Bins"]["number"], endpoint=True, base=10)
  150. KQT = np.real(buildKQT(np.abs(K0),tg,T2Bins))
  151. # model resolution matrix
  152. np.linalg.svd(KQT)
  153. exit()
  154. ###############################################
  155. # Linear Inversion
  156. ###############################################
  157. print("Calling inversion", flush=True)
  158. 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" )
  159. ###############################################
  160. # Non-linear refinement!
  161. ###############################################
  162. KQTc = buildKQT(K0, tg, T2Bins)
  163. prec = np.abs(np.dot(KQTc, inv))
  164. phidc = np.linalg.norm(np.dot(Wd,prec-np.ravel(V)))**2
  165. #PREc = np.reshape( prec, np.shape(V) )
  166. print("PHID linear=", errn, "PHID complex=", phidc/len(np.ravel(V)))
  167. res = nl.nonlinearinversion(inv, Wd, KQTc, np.ravel(V), Wm, alphastar )
  168. if res.success == True:
  169. INVc = np.reshape(res.x, (len(ifaces)-1,cont["T2Bins"]["number"]) )
  170. prec = np.abs(np.dot(KQTc, res.x))
  171. phidc = np.linalg.norm(np.dot(Wd,prec-np.ravel(V)))**2
  172. #PREc = np.reshape( prec, np.shape(V) )
  173. print("PHID linear=", errn, "PHID nonlinear=", phidc/len(np.ravel(V)))
  174. # Perform second fit around results of first
  175. res = nl.nonlinearinversion(res.x, Wd, KQTc, np.ravel(V), Wm, alphastar )
  176. if res.success == True:
  177. INVc = np.reshape(res.x, (len(ifaces)-1,cont["T2Bins"]["number"]) )
  178. prec = np.abs(np.dot(KQTc, res.x))
  179. phidc = np.linalg.norm(np.dot(Wd,prec-np.ravel(V)))**2
  180. #PREc = np.reshape( prec, np.shape(V) )
  181. print("PHID linear=", errn, "PHID nonlinear=", phidc/len(np.ravel(V)))
  182. #plt.matshow(INVc)
  183. #KQTc = buildKQT(K0,tg,T2Bins)
  184. #plt.matshow(PREc, cmap='Blues')
  185. #plt.gca().set_title("complex predicted")
  186. #plt.colorbar()
  187. ###############################################
  188. # Appraise
  189. ###############################################
  190. pre = np.dot(KQT,inv)
  191. PRE = np.reshape( pre, np.shape(V) )
  192. plt.matshow(PRE, cmap='Blues')
  193. plt.gca().set_title("predicted")
  194. plt.colorbar()
  195. DIFF = (PRE-V) / VS
  196. md = np.max(np.abs(DIFF))
  197. plt.matshow(DIFF, cmap=cmocean.cm.balance, vmin=-md, vmax=md)
  198. plt.gca().set_title("misfit / $\widehat{\sigma}$")
  199. plt.colorbar()
  200. plt.matshow(V, cmap='Blues')
  201. plt.gca().set_title("observed")
  202. plt.colorbar()
  203. T2Bins = np.append( T2Bins, T2Bins[-1] + (T2Bins[-1]-T2Bins[-2]) )
  204. INV = np.reshape(inv, (len(ifaces)-1,cont["T2Bins"]["number"]) )
  205. #alphas = np.tile(SNR, (len(T2Bins)-1,1))
  206. #colors = Normalize(1e-6, np.max(INV.T), clip=True)(INV.T)
  207. #colors = cmocean.cm.tempo(colors)
  208. ##colors[..., -1] = alphas
  209. #print(np.shape(colors))
  210. #print(np.shape(INV.T))
  211. #greys = np.full((*(INV.T).shape, 3), 70, dtype=np.uint8)
  212. ############## LINEAR RESULT ##########################
  213. Y,X = meshgrid( ifaces, T2Bins )
  214. fig = plt.figure( figsize=(pc2in(20.0),pc2in(22.)) )
  215. ax1 = fig.add_axes( [.2,.15,.6,.7] )
  216. im = ax1.pcolor(X, Y, INV.T, cmap=cmocean.cm.tempo) #cmap='viridis')
  217. #im = ax1.pcolor(X[0:SNRidx,:], Y[0:SNRidx,:], INV.T[0:SNRidx,:], cmap=cmocean.cm.tempo) #cmap='viridis')
  218. #im = ax1.pcolor(X[SNRidx::,:], Y[SNRidx::,:], INV.T[SNRidx::,:], cmap=cmocean.cm.tempo, alpha=.5) #cmap='viridis')
  219. #im = ax1.pcolormesh(X, Y, INV.T, alpha=alphas) #, cmap=cmocean.cm.tempo) #cmap='viridis')
  220. #im = ax1.pcolormesh(X, Y, INV.T, alpha=alphas) #, cmap=cmocean.cm.tempo) #cmap='viridis')
  221. #ax1.axhline( y=ifaces[SNRidx], xmin=T2Bins[0], xmax=T2Bins[-1], color='black' )
  222. im.set_edgecolor('face')
  223. ax1.set_xlim( T2Bins[0], T2Bins[-1] )
  224. ax1.set_ylim( ifaces[-1], ifaces[0] )
  225. cb = plt.colorbar(im, label = u"PWC (m$^3$/m$^3$)") #, format='%1.1f')
  226. cb.locator = MaxNLocator( nbins = 4)
  227. cb.ax.yaxis.set_offset_position('left')
  228. cb.update_ticks()
  229. ax1.set_xlabel(u"$T_2^*$ (ms)")
  230. ax1.set_ylabel(u"depth (m)")
  231. ax1.get_xaxis().set_major_formatter(FormatStrFormatter('%1.0f'))
  232. ax1.get_yaxis().set_major_formatter(FormatStrFormatter('%1.0f'))
  233. ax1.xaxis.set_major_locator( MaxNLocator(nbins = 4) )
  234. #ax1.xaxis.set_label_position('top')
  235. ax2 = ax1.twiny()
  236. ax2.plot( np.sum(INV, axis=1), (ifaces[1:]+ifaces[0:-1])/2 , color='red' )
  237. ax2.set_xlabel(u"total water (m$^3$/m$^3$)")
  238. ax2.set_ylim( ifaces[-1], ifaces[0] )
  239. ax2.xaxis.set_major_locator( MaxNLocator(nbins = 3) )
  240. ax2.get_xaxis().set_major_formatter(FormatStrFormatter('%0.2f'))
  241. ax2.axhline( y=ifaces[SNRidx], xmin=0, xmax=1, color='black', linestyle='dashed' )
  242. #ax2.xaxis.set_label_position('bottom')
  243. plt.savefig("akvoInversion.pdf")
  244. ############## NONLINEAR RESULT ##########################
  245. Y,X = meshgrid( ifaces, T2Bins )
  246. fig = plt.figure( figsize=(pc2in(20.0),pc2in(22.)) )
  247. ax1 = fig.add_axes( [.2,.15,.6,.7] )
  248. im = ax1.pcolor(X, Y, INVc.T, cmap=cmocean.cm.tempo) #cmap='viridis')
  249. #im = ax1.pcolor(X[0:SNRidx,:], Y[0:SNRidx,:], INV.T[0:SNRidx,:], cmap=cmocean.cm.tempo) #cmap='viridis')
  250. #im = ax1.pcolor(X[SNRidx::,:], Y[SNRidx::,:], INV.T[SNRidx::,:], cmap=cmocean.cm.tempo, alpha=.5) #cmap='viridis')
  251. #im = ax1.pcolormesh(X, Y, INV.T, alpha=alphas) #, cmap=cmocean.cm.tempo) #cmap='viridis')
  252. #im = ax1.pcolormesh(X, Y, INV.T, alpha=alphas) #, cmap=cmocean.cm.tempo) #cmap='viridis')
  253. #ax1.axhline( y=ifaces[SNRidx], xmin=T2Bins[0], xmax=T2Bins[-1], color='black' )
  254. im.set_edgecolor('face')
  255. ax1.set_xlim( T2Bins[0], T2Bins[-1] )
  256. ax1.set_ylim( ifaces[-1], ifaces[0] )
  257. cb = plt.colorbar(im, label = u"PWC (m$^3$/m$^3$)") #, format='%1.1f')
  258. cb.locator = MaxNLocator( nbins = 4)
  259. cb.ax.yaxis.set_offset_position('left')
  260. cb.update_ticks()
  261. ax1.set_xlabel(u"$T_2^*$ (ms)")
  262. ax1.set_ylabel(u"depth (m)")
  263. ax1.get_xaxis().set_major_formatter(FormatStrFormatter('%1.0f'))
  264. ax1.get_yaxis().set_major_formatter(FormatStrFormatter('%1.0f'))
  265. ax1.xaxis.set_major_locator( MaxNLocator(nbins = 4) )
  266. #ax1.xaxis.set_label_position('top')
  267. ax2 = ax1.twiny()
  268. ax2.plot( np.sum(INVc, axis=1), (ifaces[1:]+ifaces[0:-1])/2 , color='red' )
  269. ax2.set_xlabel(u"total water (m$^3$/m$^3$)")
  270. ax2.set_ylim( ifaces[-1], ifaces[0] )
  271. ax2.xaxis.set_major_locator( MaxNLocator(nbins = 3) )
  272. ax2.get_xaxis().set_major_formatter(FormatStrFormatter('%0.2f'))
  273. #ax2.axhline( y=ifaces[SNRidx], xmin=0, xmax=1, color='black', linestyle='dashed' )
  274. #ax2.xaxis.set_label_position('bottom')
  275. fig.suptitle("Non linear inversion")
  276. plt.savefig("akvoInversionNL.pdf")
  277. #############
  278. # water plot#
  279. fig2 = plt.figure( figsize=(pc2in(20.0),pc2in(22.)) )
  280. ax = fig2.add_axes( [.2,.15,.6,.7] )
  281. # Bound water cutoff
  282. Bidx = T2Bins[0:-1]<33.0
  283. twater = np.sum(INV, axis=1)
  284. bwater = np.sum(INV[:,Bidx], axis=1)
  285. ax.plot( twater, (ifaces[0:-1]+ifaces[1::])/2, label="NMR total water", color='blue' )
  286. ax.plot( bwater, (ifaces[0:-1]+ifaces[1::])/2, label="NMR bound water", color='green' )
  287. ax.fill_betweenx((ifaces[0:-1]+ifaces[1::])/2 , twater, bwater, where=twater >= bwater, facecolor='blue', alpha=.5)
  288. ax.fill_betweenx((ifaces[0:-1]+ifaces[1::])/2 , bwater, 0, where=bwater >= 0, facecolor='green', alpha=.5)
  289. ax.set_xlabel(r"$\theta_N$ (m$^3$/m$^3$)")
  290. ax.set_ylabel(r"depth (m)")
  291. ax.set_ylim( ifaces[-1], ifaces[0] )
  292. ax.set_xlim( 0, ax.get_xlim()[1] )
  293. #ax.axhline( y=ifaces[SNRidx], xmin=0, xmax=1, color='black', linestyle='dashed' )
  294. plt.savefig("akvoInversionWC.pdf")
  295. plt.legend()
  296. # Report results into a text file
  297. fr = pd.DataFrame( INV, columns=T2Bins[0:-1] )
  298. fr.insert(0, "layer top", ifaces[0:-1] )
  299. fr.insert(1, "layer bottom", ifaces[1::] )
  300. fr.insert(2, "NMR total water", np.sum(INV, axis=1) )
  301. fr.insert(3, "NMR bound water", bwater )
  302. fr.insert(4, "Layer SNR", SNR )
  303. fr.to_csv("akvoInversion.csv")
  304. #fr.to_excel("akvoInversion.xlsx")
  305. plt.show()
  306. if __name__ == "__main__":
  307. main()