fdtd.py 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. #!/usr/bin/env python
  2. # File: fdtd.py
  3. # Name: D.Saravanan
  4. # Date: 21/05/2022
  5. """ Script for 1-dimensional fdtd with gaussian pulse as source """
  6. import numpy as np
  7. from mpi4py import MPI
  8. import matplotlib.pyplot as plt
  9. plt.style.use("classic")
  10. plt.rcParams["text.usetex"] = True
  11. plt.rcParams["pgf.texsystem"] = "pdflatex"
  12. plt.rcParams.update(
  13. {
  14. "font.family": "serif",
  15. "font.size": 8,
  16. "axes.labelsize": 10,
  17. "axes.titlesize": 10,
  18. "figure.titlesize": 10,
  19. }
  20. )
  21. def main():
  22. comm = MPI.COMM_WORLD
  23. rank = comm.Get_rank()
  24. size = comm.Get_size()
  25. ke = 200
  26. # Pulse parameters
  27. kc = int(ke/2)
  28. t0 = 40
  29. spread = 12
  30. nsteps = 100
  31. # determine the workload of each rank
  32. workloads = [ ke // size for i in range(size) ]
  33. for i in range( ke % size ):
  34. workloads[i] += 1
  35. start = 0
  36. for i in range(rank):
  37. start += workloads[i]
  38. end = start + workloads[rank]
  39. #timeloads = [ nsteps // size for i in range(size) ]
  40. #for i in range( nsteps % size ):
  41. # timeloads[i] += 1
  42. #start = 0
  43. #for i in range(rank):
  44. # start += timeloads[i]
  45. #end = start + timeloads[rank]
  46. N = workloads[rank]
  47. ex = np.zeros(N)
  48. hy = np.zeros(N)
  49. for time_step in range(1, nsteps + 1):
  50. ex[1:N] = ex[1:N] + 0.5 * (hy[0:N-1] - hy[1:N])
  51. ex[10] = np.exp(-0.5 * ((t0 - time_step) / spread) ** 2)
  52. hy[0:N-1] = hy[0:N-1] + 0.5 * (ex[0:N-1] - ex[1:N])
  53. comm.Bcast(ex, root=0)
  54. comm.Bcast(hy, root=0)
  55. fig, (ax1, ax2) = plt.subplots(2)
  56. fig.suptitle(r"FDTD simulation of a pulse in free space after 100 time steps")
  57. ax1.plot(ex, "k", lw=1)
  58. ax1.text(100, 0.5, "T = {}".format(time_step), horizontalalignment="center")
  59. ax1.set(xlim=(0, 200), ylim=(-1.2, 1.2), ylabel=r"E$_x$")
  60. ax1.set(xticks=range(0, 220, 20), yticks=np.arange(-1, 1.2, 1))
  61. ax2.plot(hy, "k", lw=1)
  62. ax2.set(xlim=(0, 200), ylim=(-1.2, 1.2), xlabel=r"FDTD cells", ylabel=r"H$_y$")
  63. ax2.set(xticks=range(0, 220, 20), yticks=np.arange(-1, 1.2, 1))
  64. plt.subplots_adjust(bottom=0.2, hspace=0.45)
  65. plt.savefig("fdtd.png")
  66. if __name__ == "__main__":
  67. main()