Added a pre-commit config file and reformatted all the files accordingly by using it.

这个提交包含在:
Sai-Suraj-27
2023-06-26 16:09:39 +05:30
父节点 c71e87e34f
当前提交 f9dd7f2420
共有 155 个文件被更改,包括 11383 次插入8802 次删除

查看文件

@@ -253,7 +253,7 @@ where :math:`dt` is the temporal resolution (timestep) of the model.
Example of the ``impulse`` waveform - time domain.
.. note::
* The impulse waveform should be used with care!
* The impulse response of a model, i.e. when the source in the model is excited using the impulse waveform, is not likely to be useful when viewed in isolation.
* The impulse waveform should be used with care!
* The impulse response of a model, i.e. when the source in the model is excited using the impulse waveform, is not likely to be useful when viewed in isolation.
* However, the impulse response of a model can be convolved with different inputs (waveforms) to provide valid outputs without having to run a separate model for each different input (waveform).
* The impulse response of the model can only be legitimately convolved with inputs (waveforms) that respect the limits of numerical dispersion in the original model, i.e. if a waveform contains frequencies that will not propagate correctly (due to numerical dispersion) in the original model, then the convolution of the waveform with the impulse response will not be valid.
* The impulse response of the model can only be legitimately convolved with inputs (waveforms) that respect the limits of numerical dispersion in the original model, i.e. if a waveform contains frequencies that will not propagate correctly (due to numerical dispersion) in the original model, then the convolution of the waveform with the impulse response will not be valid.

查看文件

@@ -48,55 +48,53 @@ def mpl_plot(filename, outputs=Rx.defaultoutputs, fft=False, save=False):
file = Path(filename)
# Open output file and read iterations
f = h5py.File(file, 'r')
f = h5py.File(file, "r")
# Paths to grid(s) to traverse for outputs
paths = ['/']
paths = ["/"]
# Check if any subgrids and add path(s)
is_subgrids = "/subgrids" in f
if is_subgrids:
paths = paths + ['/subgrids/' + path + '/' for path in f['/subgrids'].keys()]
paths = paths + ["/subgrids/" + path + "/" for path in f["/subgrids"].keys()]
# Get number of receivers in grid(s)
nrxs = []
for path in paths:
if f[path].attrs['nrx'] > 0:
nrxs.append(f[path].attrs['nrx'])
if f[path].attrs["nrx"] > 0:
nrxs.append(f[path].attrs["nrx"])
else:
paths.remove(path)
# Check there are any receivers
if not paths:
logger.exception(f'No receivers found in {file}')
logger.exception(f"No receivers found in {file}")
raise ValueError
# Loop through all grids
for path in paths:
iterations = f[path].attrs['Iterations']
nrx = f[path].attrs['nrx']
dt = f[path].attrs['dt']
iterations = f[path].attrs["Iterations"]
nrx = f[path].attrs["nrx"]
dt = f[path].attrs["dt"]
time = np.linspace(0, (iterations - 1) * dt, num=iterations)
# Check for single output component when doing a FFT
if fft:
if not len(outputs) == 1:
logger.exception('A single output must be specified when using ' +
'the -fft option')
logger.exception("A single output must be specified when using " + "the -fft option")
raise ValueError
# New plot for each receiver
for rx in range(1, nrx + 1):
rxpath = path + 'rxs/rx' + str(rx) + '/'
rxpath = path + "rxs/rx" + str(rx) + "/"
availableoutputs = list(f[rxpath].keys())
# If only a single output is required, create one subplot
if len(outputs) == 1:
# Check for polarity of output and if requested output is in file
if outputs[0][-1] == '-':
if outputs[0][-1] == "-":
polarity = -1
outputtext = '-' + outputs[0][0:-1]
outputtext = "-" + outputs[0][0:-1]
output = outputs[0][0:-1]
else:
polarity = 1
@@ -104,9 +102,11 @@ def mpl_plot(filename, outputs=Rx.defaultoutputs, fft=False, save=False):
output = outputs[0]
if output not in availableoutputs:
logger.exception(f"{output} output requested to plot, but " +
f"the available output for receiver 1 is " +
f"{', '.join(availableoutputs)}")
logger.exception(
f"{output} output requested to plot, but "
+ f"the available output for receiver 1 is "
+ f"{', '.join(availableoutputs)}"
)
raise ValueError
outputdata = f[rxpath + output][:] * polarity
@@ -118,7 +118,7 @@ def mpl_plot(filename, outputs=Rx.defaultoutputs, fft=False, save=False):
freqmaxpower = np.where(np.isclose(power, 0))[0][0]
# Set plotting range to -60dB from maximum power or 4 times
# frequency at maximum power
# frequency at maximum power
try:
pltrange = np.where(power[freqmaxpower:] < -60)[0][0] + freqmaxpower + 1
except:
@@ -127,82 +127,91 @@ def mpl_plot(filename, outputs=Rx.defaultoutputs, fft=False, save=False):
pltrange = np.s_[0:pltrange]
# Plot time history of output component
fig, (ax1, ax2) = plt.subplots(nrows=1, ncols=2,
num=rxpath + ' - ' + f[rxpath].attrs['Name'],
figsize=(20, 10), facecolor='w',
edgecolor='w')
line1 = ax1.plot(time, outputdata, 'r', lw=2, label=outputtext)
ax1.set_xlabel('Time [s]')
ax1.set_ylabel(outputtext + ' field strength [V/m]')
fig, (ax1, ax2) = plt.subplots(
nrows=1,
ncols=2,
num=rxpath + " - " + f[rxpath].attrs["Name"],
figsize=(20, 10),
facecolor="w",
edgecolor="w",
)
line1 = ax1.plot(time, outputdata, "r", lw=2, label=outputtext)
ax1.set_xlabel("Time [s]")
ax1.set_ylabel(outputtext + " field strength [V/m]")
ax1.set_xlim([0, np.amax(time)])
ax1.grid(which='both', axis='both', linestyle='-.')
ax1.grid(which="both", axis="both", linestyle="-.")
# Plot frequency spectra
markerline, stemlines, baseline = ax2.stem(freqs[pltrange],
power[pltrange], '-.',
use_line_collection=True)
plt.setp(baseline, 'linewidth', 0)
plt.setp(stemlines, 'color', 'r')
plt.setp(markerline, 'markerfacecolor', 'r', 'markeredgecolor', 'r')
line2 = ax2.plot(freqs[pltrange], power[pltrange], 'r', lw=2)
ax2.set_xlabel('Frequency [Hz]')
ax2.set_ylabel('Power [dB]')
ax2.grid(which='both', axis='both', linestyle='-.')
markerline, stemlines, baseline = ax2.stem(
freqs[pltrange], power[pltrange], "-.", use_line_collection=True
)
plt.setp(baseline, "linewidth", 0)
plt.setp(stemlines, "color", "r")
plt.setp(markerline, "markerfacecolor", "r", "markeredgecolor", "r")
line2 = ax2.plot(freqs[pltrange], power[pltrange], "r", lw=2)
ax2.set_xlabel("Frequency [Hz]")
ax2.set_ylabel("Power [dB]")
ax2.grid(which="both", axis="both", linestyle="-.")
# Change colours and labels for magnetic field components
# Change colours and labels for magnetic field components
# or currents
if 'H' in outputs[0]:
plt.setp(line1, color='g')
plt.setp(line2, color='g')
plt.setp(ax1, ylabel=outputtext + ' field strength [A/m]')
plt.setp(stemlines, 'color', 'g')
plt.setp(markerline, 'markerfacecolor', 'g',
'markeredgecolor', 'g')
elif 'I' in outputs[0]:
plt.setp(line1, color='b')
plt.setp(line2, color='b')
plt.setp(ax1, ylabel=outputtext + ' current [A]')
plt.setp(stemlines, 'color', 'b')
plt.setp(markerline, 'markerfacecolor', 'b',
'markeredgecolor', 'b')
if "H" in outputs[0]:
plt.setp(line1, color="g")
plt.setp(line2, color="g")
plt.setp(ax1, ylabel=outputtext + " field strength [A/m]")
plt.setp(stemlines, "color", "g")
plt.setp(markerline, "markerfacecolor", "g", "markeredgecolor", "g")
elif "I" in outputs[0]:
plt.setp(line1, color="b")
plt.setp(line2, color="b")
plt.setp(ax1, ylabel=outputtext + " current [A]")
plt.setp(stemlines, "color", "b")
plt.setp(markerline, "markerfacecolor", "b", "markeredgecolor", "b")
plt.show()
# Plotting if no FFT required
else:
fig, ax = plt.subplots(subplot_kw=dict(xlabel='Time [s]',
ylabel=outputtext + ' field strength [V/m]'),
num=rxpath + ' - ' + f[rxpath].attrs['Name'],
figsize=(20, 10), facecolor='w', edgecolor='w')
line = ax.plot(time, outputdata, 'r', lw=2, label=outputtext)
fig, ax = plt.subplots(
subplot_kw=dict(xlabel="Time [s]", ylabel=outputtext + " field strength [V/m]"),
num=rxpath + " - " + f[rxpath].attrs["Name"],
figsize=(20, 10),
facecolor="w",
edgecolor="w",
)
line = ax.plot(time, outputdata, "r", lw=2, label=outputtext)
ax.set_xlim([0, np.amax(time)])
# ax.set_ylim([-15, 20])
ax.grid(which='both', axis='both', linestyle='-.')
ax.grid(which="both", axis="both", linestyle="-.")
if 'H' in output:
plt.setp(line, color='g')
plt.setp(ax, ylabel=outputtext + ', field strength [A/m]')
elif 'I' in output:
plt.setp(line, color='b')
plt.setp(ax, ylabel=outputtext + ', current [A]')
if "H" in output:
plt.setp(line, color="g")
plt.setp(ax, ylabel=outputtext + ", field strength [A/m]")
elif "I" in output:
plt.setp(line, color="b")
plt.setp(ax, ylabel=outputtext + ", current [A]")
# If multiple outputs required, create all nine subplots and
# If multiple outputs required, create all nine subplots and
# populate only the specified ones
else:
fig, ax = plt.subplots(subplot_kw=dict(xlabel='Time [s]'),
num=rxpath + ' - ' + f[rxpath].attrs['Name'],
figsize=(20, 10), facecolor='w', edgecolor='w')
fig, ax = plt.subplots(
subplot_kw=dict(xlabel="Time [s]"),
num=rxpath + " - " + f[rxpath].attrs["Name"],
figsize=(20, 10),
facecolor="w",
edgecolor="w",
)
if len(outputs) == 9:
gs = gridspec.GridSpec(3, 3, hspace=0.3, wspace=0.3)
else:
gs = gridspec.GridSpec(3, 2, hspace=0.3, wspace=0.3)
for output in outputs:
# Check for polarity of output and if requested output
# Check for polarity of output and if requested output
# is in file
if output[-1] == 'm':
if output[-1] == "m":
polarity = -1
outputtext = '-' + output[0:-1]
outputtext = "-" + output[0:-1]
output = output[0:-1]
else:
polarity = 1
@@ -210,93 +219,115 @@ def mpl_plot(filename, outputs=Rx.defaultoutputs, fft=False, save=False):
# Check if requested output is in file
if output not in availableoutputs:
logger.exception(f"Output(s) requested to plot: " +
f"{', '.join(outputs)}, but available output(s) " +
f"for receiver {rx} in the file: " +
f"{', '.join(availableoutputs)}")
logger.exception(
f"Output(s) requested to plot: "
+ f"{', '.join(outputs)}, but available output(s) "
+ f"for receiver {rx} in the file: "
+ f"{', '.join(availableoutputs)}"
)
raise ValueError
outputdata = f[rxpath + output][:] * polarity
if output == 'Ex':
if output == "Ex":
ax = plt.subplot(gs[0, 0])
ax.plot(time, outputdata, 'r', lw=2, label=outputtext)
ax.set_ylabel(outputtext + ', field strength [V/m]')
ax.plot(time, outputdata, "r", lw=2, label=outputtext)
ax.set_ylabel(outputtext + ", field strength [V/m]")
# ax.set_ylim([-15, 20])
elif output == 'Ey':
elif output == "Ey":
ax = plt.subplot(gs[1, 0])
ax.plot(time, outputdata, 'r', lw=2, label=outputtext)
ax.set_ylabel(outputtext + ', field strength [V/m]')
ax.plot(time, outputdata, "r", lw=2, label=outputtext)
ax.set_ylabel(outputtext + ", field strength [V/m]")
# ax.set_ylim([-15, 20])
elif output == 'Ez':
elif output == "Ez":
ax = plt.subplot(gs[2, 0])
ax.plot(time, outputdata, 'r', lw=2, label=outputtext)
ax.set_ylabel(outputtext + ', field strength [V/m]')
ax.plot(time, outputdata, "r", lw=2, label=outputtext)
ax.set_ylabel(outputtext + ", field strength [V/m]")
# ax.set_ylim([-15, 20])
elif output == 'Hx':
elif output == "Hx":
ax = plt.subplot(gs[0, 1])
ax.plot(time, outputdata, 'g', lw=2, label=outputtext)
ax.set_ylabel(outputtext + ', field strength [A/m]')
ax.plot(time, outputdata, "g", lw=2, label=outputtext)
ax.set_ylabel(outputtext + ", field strength [A/m]")
# ax.set_ylim([-0.03, 0.03])
elif output == 'Hy':
elif output == "Hy":
ax = plt.subplot(gs[1, 1])
ax.plot(time, outputdata, 'g', lw=2, label=outputtext)
ax.set_ylabel(outputtext + ', field strength [A/m]')
ax.plot(time, outputdata, "g", lw=2, label=outputtext)
ax.set_ylabel(outputtext + ", field strength [A/m]")
# ax.set_ylim([-0.03, 0.03])
elif output == 'Hz':
elif output == "Hz":
ax = plt.subplot(gs[2, 1])
ax.plot(time, outputdata, 'g', lw=2, label=outputtext)
ax.set_ylabel(outputtext + ', field strength [A/m]')
ax.plot(time, outputdata, "g", lw=2, label=outputtext)
ax.set_ylabel(outputtext + ", field strength [A/m]")
# ax.set_ylim([-0.03, 0.03])
elif output == 'Ix':
elif output == "Ix":
ax = plt.subplot(gs[0, 2])
ax.plot(time, outputdata, 'b', lw=2, label=outputtext)
ax.set_ylabel(outputtext + ', current [A]')
elif output == 'Iy':
ax.plot(time, outputdata, "b", lw=2, label=outputtext)
ax.set_ylabel(outputtext + ", current [A]")
elif output == "Iy":
ax = plt.subplot(gs[1, 2])
ax.plot(time, outputdata, 'b', lw=2, label=outputtext)
ax.set_ylabel(outputtext + ', current [A]')
elif output == 'Iz':
ax.plot(time, outputdata, "b", lw=2, label=outputtext)
ax.set_ylabel(outputtext + ", current [A]")
elif output == "Iz":
ax = plt.subplot(gs[2, 2])
ax.plot(time, outputdata, 'b', lw=2, label=outputtext)
ax.set_ylabel(outputtext + ', current [A]')
ax.plot(time, outputdata, "b", lw=2, label=outputtext)
ax.set_ylabel(outputtext + ", current [A]")
for ax in fig.axes:
ax.set_xlim([0, np.amax(time)])
ax.grid(which='both', axis='both', linestyle='-.')
ax.grid(which="both", axis="both", linestyle="-.")
f.close()
if save:
# Save a PDF of the figure
fig.savefig(filename[:-3] + '.pdf', dpi=None, format='pdf',
bbox_inches='tight', pad_inches=0.1)
fig.savefig(filename[:-3] + ".pdf", dpi=None, format="pdf", bbox_inches="tight", pad_inches=0.1)
# Save a PNG of the figure
# fig.savefig(filename[:-3] + '.png', dpi=150, format='png',
# fig.savefig(filename[:-3] + '.png', dpi=150, format='png',
# bbox_inches='tight', pad_inches=0.1)
return plt
if __name__ == "__main__":
# Parse command line arguments
parser = argparse.ArgumentParser(description='Plots electric and magnetic fields and ' +
'currents from all receiver points in the given output file. ' +
'Each receiver point is plotted in a new figure window.',
usage='cd gprMax; python -m toolboxes.Plotting.plot_Ascan outputfile')
parser.add_argument('outputfile', help='name of output file including path')
parser.add_argument('--outputs', help='outputs to be plotted',
default=Rx.defaultoutputs,
choices=['Ex', 'Ey', 'Ez', 'Hx', 'Hy', 'Hz',
'Ix', 'Iy', 'Iz', 'Ex-', 'Ey-', 'Ez-',
'Hx-', 'Hy-', 'Hz-', 'Ix-', 'Iy-', 'Iz-'],
nargs='+')
parser.add_argument('-fft', action='store_true', default=False,
help='plot FFT (single output must be specified)')
parser.add_argument('-save', action='store_true', default=False,
help='save plot directly to file, i.e. do not display')
parser = argparse.ArgumentParser(
description="Plots electric and magnetic fields and "
+ "currents from all receiver points in the given output file. "
+ "Each receiver point is plotted in a new figure window.",
usage="cd gprMax; python -m toolboxes.Plotting.plot_Ascan outputfile",
)
parser.add_argument("outputfile", help="name of output file including path")
parser.add_argument(
"--outputs",
help="outputs to be plotted",
default=Rx.defaultoutputs,
choices=[
"Ex",
"Ey",
"Ez",
"Hx",
"Hy",
"Hz",
"Ix",
"Iy",
"Iz",
"Ex-",
"Ey-",
"Ez-",
"Hx-",
"Hy-",
"Hz-",
"Ix-",
"Iy-",
"Iz-",
],
nargs="+",
)
parser.add_argument("-fft", action="store_true", default=False, help="plot FFT (single output must be specified)")
parser.add_argument(
"-save", action="store_true", default=False, help="save plot directly to file, i.e. do not display"
)
args = parser.parse_args()
plthandle = mpl_plot(args.outputfile, args.outputs, fft=args.fft, save=args.save)
plthandle.show()
plthandle.show()

查看文件

@@ -46,59 +46,69 @@ def mpl_plot(filename, outputdata, dt, rxnumber, rxcomponent, save=False):
file = Path(filename)
fig = plt.figure(num=file.stem + ' - rx' + str(rxnumber), figsize=(20, 10),
facecolor='w', edgecolor='w')
plt.imshow(outputdata, extent=[0, outputdata.shape[1], outputdata.shape[0] * dt, 0],
interpolation='nearest', aspect='auto', cmap='seismic',
vmin=-np.amax(np.abs(outputdata)), vmax=np.amax(np.abs(outputdata)))
plt.xlabel('Trace number')
plt.ylabel('Time [s]')
fig = plt.figure(num=file.stem + " - rx" + str(rxnumber), figsize=(20, 10), facecolor="w", edgecolor="w")
plt.imshow(
outputdata,
extent=[0, outputdata.shape[1], outputdata.shape[0] * dt, 0],
interpolation="nearest",
aspect="auto",
cmap="seismic",
vmin=-np.amax(np.abs(outputdata)),
vmax=np.amax(np.abs(outputdata)),
)
plt.xlabel("Trace number")
plt.ylabel("Time [s]")
# Grid properties
ax = fig.gca()
ax.grid(which='both', axis='both', linestyle='-.')
ax.grid(which="both", axis="both", linestyle="-.")
cb = plt.colorbar()
if 'E' in rxcomponent:
cb.set_label('Field strength [V/m]')
elif 'H' in rxcomponent:
cb.set_label('Field strength [A/m]')
elif 'I' in rxcomponent:
cb.set_label('Current [A]')
if "E" in rxcomponent:
cb.set_label("Field strength [V/m]")
elif "H" in rxcomponent:
cb.set_label("Field strength [A/m]")
elif "I" in rxcomponent:
cb.set_label("Current [A]")
if save:
# Save a PDF of the figure
fig.savefig(filename[:-3] + '.pdf', dpi=None, format='pdf',
bbox_inches='tight', pad_inches=0.1)
fig.savefig(filename[:-3] + ".pdf", dpi=None, format="pdf", bbox_inches="tight", pad_inches=0.1)
# Save a PNG of the figure
# fig.savefig(filename[:-3] + '.png', dpi=150, format='png',
# fig.savefig(filename[:-3] + '.png', dpi=150, format='png',
# bbox_inches='tight', pad_inches=0.1)
return plt
if __name__ == "__main__":
# Parse command line arguments
parser = argparse.ArgumentParser(description='Plots a B-scan image.',
usage='cd gprMax; python -m toolboxes.Plotting.plot_Bscan outputfile output')
parser.add_argument('outputfile', help='name of output file including path')
parser.add_argument('rx_component', help='name of output component to be plotted',
choices=['Ex', 'Ey', 'Ez', 'Hx', 'Hy', 'Hz', 'Ix', 'Iy', 'Iz'])
parser.add_argument('-gather', action='store_true', default=False,
help='gather together all receiver outputs in file')
parser.add_argument('-save', action='store_true', default=False,
help='save plot directly to file, i.e. do not display')
parser = argparse.ArgumentParser(
description="Plots a B-scan image.",
usage="cd gprMax; python -m toolboxes.Plotting.plot_Bscan outputfile output",
)
parser.add_argument("outputfile", help="name of output file including path")
parser.add_argument(
"rx_component",
help="name of output component to be plotted",
choices=["Ex", "Ey", "Ez", "Hx", "Hy", "Hz", "Ix", "Iy", "Iz"],
)
parser.add_argument(
"-gather", action="store_true", default=False, help="gather together all receiver outputs in file"
)
parser.add_argument(
"-save", action="store_true", default=False, help="save plot directly to file, i.e. do not display"
)
args = parser.parse_args()
# Open output file and read number of outputs (receivers)
f = h5py.File(args.outputfile, 'r')
nrx = f.attrs['nrx']
f = h5py.File(args.outputfile, "r")
nrx = f.attrs["nrx"]
f.close()
# Check there are any receivers
if nrx == 0:
logger.exception(f'No receivers found in {args.outputfile}')
logger.exception(f"No receivers found in {args.outputfile}")
raise ValueError
for rx in range(1, nrx + 1):
@@ -108,12 +118,10 @@ if __name__ == "__main__":
rxsgather = outputdata
rxsgather = np.column_stack((rxsgather, outputdata))
else:
plthandle = mpl_plot(args.outputfile, outputdata, dt, rx,
args.rx_component, save=args.save)
plthandle = mpl_plot(args.outputfile, outputdata, dt, rx, args.rx_component, save=args.save)
# Plot all receivers from single output file together if required
if args.gather:
plthandle = mpl_plot(args.outputfile, rxsgather, dt, rx,
args.rx_component, save=args.save)
plthandle = mpl_plot(args.outputfile, rxsgather, dt, rx, args.rx_component, save=args.save)
plthandle.show()

查看文件

@@ -45,65 +45,67 @@ def calculate_antenna_params(filename, tltxnumber=1, tlrxnumber=None, rxnumber=N
# Open output file and read some attributes
file = Path(filename)
f = h5py.File(file, 'r')
dxdydz = f.attrs['dx_dy_dz']
dt = f.attrs['dt']
iterations = f.attrs['Iterations']
f = h5py.File(file, "r")
dxdydz = f.attrs["dx_dy_dz"]
dt = f.attrs["dt"]
iterations = f.attrs["Iterations"]
# Calculate time array and frequency bin spacing
time = np.linspace(0, (iterations - 1) * dt, num=iterations)
df = 1 / np.amax(time)
logger.info(f'Time window: {np.amax(time):g} s ({iterations} iterations)')
logger.info(f'Time step: {dt:g} s')
logger.info(f'Frequency bin spacing: {df:g} Hz')
logger.info(f"Time window: {np.amax(time):g} s ({iterations} iterations)")
logger.info(f"Time step: {dt:g} s")
logger.info(f"Frequency bin spacing: {df:g} Hz")
# Read/calculate voltages and currents from transmitter antenna
tltxpath = '/tls/tl' + str(tltxnumber) + '/'
tltxpath = "/tls/tl" + str(tltxnumber) + "/"
# Incident voltages/currents
Vinc = f[tltxpath + 'Vinc'][:]
Iinc = f[tltxpath + 'Iinc'][:]
Vinc = f[tltxpath + "Vinc"][:]
Iinc = f[tltxpath + "Iinc"][:]
# Total (incident + reflected) voltages/currents
Vtotal = f[tltxpath + 'Vtotal'][:]
Itotal = f[tltxpath + 'Itotal'][:]
Vtotal = f[tltxpath + "Vtotal"][:]
Itotal = f[tltxpath + "Itotal"][:]
# Reflected voltages/currents
Vref = Vtotal - Vinc
Iref = Itotal - Iinc
# If a receiver antenna is used (with a transmission line or receiver),
# If a receiver antenna is used (with a transmission line or receiver),
# get received voltage for s21
if tlrxnumber:
tlrxpath = '/tls/tl' + str(tlrxnumber) + '/'
Vrec = f[tlrxpath + 'Vtotal'][:]
tlrxpath = "/tls/tl" + str(tlrxnumber) + "/"
Vrec = f[tlrxpath + "Vtotal"][:]
elif rxnumber:
rxpath = '/rxs/rx' + str(rxnumber) + '/'
rxpath = "/rxs/rx" + str(rxnumber) + "/"
availableoutputs = list(f[rxpath].keys())
if rxcomponent not in availableoutputs:
logger.exception(f"{rxcomponent} output requested, but the available " +
f"output for receiver {rxnumber} is " +
f"{', '.join(availableoutputs)}")
logger.exception(
f"{rxcomponent} output requested, but the available "
+ f"output for receiver {rxnumber} is "
+ f"{', '.join(availableoutputs)}"
)
raise ValueError
rxpath += rxcomponent
# Received voltage
if rxcomponent == 'Ex':
if rxcomponent == "Ex":
Vrec = f[rxpath][:] * -1 * dxdydz[0]
elif rxcomponent == 'Ey':
elif rxcomponent == "Ey":
Vrec = f[rxpath][:] * -1 * dxdydz[1]
elif rxcomponent == 'Ez':
elif rxcomponent == "Ez":
Vrec = f[rxpath][:] * -1 * dxdydz[2]
f.close()
# Frequency bins
freqs = np.fft.fftfreq(Vinc.size, d=dt)
# Delay correction - current lags voltage, so delay voltage to match
# Delay correction - current lags voltage, so delay voltage to match
# current timestep
delaycorrection = np.exp(1j * 2 * np.pi * freqs * (dt / 2))
@@ -119,7 +121,7 @@ def calculate_antenna_params(filename, tltxnumber=1, tlrxnumber=None, rxnumber=N
yin = np.fft.fft(Itotal) / (np.fft.fft(Vtotal) * delaycorrection)
# Convert to decibels (ignore warning from taking a log of any zero values)
with np.errstate(divide='ignore'):
with np.errstate(divide="ignore"):
Vincp = 20 * np.log10(np.abs((np.fft.fft(Vinc) * delaycorrection)))
Iincp = 20 * np.log10(np.abs(np.fft.fft(Iinc)))
Vrefp = 20 * np.log10(np.abs((np.fft.fft(Vref) * delaycorrection)))
@@ -138,23 +140,56 @@ def calculate_antenna_params(filename, tltxnumber=1, tlrxnumber=None, rxnumber=N
s11[np.invert(np.isfinite(s11))] = 0
# Create dictionary of antenna parameters
antennaparams = {'time': time, 'freqs': freqs, 'Vinc': Vinc, 'Vincp': Vincp,
'Iinc': Iinc, 'Iincp': Iincp, 'Vref': Vref, 'Vrefp': Vrefp,
'Iref': Iref, 'Irefp': Irefp, 'Vtotal': Vtotal,
'Vtotalp': Vtotalp, 'Itotal': Itotal, 'Itotalp': Itotalp,
's11': s11, 'zin': zin, 'yin': yin}
antennaparams = {
"time": time,
"freqs": freqs,
"Vinc": Vinc,
"Vincp": Vincp,
"Iinc": Iinc,
"Iincp": Iincp,
"Vref": Vref,
"Vrefp": Vrefp,
"Iref": Iref,
"Irefp": Irefp,
"Vtotal": Vtotal,
"Vtotalp": Vtotalp,
"Itotal": Itotal,
"Itotalp": Itotalp,
"s11": s11,
"zin": zin,
"yin": yin,
}
if tlrxnumber or rxnumber:
with np.errstate(divide='ignore'): # Ignore warning from taking a log of any zero values
with np.errstate(divide="ignore"): # Ignore warning from taking a log of any zero values
s21 = 20 * np.log10(s21)
s21[np.invert(np.isfinite(s21))] = 0
antennaparams['s21'] = s21
antennaparams["s21"] = s21
return antennaparams
def mpl_plot(filename, time, freqs, Vinc, Vincp, Iinc, Iincp, Vref, Vrefp,
Iref, Irefp, Vtotal, Vtotalp, Itotal, Itotalp, s11, zin, yin,
s21=None, save=False):
def mpl_plot(
filename,
time,
freqs,
Vinc,
Vincp,
Iinc,
Iincp,
Vref,
Vrefp,
Iref,
Irefp,
Vtotal,
Vtotalp,
Itotal,
Itotalp,
s11,
zin,
yin,
s21=None,
save=False,
):
"""Plots antenna parameters - incident, reflected and total voltages and
currents; s11, (s21) and input impedance.
@@ -162,14 +197,14 @@ def mpl_plot(filename, time, freqs, Vinc, Vincp, Iinc, Iincp, Vref, Vrefp,
filename: string of filename (including path) of output file.
time: array of simulation time.
freq: array of frequencies for FFTs.
Vinc, Vincp, Iinc, Iincp: arrays of time and frequency domain
representations of incident voltage and
Vinc, Vincp, Iinc, Iincp: arrays of time and frequency domain
representations of incident voltage and
current.
Vref, Vrefp, Iref, Irefp: arrays of time and frequency domain
representations of reflected voltage and
Vref, Vrefp, Iref, Irefp: arrays of time and frequency domain
representations of reflected voltage and
current.
Vtotal, Vtotalp, Itotal, Itotalp: arrays of time and frequency domain
representations of total voltage and
Vtotal, Vtotalp, Itotal, Itotalp: arrays of time and frequency domain
representations of total voltage and
current.
s11, s21: array(s) of s11 and, optionally, s21 parameters.
zin, yin: arrays of input impedance and input admittance parameters.
@@ -189,105 +224,103 @@ def mpl_plot(filename, time, freqs, Vinc, Vincp, Iinc, Iincp, Vref, Vrefp,
# Print some useful values from s11, and input impedance
s11minfreq = np.where(s11[pltrange] == np.amin(s11[pltrange]))[0][0]
logger.info(f's11 minimum: {np.amin(s11[pltrange]):g} dB at ' +
f'{freqs[s11minfreq + pltrangemin]:g} Hz')
logger.info(f'At {freqs[s11minfreq + pltrangemin]:g} Hz...')
logger.info(f'Input impedance: {np.abs(zin[s11minfreq + pltrangemin]):.1f}' +
f'{zin[s11minfreq + pltrangemin].imag:+.1f}j Ohms')
logger.info(f"s11 minimum: {np.amin(s11[pltrange]):g} dB at " + f"{freqs[s11minfreq + pltrangemin]:g} Hz")
logger.info(f"At {freqs[s11minfreq + pltrangemin]:g} Hz...")
logger.info(
f"Input impedance: {np.abs(zin[s11minfreq + pltrangemin]):.1f}"
+ f"{zin[s11minfreq + pltrangemin].imag:+.1f}j Ohms"
)
# logger.info(f'Input admittance (mag): {np.abs(yin[s11minfreq + pltrangemin]):g} S')
# logger.info(f'Input admittance (phase): {np.angle(yin[s11minfreq + pltrangemin], deg=True):.1f} deg')
# Figure 1
# Plot incident voltage
fig1, ax = plt.subplots(num='Transmitter transmission line parameters',
figsize=(20, 12), facecolor='w', edgecolor='w')
fig1, ax = plt.subplots(
num="Transmitter transmission line parameters", figsize=(20, 12), facecolor="w", edgecolor="w"
)
gs1 = gridspec.GridSpec(4, 2, hspace=0.7)
ax = plt.subplot(gs1[0, 0])
ax.plot(time, Vinc, 'r', lw=2, label='Vinc')
ax.set_title('Incident voltage')
ax.set_xlabel('Time [s]')
ax.set_ylabel('Voltage [V]')
ax.plot(time, Vinc, "r", lw=2, label="Vinc")
ax.set_title("Incident voltage")
ax.set_xlabel("Time [s]")
ax.set_ylabel("Voltage [V]")
ax.set_xlim([0, np.amax(time)])
ax.grid(which='both', axis='both', linestyle='-.')
ax.grid(which="both", axis="both", linestyle="-.")
# Plot frequency spectra of incident voltage
ax = plt.subplot(gs1[0, 1])
markerline, stemlines, baseline = ax.stem(freqs[pltrange], Vincp[pltrange],
'-.', use_line_collection=True)
plt.setp(baseline, 'linewidth', 0)
plt.setp(stemlines, 'color', 'r')
plt.setp(markerline, 'markerfacecolor', 'r', 'markeredgecolor', 'r')
ax.plot(freqs[pltrange], Vincp[pltrange], 'r', lw=2)
ax.set_title('Incident voltage')
ax.set_xlabel('Frequency [Hz]')
ax.set_ylabel('Power [dB]')
ax.grid(which='both', axis='both', linestyle='-.')
markerline, stemlines, baseline = ax.stem(freqs[pltrange], Vincp[pltrange], "-.", use_line_collection=True)
plt.setp(baseline, "linewidth", 0)
plt.setp(stemlines, "color", "r")
plt.setp(markerline, "markerfacecolor", "r", "markeredgecolor", "r")
ax.plot(freqs[pltrange], Vincp[pltrange], "r", lw=2)
ax.set_title("Incident voltage")
ax.set_xlabel("Frequency [Hz]")
ax.set_ylabel("Power [dB]")
ax.grid(which="both", axis="both", linestyle="-.")
# Plot incident current
ax = plt.subplot(gs1[1, 0])
ax.plot(time, Iinc, 'b', lw=2, label='Vinc')
ax.set_title('Incident current')
ax.set_xlabel('Time [s]')
ax.set_ylabel('Current [A]')
ax.plot(time, Iinc, "b", lw=2, label="Vinc")
ax.set_title("Incident current")
ax.set_xlabel("Time [s]")
ax.set_ylabel("Current [A]")
ax.set_xlim([0, np.amax(time)])
ax.grid(which='both', axis='both', linestyle='-.')
ax.grid(which="both", axis="both", linestyle="-.")
# Plot frequency spectra of incident current
ax = plt.subplot(gs1[1, 1])
markerline, stemlines, baseline = ax.stem(freqs[pltrange], Iincp[pltrange],
'-.', use_line_collection=True)
plt.setp(baseline, 'linewidth', 0)
plt.setp(stemlines, 'color', 'b')
plt.setp(markerline, 'markerfacecolor', 'b', 'markeredgecolor', 'b')
ax.plot(freqs[pltrange], Iincp[pltrange], 'b', lw=2)
ax.set_title('Incident current')
ax.set_xlabel('Frequency [Hz]')
ax.set_ylabel('Power [dB]')
ax.grid(which='both', axis='both', linestyle='-.')
markerline, stemlines, baseline = ax.stem(freqs[pltrange], Iincp[pltrange], "-.", use_line_collection=True)
plt.setp(baseline, "linewidth", 0)
plt.setp(stemlines, "color", "b")
plt.setp(markerline, "markerfacecolor", "b", "markeredgecolor", "b")
ax.plot(freqs[pltrange], Iincp[pltrange], "b", lw=2)
ax.set_title("Incident current")
ax.set_xlabel("Frequency [Hz]")
ax.set_ylabel("Power [dB]")
ax.grid(which="both", axis="both", linestyle="-.")
# Plot total voltage
ax = plt.subplot(gs1[2, 0])
ax.plot(time, Vtotal, 'r', lw=2, label='Vinc')
ax.set_title('Total (incident + reflected) voltage')
ax.set_xlabel('Time [s]')
ax.set_ylabel('Voltage [V]')
ax.plot(time, Vtotal, "r", lw=2, label="Vinc")
ax.set_title("Total (incident + reflected) voltage")
ax.set_xlabel("Time [s]")
ax.set_ylabel("Voltage [V]")
ax.set_xlim([0, np.amax(time)])
ax.grid(which='both', axis='both', linestyle='-.')
ax.grid(which="both", axis="both", linestyle="-.")
# Plot frequency spectra of total voltage
ax = plt.subplot(gs1[2, 1])
markerline, stemlines, baseline = ax.stem(freqs[pltrange], Vtotalp[pltrange],
'-.', use_line_collection=True)
plt.setp(baseline, 'linewidth', 0)
plt.setp(stemlines, 'color', 'r')
plt.setp(markerline, 'markerfacecolor', 'r', 'markeredgecolor', 'r')
ax.plot(freqs[pltrange], Vtotalp[pltrange], 'r', lw=2)
ax.set_title('Total (incident + reflected) voltage')
ax.set_xlabel('Frequency [Hz]')
ax.set_ylabel('Power [dB]')
ax.grid(which='both', axis='both', linestyle='-.')
markerline, stemlines, baseline = ax.stem(freqs[pltrange], Vtotalp[pltrange], "-.", use_line_collection=True)
plt.setp(baseline, "linewidth", 0)
plt.setp(stemlines, "color", "r")
plt.setp(markerline, "markerfacecolor", "r", "markeredgecolor", "r")
ax.plot(freqs[pltrange], Vtotalp[pltrange], "r", lw=2)
ax.set_title("Total (incident + reflected) voltage")
ax.set_xlabel("Frequency [Hz]")
ax.set_ylabel("Power [dB]")
ax.grid(which="both", axis="both", linestyle="-.")
# Plot total current
ax = plt.subplot(gs1[3, 0])
ax.plot(time, Itotal, 'b', lw=2, label='Vinc')
ax.set_title('Total (incident + reflected) current')
ax.set_xlabel('Time [s]')
ax.set_ylabel('Current [A]')
ax.plot(time, Itotal, "b", lw=2, label="Vinc")
ax.set_title("Total (incident + reflected) current")
ax.set_xlabel("Time [s]")
ax.set_ylabel("Current [A]")
ax.set_xlim([0, np.amax(time)])
ax.grid(which='both', axis='both', linestyle='-.')
ax.grid(which="both", axis="both", linestyle="-.")
# Plot frequency spectra of total current
ax = plt.subplot(gs1[3, 1])
markerline, stemlines, baseline = ax.stem(freqs[pltrange], Itotalp[pltrange],
'-.', use_line_collection=True)
plt.setp(baseline, 'linewidth', 0)
plt.setp(stemlines, 'color', 'b')
plt.setp(markerline, 'markerfacecolor', 'b', 'markeredgecolor', 'b')
ax.plot(freqs[pltrange], Itotalp[pltrange], 'b', lw=2)
ax.set_title('Total (incident + reflected) current')
ax.set_xlabel('Frequency [Hz]')
ax.set_ylabel('Power [dB]')
ax.grid(which='both', axis='both', linestyle='-.')
markerline, stemlines, baseline = ax.stem(freqs[pltrange], Itotalp[pltrange], "-.", use_line_collection=True)
plt.setp(baseline, "linewidth", 0)
plt.setp(stemlines, "color", "b")
plt.setp(markerline, "markerfacecolor", "b", "markeredgecolor", "b")
ax.plot(freqs[pltrange], Itotalp[pltrange], "b", lw=2)
ax.set_title("Total (incident + reflected) current")
ax.set_xlabel("Frequency [Hz]")
ax.set_ylabel("Power [dB]")
ax.grid(which="both", axis="both", linestyle="-.")
# Plot reflected (reflected) voltage
# ax = plt.subplot(gs1[4, 0])
@@ -335,69 +368,64 @@ def mpl_plot(filename, time, freqs, Vinc, Vincp, Iinc, Iincp, Vref, Vrefp,
# Figure 2
# Plot frequency spectra of s11
fig2, ax = plt.subplots(num='Antenna parameters', figsize=(20, 12),
facecolor='w', edgecolor='w')
fig2, ax = plt.subplots(num="Antenna parameters", figsize=(20, 12), facecolor="w", edgecolor="w")
gs2 = gridspec.GridSpec(2, 2, hspace=0.3)
ax = plt.subplot(gs2[0, 0])
markerline, stemlines, baseline = ax.stem(freqs[pltrange], s11[pltrange],
'-.', use_line_collection=True)
plt.setp(baseline, 'linewidth', 0)
plt.setp(stemlines, 'color', 'g')
plt.setp(markerline, 'markerfacecolor', 'g', 'markeredgecolor', 'g')
ax.plot(freqs[pltrange], s11[pltrange], 'g', lw=2)
ax.set_title('s11')
ax.set_xlabel('Frequency [Hz]')
ax.set_ylabel('Power [dB]')
markerline, stemlines, baseline = ax.stem(freqs[pltrange], s11[pltrange], "-.", use_line_collection=True)
plt.setp(baseline, "linewidth", 0)
plt.setp(stemlines, "color", "g")
plt.setp(markerline, "markerfacecolor", "g", "markeredgecolor", "g")
ax.plot(freqs[pltrange], s11[pltrange], "g", lw=2)
ax.set_title("s11")
ax.set_xlabel("Frequency [Hz]")
ax.set_ylabel("Power [dB]")
# ax.set_xlim([0, 5e9])
# ax.set_ylim([-25, 0])
ax.grid(which='both', axis='both', linestyle='-.')
ax.grid(which="both", axis="both", linestyle="-.")
# Plot frequency spectra of s21
if s21 is not None:
ax = plt.subplot(gs2[0, 1])
markerline, stemlines, baseline = ax.stem(freqs[pltrange], s21[pltrange],
'-.', use_line_collection=True)
plt.setp(baseline, 'linewidth', 0)
plt.setp(stemlines, 'color', 'g')
plt.setp(markerline, 'markerfacecolor', 'g', 'markeredgecolor', 'g')
ax.plot(freqs[pltrange], s21[pltrange], 'g', lw=2)
ax.set_title('s21')
ax.set_xlabel('Frequency [Hz]')
ax.set_ylabel('Power [dB]')
markerline, stemlines, baseline = ax.stem(freqs[pltrange], s21[pltrange], "-.", use_line_collection=True)
plt.setp(baseline, "linewidth", 0)
plt.setp(stemlines, "color", "g")
plt.setp(markerline, "markerfacecolor", "g", "markeredgecolor", "g")
ax.plot(freqs[pltrange], s21[pltrange], "g", lw=2)
ax.set_title("s21")
ax.set_xlabel("Frequency [Hz]")
ax.set_ylabel("Power [dB]")
# ax.set_xlim([0.88e9, 1.02e9])
# ax.set_ylim([-25, 50])
ax.grid(which='both', axis='both', linestyle='-.')
ax.grid(which="both", axis="both", linestyle="-.")
# Plot input resistance (real part of impedance)
ax = plt.subplot(gs2[1, 0])
markerline, stemlines, baseline = ax.stem(freqs[pltrange], zin[pltrange].real,
'-.', use_line_collection=True)
plt.setp(baseline, 'linewidth', 0)
plt.setp(stemlines, 'color', 'g')
plt.setp(markerline, 'markerfacecolor', 'g', 'markeredgecolor', 'g')
ax.plot(freqs[pltrange], zin[pltrange].real, 'g', lw=2)
ax.set_title('Input impedance (resistive)')
ax.set_xlabel('Frequency [Hz]')
ax.set_ylabel('Resistance [Ohms]')
markerline, stemlines, baseline = ax.stem(freqs[pltrange], zin[pltrange].real, "-.", use_line_collection=True)
plt.setp(baseline, "linewidth", 0)
plt.setp(stemlines, "color", "g")
plt.setp(markerline, "markerfacecolor", "g", "markeredgecolor", "g")
ax.plot(freqs[pltrange], zin[pltrange].real, "g", lw=2)
ax.set_title("Input impedance (resistive)")
ax.set_xlabel("Frequency [Hz]")
ax.set_ylabel("Resistance [Ohms]")
# ax.set_xlim([0.88e9, 1.02e9])
ax.set_ylim(bottom=0)
# ax.set_ylim([0, 300])
ax.grid(which='both', axis='both', linestyle='-.')
ax.grid(which="both", axis="both", linestyle="-.")
# Plot input reactance (imaginery part of impedance)
ax = plt.subplot(gs2[1, 1])
markerline, stemlines, baseline = ax.stem(freqs[pltrange], zin[pltrange].imag,
'-.', use_line_collection=True)
plt.setp(baseline, 'linewidth', 0)
plt.setp(stemlines, 'color', 'g')
plt.setp(markerline, 'markerfacecolor', 'g', 'markeredgecolor', 'g')
ax.plot(freqs[pltrange], zin[pltrange].imag, 'g', lw=2)
ax.set_title('Input impedance (reactive)')
ax.set_xlabel('Frequency [Hz]')
ax.set_ylabel('Reactance [Ohms]')
markerline, stemlines, baseline = ax.stem(freqs[pltrange], zin[pltrange].imag, "-.", use_line_collection=True)
plt.setp(baseline, "linewidth", 0)
plt.setp(stemlines, "color", "g")
plt.setp(markerline, "markerfacecolor", "g", "markeredgecolor", "g")
ax.plot(freqs[pltrange], zin[pltrange].imag, "g", lw=2)
ax.set_title("Input impedance (reactive)")
ax.set_xlabel("Frequency [Hz]")
ax.set_ylabel("Reactance [Ohms]")
# ax.set_xlim([0.88e9, 1.02e9])
# ax.set_ylim([-300, 300])
ax.grid(which='both', axis='both', linestyle='-.')
ax.grid(which="both", axis="both", linestyle="-.")
# Plot input admittance (magnitude)
# ax = plt.subplot(gs2[2, 0])
@@ -430,49 +458,49 @@ def mpl_plot(filename, time, freqs, Vinc, Vincp, Iinc, Iincp, Vref, Vrefp,
# ax.grid(which='both', axis='both', linestyle='-.')
if save:
savename1 = filename.stem + '_tl_params'
savename1 = filename.stem + "_tl_params"
savename1 = filename.parent / savename1
savename2 = filename.stem + '_ant_params'
savename2 = filename.stem + "_ant_params"
savename2 = filename.parent / savename2
# Save a PDF of the figure
fig1.savefig(savename1.with_suffix('.pdf'), dpi=None, format='pdf',
bbox_inches='tight', pad_inches=0.1)
fig2.savefig(savename2.with_suffix('.pdf'), dpi=None, format='pdf',
bbox_inches='tight', pad_inches=0.1)
fig1.savefig(savename1.with_suffix(".pdf"), dpi=None, format="pdf", bbox_inches="tight", pad_inches=0.1)
fig2.savefig(savename2.with_suffix(".pdf"), dpi=None, format="pdf", bbox_inches="tight", pad_inches=0.1)
# Save a PNG of the figure
# fig1.savefig(savename1.with_suffix('.png'), dpi=150, format='png',
# fig1.savefig(savename1.with_suffix('.png'), dpi=150, format='png',
# bbox_inches='tight', pad_inches=0.1)
# fig2.savefig(savename2.with_suffix('.png'), dpi=150, format='png',
# fig2.savefig(savename2.with_suffix('.png'), dpi=150, format='png',
# bbox_inches='tight', pad_inches=0.1)
return plt
if __name__ == "__main__":
# Parse command line arguments
parser = argparse.ArgumentParser(description='Plots antenna parameters - ' +
'incident, reflected and total voltages ' +
'and currents; s11, (s21) and input impedance ' +
'from an output file containing a transmission ' +
'line source.',
usage='cd gprMax; python -m toolboxes.Plotting.plot_antenna_params outputfile')
parser.add_argument('outputfile', help='name of output file including path')
parser.add_argument('--tltx-num', default=1, type=int,
help='transmitter antenna - transmission line number')
parser.add_argument('--tlrx-num', type=int,
help='receiver antenna - transmission line number')
parser.add_argument('--rx-num', type=int,
help='receiver antenna - output number')
parser.add_argument('--rx-component', type=str,
help='receiver antenna - output electric field component',
choices=['Ex', 'Ey', 'Ez'])
parser.add_argument('-save', action='store_true', default=False,
help='save plot directly to file, i.e. do not display')
parser = argparse.ArgumentParser(
description="Plots antenna parameters - "
+ "incident, reflected and total voltages "
+ "and currents; s11, (s21) and input impedance "
+ "from an output file containing a transmission "
+ "line source.",
usage="cd gprMax; python -m toolboxes.Plotting.plot_antenna_params outputfile",
)
parser.add_argument("outputfile", help="name of output file including path")
parser.add_argument("--tltx-num", default=1, type=int, help="transmitter antenna - transmission line number")
parser.add_argument("--tlrx-num", type=int, help="receiver antenna - transmission line number")
parser.add_argument("--rx-num", type=int, help="receiver antenna - output number")
parser.add_argument(
"--rx-component",
type=str,
help="receiver antenna - output electric field component",
choices=["Ex", "Ey", "Ez"],
)
parser.add_argument(
"-save", action="store_true", default=False, help="save plot directly to file, i.e. do not display"
)
args = parser.parse_args()
antennaparams = calculate_antenna_params(args.outputfile, args.tltx_num,
args.tlrx_num, args.rx_num,
args.rx_component)
antennaparams = calculate_antenna_params(
args.outputfile, args.tltx_num, args.tlrx_num, args.rx_num, args.rx_component
)
plthandle = mpl_plot(args.outputfile, **antennaparams, save=args.save)
plthandle.show()

查看文件

@@ -25,7 +25,7 @@ import numpy as np
from gprMax.utilities.utilities import fft_power, round_value
from gprMax.waveforms import Waveform
logging.basicConfig(format='%(message)s', level=logging.INFO)
logging.basicConfig(format="%(message)s", level=logging.INFO)
def check_timewindow(timewindow, dt):
@@ -53,7 +53,7 @@ def check_timewindow(timewindow, dt):
if timewindow > 0:
iterations = round_value((timewindow / dt)) + 1
else:
logging.exception('Time window must have a value greater than zero')
logging.exception("Time window must have a value greater than zero")
raise ValueError
return timewindow, iterations
@@ -76,36 +76,41 @@ def mpl_plot(w, timewindow, dt, iterations, fft=False, save=False):
time = np.linspace(0, (iterations - 1) * dt, num=iterations)
waveform = np.zeros(len(time))
timeiter = np.nditer(time, flags=['c_index'])
timeiter = np.nditer(time, flags=["c_index"])
while not timeiter.finished:
waveform[timeiter.index] = w.calculate_value(timeiter[0], dt)
timeiter.iternext()
logging.info('Waveform characteristics...')
logging.info(f'Type: {w.type}')
logging.info(f'Maximum (absolute) amplitude: {np.max(np.abs(waveform)):g}')
logging.info("Waveform characteristics...")
logging.info(f"Type: {w.type}")
logging.info(f"Maximum (absolute) amplitude: {np.max(np.abs(waveform)):g}")
if w.freq and not w.type == 'gaussian' and not w.type == 'impulse':
logging.info(f'Centre frequency: {w.freq:g} Hz')
if w.freq and not w.type == "gaussian" and not w.type == "impulse":
logging.info(f"Centre frequency: {w.freq:g} Hz")
if (w.type == 'gaussian' or w.type == 'gaussiandot' or w.type == 'gaussiandotnorm'
or w.type == 'gaussianprime' or w.type == 'gaussiandoubleprime'):
if (
w.type == "gaussian"
or w.type == "gaussiandot"
or w.type == "gaussiandotnorm"
or w.type == "gaussianprime"
or w.type == "gaussiandoubleprime"
):
delay = 1 / w.freq
logging.info(f'Time to centre of pulse: {delay:g} s')
elif w.type == 'gaussiandotdot' or w.type == 'gaussiandotdotnorm' or w.type == 'ricker':
logging.info(f"Time to centre of pulse: {delay:g} s")
elif w.type == "gaussiandotdot" or w.type == "gaussiandotdotnorm" or w.type == "ricker":
delay = np.sqrt(2) / w.freq
logging.info(f'Time to centre of pulse: {delay:g} s')
logging.info(f"Time to centre of pulse: {delay:g} s")
logging.info(f'Time window: {timewindow:g} s ({iterations} iterations)')
logging.info(f'Time step: {dt:g} s')
logging.info(f"Time window: {timewindow:g} s ({iterations} iterations)")
logging.info(f"Time step: {dt:g} s")
if fft:
# FFT
freqs, power = fft_power(waveform, dt)
# Set plotting range to 4 times frequency at max power of waveform or
# 4 times the centre frequency
# 4 times the centre frequency
freqmaxpower = np.where(np.isclose(power, 0))[0][0]
if freqs[freqmaxpower] > w.freq:
pltrange = np.where(freqs > 4 * freqs[freqmaxpower])[0][0]
@@ -113,73 +118,66 @@ def mpl_plot(w, timewindow, dt, iterations, fft=False, save=False):
pltrange = np.where(freqs > 4 * w.freq)[0][0]
pltrange = np.s_[0:pltrange]
fig, (ax1, ax2) = plt.subplots(nrows=1, ncols=2, num=w.type,
figsize=(20, 10), facecolor='w',
edgecolor='w')
fig, (ax1, ax2) = plt.subplots(nrows=1, ncols=2, num=w.type, figsize=(20, 10), facecolor="w", edgecolor="w")
# Plot waveform
ax1.plot(time, waveform, 'r', lw=2)
ax1.set_xlabel('Time [s]')
ax1.set_ylabel('Amplitude')
ax1.plot(time, waveform, "r", lw=2)
ax1.set_xlabel("Time [s]")
ax1.set_ylabel("Amplitude")
# Plot frequency spectra
markerline, stemlines, baseline = ax2.stem(freqs[pltrange], power[pltrange],
'-.', use_line_collection=True)
plt.setp(baseline, 'linewidth', 0)
plt.setp(stemlines, 'color', 'r')
plt.setp(markerline, 'markerfacecolor', 'r', 'markeredgecolor', 'r')
ax2.plot(freqs[pltrange], power[pltrange], 'r', lw=2)
ax2.set_xlabel('Frequency [Hz]')
ax2.set_ylabel('Power [dB]')
markerline, stemlines, baseline = ax2.stem(freqs[pltrange], power[pltrange], "-.", use_line_collection=True)
plt.setp(baseline, "linewidth", 0)
plt.setp(stemlines, "color", "r")
plt.setp(markerline, "markerfacecolor", "r", "markeredgecolor", "r")
ax2.plot(freqs[pltrange], power[pltrange], "r", lw=2)
ax2.set_xlabel("Frequency [Hz]")
ax2.set_ylabel("Power [dB]")
else:
fig, ax1 = plt.subplots(num=w.type, figsize=(10, 10), facecolor='w',
edgecolor='w')
fig, ax1 = plt.subplots(num=w.type, figsize=(10, 10), facecolor="w", edgecolor="w")
# Plot waveform
ax1.plot(time, waveform, 'r', lw=2)
ax1.set_xlabel('Time [s]')
ax1.set_ylabel('Amplitude')
ax1.plot(time, waveform, "r", lw=2)
ax1.set_xlabel("Time [s]")
ax1.set_ylabel("Amplitude")
# Turn on grid
[ax.grid(which='both', axis='both', linestyle='-.') for ax in fig.axes]
[ax.grid(which="both", axis="both", linestyle="-.") for ax in fig.axes]
if save:
savefile = Path(__file__).parent / w.type
# Save a PDF of the figure
fig.savefig(savefile.with_suffix('.pdf'), dpi=None, format='pdf',
bbox_inches='tight', pad_inches=0.1)
fig.savefig(savefile.with_suffix(".pdf"), dpi=None, format="pdf", bbox_inches="tight", pad_inches=0.1)
# Save a PNG of the figure
fig.savefig(savefile.with_suffix('.png'), dpi=150, format='png',
bbox_inches='tight', pad_inches=0.1)
fig.savefig(savefile.with_suffix(".png"), dpi=150, format="png", bbox_inches="tight", pad_inches=0.1)
return plt
if __name__ == "__main__":
# Parse command line arguments
parser = argparse.ArgumentParser(description='Plot built-in waveforms that can be used for sources.',
usage='cd gprMax; python -m toolboxes.Plotting.plot_source_wave type amp freq timewindow dt')
parser.add_argument('type', help='type of waveform', choices=Waveform.types)
parser.add_argument('amp', type=float, help='amplitude of waveform')
parser.add_argument('freq', type=float, help='centre frequency of waveform')
parser.add_argument('timewindow', help='time window to view waveform')
parser.add_argument('dt', type=float, help='time step to view waveform')
parser.add_argument('-fft', action='store_true', default=False,
help='plot FFT of waveform')
parser.add_argument('-save', action='store_true', default=False,
help='save plot directly to file, i.e. do not display')
parser = argparse.ArgumentParser(
description="Plot built-in waveforms that can be used for sources.",
usage="cd gprMax; python -m toolboxes.Plotting.plot_source_wave type amp freq timewindow dt",
)
parser.add_argument("type", help="type of waveform", choices=Waveform.types)
parser.add_argument("amp", type=float, help="amplitude of waveform")
parser.add_argument("freq", type=float, help="centre frequency of waveform")
parser.add_argument("timewindow", help="time window to view waveform")
parser.add_argument("dt", type=float, help="time step to view waveform")
parser.add_argument("-fft", action="store_true", default=False, help="plot FFT of waveform")
parser.add_argument(
"-save", action="store_true", default=False, help="save plot directly to file, i.e. do not display"
)
args = parser.parse_args()
# Check waveform parameters
if args.type.lower() not in Waveform.types:
logging.exception(f"The waveform must have one of the following types " +
f"{', '.join(Waveform.types)}")
logging.exception(f"The waveform must have one of the following types " + f"{', '.join(Waveform.types)}")
raise ValueError
if args.freq <= 0:
logging.exception('The waveform requires an excitation frequency value of ' +
'greater than zero')
logging.exception("The waveform requires an excitation frequency value of " + "greater than zero")
raise ValueError
# Create waveform instance
@@ -189,6 +187,5 @@ if __name__ == "__main__":
w.freq = args.freq
timewindow, iterations = check_timewindow(args.timewindow, args.dt)
plthandle = mpl_plot(w, timewindow, args.dt, iterations, fft=args.fft,
save=args.save)
plthandle = mpl_plot(w, timewindow, args.dt, iterations, fft=args.fft, save=args.save)
plthandle.show()