fieldplot.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344
  1. #!/usr/bin/env python
  2. # -*- coding: UTF-8 -*-
  3. #
  4. # Copyright (C) 2009-2015 Ovidio Peña Rodríguez <ovidio@bytesfall.com>
  5. # Copyright (C) 2013-2015 Konstantin Ladutenko <kostyfisik@gmail.com>
  6. #
  7. # This file is part of python-scattnlay
  8. #
  9. # This program is free software: you can redistribute it and/or modify
  10. # it under the terms of the GNU General Public License as published by
  11. # the Free Software Foundation, either version 3 of the License, or
  12. # (at your option) any later version.
  13. #
  14. # This program is distributed in the hope that it will be useful,
  15. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  16. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  17. # GNU General Public License for more details.
  18. #
  19. # The only additional remark is that we expect that all publications
  20. # describing work using this software, or all commercial products
  21. # using it, cite the following reference:
  22. # [1] O. Pena and U. Pal, "Scattering of electromagnetic radiation by
  23. # a multilayered sphere," Computer Physics Communications,
  24. # vol. 180, Nov. 2009, pp. 2348-2354.
  25. #
  26. # You should have received a copy of the GNU General Public License
  27. # along with this program. If not, see <http://www.gnu.org/licenses/>.
  28. # Several functions to plot field and streamlines (power flow lines).
  29. import scattnlay
  30. from scattnlay import fieldnlay
  31. from scattnlay import scattnlay
  32. import numpy as np
  33. import cmath
  34. def unit_vector(vector):
  35. """ Returns the unit vector of the vector. """
  36. return vector / np.linalg.norm(vector)
  37. def angle_between(v1, v2):
  38. """ Returns the angle in radians between vectors 'v1' and 'v2'::
  39. >>> angle_between((1, 0, 0), (0, 1, 0))
  40. 1.5707963267948966
  41. >>> angle_between((1, 0, 0), (1, 0, 0))
  42. 0.0
  43. >>> angle_between((1, 0, 0), (-1, 0, 0))
  44. 3.141592653589793
  45. """
  46. v1_u = unit_vector(v1)
  47. v2_u = unit_vector(v2)
  48. angle = np.arccos(np.dot(v1_u, v2_u))
  49. if np.isnan(angle):
  50. if (v1_u == v2_u).all():
  51. return 0.0
  52. else:
  53. return np.pi
  54. return angle
  55. ###############################################################################
  56. def GetFlow3D(x0, y0, z0, max_length, max_angle, x, m, pl):
  57. # Initial position
  58. flow_x = [x0]
  59. flow_y = [y0]
  60. flow_z = [z0]
  61. max_step = x[-1]/3
  62. min_step = x[0]/2000
  63. # max_step = min_step
  64. step = min_step*2.0
  65. if max_step < min_step:
  66. max_step = min_step
  67. coord = np.vstack(([flow_x[-1]], [flow_y[-1]], [flow_z[-1]])).transpose()
  68. terms, E, H = fieldnlay(np.array([x]), np.array([m]), coord,pl=pl)
  69. Ec, Hc = E[0, 0, :], H[0, 0, :]
  70. S = np.cross(Ec, Hc.conjugate()).real
  71. Snorm_prev = S/np.linalg.norm(S)
  72. Sprev = S
  73. length = 0
  74. dpos = step
  75. count = 0
  76. while length < max_length:
  77. count = count + 1
  78. if (count>3000): # Limit length of the absorbed power streamlines
  79. break
  80. if step<max_step:
  81. step = step*2.0
  82. r = np.sqrt(flow_x[-1]**2 + flow_y[-1]**2 + flow_z[-1]**2)
  83. while step > min_step:
  84. #Evaluate displacement from previous poynting vector
  85. dpos = step
  86. dx = dpos*Snorm_prev[0];
  87. dy = dpos*Snorm_prev[1];
  88. dz = dpos*Snorm_prev[2];
  89. #Test the next position not to turn\chang size for more than max_angle
  90. coord = np.vstack(([flow_x[-1]+dx], [flow_y[-1]+dy], [flow_z[-1]+dz])).transpose()
  91. terms, E, H = fieldnlay(np.array([x]), np.array([m]), coord,pl=pl)
  92. Ec, Hc = E[0, 0, :], H[0, 0, :]
  93. Eth = max(np.absolute(Ec))/1e10
  94. Hth = max(np.absolute(Hc))/1e10
  95. for i in xrange(0,len(Ec)):
  96. if abs(Ec[i]) < Eth:
  97. Ec[i] = 0+0j
  98. if abs(Hc[i]) < Hth:
  99. Hc[i] = 0+0j
  100. S = np.cross(Ec, Hc.conjugate()).real
  101. if not np.isfinite(S).all():
  102. break
  103. Snorm = S/np.linalg.norm(S)
  104. diff = (S-Sprev)/max(np.linalg.norm(S), np.linalg.norm(Sprev))
  105. if np.linalg.norm(diff)<max_angle:
  106. # angle = angle_between(Snorm, Snorm_prev)
  107. # if abs(angle) < max_angle:
  108. break
  109. step = step/2.0
  110. #3. Save result
  111. Sprev = S
  112. Snorm_prev = Snorm
  113. dx = dpos*Snorm_prev[0];
  114. dy = dpos*Snorm_prev[1];
  115. dz = dpos*Snorm_prev[2];
  116. length = length + step
  117. flow_x.append(flow_x[-1] + dx)
  118. flow_y.append(flow_y[-1] + dy)
  119. flow_z.append(flow_z[-1] + dz)
  120. return np.array(flow_x), np.array(flow_y), np.array(flow_z)
  121. ###############################################################################
  122. def GetField(crossplane, npts, factor, x, m, pl):
  123. """
  124. crossplane: XZ, YZ, XY, or XYZ (half is XZ, half is YZ)
  125. npts: number of point in each direction
  126. factor: ratio of plotting size to outer size of the particle
  127. x: size parameters for particle layers
  128. m: relative index values for particle layers
  129. """
  130. scan = np.linspace(-factor*x[-1], factor*x[-1], npts)
  131. zero = np.zeros(npts*npts, dtype = np.float64)
  132. if crossplane=='XZ':
  133. coordX, coordZ = np.meshgrid(scan, scan)
  134. coordX.resize(npts*npts)
  135. coordZ.resize(npts*npts)
  136. coordY = zero
  137. elif crossplane=='YZ':
  138. coordY, coordZ = np.meshgrid(scan, scan)
  139. coordY.resize(npts*npts)
  140. coordZ.resize(npts*npts)
  141. coordX = zero
  142. elif crossplane=='XY':
  143. coordX, coordY = np.meshgrid(scan, scan)
  144. coordX.resize(npts*npts)
  145. coordY.resize(npts*npts)
  146. coordZ = zero
  147. elif crossplane=='XYZ':
  148. coordX, coordZ = np.meshgrid(scan, scan)
  149. coordY, coordZ = np.meshgrid(scan, scan)
  150. half=npts//2
  151. # coordX = np.copy(coordX)
  152. # coordY = np.copy(coordY)
  153. coordX[:,:half]=0
  154. coordY[:,half:]=0
  155. coordX.resize(npts*npts)
  156. coordY.resize(npts*npts)
  157. coordZ.resize(npts*npts)
  158. coord = np.vstack((coordX, coordY, coordZ)).transpose()
  159. terms, E, H = fieldnlay(np.array([x]), np.array([m]), coord, pl=pl)
  160. Ec = E[0, :, :]
  161. Hc = H[0, :, :]
  162. P=[]
  163. P = np.array(map(lambda n: np.linalg.norm(np.cross(Ec[n], Hc[n])), range(0, len(E[0]))))
  164. # for n in range(0, len(E[0])):
  165. # P.append(np.linalg.norm( np.cross(Ec[n], np.conjugate(Hc[n]) ).real/2 ))
  166. return Ec, Hc, P
  167. ###############################################################################
  168. def fieldplot(x,m, WL, comment='', WL_units=' ', crossplane='XZ', field_to_plot='Pabs',npts=101, factor=2.1, flow_total=11, is_flow_extend=True, pl=-1, outline_width=1):
  169. Ec, Hc, P = GetField(crossplane, npts, factor, x, m, pl)
  170. scan = np.linspace(-factor*x[-1], factor*x[-1], npts)
  171. coordX1, coordZ1 = np.meshgrid(scan, scan)
  172. Er = np.absolute(Ec)
  173. Hr = np.absolute(Hc)
  174. try:
  175. import matplotlib.pyplot as plt
  176. from matplotlib import cm
  177. from matplotlib.colors import LogNorm
  178. if field_to_plot == 'Pabs':
  179. Eabs_data = np.resize(P, (npts, npts)).T
  180. #label = r'$\operatorname{Re}(E \times H^*)$'
  181. label = r'$\left |E \times H\right|$'
  182. elif field_to_plot == 'Eabs':
  183. Eabs = np.sqrt(Er[ :, 0]**2 + Er[ :, 1]**2 + Er[ :, 2]**2)
  184. Eabs_data = np.resize(Eabs, (npts, npts)).T
  185. label = r'$|E|$'
  186. elif field_to_plot == 'Habs':
  187. Habs= np.sqrt(Hr[ :, 0]**2 + Hr[ :, 1]**2 + Hr[ :, 2]**2)
  188. Eabs_data = np.resize(Habs, (npts, npts)).T
  189. label = r'$|H|$'
  190. elif field_to_plot == 'angleEx':
  191. Eangle = np.angle(Ec[ :, 0])/np.pi*180
  192. Eabs_data = np.resize(Eangle, (npts, npts)).T
  193. label = r'$arg(E_x)$'
  194. elif field_to_plot == 'angleHy':
  195. Hangle = np.angle(Hc[ :, 1])/np.pi*180
  196. Eabs_data = np.resize(Hangle, (npts, npts)).T
  197. label = r'$arg(H_y)$'
  198. fig, ax = plt.subplots(1,1)
  199. # Rescale to better show the axes
  200. # scale_x = np.linspace(min(coordX1)*WL/2.0/np.pi, max(coordX1)*WL/2.0/np.pi, npts)
  201. # scale_z = np.linspace(min(coordZ1)*WL/2.0/np.pi, max(coordZ1)*WL/2.0/np.pi, npts)
  202. scale_x = np.linspace(-factor*x[-1]*WL/2.0/np.pi, factor*x[-1]*WL/2.0/np.pi, npts)
  203. scale_z = np.linspace(-factor*x[-1]*WL/2.0/np.pi, factor*x[-1]*WL/2.0/np.pi, npts)
  204. # Define scale ticks
  205. min_tick = np.amin(Eabs_data[~np.isnan(Eabs_data)])
  206. max_tick = np.amax(Eabs_data[~np.isnan(Eabs_data)])
  207. scale_ticks = np.linspace(min_tick, max_tick, 6)
  208. # Interpolation can be 'nearest', 'bilinear' or 'bicubic'
  209. ax.set_title(label)
  210. my_cmap = cm.jet
  211. if not (field_to_plot == 'angleEx' or field_to_plot == 'angleHy'):
  212. my_cmap.set_under('w')
  213. cax = ax.imshow(Eabs_data, interpolation = 'nearest', cmap = my_cmap,
  214. origin = 'lower'
  215. , vmin = min_tick+max_tick*1e-15, vmax = max_tick
  216. , extent = (min(scale_x), max(scale_x), min(scale_z), max(scale_z))
  217. #,norm = LogNorm()
  218. )
  219. ax.axis("image")
  220. # Add colorbar
  221. cbar = fig.colorbar(cax, ticks = [a for a in scale_ticks])
  222. cbar.ax.set_yticklabels(['%5.3g' % (a) for a in scale_ticks]) # vertically oriented colorbar
  223. pos = list(cbar.ax.get_position().bounds)
  224. #fig.text(pos[0] - 0.02, 0.925, '|E|/|E$_0$|', fontsize = 14)
  225. if crossplane=='XZ':
  226. plt.xlabel('Z, '+WL_units)
  227. plt.ylabel('X, '+WL_units)
  228. elif crossplane=='YZ':
  229. plt.xlabel('Z, '+WL_units)
  230. plt.ylabel('Y, '+WL_units)
  231. elif crossplane=='XYZ':
  232. plt.xlabel('Z, '+WL_units)
  233. plt.ylabel('Y:X, '+WL_units)
  234. elif crossplane=='XY':
  235. plt.xlabel('Y, '+WL_units)
  236. plt.ylabel('X, '+WL_units)
  237. # # This part draws the nanoshell
  238. from matplotlib import patches
  239. from matplotlib.path import Path
  240. x_edge = (x[-1], x[0])
  241. for xx in x_edge:
  242. r= xx*WL/2.0/np.pi
  243. s1 = patches.Arc((0, 0), 2.0*r, 2.0*r, angle=0.0, zorder=1.8,
  244. theta1=0.0, theta2=360.0, linewidth=outline_width, color='black')
  245. ax.add_patch(s1)
  246. if (not crossplane=='XY') and flow_total>0:
  247. from matplotlib.path import Path
  248. scanSP = np.linspace(-factor*x[-1], factor*x[-1], npts)
  249. min_SP = -factor*x[-1]
  250. step_SP = 2.0*factor*x[-1]/(flow_total-1)
  251. x0, y0, z0, f = 0, 0, 0, 0
  252. max_length=factor*x[-1]*8
  253. #max_length=factor*x[-1]*4
  254. max_angle = np.pi/160
  255. if is_flow_extend:
  256. rg = range(0,flow_total*2+1)
  257. else:
  258. rg = range(0,flow_total)
  259. for flow in rg:
  260. if is_flow_extend:
  261. f = min_SP*2 + flow*step_SP
  262. else:
  263. f = min_SP + flow*step_SP
  264. if crossplane=='XZ':
  265. x0 = f
  266. elif crossplane=='YZ':
  267. y0 = f
  268. elif crossplane=='XYZ':
  269. x0 = 0
  270. y0 = 0
  271. if f > 0:
  272. x0 = f
  273. else:
  274. y0 = f
  275. z0 = min_SP
  276. flow_xSP, flow_ySP, flow_zSP = GetFlow3D(x0, y0, z0, max_length, max_angle, x, m,pl)
  277. if crossplane=='XZ':
  278. flow_z_plot = flow_zSP*WL/2.0/np.pi
  279. flow_f_plot = flow_xSP*WL/2.0/np.pi
  280. elif crossplane=='YZ':
  281. flow_z_plot = flow_zSP*WL/2.0/np.pi
  282. flow_f_plot = flow_ySP*WL/2.0/np.pi
  283. elif crossplane=='XYZ':
  284. if f > 0:
  285. flow_z_plot = flow_zSP*WL/2.0/np.pi
  286. flow_f_plot = flow_xSP*WL/2.0/np.pi
  287. else:
  288. flow_z_plot = flow_zSP*WL/2.0/np.pi
  289. flow_f_plot = flow_ySP*WL/2.0/np.pi
  290. verts = np.vstack((flow_z_plot, flow_f_plot)).transpose().tolist()
  291. codes = [Path.LINETO]*len(verts)
  292. codes[0] = Path.MOVETO
  293. path = Path(verts, codes)
  294. #patch = patches.PathPatch(path, facecolor='none', lw=0.2, edgecolor='white',zorder = 2.7)
  295. patch = patches.PathPatch(path, facecolor='none', lw=1, edgecolor='white',zorder = 1.9)
  296. ax.add_patch(patch)
  297. #ax.plot(flow_z_plot, flow_f_plot, 'x',ms=2, mew=0.1, linewidth=0.5, color='k', fillstyle='none')
  298. bbox_props = dict(boxstyle="round,pad=0.3", fc="w", ec="w", lw=2)
  299. if crossplane=='XYZ':
  300. ax.annotate('E-k', xy=(0.96, 0.96), xycoords='axes fraction', fontsize=16,
  301. horizontalalignment='right', verticalalignment='top',
  302. bbox=bbox_props)
  303. ax.annotate('H-k', xy=(0.96, 0.04), xycoords='axes fraction', fontsize=16,
  304. horizontalalignment='right', verticalalignment='bottom',
  305. bbox=bbox_props)
  306. ax.axhline(y=0.0, ls='--', dashes=[5,3], color='gray', lw=1.5)
  307. plt.savefig(comment+"-R"+str(int(round(x[-1]*WL/2.0/np.pi)))+"-"+crossplane+"-"
  308. # +field_to_plot+".png")
  309. +field_to_plot+".pdf")
  310. plt.draw()
  311. # plt.show()
  312. plt.clf()
  313. plt.close()
  314. finally:
  315. terms, Qext, Qsca, Qabs, Qbk, Qpr, g, Albedo, S1, S2 = scattnlay(np.array([x]),
  316. np.array([m]))
  317. print("Qabs = "+str(Qabs));
  318. #