forked from sunpy/eitwave
/
swave_characterize_load_and_plot.py
428 lines (331 loc) · 13.9 KB
/
swave_characterize_load_and_plot.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
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
#
# Load in multiple noisy realizations of a given simulated wave, and
# characterize the performance of AWARE on detecting the wave
#
import os
import pickle
import numpy as np
import matplotlib.pyplot as plt
import astropy.units as u
import matplotlib
# AWARE constants
import aware_constants
# AWARE utilities
import aware_utils
from aware_plot import longitudinal_lines
# Simulated wave parameters
import swave_params
#
from aware_constants import solar_circumference_per_degree_in_km
import swave_study as sws
# Output fontsize
matplotlib.rcParams.update({'font.size': 18})
# Simulated data
# TODO - run the same analysis on multiple noisy realizations of the simulated
# TODO - data. Generate average result plots over the multiple realizations
# TODO - either as relative error or absolute error as appropriate.
# TODO - First mode: use multiple noisy realizations of the same model.
# TODO - Second mode: choose a bunch of simulated data parameters, and then
# TODO - randomly select values for them (within reason).
# TODO - The recovered parameters should be reasonably close to the simulated
# TODO - parameters.
#
#
use_error_bar = False
for_paper = True
zorder_min = 10000000
true_velocity_kwargs = {"color": "blue", "linewidth": 3, "linestyle": "-.", "zorder": zorder_min+1}
true_acceleration_kwargs = {"color": "red", "linewidth": 3, "linestyle": "-.", "zorder": zorder_min+1}
# Define the Analysis object
class Analysis:
def __init__(self):
self.method = None
self.n_degree = None
self.lon = None
self.ils = None
self.answer = None
self.aware_version = None
###############################################################################
#
# How to select good arcs
#
# Reduced chi-squared must be below this limit
rchi2_limit = 1.0 #sws.rchi2_limit
###############################################################################
#
# Simulated observations of a wave
#
example = sws.wave_name
# Number of trials
ntrials = sws.n_random
# Number of images
max_steps = sws.max_steps
# Use the second version of the HG to HPC transform
use_transform2 = sws.use_transform2
###############################################################################
#
# Preparation of the simulated observations to create a mapcube that will be
# used by AWARE.
#
# Analysis source data
analysis_data_sources = sws.analysis_data_sources
# Summing of the simulated observations in the time direction
temporal_summing = sws.temporal_summing
# Summing of the simulated observations in the spatial directions
spatial_summing = sws.spatial_summing
# HPC to HG transformation: methods used to calculate the griddata interpolation
griddata_methods = sws.griddata_methods
###############################################################################
#
# AWARE processing: details
#
# Which version of AWARE to use?
aware_version = sws.aware_version
# Radii of the morphological operations in the HG co-ordinate and HPC
# co-ordinates
radii = sws.morphology_radii(aware_version)
################################################################################
#
# Measure the velocity and acceleration of the HG arcs
#
# Position measuring choices
position_choice = sws.position_choice
error_choice = sws.error_choice
# Number of degrees in the polynomial fit
n_degrees = sws.n_degrees
# RANSAC
ransac_kwargs = sws.ransac_kwargs
# Great circle points
great_circle_points = sws.great_circle_points
################################################################################
#
# Where to dump the output
#
# Output directory
output = sws.output
# Special designation: an extra description added to the file and directory
# names in order to differentiate between experiments on the same example wave.
# special_designation = '_ignore_first_six_points'
# special_designation = '_after_editing_for_dsun_and_consolidation'
# special_designation = '_fix_for_crpix12'
special_designation = sws.special_designation
# Output types
otypes = sws.otypes
# Save images in this format
image_file_type = sws.image_file_type
###############################################################################
###############################################################################
#
# Everything below here is set from above
#
# Output directories and filename
odir = os.path.expanduser(output)
otypes_dir = {}
otypes_filename = {}
# Morphological radii
sradii = ''
for r in radii:
for v in r:
sradii = sradii + str(v.value) + '_'
sradii = sradii[0: -1]
# Create the storage directories and filenames
for ot in otypes:
# root directory
idir = os.path.join(odir, ot)
# filename
filename = ''
# All the subdirectories
for loc in [example + special_designation,
'use_transform2=' + str(use_transform2),
'finalmaps',
str(ntrials) + '_' + str(max_steps) + '_' + str(temporal_summing) + '_' + str(spatial_summing.value),
sradii,
position_choice + '_' + error_choice,
aware_utils.convert_dict_to_single_string(ransac_kwargs)]:
idir = os.path.join(idir, loc)
filename = filename + loc + '.'
filename = filename[0: -1]
if not(os.path.exists(idir)):
os.makedirs(idir)
otypes_dir[ot] = idir
otypes_filename[ot] = filename + '.' + str(great_circle_points)
# Load in the wave params
if not sws.observational:
params = swave_params.waves()[example]
#
# Load the results
#
if not os.path.exists(otypes_dir['dat']):
os.makedirs(otypes_dir['dat'])
filepath = os.path.join(otypes_dir['dat'], otypes_filename['dat'] + '.pkl')
print('\nLoading ' + filepath + '\n')
f = open(filepath, 'rb')
results = pickle.load(f)
f.close()
# How many arcs?
nlon = len(results[0])
angles = ((np.linspace(0, 2*np.pi, nlon+1))[0:-1] * u.rad).to(u.deg)
# Long score
long_score = np.asarray([aaa[1].answer.long_score.final_score if aaa[1].answer.fitted else 0.0 for aaa in results[0]])
# Best Long score
long_score_argmax = long_score.argmax()
# Initial value to the velocity
velocity_unit = u.km/u.s
acceleration_unit = u.km/u.s/u.s
if not sws.observational:
true_values = {"velocity": (params['speed'][0] * aware_constants.solar_circumference_per_degree).to(velocity_unit).value,
"acceleration": (params['acceleration'] * aware_constants.solar_circumference_per_degree).to(acceleration_unit).value}
true_value_labels = {"velocity": velocity_unit.to_string('latex_inline'),
"acceleration": acceleration_unit.to_string('latex_inline')}
longitudinal_lines_kwargs = {"bbox": dict(facecolor='yellow', alpha=0.8),
"fontsize": 9,
"horizontalalignment": 'center',
"zorder": 10000
}
best_long_score_text_kwargs = {"bbox": dict(facecolor='red', alpha=0.8),
"fontsize": 9,
"horizontalalignment": 'center',
"zorder": 10000
}
# Legend keywords
legend_kwargs = {"framealpha": 0.7, "facecolor": "yellow", "loc": "best", "fontsize": 12}
def extract(results, n_degree=1, measurement_type='velocity'):
"""
Extract the particular measurements from the results structure
:param results:
:param n_degree:
:param measurement_type:
:return:
"""
n_trials = len(results)
nlon = len(results[0])
measurement = np.zeros(shape=(n_trials, nlon))
measurement_error = np.zeros_like(measurement)
fitted = np.zeros_like(measurement)
rchi2 = np.zeros_like(measurement)
for this_arc in range(0, nlon):
for this_trial in range(0, n_trials):
answer = (results[this_trial][this_arc][n_degree-1]).answer
if answer.fitted:
fitted[this_trial, this_arc] = True
rchi2[this_trial, this_arc] = answer.rchi2
if measurement_type == 'velocity':
measurement[this_trial, this_arc] = (answer.velocity * solar_circumference_per_degree_in_km).value
measurement_error[this_trial, this_arc] = (answer.velocity_error * solar_circumference_per_degree_in_km).value
if measurement_type == 'acceleration':
measurement[this_trial, this_arc] = (answer.acceleration * solar_circumference_per_degree_in_km).value
measurement_error[this_trial, this_arc] = (answer.acceleration * solar_circumference_per_degree_in_km).value
else:
fitted[this_trial, this_arc] = False
measurement[this_trial, this_arc] = np.nan
measurement_error[this_trial, this_arc] = np.nan
rchi2[this_trial, this_arc] = np.nan
return fitted, rchi2, measurement, measurement_error
def summarize(fitted, rchi2, measurement, rchi2_limit=1.5):
"""
Create summaries of the input measurement
:param fitted:
:param rchi2:
:param measurement:
:param summary:
:param rchi2_limit:
:return:
"""
nlon = measurement.shape[1]
mean = np.zeros(shape=nlon)
std = np.zeros_like(mean)
median = np.zeros_like(mean)
mad = np.zeros_like(mean)
n_found = np.zeros_like(mean)
for i in range(0, nlon):
# Find where the successful fits were
successful_fit = fitted[:, i]
# Reduced chi-squared
rc2 = rchi2[:, i]
# Successful fit
f = np.logical_and(successful_fit, rc2 < rchi2_limit)
# Indices of the successful fits
trial_index = np.nonzero(f)
# Number of successful trials
n_found[i] = np.sum(f)
m = measurement[trial_index, i]
mean[i] = np.nansum(m) / (1.0 * n_found[i])
std[i] = np.std(m)
median[i] = np.nanmedian(m)
mad[i] = np.nanmedian(np.abs(m - median[i]))
mean_mean = np.nanmean(mean)
mean_std = np.nanmean(std)
median_median = np.nanmedian(median)
median_mad = np.nanmedian(mad)
return ("mean value (standard deviation)", mean, std, mean_mean, mean_std),\
("median value (median absolute deviation)", median, mad, median_median, median_mad),\
("n_found", n_found)
for n_degree in [1, 2]:
if n_degree == 1:
measurement_types = ['velocity']
fit = 'linear fit'
if n_degree == 2:
measurement_types = ['velocity', 'acceleration']
fit = 'quadratic fit'
for measurement_type in measurement_types:
if measurement_type == 'velocity':
figure_label = '(a)'
if measurement_type == 'acceleration':
figure_label = '(b)'
if not sws.observational:
true_value = true_values[measurement_type]
true_value_label = true_value_labels[measurement_type]
# Make plots of the central tendency of the velocity
fitted, rchi2, measurement, measurement_error = extract(results,
n_degree=n_degree,
measurement_type=measurement_type)
summaries = summarize(fitted, rchi2, measurement, rchi2_limit=rchi2_limit)
print(summaries[0][3], summaries[0][4])
for summary in summaries[0:1]:
plt.close('all')
fig, ax = plt.subplots()
# ax.errorbar(angles.value, summary[1], summary[2], linewidth=0.5, color='green', label=summary[0])
ax.plot(angles.value, summary[1], color='green', label='mean')
ax.plot(angles.value, summary[1] + summary[2], color='green', linestyle=":", label='mean $\pm$ standard deviation')
ax.plot(angles.value, summary[1] - summary[2], color='green', linestyle=":")
ax.xaxis.set_ticks(np.arange(0, 360, 45))
ax.grid('on', linestyle=":")
if not sws.observational:
hline_label = "true {:s} ({:n} {:s})".format(measurement_type, true_value, true_value_label)
if measurement_type == 'velocity':
ax.axhline(true_value, label=hline_label, **true_velocity_kwargs)
if measurement_type == 'acceleration':
ax.axhline(true_value, label=hline_label, **true_acceleration_kwargs)
for key in longitudinal_lines.keys():
ax.axvline(key, **longitudinal_lines[key]['kwargs'])
ax.axvline(long_score_argmax, color='red',
label='best Long score (' + str(long_score_argmax) + u.degree.to_string('latex_inline') + ')')
ax.set_xlabel('longitude (degrees)')
ax.set_ylabel(measurement_type + " ({:s})".format(true_value_label))
if for_paper:
title = "{:s} {:s}\n({:s})".format(figure_label, measurement_type, summary[0])
title = "{:s} {:s}".format(figure_label, measurement_type)
else:
title = "{:s} ({:s})\n{:s}".format(measurement_type, summary[0], fit)
ax.set_title(title)
ax.legend(**legend_kwargs)
filename = "{:s}.{:s}.{:s}.{:s}".format(otypes_filename["img"], measurement_type, summary[0], fit)
filename = "{:s}".format(aware_utils.clean_for_overleaf(filename))
filename = "{:s}.{:s}".format(filename, image_file_type)
file_path = os.path.join(otypes_dir['img'], filename)
print('Saving {:s}'.format(file_path))
fig.tight_layout()
fig.savefig(file_path)
#
# Plot and save the best long score arc
##
plt.close('all')
bls_string = (angles[long_score_argmax].to(u.deg))._repr_latex_()
results[0][long_score_argmax][1].answer.plot(title='wave propagation at the best Long score\n(longitude={:s})'.format(bls_string))
plt.tight_layout()
directory = otypes_dir['img']
filename = "{:s}_{:s}".format(otypes_filename['img'], 'arc_with_highest_score')
filename = "{:s}".format(aware_utils.clean_for_overleaf(filename))
filename = "{:s}.{:s}".format(filename, image_file_type)
full_file_path = os.path.join(directory, filename)
plt.savefig(full_file_path)