Surface NMR processing and inversion GUI
Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

invertTA.py 7.5KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218
  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. import cmocean
  17. from akvo.tressel.lemma_yaml import *
  18. def buildKQT(K0,tg,T2Bins):
  19. """
  20. Constructs a QT inversion kernel from an initial amplitude one.
  21. """
  22. nlay, nq = np.shape(K0)
  23. nt2 = len(T2Bins)
  24. nt = len(tg)
  25. KQT = np.zeros( ( nq*nt,nt2*nlay) )
  26. for iq in range(nq):
  27. for it in range(nt):
  28. for ilay in range(nlay):
  29. for it2 in range(nt2):
  30. #KQT[iq*nt + it,ilay*nt2+it2] = K0[ilay,iq]*np.exp(-((10+tg[it])*1e-3)/(1e-3*T2Bins[it2]))
  31. KQT[iq*nt + it,ilay*nt2+it2] = K0[ilay,iq]*np.exp(-((10+tg[it])*1e-3)/(1e-3*T2Bins[it2]))
  32. return KQT
  33. def loadAkvoData(fnamein, chan):
  34. """ Loads data from an Akvo YAML file. The 0.02 is hard coded as the pulse length. This needs to be
  35. corrected in future kernel calculations. The current was reported but not the pulse length.
  36. """
  37. fname = (os.path.splitext(fnamein)[0])
  38. with open(fnamein, 'r') as stream:
  39. try:
  40. AKVO = (yaml.load(stream, Loader=yaml.Loader))
  41. except yaml.YAMLError as exc:
  42. print(exc)
  43. exit()
  44. Z = np.zeros( (AKVO.nPulseMoments, AKVO.Gated["Pulse 1"]["abscissa"].size ) )
  45. ZS = np.zeros( (AKVO.nPulseMoments, AKVO.Gated["Pulse 1"]["abscissa"].size ) )
  46. for q in range(AKVO.nPulseMoments):
  47. Z[q] = AKVO.Gated["Pulse 1"][chan]["Q-"+str(q) + " CA"].data
  48. if chan == "Chan. 1":
  49. ZS[q] = AKVO.Gated["Pulse 1"][chan]["STD"].data
  50. elif chan == "Chan. 2":
  51. ZS[q] = AKVO.Gated["Pulse 1"][chan]["STD"].data
  52. elif chan == "Chan. 3":
  53. ZS[q] = AKVO.Gated["Pulse 1"][chan]["STD"].data
  54. elif chan == "Chan. 4":
  55. ZS[q] = AKVO.Gated["Pulse 1"][chan]["STD"].data
  56. else:
  57. print("DOOM!!!")
  58. exit()
  59. #Z *= 1e-9
  60. #ZS *= 1e-9
  61. J = AKVO.Pulses["Pulse 1"]["current"].data
  62. J = np.append(J,J[-1]+(J[-1]-J[-2]))
  63. Q = AKVO.pulseLength[0]*J
  64. return Z, ZS, AKVO.Gated["Pulse 1"]["abscissa"].data #, Q
  65. def catLayers(K0):
  66. K = np.zeros( (len(K0.keys()), len(K0["layer-0"].data)) , dtype=complex )
  67. for lay in range(len(K0.keys())):
  68. #print(K0["layer-"+str(lay)].data) # print (lay)
  69. K[lay] =K0["layer-"+str(lay)].data # print (lay)
  70. return 1e9*K # invert in nV
  71. def loadK0(fname):
  72. """ Loads in initial amplitude kernel
  73. """
  74. print("loading K0", fname)
  75. with open(fname) as f:
  76. K0 = yaml.load(f, Loader=yaml.Loader)
  77. K = catLayers(K0.K0)
  78. ifaces = np.array(K0.Interfaces.data)
  79. return ifaces, np.abs(K)
  80. def main():
  81. if (len (sys.argv) < 3):
  82. print ("python invertTA.py K0.dat Data.yaml")
  83. print (sys.argv[1])
  84. with open(sys.argv[1], 'r') as stream:
  85. try:
  86. cont = (yaml.load(stream, Loader=yaml.Loader))
  87. except yaml.YAMLError as exc:
  88. print(exc)
  89. ###############################################
  90. # Load in data
  91. ###############################################
  92. V = []
  93. VS = []
  94. tg = 0
  95. for dat in cont['data']:
  96. for ch in cont['data'][dat]['channels']:
  97. print("dat", dat, "ch", ch)
  98. v,vs,tg = loadAkvoData(dat, ch)
  99. V.append(v)
  100. VS.append(vs)
  101. for iv in range(1, len(V)):
  102. V[0] = np.concatenate( (V[0], V[iv]) )
  103. VS[0] = np.concatenate( (VS[0], VS[iv]) )
  104. V = V[0]
  105. VS = VS[0]
  106. #plt.matshow(V, cmap='RdBu', vmin=-np.max(np.abs(V)), vmax=np.max(np.abs(V)))
  107. #plt.title("data")
  108. #plt.colorbar()
  109. #plt.show()
  110. #exit()
  111. #plt.matshow(VS, cmap='inferno', vmin=-np.max(np.abs(VS)), vmax=np.max(np.abs(VS)))
  112. #plt.title("error")
  113. #plt.colorbar()
  114. ###############################################
  115. # Load in kernels
  116. ###############################################
  117. K0 = []
  118. for kern in cont["K0"]:
  119. ifaces,k0 = loadK0( kern )
  120. K0.append(k0)
  121. for ik in range(1, len(K0)):
  122. K0[0] = np.concatenate( (K0[0].T, K0[ik].T) ).T
  123. K0 = K0[0]
  124. #plt.matshow(K0)
  125. ###############################################
  126. # Build full kernel
  127. ###############################################
  128. T2Bins = np.logspace( np.log10(cont["T2Bins"]["low"]), np.log10(cont["T2Bins"]["high"]), cont["T2Bins"]["number"], endpoint=True, base=10)
  129. KQT = buildKQT(K0,tg,T2Bins)
  130. #plt.matshow(KQT)
  131. # Chan. 1 reg = 1.5
  132. # Chan. 2 reg = 1.35
  133. # Chan. 4 reg = 1.95
  134. ###############################################
  135. # Invert
  136. ###############################################
  137. print("Calling inversion", flush=True)
  138. inv, ibreak, errn, phim, phid, mkappa = logBarrier(KQT, np.ravel(V), T2Bins, "lcurve", MAXITER=150, sigma=np.ravel(VS), alpha=1e6, smooth="Smallest" ) #, smooth=True) #
  139. #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):
  140. #return x, ibreak, np.sqrt(phid/len(b)), PHIM, PHID/len(b), np.argmax(kappa)
  141. ###############################################
  142. # Appraise
  143. ###############################################
  144. pre = np.dot(KQT,inv)
  145. PRE = np.reshape( pre, np.shape(V) )
  146. plt.matshow(PRE, cmap='Blues')
  147. plt.gca().set_title("predicted")
  148. plt.colorbar()
  149. DIFF = (PRE-V) / VS
  150. md = np.max(np.abs(DIFF))
  151. plt.matshow(DIFF, cmap=cmocean.cm.balance, vmin=-md, vmax=md)
  152. plt.gca().set_title("misfit / $\widehat{\sigma}$")
  153. plt.colorbar()
  154. plt.matshow(V, cmap='Blues')
  155. plt.gca().set_title("observed")
  156. plt.colorbar()
  157. T2Bins = np.append( T2Bins, T2Bins[-1] + (T2Bins[-1]-T2Bins[-2]) )
  158. print( np.shape(inv), len(ifaces)-1,cont["T2Bins"]["number"] )
  159. INV = np.reshape(inv, (len(ifaces)-1,cont["T2Bins"]["number"]) )
  160. Y,X = meshgrid( ifaces, T2Bins )
  161. fig = plt.figure( figsize=(pc2in(17.0),pc2in(18.)) )
  162. ax1 = fig.add_axes( [.2,.15,.6,.7] )
  163. im = ax1.pcolor(X, Y, INV.T, cmap=cmocean.cm.tempo) #cmap='viridis')
  164. im.set_edgecolor('face')
  165. ax1.set_xlim( T2Bins[0], T2Bins[-1] )
  166. ax1.set_ylim( ifaces[-1], ifaces[0] )
  167. cb = plt.colorbar(im, label = u"PWC (m$^3$/m$^3$)") #, format='%1.1f')
  168. cb.locator = MaxNLocator( nbins = 4)
  169. cb.ax.yaxis.set_offset_position('left')
  170. cb.update_ticks()
  171. #ax1.set_xlabel(u"$T_2^*$ (ms)")
  172. #ax1.set_ylabel(u"depth (m)$")
  173. ax1.get_xaxis().set_major_formatter(FormatStrFormatter('%1.0f'))
  174. ax1.get_yaxis().set_major_formatter(FormatStrFormatter('%1.0f'))
  175. ax1.xaxis.set_major_locator( MaxNLocator(nbins = 4) )
  176. #ax1.xaxis.set_label_position('top')
  177. ax2 = ax1.twiny()
  178. ax2.plot( np.sum(INV, axis=1), (ifaces[1:]+ifaces[0:-1])/2 , color='red' )
  179. ax2.set_xlabel(u"total water (m$^3$/m$^3$)")
  180. ax2.set_ylim( ifaces[-1], ifaces[0] )
  181. ax2.xaxis.set_major_locator( MaxNLocator(nbins = 3) )
  182. ax2.get_xaxis().set_major_formatter(FormatStrFormatter('%0.2f'))
  183. #ax2.xaxis.set_label_position('bottom')
  184. plt.savefig("akvoInversion.pdf")
  185. plt.show()
  186. if __name__ == "__main__":
  187. main()