NuMRI/kalman/graphics/figure2.py

219 lines
6.1 KiB
Python
Raw Normal View History

2020-12-16 18:41:44 +01:00
import matplotlib.pyplot as plt
import numpy as np
from itertools import cycle
import argparse
import pickle
import yaml
def is_ipython():
''' Check if script is run in IPython.
Returns:
bool: True if IPython, else False '''
try:
get_ipython()
ipy = True
except NameError:
ipy = False
return ipy
def load_data(file):
''' Load numpy data from file.
Returns
dict: data dictionary
'''
dat = np.load(file)
return dat
2021-03-17 19:47:23 +01:00
def plot_parameters(dat, input_file, deparameterize=False, ref=None):
2020-12-16 18:41:44 +01:00
''' Plot the parameters in separate subplots with uncertainties.
Args:
dat (dict): data dictionary
deparameterize (bool): flag indicating if parameters should be
deparameterized via 2**theta
ref: reference value to be plotted with parameters
'''
if is_ipython():
plt.ion()
2021-03-17 19:47:23 +01:00
idx_a = input_file.find('/')
idx_b = input_file[idx_a+1::].find('/')
name_file = input_file[idx_a+1:idx_b+idx_a+1]
inputfile_path = 'results/' + name_file + '/input.yaml'
2020-12-16 18:41:44 +01:00
with open(inputfile_path) as file:
inputfile = yaml.full_load(file)
2021-04-02 13:11:34 +02:00
2021-05-28 10:01:29 +02:00
2021-03-24 17:00:14 +01:00
true_values = {
2021-05-28 10:01:29 +02:00
3: 4800,
2021-06-09 12:35:12 +02:00
4: 7200,
2021-05-28 10:01:29 +02:00
5: 11520,
6: 11520,
2: 75
2021-03-24 17:00:14 +01:00
}
2021-05-28 10:01:29 +02:00
2021-06-09 12:35:12 +02:00
true_values_C = {
3: 0.0004,
4: 0.0004,
5: 0.0003,
6: 0.0003,
}
2021-05-28 10:01:29 +02:00
2021-06-09 12:35:12 +02:00
meas_flag = False
RC_mod = True
line_split = 1.5
2020-12-16 18:41:44 +01:00
current_val = []
2021-06-09 12:35:12 +02:00
current_val_C = []
ids_type = []
2021-03-22 10:22:00 +01:00
labels = []
2021-03-24 17:00:14 +01:00
ids = []
2021-03-17 19:47:23 +01:00
for bnd_c in inputfile['estimation']['boundary_conditions']:
2021-03-22 10:22:00 +01:00
2021-03-17 19:47:23 +01:00
if 'windkessel' in bnd_c['type']:
for bnd_set in inputfile['boundary_conditions']:
if bnd_c['id'] == bnd_set['id']:
2021-03-24 17:00:14 +01:00
ids.append(bnd_c['id'])
2021-06-09 12:35:12 +02:00
ids_type.append('windkessel')
2021-04-02 13:11:34 +02:00
current_val.append(bnd_set['parameters']['R_d'])
2021-03-29 10:45:02 +02:00
labels.append('$R_' + str(bnd_c['id']))
2021-06-09 12:35:12 +02:00
if RC_mod:
current_val_C.append(bnd_set['parameters']['C'])
labels.append('$C_' + str(bnd_c['id']))
2021-03-17 19:47:23 +01:00
2021-03-22 10:22:00 +01:00
elif 'dirichlet' in bnd_c['type']:
2021-05-28 10:01:29 +02:00
current_val.append(inputfile['boundary_conditions'][0]['parameters']['U'])
2021-03-24 17:00:14 +01:00
ids.append(bnd_c['id'])
2021-06-09 12:35:12 +02:00
ids_type.append('dirichlet')
2021-05-28 10:01:29 +02:00
labels.append('$U')
2020-12-16 18:41:44 +01:00
2021-06-09 12:35:12 +02:00
2020-12-16 18:41:44 +01:00
dim = dat['theta'].shape[-1]
fig1, axes = plt.subplots(1,1,figsize=(8,6))
axes.set_ylabel(r'$\theta$',fontsize=18)
t = dat['times']
theta = dat['theta']
P = dat['P_theta']
col = cycle(['C0', 'C1', 'C2', 'C3','C4'])
ls = cycle(['-', '-', '--', '--', ':', ':', '-.', '-.'])
2021-03-22 10:22:00 +01:00
legends = cycle(labels)
2021-06-09 12:35:12 +02:00
if meas_flag:
t_und = t[0::30]
t_und = np.append( t_und , [t[-1]])
meas_mark = t_und*0
2020-12-16 18:41:44 +01:00
col_ = next(col)
ls_ = next(ls)
legends_=next(legends)
if dim == 1:
theta = theta.reshape((-1, 1))
P = P.reshape((-1, 1, 1))
2021-06-09 12:35:12 +02:00
2020-12-16 18:41:44 +01:00
2021-06-09 12:35:12 +02:00
idx = 0
idc = 0
for i in range(len(ids)):
2021-03-29 10:45:02 +02:00
cur_key = ids[i]
2021-06-09 12:35:12 +02:00
true_level = np.log(true_values[ids[i]]/current_val[i])/np.log(2)
rec_value = np.round(2**theta[-1, idx]*current_val[i],2)
#curve = theta[:,i] + line_split*i
#dash_curve = line_split*i + t*0 + true_level
curve = theta[:,idx] + line_split*idx - true_level
dash_curve = line_split*idx + t*0
axes.plot(t, curve , '-', color=col_,label= legends_ + '= ' + str(rec_value) + '/' + str(true_values[cur_key]) + '$')
axes.fill_between(t, curve - np.sqrt(P[:, idx, idx]), curve + np.sqrt(P[:, idx, idx]), alpha=0.3, color=col_)
legends_=next(legends)
axes.plot(t, dash_curve , color=col_,ls='--')
if RC_mod:
2020-12-16 18:41:44 +01:00
2021-06-09 12:35:12 +02:00
if i<len(current_val_C):
true_level_C = np.log(true_values_C[ids[i]]/current_val_C[i])/np.log(2)
rec_value_C = np.round(2**theta[-1, idc]*current_val_C[idc],6)
curve_C = theta[:,idx+1] + line_split*(idx+1) - true_level_C
dash_curve_C = line_split*(idx+1) + t*0
#print(true_values_C[cur_key_C])
axes.plot(t, curve_C , '-', color=col_,label= legends_ + '= ' + str(rec_value_C) + '/' + str(true_values_C[cur_key]) + '$')
axes.fill_between(t, curve_C - np.sqrt(P[:, idx+1, idx+1]), curve_C + np.sqrt(P[:, idx+1, idx+1]), alpha=0.3, color=col_)
axes.plot(t, dash_curve_C , color=col_,ls='--')
legends_=next(legends)
idx +=1
idc +=1
if meas_flag:
axes.plot(t_und, meas_mark + line_split*idx, marker = 'x', color='red')
2020-12-16 18:41:44 +01:00
col_ = next(col)
2021-06-09 12:35:12 +02:00
idx +=1
2020-12-16 18:41:44 +01:00
axes.legend(fontsize=14,loc='lower right')
axes.set_xlim([-0.01,0.81])
axes.set_xlabel(r'time (s)',fontsize=18)
# print('theta_peak: \t {}'.format(theta[round(len(theta)/2), :]))
print('Final value theta: \t {}'.format(theta[-1, :]))
print('Deparameterized: 2^theta_end: \t {}'.format(2**theta[-1, :]))
2021-03-24 17:00:14 +01:00
print('Real values: \t {}'.format(true_values))
2021-06-09 12:35:12 +02:00
#print('Recon values: \t {a}:{b} '.format(a=ids[:],b=np.round(2**theta[-1, :]*current_val,2)))
2020-12-16 18:41:44 +01:00
plt.savefig('windk_res')
if not is_ipython():
plt.show()
def get_parser():
parser = argparse.ArgumentParser(
description='''
Plot the time evolution of the ROUKF estimated parameters.
To execute in IPython::
%run plot_roukf_parameters.py [-d] [-r N [N \
...]] file
''',
formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument('file', type=str, help='path to ROUKF stats file')
parser.add_argument('-d', '--deparameterize', action='store_true',
help='deparameterize the parameters by 2**theta')
parser.add_argument('-r', '--ref', metavar='N', nargs='+', default=None,
type=float, help='Reference values for parameters')
return parser
if __name__ == '__main__':
args = get_parser().parse_args()
dat = load_data(args.file)
2021-03-17 19:47:23 +01:00
plot_parameters(dat, args.file,deparameterize=args.deparameterize, ref=args.ref)