你已经派生过 gprMax
镜像自地址
https://gitee.com/sunhf/gprMax.git
已同步 2025-08-07 15:10:13 +08:00
More docstring cleaning.
这个提交包含在:
@@ -23,16 +23,18 @@ from gprMax.waveforms import Waveform
|
||||
|
||||
|
||||
def hertzian_dipole_fs(iterations, dt, dxdydz, rx):
|
||||
"""Analytical solution of a z-directed Hertzian dipole in free space with a Gaussian current waveform (http://dx.doi.org/10.1016/0021-9991(83)90103-1).
|
||||
"""Analytical solution of a z-directed Hertzian dipole in free space with a
|
||||
Gaussian current waveform (http://dx.doi.org/10.1016/0021-9991(83)90103-1).
|
||||
|
||||
Args:
|
||||
iterations (int): Number of time steps.
|
||||
dt (float): Time step (seconds).
|
||||
dxdydz (float): Tuple of spatial resolution (metres).
|
||||
rx (float): Tuple of coordinates of receiver position relative to transmitter position (metres).
|
||||
iterations: int for number of time steps.
|
||||
dt: float for time step (seconds).
|
||||
dxdydz: tuple of floats for spatial resolution (metres).
|
||||
rx: tuple of floats for coordinates of receiver position relative to
|
||||
transmitter position (metres).
|
||||
|
||||
Returns:
|
||||
fields (float): Array contain electric and magnetic field components.
|
||||
fields: float array containing electric and magnetic field components.
|
||||
"""
|
||||
|
||||
# Waveform
|
||||
@@ -111,7 +113,8 @@ def hertzian_dipole_fs(iterations, dt, dxdydz, rx):
|
||||
# Calculate fields
|
||||
for timestep in range(iterations):
|
||||
|
||||
# Calculate values for waveform, I * dl (current multiplied by dipole length) to match gprMax behaviour
|
||||
# Calculate values for waveform, I * dl (current multiplied by dipole
|
||||
# length) to match gprMax behaviour
|
||||
fint_Ex = wint.calculate_value((timestep * dt) - tau_Ex, dt) * dl
|
||||
f_Ex = w.calculate_value((timestep * dt) - tau_Ex, dt) * dl
|
||||
fdot_Ex = wdot.calculate_value((timestep * dt) - tau_Ex, dt) * dl
|
||||
@@ -131,17 +134,21 @@ def hertzian_dipole_fs(iterations, dt, dxdydz, rx):
|
||||
fdot_Hy = wdot.calculate_value((timestep * dt) - tau_Hy, dt) * dl
|
||||
|
||||
# Ex
|
||||
fields[timestep, 0] = ((Ex_x * Ex_z) / (4 * np.pi * config.sim_config.em_consts['e0'] * Er_x**5)) * (3 * (fint_Ex + (tau_Ex * f_Ex)) + (tau_Ex**2 * fdot_Ex))
|
||||
fields[timestep, 0] = (((Ex_x * Ex_z) / (4 * np.pi * config.sim_config.em_consts['e0'] * Er_x**5)) *
|
||||
(3 * (fint_Ex + (tau_Ex * f_Ex)) + (tau_Ex**2 * fdot_Ex)))
|
||||
|
||||
# Ey
|
||||
try:
|
||||
tmp = Ey_y / Ey_x
|
||||
except ZeroDivisionError:
|
||||
tmp = 0
|
||||
fields[timestep, 1] = tmp * ((Ey_x * Ey_z) / (4 * np.pi * config.sim_config.em_consts['e0'] * Er_y**5)) * (3 * (fint_Ey + (tau_Ey * f_Ey)) + (tau_Ey**2 * fdot_Ey))
|
||||
fields[timestep, 1] = (tmp * ((Ey_x * Ey_z) / (4 * np.pi * config.sim_config.em_consts['e0'] * Er_y**5)) *
|
||||
(3 * (fint_Ey + (tau_Ey * f_Ey)) + (tau_Ey**2 * fdot_Ey)))
|
||||
|
||||
# Ez
|
||||
fields[timestep, 2] = (1 / (4 * np.pi * config.sim_config.em_consts['e0'] * Er_z**5)) * ((2 * Ez_z**2 - (Ez_x**2 + Ez_y**2)) * (fint_Ez + (tau_Ez * f_Ez)) - (Ez_x**2 + Ez_y**2) * tau_Ez**2 * fdot_Ez)
|
||||
fields[timestep, 2] = ((1 / (4 * np.pi * config.sim_config.em_consts['e0'] * Er_z**5)) *
|
||||
((2 * Ez_z**2 - (Ez_x**2 + Ez_y**2)) * (fint_Ez + (tau_Ez * f_Ez)) -
|
||||
(Ez_x**2 + Ez_y**2) * tau_Ez**2 * fdot_Ez))
|
||||
|
||||
# Hx
|
||||
fields[timestep, 3] = - (Hx_y / (4 * np.pi * Hr_x**3)) * (f_Hx + (tau_Hx * fdot_Hx))
|
||||
|
@@ -1,211 +0,0 @@
|
||||
# Copyright (C) 2015-2022: The University of Edinburgh, United Kingdom
|
||||
# Authors: Craig Warren, Antonis Giannopoulos, and John Hartley
|
||||
#
|
||||
# This file is part of gprMax.
|
||||
#
|
||||
# gprMax is free software: you can redistribute it and/or modify
|
||||
# it under the terms of the GNU General Public License as published by
|
||||
# the Free Software Foundation, either version 3 of the License, or
|
||||
# (at your option) any later version.
|
||||
#
|
||||
# gprMax is distributed in the hope that it will be useful,
|
||||
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
# GNU General Public License for more details.
|
||||
#
|
||||
# You should have received a copy of the GNU General Public License
|
||||
# along with gprMax. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
import argparse
|
||||
import itertools
|
||||
import os
|
||||
|
||||
import matplotlib.pyplot as plt
|
||||
import matplotlib.gridspec as gridspec
|
||||
import numpy as np
|
||||
|
||||
from gprMax._version import __version__
|
||||
from gprMax.utilities.host_info import get_host_info
|
||||
from gprMax.utilities.utilities import human_size
|
||||
|
||||
|
||||
"""Plots execution times and speedup factors from benchmarking models run with different numbers of CPU (OpenMP) threads. Can also benchmark GPU(s) if required. Results are read from a NumPy archive."""
|
||||
|
||||
# Parse command line arguments
|
||||
parser = argparse.ArgumentParser(description='Plots execution times and speedup factors from benchmarking models run with different numbers of CPU (OpenMP) threads. Can also benchmark GPU(s) if required. Results are read from a NumPy archive.', usage='cd gprMax; python -m tests.benchmarking.plot_benchmark numpyfile')
|
||||
parser.add_argument('baseresult', help='name of NumPy archive file including path')
|
||||
parser.add_argument('--otherresults', default=None, help='list of NumPy archives file including path', nargs='+')
|
||||
args = parser.parse_args()
|
||||
|
||||
# Load base result
|
||||
baseresult = dict(np.load(args.baseresult))
|
||||
|
||||
# Get machine/CPU/OS details
|
||||
hostinfo = get_host_info()
|
||||
try:
|
||||
machineIDlong = str(baseresult['machineID'])
|
||||
# machineIDlong = 'Dell PowerEdge R630; Intel(R) Xeon(R) CPU E5-2630 v3 @ 2.40GHz; Linux (3.10.0-327.18.2.el7.x86_64)' # Use to manually describe machine
|
||||
machineID = machineIDlong.split(';')[0]
|
||||
cpuID = machineIDlong.split(';')[1]
|
||||
cpuID = cpuID.split('GHz')[0].split('x')[1][1::] + 'GHz'
|
||||
except KeyError:
|
||||
hyperthreading = ', {} cores with Hyper-Threading'.format(hostinfo['logicalcores']) if hostinfo['hyperthreading'] else ''
|
||||
machineIDlong = '{}; {} x {} ({} cores{}); {} RAM; {}'.format(hostinfo['machineID'], hostinfo['sockets'], hostinfo['cpuID'], hostinfo['physicalcores'], hyperthreading, human_size(hostinfo['ram'], a_kilobyte_is_1024_bytes=True), hostinfo['osversion'])
|
||||
print('Host: {}'.format(machineIDlong))
|
||||
|
||||
# Base result - general info
|
||||
print('Model: {}'.format(args.baseresult))
|
||||
cells = np.array([baseresult['numcells'][0]]) # Length of cubic model side for cells per second metric
|
||||
baseplotlabel = os.path.splitext(os.path.split(args.baseresult)[1])[0] + '.in'
|
||||
|
||||
# Base result - CPU threads and times info from Numpy archive
|
||||
if baseresult['cputhreads'].size != 0:
|
||||
for i in range(len(baseresult['cputhreads'])):
|
||||
print('{} CPU (OpenMP) thread(s): {:g} s'.format(baseresult['cputhreads'][i], baseresult['cputimes'][i]))
|
||||
cpucellspersec = np.array([(baseresult['numcells'][0] * baseresult['numcells'][1] * baseresult['numcells'][2] * baseresult['iterations']) / baseresult['cputimes'][0]])
|
||||
|
||||
# Base result - GPU time info
|
||||
gpuIDs = baseresult['gpuIDs'].tolist()
|
||||
if gpuIDs:
|
||||
gpucellspersec = np.zeros((len(gpuIDs), 1))
|
||||
for i in range(len(gpuIDs)):
|
||||
print('NVIDIA {}: {:g} s'.format(gpuIDs[i], baseresult['gputimes'][i]))
|
||||
gpucellspersec[i] = (baseresult['numcells'][0] * baseresult['numcells'][1] * baseresult['numcells'][2] * baseresult['iterations']) / baseresult['gputimes'][i]
|
||||
|
||||
# Load any other results and info
|
||||
otherresults = []
|
||||
otherplotlabels = []
|
||||
if args.otherresults is not None:
|
||||
for i, result in enumerate(args.otherresults):
|
||||
otherresults.append(dict(np.load(result)))
|
||||
print('\nModel: {}'.format(result))
|
||||
cells = np.append(cells, otherresults[i]['numcells'][0]) # Length of cubic model side for cells per second metric
|
||||
otherplotlabels.append(os.path.splitext(os.path.split(result)[1])[0] + '.in')
|
||||
|
||||
# CPU
|
||||
if otherresults[i]['cputhreads'].size != 0:
|
||||
for thread in range(len(otherresults[i]['cputhreads'])):
|
||||
print('{} CPU (OpenMP) thread(s): {:g} s'.format(otherresults[i]['cputhreads'][thread], otherresults[i]['cputimes'][thread]))
|
||||
cpucellspersec = np.append(cpucellspersec, (otherresults[i]['numcells'][0] * otherresults[i]['numcells'][1] * otherresults[i]['numcells'][2] * otherresults[i]['iterations']) / otherresults[i]['cputimes'][0])
|
||||
|
||||
# GPU
|
||||
othergpuIDs = otherresults[i]['gpuIDs'].tolist()
|
||||
if othergpuIDs:
|
||||
# Array for cells per second metric
|
||||
tmp = np.zeros((len(gpuIDs), len(args.otherresults) + 1))
|
||||
tmp[:gpucellspersec.shape[0],:gpucellspersec.shape[1]] = gpucellspersec
|
||||
gpucellspersec = tmp
|
||||
for j in range(len(othergpuIDs)):
|
||||
print('NVIDIA {}: {:g} s'.format(othergpuIDs[j], otherresults[i]['gputimes'][j]))
|
||||
gpucellspersec[j,i+1] = (otherresults[i]['numcells'][0] * otherresults[i]['numcells'][1] * otherresults[i]['numcells'][2] * otherresults[i]['iterations']) / otherresults[i]['gputimes'][j]
|
||||
|
||||
# Get gprMax version
|
||||
try:
|
||||
version = str(baseresult['version'])
|
||||
except KeyError:
|
||||
version = __version__
|
||||
|
||||
# Create/setup plot figure
|
||||
#colors = ['#E60D30', '#5CB7C6', '#A21797', '#A3B347'] # Plot colours from http://tools.medialab.sciences-po.fr/iwanthue/index.php
|
||||
colorIDs = ['#015dbb', '#c23100', '#00a15a', '#c84cd0', '#ff9aa0']
|
||||
colors = itertools.cycle(colorIDs)
|
||||
lines = itertools.cycle(('--', ':', '-.', '-'))
|
||||
markers = ['o', 'd', '^', 's', '*']
|
||||
fig, ax = plt.subplots(num=machineID, figsize=(30, 10), facecolor='w', edgecolor='w')
|
||||
fig.suptitle(machineIDlong + '\ngprMax v' + version)
|
||||
gs = gridspec.GridSpec(1, 3, hspace=0.5)
|
||||
plotcount = 0
|
||||
|
||||
###########################################
|
||||
# Subplot of CPU (OpenMP) threads vs time #
|
||||
###########################################
|
||||
if baseresult['cputhreads'].size != 0:
|
||||
ax = plt.subplot(gs[0, plotcount])
|
||||
ax.plot(baseresult['cputhreads'], baseresult['cputimes'], color=next(colors), marker=markers[0], markeredgecolor='none', ms=8, lw=2, label=baseplotlabel)
|
||||
|
||||
if args.otherresults is not None:
|
||||
for i, result in enumerate(otherresults):
|
||||
ax.plot(result['cputhreads'], result['cputimes'], color=next(colors), marker=markers[0], markeredgecolor='none', ms=8, lw=2, ls=next(lines), label=otherplotlabels[i])
|
||||
|
||||
ax.set_xlabel('Number of CPU (OpenMP) threads')
|
||||
ax.set_ylabel('Time [s]')
|
||||
ax.grid()
|
||||
legend = ax.legend(loc=1)
|
||||
frame = legend.get_frame()
|
||||
frame.set_edgecolor('white')
|
||||
ax.set_xlim([0, baseresult['cputhreads'][0] * 1.1])
|
||||
ax.set_xticks(np.append(baseresult['cputhreads'], 0))
|
||||
ax.set_ylim(0, top=ax.get_ylim()[1] * 1.1)
|
||||
plotcount += 1
|
||||
|
||||
######################################################
|
||||
# Subplot of CPU (OpenMP) threads vs speed-up factor #
|
||||
######################################################
|
||||
colors = itertools.cycle(colorIDs) # Reset color iterator
|
||||
if baseresult['cputhreads'].size != 0:
|
||||
ax = plt.subplot(gs[0, plotcount])
|
||||
ax.plot(baseresult['cputhreads'], baseresult['cputimes'][-1] / baseresult['cputimes'], color=next(colors), marker=markers[0], markeredgecolor='none', ms=8, lw=2, label=baseplotlabel)
|
||||
|
||||
if args.otherresults is not None:
|
||||
for i, result in enumerate(otherresults):
|
||||
ax.plot(result['cputhreads'], result['cputimes'][-1] / result['cputimes'], color=next(colors), marker=markers[0], markeredgecolor='none', ms=8, lw=2, ls=next(lines), label=otherplotlabels[i])
|
||||
|
||||
ax.set_xlabel('Number of CPU (OpenMP) threads')
|
||||
ax.set_ylabel('Speed-up factor')
|
||||
ax.grid()
|
||||
legend = ax.legend(loc=2)
|
||||
frame = legend.get_frame()
|
||||
frame.set_edgecolor('white')
|
||||
ax.set_xlim([0, baseresult['cputhreads'][0] * 1.1])
|
||||
ax.set_xticks(np.append(baseresult['cputhreads'], 0))
|
||||
ax.set_ylim(bottom=1, top=ax.get_ylim()[1] * 1.1)
|
||||
plotcount += 1
|
||||
|
||||
###########################################
|
||||
# Subplot of simulation size vs cells/sec #
|
||||
###########################################
|
||||
|
||||
def autolabel(rects):
|
||||
"""Attach a text label above each bar on a matplotlib bar chart displaying its height.
|
||||
|
||||
Args:
|
||||
rects: Handle to bar chart
|
||||
"""
|
||||
for rect in rects:
|
||||
height = rect.get_height()
|
||||
ax.text(rect.get_x() + rect.get_width()/2, height,
|
||||
'%d' % int(height),
|
||||
ha='center', va='bottom', fontsize=10, rotation=90)
|
||||
|
||||
colors = itertools.cycle(colorIDs) # Reset color iterator
|
||||
ax = plt.subplot(gs[0, plotcount])
|
||||
barwidth = 8 # the width of the bars
|
||||
|
||||
if baseresult['cputhreads'].size != 0:
|
||||
cpu = ax.bar(cells - (1/2) * barwidth, cpucellspersec / 1e6, barwidth, color=next(colors), edgecolor='none', label=cpuID)
|
||||
autolabel(cpu)
|
||||
|
||||
if gpuIDs:
|
||||
positions = np.arange(-gpucellspersec.shape[0] / 2, gpucellspersec.shape[0] / 2, 1)
|
||||
for i in range(gpucellspersec.shape[0]):
|
||||
gpu = ax.bar(cells + positions[i] * barwidth, gpucellspersec[i,:] / 1e6, barwidth, color=next(colors), edgecolor='none', label='NVIDIA ' + gpuIDs[i])
|
||||
autolabel(gpu)
|
||||
|
||||
ax.set_xlabel('Side length of cubic domain [cells]')
|
||||
ax.set_ylabel('Performance [Mcells/s]')
|
||||
ax.grid()
|
||||
legend = ax.legend(loc=2)
|
||||
frame = legend.get_frame()
|
||||
frame.set_edgecolor('white')
|
||||
ax.set_xticks(cells)
|
||||
ax.set_xticklabels(cells)
|
||||
ax.set_xlim([0, cells[-1] * 1.1])
|
||||
ax.set_ylim(bottom=0, top=ax.get_ylim()[1] * 1.1)
|
||||
|
||||
##########################
|
||||
# Save a png of the plot #
|
||||
##########################
|
||||
fig.savefig(os.path.join(os.path.dirname(args.baseresult), machineID.replace(' ', '_') + '.png'), dpi=150, format='png', bbox_inches='tight', pad_inches=0.1)
|
||||
#fig.savefig(os.path.join(os.path.dirname(args.baseresult), machineID.replace(' ', '_') + '.pdf'), dpi='none', format='pdf', bbox_inches='tight', pad_inches=0.1)
|
||||
|
||||
plt.show()
|
@@ -17,16 +17,23 @@
|
||||
# along with gprMax. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
import argparse
|
||||
import logging
|
||||
from pathlib import Path
|
||||
|
||||
import h5py
|
||||
import matplotlib.pyplot as plt
|
||||
import numpy as np
|
||||
|
||||
"""Plots a comparison of fields between given simulation output and experimental data files."""
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
"""Plots a comparison of fields between given simulation output and experimental
|
||||
data files.
|
||||
"""
|
||||
|
||||
# Parse command line arguments
|
||||
parser = argparse.ArgumentParser(description='Plots a comparison of fields between given simulation output and experimental data files.', usage='cd gprMax; python -m tests.test_experimental modelfile realfile output')
|
||||
parser = argparse.ArgumentParser(description='Plots a comparison of fields between ' +
|
||||
'given simulation output and experimental data files.',
|
||||
usage='cd gprMax; python -m tests.test_experimental modelfile realfile output')
|
||||
parser.add_argument('modelfile', help='name of model output file including path')
|
||||
parser.add_argument('realfile', help='name of file containing experimental data including path')
|
||||
parser.add_argument('output', help='output to be plotted, i.e. Ex Ey Ez', nargs='+')
|
||||
@@ -48,7 +55,8 @@ else:
|
||||
polarity = 1
|
||||
|
||||
if args.output[0] not in availablecomponents:
|
||||
logger.exception(f"{args.output[0]} output requested to plot, but the available output for receiver 1 is {', '.join(availablecomponents)}")
|
||||
logger.exception(f"{args.output[0]} output requested to plot, but the " +
|
||||
f"available output for receiver 1 is {', '.join(availablecomponents)}")
|
||||
raise ValueError
|
||||
|
||||
floattype = f[path + args.output[0]].dtype
|
||||
@@ -73,7 +81,8 @@ realmax = np.where(np.abs(real[:, 1]) == 1)[0][0]
|
||||
difftime = - (timemodel[modelmax] - real[realmax, 0])
|
||||
|
||||
# Plot modelled and real data
|
||||
fig, ax = plt.subplots(num=modelfile.stem + '_vs_' + realfile.stem, figsize=(20, 10), facecolor='w', edgecolor='w')
|
||||
fig, ax = plt.subplots(num=modelfile.stem + '_vs_' + realfile.stem,
|
||||
figsize=(20, 10), facecolor='w', edgecolor='w')
|
||||
ax.plot(timemodel + difftime, model, 'r', lw=2, label='Model')
|
||||
ax.plot(real[:, 0], real[:, 1], 'r', ls='--', lw=2, label='Experiment')
|
||||
ax.set_xlabel('Time [s]')
|
||||
@@ -86,7 +95,9 @@ ax.grid()
|
||||
# Save a PDF/PNG of the figure
|
||||
savename = modelfile.stem + '_vs_' + realfile.stem
|
||||
savename = modelfile.parent / savename
|
||||
# fig.savefig(savename.with_suffix('.pdf'), dpi=None, format='pdf', bbox_inches='tight', pad_inches=0.1)
|
||||
# fig.savefig(savename.with_suffix('.png'), dpi=150, format='png', bbox_inches='tight', pad_inches=0.1)
|
||||
# fig.savefig(savename.with_suffix('.pdf'), dpi=None, format='pdf',
|
||||
# bbox_inches='tight', pad_inches=0.1)
|
||||
# fig.savefig(savename.with_suffix('.png'), dpi=150, format='png',
|
||||
# bbox_inches='tight', pad_inches=0.1)
|
||||
|
||||
plt.show()
|
||||
|
@@ -24,8 +24,7 @@ import gprMax
|
||||
import h5py
|
||||
import matplotlib.pyplot as plt
|
||||
import numpy as np
|
||||
from colorama import Fore, Style, init
|
||||
init()
|
||||
|
||||
from tests.analytical_solutions import hertzian_dipole_fs
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
@@ -50,7 +49,9 @@ basepath = Path(__file__).parents[0] / modelset
|
||||
|
||||
|
||||
# List of available basic test models
|
||||
testmodels = ['hertzian_dipole_fs_analytical', '2D_ExHyHz', '2D_EyHxHz', '2D_EzHxHy', 'cylinder_Ascan_2D', 'hertzian_dipole_fs', 'hertzian_dipole_hs', 'hertzian_dipole_dispersive', 'magnetic_dipole_fs']
|
||||
testmodels = ['hertzian_dipole_fs_analytical', '2D_ExHyHz', '2D_EyHxHz', '2D_EzHxHy',
|
||||
'cylinder_Ascan_2D', 'hertzian_dipole_fs', 'hertzian_dipole_hs',
|
||||
'hertzian_dipole_dispersive', 'magnetic_dipole_fs']
|
||||
|
||||
# List of available advanced test models
|
||||
# testmodels = ['antenna_GSSI_1500_fs', 'antenna_MALA_1200_fs']
|
||||
@@ -86,11 +87,13 @@ for i, model in enumerate(testmodels):
|
||||
|
||||
# Arrays for storing time
|
||||
float_or_double = filetest[path + outputstest[0]].dtype
|
||||
timetest = np.linspace(0, (filetest.attrs['Iterations'] - 1) * filetest.attrs['dt'], num=filetest.attrs['Iterations']) / 1e-9
|
||||
timetest = np.linspace(0, (filetest.attrs['Iterations'] - 1) * filetest.attrs['dt'],
|
||||
num=filetest.attrs['Iterations']) / 1e-9
|
||||
timeref = timetest
|
||||
|
||||
# Arrays for storing field data
|
||||
datatest = np.zeros((filetest.attrs['Iterations'], len(outputstest)), dtype=float_or_double)
|
||||
datatest = np.zeros((filetest.attrs['Iterations'], len(outputstest)),
|
||||
dtype=float_or_double)
|
||||
for ID, name in enumerate(outputstest):
|
||||
datatest[:, ID] = filetest[path + str(name)][:]
|
||||
if np.any(np.isnan(datatest[:, ID])):
|
||||
@@ -100,10 +103,14 @@ for i, model in enumerate(testmodels):
|
||||
# Tx/Rx position to feed to analytical solution
|
||||
rxpos = filetest[path].attrs['Position']
|
||||
txpos = filetest['/srcs/src1/'].attrs['Position']
|
||||
rxposrelative = ((rxpos[0] - txpos[0]), (rxpos[1] - txpos[1]), (rxpos[2] - txpos[2]))
|
||||
rxposrelative = ((rxpos[0] - txpos[0]),
|
||||
(rxpos[1] - txpos[1]),
|
||||
(rxpos[2] - txpos[2]))
|
||||
|
||||
# Analytical solution of a dipole in free space
|
||||
dataref = hertzian_dipole_fs(filetest.attrs['Iterations'], filetest.attrs['dt'], filetest.attrs['dx_dy_dz'], rxposrelative)
|
||||
dataref = hertzian_dipole_fs(filetest.attrs['Iterations'],
|
||||
filetest.attrs['dt'],
|
||||
filetest.attrs['dx_dy_dz'], rxposrelative)
|
||||
|
||||
filetest.close()
|
||||
|
||||
@@ -125,19 +132,25 @@ for i, model in enumerate(testmodels):
|
||||
|
||||
# Check that type of float used to store fields matches
|
||||
if filetest[path + outputstest[0]].dtype != fileref[path + outputsref[0]].dtype:
|
||||
print(Fore.RED + f'WARNING: Type of floating point number in test model ({filetest[path + outputstest[0]].dtype}) does not match type in reference solution ({fileref[path + outputsref[0]].dtype})\n' + Style.RESET_ALL)
|
||||
logger.warning(f'Type of floating point number in test model ' +
|
||||
f'({filetest[path + outputstest[0]].dtype}) does not ' +
|
||||
f'match type in reference solution ({fileref[path + outputsref[0]].dtype})\n')
|
||||
float_or_doubleref = fileref[path + outputsref[0]].dtype
|
||||
float_or_doubletest = filetest[path + outputstest[0]].dtype
|
||||
|
||||
# Arrays for storing time
|
||||
timeref = np.zeros((fileref.attrs['Iterations']), dtype=float_or_doubleref)
|
||||
timeref = np.linspace(0, (fileref.attrs['Iterations'] - 1) * fileref.attrs['dt'], num=fileref.attrs['Iterations']) / 1e-9
|
||||
timeref = np.linspace(0, (fileref.attrs['Iterations'] - 1) * fileref.attrs['dt'],
|
||||
num=fileref.attrs['Iterations']) / 1e-9
|
||||
timetest = np.zeros((filetest.attrs['Iterations']), dtype=float_or_doubletest)
|
||||
timetest = np.linspace(0, (filetest.attrs['Iterations'] - 1) * filetest.attrs['dt'], num=filetest.attrs['Iterations']) / 1e-9
|
||||
timetest = np.linspace(0, (filetest.attrs['Iterations'] - 1) * filetest.attrs['dt'],
|
||||
num=filetest.attrs['Iterations']) / 1e-9
|
||||
|
||||
# Arrays for storing field data
|
||||
dataref = np.zeros((fileref.attrs['Iterations'], len(outputsref)), dtype=float_or_doubleref)
|
||||
datatest = np.zeros((filetest.attrs['Iterations'], len(outputstest)), dtype=float_or_doubletest)
|
||||
dataref = np.zeros((fileref.attrs['Iterations'], len(outputsref)),
|
||||
dtype=float_or_doubleref)
|
||||
datatest = np.zeros((filetest.attrs['Iterations'], len(outputstest)),
|
||||
dtype=float_or_doubletest)
|
||||
for ID, name in enumerate(outputsref):
|
||||
dataref[:, ID] = fileref[path + str(name)][:]
|
||||
datatest[:, ID] = filetest[path + str(name)][:]
|
||||
@@ -152,7 +165,9 @@ for i, model in enumerate(testmodels):
|
||||
datadiffs = np.zeros(datatest.shape, dtype=np.float64)
|
||||
for i in range(len(outputstest)):
|
||||
max = np.amax(np.abs(dataref[:, i]))
|
||||
datadiffs[:, i] = np.divide(np.abs(dataref[:, i] - datatest[:, i]), max, out=np.zeros_like(dataref[:, i]), where=max != 0) # Replace any division by zero with zero
|
||||
datadiffs[:, i] = np.divide(np.abs(dataref[:, i] - datatest[:, i]), max,
|
||||
out=np.zeros_like(dataref[:, i]),
|
||||
where=max != 0) # Replace any division by zero with zero
|
||||
|
||||
# Calculate power (ignore warning from taking a log of any zero values)
|
||||
with np.errstate(divide='ignore'):
|
||||
@@ -165,7 +180,13 @@ for i, model in enumerate(testmodels):
|
||||
testresults[model]['Max diff'] = maxdiff
|
||||
|
||||
# Plot datasets
|
||||
fig1, ((ex1, hx1), (ey1, hy1), (ez1, hz1)) = plt.subplots(nrows=3, ncols=2, sharex=False, sharey='col', subplot_kw=dict(xlabel='Time [ns]'), num=model + '.in', figsize=(20, 10), facecolor='w', edgecolor='w')
|
||||
fig1, ((ex1, hx1), (ey1, hy1), (ez1, hz1)) = plt.subplots(nrows=3, ncols=2,
|
||||
sharex=False, sharey='col',
|
||||
subplot_kw=dict(xlabel='Time [ns]'),
|
||||
num=model + '.in',
|
||||
figsize=(20, 10),
|
||||
facecolor='w',
|
||||
edgecolor='w')
|
||||
ex1.plot(timetest, datatest[:, 0], 'r', lw=2, label=model)
|
||||
ex1.plot(timeref, dataref[:, 0], 'g', lw=2, ls='--', label=model + '(Ref)')
|
||||
ey1.plot(timetest, datatest[:, 1], 'r', lw=2, label=model)
|
||||
@@ -178,7 +199,9 @@ for i, model in enumerate(testmodels):
|
||||
hy1.plot(timeref, dataref[:, 4], 'g', lw=2, ls='--', label=model + '(Ref)')
|
||||
hz1.plot(timetest, datatest[:, 5], 'r', lw=2, label=model)
|
||||
hz1.plot(timeref, dataref[:, 5], 'g', lw=2, ls='--', label=model + '(Ref)')
|
||||
ylabels = ['$E_x$, field strength [V/m]', '$H_x$, field strength [A/m]', '$E_y$, field strength [V/m]', '$H_y$, field strength [A/m]', '$E_z$, field strength [V/m]', '$H_z$, field strength [A/m]']
|
||||
ylabels = ['$E_x$, field strength [V/m]', '$H_x$, field strength [A/m]',
|
||||
'$E_y$, field strength [V/m]', '$H_y$, field strength [A/m]',
|
||||
'$E_z$, field strength [V/m]', '$H_z$, field strength [A/m]']
|
||||
for i, ax in enumerate(fig1.axes):
|
||||
ax.set_ylabel(ylabels[i])
|
||||
ax.set_xlim(0, np.amax(timetest))
|
||||
@@ -186,14 +209,22 @@ for i, model in enumerate(testmodels):
|
||||
ax.legend()
|
||||
|
||||
# Plot diffs
|
||||
fig2, ((ex2, hx2), (ey2, hy2), (ez2, hz2)) = plt.subplots(nrows=3, ncols=2, sharex=False, sharey='col', subplot_kw=dict(xlabel='Time [ns]'), num='Diffs: ' + model + '.in', figsize=(20, 10), facecolor='w', edgecolor='w')
|
||||
fig2, ((ex2, hx2), (ey2, hy2), (ez2, hz2)) = plt.subplots(nrows=3, ncols=2,
|
||||
sharex=False, sharey='col',
|
||||
subplot_kw=dict(xlabel='Time [ns]'),
|
||||
num='Diffs: ' + model + '.in',
|
||||
figsize=(20, 10),
|
||||
facecolor='w',
|
||||
edgecolor='w')
|
||||
ex2.plot(timeref, datadiffs[:, 0], 'r', lw=2, label='Ex')
|
||||
ey2.plot(timeref, datadiffs[:, 1], 'r', lw=2, label='Ey')
|
||||
ez2.plot(timeref, datadiffs[:, 2], 'r', lw=2, label='Ez')
|
||||
hx2.plot(timeref, datadiffs[:, 3], 'r', lw=2, label='Hx')
|
||||
hy2.plot(timeref, datadiffs[:, 4], 'r', lw=2, label='Hy')
|
||||
hz2.plot(timeref, datadiffs[:, 5], 'r', lw=2, label='Hz')
|
||||
ylabels = ['$E_x$, difference [dB]', '$H_x$, difference [dB]', '$E_y$, difference [dB]', '$H_y$, difference [dB]', '$E_z$, difference [dB]', '$H_z$, difference [dB]']
|
||||
ylabels = ['$E_x$, difference [dB]', '$H_x$, difference [dB]',
|
||||
'$E_y$, difference [dB]', '$H_y$, difference [dB]',
|
||||
'$E_z$, difference [dB]', '$H_z$, difference [dB]']
|
||||
for i, ax in enumerate(fig2.axes):
|
||||
ax.set_ylabel(ylabels[i])
|
||||
ax.set_xlim(0, np.amax(timetest))
|
||||
@@ -203,14 +234,21 @@ for i, model in enumerate(testmodels):
|
||||
# Save a PDF/PNG of the figure
|
||||
filediffs = file.stem + '_diffs'
|
||||
filediffs = file.parent / Path(filediffs)
|
||||
# fig1.savefig(file.with_suffix('.pdf'), dpi=None, format='pdf', bbox_inches='tight', pad_inches=0.1)
|
||||
# fig2.savefig(savediffs.with_suffix('.pdf'), dpi=None, format='pdf', bbox_inches='tight', pad_inches=0.1)
|
||||
fig1.savefig(file.with_suffix('.png'), dpi=150, format='png', bbox_inches='tight', pad_inches=0.1)
|
||||
fig2.savefig(filediffs.with_suffix('.png'), dpi=150, format='png', bbox_inches='tight', pad_inches=0.1)
|
||||
# fig1.savefig(file.with_suffix('.pdf'), dpi=None, format='pdf',
|
||||
# bbox_inches='tight', pad_inches=0.1)
|
||||
# fig2.savefig(savediffs.with_suffix('.pdf'), dpi=None, format='pdf',
|
||||
# bbox_inches='tight', pad_inches=0.1)
|
||||
fig1.savefig(file.with_suffix('.png'), dpi=150, format='png',
|
||||
bbox_inches='tight', pad_inches=0.1)
|
||||
fig2.savefig(filediffs.with_suffix('.png'), dpi=150, format='png',
|
||||
bbox_inches='tight', pad_inches=0.1)
|
||||
|
||||
# Summary of results
|
||||
for name, data in sorted(testresults.items()):
|
||||
if 'analytical' in name:
|
||||
print(Fore.CYAN + f"Test '{name}.in' using v.{data['Test version']} compared to analytical solution. Max difference {data['Max diff']:.2f}dB." + Style.RESET_ALL)
|
||||
logger.info(f"Test '{name}.in' using v.{data['Test version']} compared " +
|
||||
f"to analytical solution. Max difference {data['Max diff']:.2f}dB.")
|
||||
else:
|
||||
print(Fore.CYAN + f"Test '{name}.in' using v.{data['Test version']} compared to reference solution using v.{data['Ref version']}. Max difference {data['Max diff']:.2f}dB." + Style.RESET_ALL)
|
||||
logger.info(f"Test '{name}.in' using v.{data['Test version']} compared to " +
|
||||
f"reference solution using v.{data['Ref version']}. Max difference " +
|
||||
f"{data['Max diff']:.2f}dB.")
|
||||
|
在新工单中引用
屏蔽一个用户