fieldplot.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320
  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
  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. coordPlot1 = coordX
  138. coordPlot2 = coordZ
  139. elif crossplane=='YZ':
  140. coordY, coordZ = np.meshgrid(scan, scan)
  141. coordY.resize(npts*npts)
  142. coordZ.resize(npts*npts)
  143. coordX = zero
  144. coordPlot1 = coordY
  145. coordPlot2 = coordZ
  146. elif crossplane=='XY':
  147. coordX, coordY = np.meshgrid(scan, scan)
  148. coordX.resize(npts*npts)
  149. coordY.resize(npts*npts)
  150. coordZ = zero
  151. coordPlot1 = coordY
  152. coordPlot2 = coordX
  153. coord = np.vstack((coordX, coordY, coordZ)).transpose()
  154. terms, E, H = fieldnlay(np.array([x]), np.array([m]), coord, pl=pl)
  155. Ec = E[0, :, :]
  156. Hc = H[0, :, :]
  157. P=[]
  158. P = np.array(map(lambda n: np.linalg.norm(np.cross(Ec[n], Hc[n])).real, range(0, len(E[0]))))
  159. # for n in range(0, len(E[0])):
  160. # P.append(np.linalg.norm( np.cross(Ec[n], np.conjugate(Hc[n]) ).real/2 ))
  161. return Ec, Hc, P, coordPlot1, coordPlot2
  162. ###############################################################################
  163. 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):
  164. Ec, Hc, P, coordX, coordZ = GetField(crossplane, npts, factor, x, m, pl)
  165. Er = np.absolute(Ec)
  166. Hr = np.absolute(Hc)
  167. try:
  168. import matplotlib.pyplot as plt
  169. from matplotlib import cm
  170. from matplotlib.colors import LogNorm
  171. if field_to_plot == 'Pabs':
  172. Eabs_data = np.resize(P, (npts, npts)).T
  173. label = r'$\operatorname{Re}(E \times H)$'
  174. elif field_to_plot == 'Eabs':
  175. Eabs = np.sqrt(Er[ :, 0]**2 + Er[ :, 1]**2 + Er[ :, 2]**2)
  176. Eabs_data = np.resize(Eabs, (npts, npts)).T
  177. label = r'$|E|$'
  178. elif field_to_plot == 'Habs':
  179. Habs= np.sqrt(Hr[ :, 0]**2 + Hr[ :, 1]**2 + Hr[ :, 2]**2)
  180. Eabs_data = np.resize(Habs, (npts, npts)).T
  181. label = r'$|H|$'
  182. elif field_to_plot == 'angleEx':
  183. Eangle = np.angle(Ec[ :, 0])/np.pi*180
  184. Eabs_data = np.resize(Eangle, (npts, npts)).T
  185. label = r'$arg(E_x)$'
  186. elif field_to_plot == 'angleHy':
  187. Hangle = np.angle(Hc[ :, 1])/np.pi*180
  188. Eabs_data = np.resize(Hangle, (npts, npts)).T
  189. label = r'$arg(H_y)$'
  190. fig, ax = plt.subplots(1,1)
  191. # Rescale to better show the axes
  192. scale_x = np.linspace(min(coordX)*WL/2.0/np.pi, max(coordX)*WL/2.0/np.pi, npts)
  193. scale_z = np.linspace(min(coordZ)*WL/2.0/np.pi, max(coordZ)*WL/2.0/np.pi, npts)
  194. # Define scale ticks
  195. min_tick = np.amin(Eabs_data[~np.isnan(Eabs_data)])
  196. max_tick = np.amax(Eabs_data[~np.isnan(Eabs_data)])
  197. scale_ticks = np.linspace(min_tick, max_tick, 6)
  198. # Interpolation can be 'nearest', 'bilinear' or 'bicubic'
  199. ax.set_title(label)
  200. cax = ax.imshow(Eabs_data, interpolation = 'nearest', cmap = cm.jet,
  201. origin = 'lower'
  202. , vmin = min_tick, vmax = max_tick
  203. , extent = (min(scale_x), max(scale_x), min(scale_z), max(scale_z))
  204. #,norm = LogNorm()
  205. )
  206. ax.axis("image")
  207. # Add colorbar
  208. cbar = fig.colorbar(cax, ticks = [a for a in scale_ticks])
  209. cbar.ax.set_yticklabels(['%5.3g' % (a) for a in scale_ticks]) # vertically oriented colorbar
  210. pos = list(cbar.ax.get_position().bounds)
  211. #fig.text(pos[0] - 0.02, 0.925, '|E|/|E$_0$|', fontsize = 14)
  212. if crossplane=='XZ':
  213. plt.xlabel('Z, '+WL_units)
  214. plt.ylabel('X, '+WL_units)
  215. elif crossplane=='YZ':
  216. plt.xlabel('Z, '+WL_units)
  217. plt.ylabel('Y, '+WL_units)
  218. elif crossplane=='XY':
  219. plt.xlabel('Y, '+WL_units)
  220. plt.ylabel('X, '+WL_units)
  221. # # This part draws the nanoshell
  222. from matplotlib import patches
  223. from matplotlib.path import Path
  224. for xx in x:
  225. r= xx*WL/2.0/np.pi
  226. s1 = patches.Arc((0, 0), 2.0*r, 2.0*r, angle=0.0, zorder=1.8,
  227. theta1=0.0, theta2=360.0, linewidth=outline_width, color='black')
  228. ax.add_patch(s1)
  229. #
  230. # for flow in range(0,flow_total):
  231. # flow_x, flow_z = GetFlow(scale_x, scale_z, Ec, Hc,
  232. # min(scale_x)+flow*(scale_x[-1]-scale_x[0])/(flow_total-1),
  233. # min(scale_z),
  234. # #0.0,
  235. # npts*16)
  236. # verts = np.vstack((flow_z, flow_x)).transpose().tolist()
  237. # #codes = [Path.CURVE4]*len(verts)
  238. # codes = [Path.LINETO]*len(verts)
  239. # codes[0] = Path.MOVETO
  240. # path = Path(verts, codes)
  241. # patch = patches.PathPatch(path, facecolor='none', lw=1, edgecolor='yellow')
  242. # ax.add_patch(patch)
  243. if (crossplane=='XZ' or crossplane=='YZ') and flow_total>0:
  244. from matplotlib.path import Path
  245. scanSP = np.linspace(-factor*x[-1], factor*x[-1], npts)
  246. min_SP = -factor*x[-1]
  247. step_SP = 2.0*factor*x[-1]/(flow_total-1)
  248. x0, y0, z0 = 0, 0, 0
  249. max_length=factor*x[-1]*8
  250. #max_length=factor*x[-1]*5
  251. max_angle = np.pi/160
  252. if is_flow_extend:
  253. rg = range(0,flow_total*2+1)
  254. else:
  255. rg = range(0,flow_total)
  256. for flow in rg:
  257. if crossplane=='XZ':
  258. if is_flow_extend:
  259. x0 = min_SP*2 + flow*step_SP
  260. else:
  261. x0 = min_SP + flow*step_SP
  262. z0 = min_SP
  263. #y0 = x[-1]/20
  264. elif crossplane=='YZ':
  265. if is_flow_extend:
  266. y0 = min_SP*2 + flow*step_SP
  267. else:
  268. y0 = min_SP + flow*step_SP
  269. z0 = min_SP
  270. #x0 = x[-1]/20
  271. flow_xSP, flow_ySP, flow_zSP = GetFlow3D(x0, y0, z0, max_length, max_angle, x, m,pl)
  272. if crossplane=='XZ':
  273. flow_z_plot = flow_zSP*WL/2.0/np.pi
  274. flow_f_plot = flow_xSP*WL/2.0/np.pi
  275. elif crossplane=='YZ':
  276. flow_z_plot = flow_zSP*WL/2.0/np.pi
  277. flow_f_plot = flow_ySP*WL/2.0/np.pi
  278. verts = np.vstack((flow_z_plot, flow_f_plot)).transpose().tolist()
  279. codes = [Path.LINETO]*len(verts)
  280. codes[0] = Path.MOVETO
  281. path = Path(verts, codes)
  282. #patch = patches.PathPatch(path, facecolor='none', lw=0.2, edgecolor='white',zorder = 2.7)
  283. patch = patches.PathPatch(path, facecolor='none', lw=0.7, edgecolor='white',zorder = 1.9)
  284. ax.add_patch(patch)
  285. #ax.plot(flow_z_plot, flow_f_plot, 'x',ms=2, mew=0.1, linewidth=0.5, color='k', fillstyle='none')
  286. plt.savefig(comment+"-R"+str(int(round(x[-1]*WL/2.0/np.pi)))+"-"+crossplane+"-"
  287. +field_to_plot+".pdf")
  288. plt.draw()
  289. # plt.show()
  290. plt.clf()
  291. plt.close()
  292. finally:
  293. terms, Qext, Qsca, Qabs, Qbk, Qpr, g, Albedo, S1, S2 = scattnlay(np.array([x]),
  294. np.array([m]))
  295. print("Qabs = "+str(Qabs));
  296. #