-
Notifications
You must be signed in to change notification settings - Fork 2
/
read_out.py
233 lines (199 loc) · 10.4 KB
/
read_out.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
#import argparse
import h5py
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
def get_output_data(filename, rxnumber, rxcomponent):
"""Gets B-scan output data from a model.
Args:
filename (string): Filename (including path) of output file.
rxnumber (int): Receiver output number.
rxcomponent (str): Receiver output field/current component.
Returns:
outputdata (array): Array of A-scans, i.e. B-scan data.
dt (float): Temporal resolution of the model.
"""
# Open output file and read some attributes
f = h5py.File(filename, 'r')
nrx = f.attrs['nrx']
dt = f.attrs['dt']
# Check there are any receivers
if nrx == 0:
print("No recievers Found!")
return
path = '/rxs/rx' + str(rxnumber) + '/'
outputdata = f[path + '/' + rxcomponent]
outputdata = np.array(outputdata)
# Check that there is more than one A-scan present
if outputdata.shape[1] == 1:
print ("Contains Single A Scan")
# A_Scan_plot(filename)
return outputdata, dt
def A_Scan_plot(filename, outputs=['Ex', 'Ey', 'Ez', 'Hx', 'Hy', 'Hz', 'Ix', 'Iy', 'Iz'], fft=False):
"""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.
Args:
filename (string): Filename (including path) of output file.
outputs (list): List of field/current components to plot.
fft (boolean): Plot FFT switch.
Returns:
plt (object): matplotlib plot object.
"""
# Open output file and read some attributes
f = h5py.File(filename, 'r')
nrx = f.attrs['nrx']
dt = f.attrs['dt']
iterations = f.attrs['Iterations']
time = np.linspace(0, 1, iterations)
time *= (iterations * dt)
# Check there are any receivers
if nrx == 0:
print('No recievers found!')
return
# raise CmdInputError('No receivers found in {}'.format(filename))
# Check for single output component when doing a FFT
if fft:
if not len(outputs) == 1:
raise CmdInputError('A single output must be specified when using the -fft option')
# New plot for each receiver
for rx in range(1, nrx + 1):
path = '/rxs/rx' + str(rx) + '/'
availableoutputs = list(f[path].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] == '-':
polarity = -1
outputtext = '-' + outputs[0][0:-1]
output = outputs[0][0:-1]
else:
polarity = 1
outputtext = outputs[0]
output = outputs[0]
# if output not in availableoutputs:
# raise CmdInputError('{} output requested to plot, but the available output for receiver 1 is {}'.format(output, ', '.join(availableoutputs)))
outputdata = f[path + output][:] * polarity
# Plotting if FFT required
if fft:
# Calculate magnitude of frequency spectra of waveform
power = 10 * np.log10(np.abs(np.fft.fft(outputdata))**2)
freqs = np.fft.fftfreq(power.size, d=dt)
# Shift powers so that frequency with maximum power is at zero decibels
power -= np.amax(power)
# Set plotting range to -60dB from maximum power
pltrange = np.where((np.amax(power[1::]) - power[1::]) > 60)[0][0] + 1
# To a maximum frequency
# pltrange = np.where(freqs > 2e9)[0][0]
pltrange = np.s_[0:pltrange]
# Plot time history of output component
fig, (ax1, ax2) = plt.subplots(nrows=1, ncols=2, num='rx' + str(rx), 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()
# Plot frequency spectra
markerline, stemlines, baseline = ax2.stem(freqs[pltrange], power[pltrange], '-.')
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()
# 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')
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='rx' + str(rx), 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()
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 populate only the specified ones
else:
fig, ax = plt.subplots(subplot_kw=dict(xlabel='Time [s]'), num='rx' + str(rx), 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 is in file
if output[-1] == 'm':
polarity = -1
outputtext = '-' + output[0:-1]
output = output[0:-1]
else:
polarity = 1
outputtext = output
# Check if requested output is in file
if output not in availableoutputs:
raise CmdInputError('Output(s) requested to plot: {}, but available output(s) for receiver {} in the file: {}'.format(', '.join(outputs), rx, ', '.join(availableoutputs)))
outputdata = f[path + output][:] * polarity
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.set_ylim([-15, 20])
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.set_ylim([-15, 20])
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.set_ylim([-15, 20])
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.set_ylim([-0.03, 0.03])
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.set_ylim([-0.03, 0.03])
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.set_ylim([-0.03, 0.03])
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 = plt.subplot(gs[1, 2])
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]')
for ax in fig.axes:
ax.set_xlim([0, np.amax(time)])
ax.grid()
# Save a PDF/PNG of the figure
# fig.savefig(os.path.splitext(os.path.abspath(filename))[0] + '_rx' + str(rx) + '.pdf', dpi=None, format='pdf', bbox_inches='tight', pad_inches=0.1)
# fig.savefig(os.path.splitext(os.path.abspath(filename))[0] + '_rx' + str(rx) + '.png', dpi=150, format='png', bbox_inches='tight', pad_inches=0.1)
plt.show()
return plt