fdtdcudanumba.py 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. #!/usr/bin/env python
  2. # File: fdtdcudanumba.py
  3. # Name: D.Saravanan
  4. # Date: 16/05/2022
  5. """ Script for 1-dimensional fdtd with gaussian pulse as source """
  6. import numpy as np
  7. import cupy as cp
  8. from numba import cuda
  9. import matplotlib.pyplot as plt
  10. plt.style.use("classic")
  11. plt.rcParams["text.usetex"] = True
  12. plt.rcParams["pgf.texsystem"] = "pdflatex"
  13. plt.rcParams.update(
  14. {
  15. "font.family": "serif",
  16. "font.size": 8,
  17. "axes.labelsize": 10,
  18. "axes.titlesize": 10,
  19. "figure.titlesize": 10,
  20. }
  21. )
  22. def plotting(time_step, ex, hy):
  23. """plot function"""
  24. fig, (ax1, ax2) = plt.subplots(2)
  25. fig.suptitle(r"FDTD simulation of a pulse in free space after 100 time steps")
  26. ax1.plot(ex.get(), "k", lw=1)
  27. ax1.text(100, 0.5, "T = {}".format(time_step), horizontalalignment="center")
  28. ax1.set(xlim=(0, 200), ylim=(-1.2, 1.2), ylabel=r"E$_x$")
  29. ax1.set(xticks=range(0, 220, 20), yticks=np.arange(-1, 1.2, 1))
  30. ax2.plot(hy.get(), "k", lw=1)
  31. ax2.set(xlim=(0, 200), ylim=(-1.2, 1.2), xlabel=r"FDTD cells", ylabel=r"H$_y$")
  32. ax2.set(xticks=range(0, 220, 20), yticks=np.arange(-1, 1.2, 1))
  33. plt.subplots_adjust(bottom=0.2, hspace=0.45)
  34. plt.savefig("fdtdcudanumba.png")
  35. @cuda.jit
  36. def electric(ke, ex, hy):
  37. start = cuda.grid(1)
  38. stride = cuda.gridsize(1)
  39. for k in range(start, ke, stride):
  40. ex[k] = ex[k] + 0.5 * (hy[k-1] - hy[k])
  41. @cuda.jit
  42. def magnetic(ke, ex, hy):
  43. start = cuda.grid(1)
  44. stride = cuda.gridsize(1)
  45. for k in range(start, ke, stride):
  46. hy[k] = hy[k] + 0.5 * (ex[k-1] - ex[k])
  47. ke = 201
  48. ex = cp.zeros(ke)
  49. hy = cp.zeros(ke)
  50. kc = cp.int32(ke/2)
  51. t0 = 40
  52. spread = 12
  53. nsteps = 100
  54. for time_step in range(1, nsteps + 1):
  55. electric[10, 32](ke, ex, hy)
  56. ex[kc] = cp.exp(-0.5 * ((t0 - time_step) / spread) ** 2)
  57. magnetic[10, 32](ke, ex, hy)
  58. plotting(time_step, ex, hy)