fdtd.py 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. #!/usr/bin/env python
  2. # File: fdtd.py
  3. # Name: D.Saravanan
  4. # Date: 13/05/2022
  5. """ Script for finite difference time domain method """
  6. import pycuda.driver as cuda
  7. import pycuda.autoinit
  8. from pycuda.elementwise import ElementwiseKernel
  9. import pycuda.gpuarray as gpuarray
  10. import pycuda.cumath as cumath
  11. import numpy as np
  12. import matplotlib.pyplot as plt
  13. plt.rcParams["text.usetex"] = True
  14. plt.rcParams["pgf.texsystem"] = "pdflatex"
  15. plt.rcParams.update(
  16. {
  17. "font.family": "serif",
  18. "font.size": 8,
  19. "axes.labelsize": 10,
  20. "axes.titlesize": 10,
  21. "figure.titlesize": 10,
  22. }
  23. )
  24. ke = np.int32(201)
  25. ex = gpuarray.zeros(ke, dtype=np.float32)
  26. hy = gpuarray.zeros(ke, dtype=np.float32)
  27. # Pulse parameters
  28. kc = np.int32(ke/2)
  29. t0 = np.int32(40)
  30. spread = np.int32(12)
  31. nsteps = np.int32(100)
  32. gaussian_pulse = ElementwiseKernel(
  33. "int t0, int time_step, int spread, int kc, float *ex",
  34. "ex[kc] = exp(-0.5 * pow(((t0 - time_step) / spread), 2))",
  35. "gaussian_pulse"
  36. )
  37. # FDTD loop
  38. for time_step in range(1, nsteps + 1):
  39. # calculate the Ex field
  40. for k in range(1, ke):
  41. ex[k] = ex[k] + 0.5 * (hy[k - 1] - hy[k])
  42. # put a Gaussian pulse in the middle
  43. #ex[kc] = cumath.exp(-0.5 * ((t0 - time_step) / spread) ** 2)
  44. gaussian_pulse(t0, time_step, spread, kc, ex)
  45. # calculate the Hy field
  46. for k in range(ke - 1):
  47. hy[k] = hy[k] + 0.5 * (ex[k] - ex[k + 1])
  48. fig, (ax1, ax2) = plt.subplots(2)
  49. fig.suptitle(r"FDTD simulation of a pulse in free space after 100 time steps")
  50. ax1.plot(ex.get(), "k", lw=1)
  51. ax1.text(100, 0.5, "T = {}".format(time_step), horizontalalignment="center")
  52. ax1.set(xlim=(0, 200), ylim=(-1.2, 1.2), ylabel=r"E$_x$")
  53. ax1.set(xticks=range(0, 220, 20), yticks=np.arange(-1, 1.2, 1))
  54. ax2.plot(hy.get(), "k", lw=1)
  55. ax2.set(xlim=(0, 200), ylim=(-1.2, 1.2), xlabel=r"FDTD cells", ylabel=r"H$_y$")
  56. ax2.set(xticks=range(0, 220, 20), yticks=np.arange(-1, 1.2, 1))
  57. plt.subplots_adjust(bottom=0.2, hspace=0.45)
  58. plt.savefig("fdtd.png")