-
Notifications
You must be signed in to change notification settings - Fork 0
/
common.py
4265 lines (3662 loc) · 139 KB
/
common.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
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import Mix as mix
import read_data as rd
import ControlPlot as cpr
import ymath
import curve as crv
import write_data as wr
import zf_gam as zf
import ITG_gamma as itg
import transport
import equil_profiles
import Distribution as distribution
import MPR
import gam_theory
import gam_exp
import Geom as geom
import fields3d
import arbitrary_data as ARD
import Global_variables as GLO
import ivis.ivis as ivis
import numpy as np
import scipy.signal
from scipy.stats import norm as stat_norm
import pywt
from scipy import constants
from scipy import interpolate
import h5py as h5
from matplotlib import animation
import matplotlib.pyplot as mpl
from IPython.display import HTML
def reload():
# Important: put here all modules that you want to reload
mix.reload_module(mix)
mix.reload_module(rd)
mix.reload_module(cpr)
mix.reload_module(ymath)
mix.reload_module(crv)
mix.reload_module(wr)
mix.reload_module(zf)
mix.reload_module(itg)
mix.reload_module(transport)
mix.reload_module(equil_profiles)
mix.reload_module(distribution)
mix.reload_module(MPR)
mix.reload_module(gam_theory)
mix.reload_module(gam_exp)
mix.reload_module(geom)
mix.reload_module(fields3d)
mix.reload_module(ARD)
mix.reload_module(GLO)
mix.reload_module(ivis)
def choose_vars(oo):
def x1x2_format(vv, xx1, xx2):
vv['x1'], vv['fx1'], vv['labx'] = xx1[0], xx1[1], xx1[2]
vv['x2'], vv['fx2'], vv['laby'] = xx2[0], xx2[1], xx2[2]
if 'signals' not in oo:
oo_signals = [oo.get('signal', None)]
else:
oo_signals = oo.get('signals', [])
count_signal, vvars = -1, []
for one_signal in oo_signals:
count_signal += 1
# choose type of the signal
opt_type = one_signal['type']
ref_module = None
if opt_type == 'zonal':
ref_module = zf
elif opt_type == 'transport':
ref_module = transport
elif opt_type == 'nonzonal':
ref_module = itg
elif opt_type == 'equ-profile':
ref_module = equil_profiles
elif opt_type == 'fields3d':
ref_module = fields3d
elif opt_type.lower() == 'distribution':
ref_module = distribution
elif opt_type.lower() == 'mpr':
ref_module = MPR
elif opt_type.lower() == 'arbitrary':
ref_module = ARD
else:
mix.error_mes('Wrong signal type.')
# choose coordinate system, where the signal will be considered:
opt_plane = one_signal['plane']
vvar_plane = None
if opt_plane == 'ts':
vvar_plane = ref_module.choose_one_var_ts(one_signal)
x1x2_format(vvar_plane,
['t', '{:0.3e}', 't'],
['s', '{:0.3f}', 's'])
elif opt_plane == 'tchi':
vvar_plane = ref_module.choose_one_var_tchi(one_signal)
x1x2_format(vvar_plane,
['t', '{:0.3e}', 't'],
['chi', '{:0.3f}', '\chi'])
elif opt_plane == 'tvpar':
vvar_plane = ref_module.choose_one_var_tvpar(one_signal)
x1x2_format(vvar_plane,
['t', '{:0.3e}', 't'],
['vpar', '{:0.3f}', 'v_{\parallel}'])
elif opt_plane == 'tnone':
vvar_plane = ref_module.choose_one_var_t(one_signal)
x1x2_format(vvar_plane,
['t', '{:0.3e}', 't'],
[None, None, None])
elif opt_plane == 'vparmu':
vvar_plane = ref_module.choose_one_var_vparmu(one_signal)
x1x2_format(vvar_plane,
['mu', '{:0.3f}', '\mu'],
['vpar', '{:0.3f}', 'v_{\parallel}'])
elif opt_plane == 'rz':
vvar_plane = ref_module.choose_one_var_rz(one_signal)
x1x2_format(vvar_plane,
['r', '{:0.3f}', 'R'],
['z', '{:0.3f}', 'Z'])
elif opt_plane == 'schi':
vvar_plane = ref_module.choose_one_var_rz(one_signal)
x1x2_format(vvar_plane,
['s', '{:0.3f}', 's'],
['chi', '{:0.3f}', '\chi'])
elif opt_plane == 'xy':
vvar_plane = ref_module.choose_one_var_xy(one_signal)
x1x2_format(vvar_plane,
[vvar_plane['x1_name'], vvar_plane['x1_format'], vvar_plane['x1_label']],
[vvar_plane['x2_name'], vvar_plane['x2_format'], vvar_plane['x2_label']],
)
elif opt_plane == 'xnone':
vvar_plane = ref_module.choose_one_var_x(one_signal)
x1x2_format(vvar_plane,
[vvar_plane['x1_name'], vvar_plane['x1_format'], vvar_plane['x1_label']],
[None, None, None],
)
else:
mix.error_mes('Wrong name of plane.')
# set reference signal:
one_signal.update({'flag_var_first': True}) if count_signal == 0 else \
one_signal.update({'flag_var_first': False})
if one_signal['flag_var_first'] and 'x2' in vvar_plane:
oo.update({vvar_plane['x1'] + '_ref': vvar_plane[vvar_plane['x1']]})
if vvar_plane['x2'] is not None:
oo.update({vvar_plane['x2'] + '_ref': vvar_plane[vvar_plane['x2']]})
# averaging of the chosen signal
vvar = ymath.avr_x1x2(vvar_plane, one_signal, oo)
# signal legend
pr_name = one_signal['dd']['project_name'] if 'dd' in one_signal else ''
pr_name += ':\ ' if pr_name is not '' else ''
vvar['leg'] = pr_name + vvar['line_avr'] + ':\ ' + vvar['tit']
# save signal
vvars.append(vvar)
return vvars
def plot_vars_2d(oo, fig=None, axs=None):
oo_use = dict(oo)
# correct averaging parameter
if 'signal' not in oo:
mix.error_mes('there is not a field \'signal\' to plot.')
signal = dict(oo.get('signal', None))
signal['avr_operation'] = 'none-'
oo_use.update({'signals': [signal]})
vvar = choose_vars(oo_use)[0]
# additional data:
ff = dict(oo.get('ff', GLO.DEF_PLOT_FORMAT)) # dictionary with format
sel_norm_x = oo.get('sel_norm_x', None)
sel_norm_y = oo.get('sel_norm_y', None)
oo_text = oo.get('text', [])
geoms = oo.get('geoms', [])
dd = signal['dd'] if 'dd' in signal else None
# postprocessing must be defined for only one signal,
# it must have a following structure: [{}, {}, ...]
oo_postprocessing = oo.get('oo_postprocessing', None)
flag_plot = oo.get('flag_plot', True)
# additional curves to plot:
curves_to_add = oo.get('curves_to_add', None)
# normalization
dict_norm = mix.normalization(sel_norm_x, dd)
coef_x_norm, line_x_norm = dict_norm['coef_norm'], dict_norm['line_norm']
dict_norm = mix.normalization(sel_norm_y, dd)
coef_y_norm, line_y_norm = dict_norm['coef_norm'], dict_norm['line_norm']
# title
if ff['title'] is not None:
ff['title'] = ff['title'] if len(ff['title']) != 0 else vvar['leg']
# xlabel and ylabel
if ff['xlabel'] is not None:
ff['xlabel'] += line_x_norm
if ff['ylabel'] is not None:
ff['ylabel'] += line_y_norm
# get grids and a variable
name_x1, name_x2 = vvar['x1'], vvar['x2']
if name_x1.lower() == 'r' and name_x2.lower() == 'z':
name_x1, name_x2 = 's', 'chi'
data, x1, x2 = vvar['data'], vvar[name_x1], vvar[name_x2]
# post-processing
data, x1, name_x1, x2, name_x2 = \
ymath.post_processing_2d(data, x1, x2,
name_x1, name_x2, oo_postprocessing)
# create curves:
curves = crv.Curves().set_ff(ff)
# original or cartesian 2d grid:
if vvar['x1'].lower() == 'r' and vvar['x2'].lower() == 'z':
_, ids_s = mix.get_array_oo(oo, x1, 's')
chi_start = oo.get('chi_start', 0)
if chi_start >= 0:
_, ids_chi = mix.get_array_oo(oo, x2, 'chi')
x1 = mix.get_slice(vvar['r'], ids_chi, ids_s)
x2 = mix.get_slice(vvar['z'], ids_chi, ids_s)
data = mix.get_slice(data, ids_s, ids_chi)
else:
# chi_end ahs to be positive:
chi_end = oo.get('chi_end', 2*np.pi)
_, ids_chi_part1 = mix.get_array(x2, 2*np.pi + chi_start, 2*np.pi)
_, ids_chi_part2 = mix.get_array(x2, 0, chi_end)
x1_part1 = mix.get_slice(vvar['r'], ids_chi_part1, ids_s)
x2_part1 = mix.get_slice(vvar['z'], ids_chi_part1, ids_s)
x1_part2 = mix.get_slice(vvar['r'], ids_chi_part2, ids_s)
x2_part2 = mix.get_slice(vvar['z'], ids_chi_part2, ids_s)
x1 = np.concatenate((x1_part1, x1_part2), axis=0)
x2 = np.concatenate((x2_part1, x2_part2), axis=0)
data_part1 = mix.get_slice(data, ids_s, ids_chi_part1)
data_part2 = mix.get_slice(data, ids_s, ids_chi_part2)
data = np.concatenate((data_part1, data_part2), axis=1)
if dd['flag_equB_mult']:
coef_R = dd['R0-axis'] # for AUG
else:
coef_R = 1 # for TCV
x1 = x1/dd['d_norm'] * coef_R
x2 = x2/dd['d_norm']
elif 'x' in vvar:
if np.ndim(vvar['x']) > 1:
pass
else:
x1, ids_x1 = mix.get_array_oo(oo, x1, name_x1)
x2, ids_x2 = mix.get_array_oo(oo, x2, name_x2)
data = mix.get_slice(data, ids_x1, ids_x2)
# additional text and geometrical figures:
curves.newt(oo_text)
curves.newg(geoms)
# plot
curves.new().XS(x1 * coef_x_norm).YS(x2 * coef_y_norm).ZS(data)
curves.load(curves_to_add)
# styling
for id_curve, one_curve in enumerate(curves.list_curves):
ff_curve = dict(GLO.DEF_CURVE_FORMAT)
for field_curve in ff_curve.keys():
temp = ff.get(field_curve+'s', [])
if len(temp) > id_curve:
ff_curve[field_curve] = temp[id_curve]
else:
if one_curve.ff[field_curve] != ff_curve[field_curve]:
ff_curve[field_curve] = one_curve.ff[field_curve]
one_curve.set_ff(ff_curve)
# plot curve
if not flag_plot:
return curves
if flag_plot:
# fig, axs, css = cpr.plot_curves_3d(curves, fig, axs)
fig, axs, css = ivis.plot_data(curves, fig, axs)
# return fig, axs, css
return None
return None
# def animation_2d(oo_anim, oo):
# def update_frame(num, fig, axs, css):
# signal_current = dict(signal_ref)
#
# # +1 since the first time moment has been already considered
# signal_current['t-point'] = ts[num+1]
#
# oo_current = dict(oo)
# oo_current['signal'] = signal_current
# fig, axs, css = plot_vars_2d(oo_current, fig, axs)
#
# return css[0],
#
# # array and initila signal description
# ts = oo_anim['t']
# signal_ref = oo['signal']
#
# # create an initial figure:
# signal_current = dict(signal_ref)
# signal_current['t-point'] = ts[0]
#
# oo_current = dict(oo)
# oo_current['signal'] = signal_current
# fig, axs, css = plot_vars_2d(oo_current)
#
# anim = animation.FuncAnimation(
# fig, func=update_frame, fargs=(fig, axs, css),
# frames=len(ts)-1,
# interval=50, blit=False,
# repeat=False
# )
#
# fig.show()
# HTML(anim.to_html5_video())
def plot_vars_1d(oo):
# signals to plot
vvars = choose_vars(oo)
signals = oo.get('signals', [])
n_vars = len(vvars)
# - additional data -
ff = dict(oo.get('ff', GLO.DEF_PLOT_FORMAT)) # format
oo_text = oo.get('text', [])
geoms = oo.get('geoms', [])
sel_norm_x = oo.get('sel_norm_x', None)
sel_norm_ys = oo.get('sel_norm_ys', [None])
oo_postprocessing = oo.get('oo_postprocessing', None)
flag_plot = oo.get('flag_plot', True)
# normalization (first stage):
line_x_norm = mix.normalization(sel_norm_x)['line_norm']
line_y_norm = mix.normalization(sel_norm_ys[0])['line_norm'] \
if len(sel_norm_ys) == 1 else ''
if len(sel_norm_ys) == 1:
sel_norm_ys = [sel_norm_ys[0]] * n_vars
# XY labels
if ff['xlabel'] is not None:
ff['xlabel'] += line_x_norm
if ff['ylabel'] is not None:
ff['ylabel'] += line_y_norm
# Create a plot
curves = crv.Curves().set_ff(ff)
# additional text and geometrical figures:
curves.newt(oo_text)
curves.newg(geoms)
# styles, colors, legends
stys = ff.get('styles', [])
colors = ff.get('colors', [])
legends = ff.get('legends', [])
flags_hist = ff.get('flags_hist', None)
# - different variables -
for ivar in range(n_vars):
vvar = vvars[ivar]
data = vvar['data']
if data is None:
continue
x = np.array(vvar['x'])
x_err = vvar.get('x_err', None)
y_err = vvar.get('y_err', None)
leg = vvar['leg']
dd_one = signals[ivar]['dd'] if 'dd' in signals[ivar] else None
oo_var_operations = oo_postprocessing[ivar] \
if oo_postprocessing is not None else None
# curve format
ff_curve = dict(GLO.DEF_CURVE_FORMAT)
# different flags:
if flags_hist is not None:
ff_curve['flag_hist'] = flags_hist[ivar]
# normalization (second stage):
coef_x_norm = 1
if not ff_curve['flag_hist']:
coef_x_norm = mix.normalization(sel_norm_x, dd_one)['coef_norm']
sel_norm_y = sel_norm_ys[ivar] if ivar < len(sel_norm_ys) else None
temp_dict = mix.normalization(sel_norm_y, dd_one)
line_leg_norm = temp_dict['line_norm']
coef_y_norm = temp_dict['coef_norm']
# - post-processing -
if not ff_curve['flag_hist']:
data, x = ymath.post_processing(data, x, oo_var_operations)
# domain of plotting:
# add x_end, x_start in your option
# to change limits of plots with rescaling of the plot
if not ff_curve['flag_hist']:
x, ids_x = mix.get_array_oo(oo, x, 'x')
data = mix.get_slice(data, ids_x)
# x normalization
if not ff_curve['flag_hist']:
x = x * coef_x_norm
data = data * coef_y_norm
# style, color
ff_curve['style'] = stys[ivar] if ivar < len(stys) else None
ff_curve['color'] = colors[ivar] if ivar < len(colors) else None
# legend
one_leg = \
leg + [line_leg_norm] if isinstance(leg, list) else \
leg + line_leg_norm
ff_curve['legend'] = legends[ivar] if len(legends) > ivar else one_leg
# - add a new curve -
curves.new().XS(x).YS(data).set_ff(ff_curve)
if x_err is not None or y_err is not None:
curves.list_curves[-1].set_errorbar(True, ys=y_err, xs=x_err)
# - plot the curves -
if len(curves.list_curves) is not 0 and flag_plot:
# cpr.plot_curves(curves)
ivis.plot_data(curves)
if not flag_plot:
return curves
else:
return None
def plot_several_curves(oo):
list_curves = oo.get('list_curves', None)
if list_curves is None:
return
flag_subplots = oo.get('flag_subplots', False)
flag_3d = oo.get('flag_3d', False)
flag_mix = oo.get('flag_mix', False)
# combine all plots
curves_result = crv.Curves()
if not flag_subplots:
count_element = -1
curves_ref = None
for current_curves in list_curves:
count_element += 1
if count_element == 0:
curves_ref = current_curves
curves_result.load(current_curves)
# set styling:
ff = dict(oo.get('ff', curves_ref.ff))
curves_result.set_ff(ff)
# styling
for id_curve, one_curve in enumerate(curves_result.list_curves):
ff_curve = dict(GLO.DEF_CURVE_FORMAT)
for field_curve in ff_curve.keys():
temp = ff.get(field_curve + 's', [])
if len(temp) > id_curve:
ff_curve[field_curve] = temp[id_curve]
else:
if one_curve.ff[field_curve] != ff_curve[field_curve]:
ff_curve[field_curve] = one_curve.ff[field_curve]
one_curve.set_ff(ff_curve)
# plot curves
if len(curves_result.list_curves) is not 0:
if not flag_3d:
cpr.plot_curves(curves_result)
else:
cpr.plot_curves_3d(curves_result)
else:
ncols = oo.get('ncols', 1)
nrows = oo.get('nrows', 1)
sel_colorbar_subplots = oo.get('sel_colorbar_subplots', 'none')
id_ref_subplot = oo.get('id_ref_subplot', 0)
ff_global = oo.get('ff', dict(GLO.DEF_PLOT_FORMAT))
curves_result.set_ff(ff_global)
curves_result.create_sub(
ncols, nrows,
selector_colorbar_subplots=sel_colorbar_subplots,
id_reference_subplot=id_ref_subplot
)
# different Curves objects from the list_curves
# are put consequently to the subplot matrix COLUMN by COLUMN:
count_curves = -1
for id_col in range(ncols):
for id_row in range(nrows):
count_curves += 1
if count_curves < len(list_curves):
curves_result.put_sub(
list_curves[count_curves], id_col, id_row
)
else:
break
if flag_mix:
cpr.plot_curves_mix(curves_result)
else:
if not flag_3d:
cpr.plot_curves(curves_result)
else:
cpr.plot_curves_3d(curves_result)
def fft_in_time(oo):
# Signal: should be 1d
signal = dict(oo.get('signals', None)[0])
vvar = choose_vars(oo)[0]
dd_one = signal['dd'] if 'dd' in signal else None
ff = dict(oo.get('ff', GLO.DEF_PLOT_FORMAT)) # format
# post-processing has to be define for only one signal ->
# structure is [{}, {}, ...]
oo_postprocessing = oo.get('oo_postprocessing', None)
# data to define FFT:
flag_data_shifted = oo.get('flag_data_shifted', False)
width_x = oo.get('width_x', None)
w_norm_domain = oo.get('w_norm_domain', None)
sel_norm_w = oo.get('sel_norm_w', 'wc')
# domain where FFT will be performed,
# this domain does not influence
# the domain where postprocessing is perfomed
x_fft_domain = oo.get('x_fft_domain', None)
# - frequency normalization (notation) -
coef_norm_w, _, line_norm_w, _ = mix.choose_wg_normalization(sel_norm_w, dd_one)
# consider every variable
x = vvar['x']
data = vvar['data']
leg = vvar['leg']
# - post-processing -
data_post, x_post = ymath.post_processing(data, x, oo_postprocessing)
data_post = np.interp(x, x_post, data_post)
del x_post
# shifted signal:
if flag_data_shifted:
data_shifted = data - data_post
else:
data_shifted = data_post
# x-domain, where the FFT will be performed:
if x_fft_domain is None:
x_fft_domain = np.array(x)
ids_x_work, x_work, _ = mix.get_ids(x, x_fft_domain)
ids_x_work = np.arange(ids_x_work[0], ids_x_work[-1] + 1)
data_work = data_shifted[ids_x_work]
# get frequency grid
_, x_interval, _ = mix.get_ids(x_work, [0, width_x])
w = ymath.fft_y(x_interval)['w']
# Time evolution of the Fourier transform:
res_fft = np.zeros([len(x_work), np.size(w)])
res_fft.fill(np.nan)
for id_x in range(np.size(x_work)):
x_right_bound = x_work[id_x] + width_x
if x_right_bound > x_work[-1]:
continue
ids_x_interval, x_interval, _ = \
mix.get_ids(x_work, [x_work[id_x], x_right_bound])
ids_x_interval = np.arange(ids_x_interval[0], ids_x_interval[-1] + 1)
res_fft[id_x, :] = ymath.fft_y(x_interval, data_work[ids_x_interval])['f']
res_fft = res_fft[np.logical_not(np.isnan(res_fft))]
res_fft = np.reshape(res_fft, (-1, np.size(w)))
# working frequency domain
ids_w_work, w_norm_work, _ = mix.get_ids(w * coef_norm_w, w_norm_domain)
ids_w_work = np.arange(ids_w_work[0], ids_w_work[-1] + 1)
fft_work = res_fft[:, ids_w_work]
# x domain of plotting
x_work_domain = x_work[0:np.shape(res_fft)[0]]
x_work_plot, ids_x_plot = mix.get_array_oo(oo, x_work_domain, 'x')
ids_x_plot = np.arange(ids_x_plot[0], ids_x_plot[-1] + 1)
fft_plot = fft_work[ids_x_plot, :]
del ids_x_plot
data_orig_plot, x_plot = mix.get_x_data_interval(x_work_domain, x, data)
data_post_plot, _ = mix.get_x_data_interval(x_work_domain, x, data_post)
data_shifted_plot, _ = mix.get_x_data_interval(x_work_domain, x, data_shifted)
del x_work_domain
# --- PLOT x-evolution of the signal ---
nsignals = 3 # original, treated, shifted
# signals:
ch_signals = GLO.create_signals_dds(
GLO.def_arbitrary_1d,
[dd_one] * nsignals,
flag_arbitrary=True,
xs=[x_plot] * nsignals,
datas=[data_orig_plot, data_post_plot, data_shifted_plot],
)
# styling:
ff_x = dict(ff)
ff_x.update({
'legends': ['original', 'treated', 'original - treated'],
'title': leg,
'styles': ['-', ':', ':'],
'xlabel': vvar['labx'],
'ylabel': 'original\ signal',
})
# plotting:
oo_plot_x = dict(oo)
oo_plot_x.update({
'signals': ch_signals,
'ff': ff_x,
})
plot_vars_1d(oo_plot_x)
# --- PLOT FFT ---
ch_signal = GLO.create_signals_dds(
GLO.def_arbitrary_2d,
[dd_one],
flag_arbitrary=True,
xs=[x_work_plot],
ys=[w_norm_work],
datas=[fft_plot],
)[0]
# styling:
ff_fft = dict(ff)
ff_fft.update({
'title': 'FFT:\ ' + leg,
'xlabel': vvar['labx'],
'ylabel': ff['ylabel-w'] + line_norm_w,
})
# plotting:
oo_plot_fft = dict(oo)
oo_plot_fft.update({
'signal': ch_signal,
'ff': ff_fft,
})
plot_vars_2d(oo_plot_fft)
def wg_in_time(oo):
# options
oo_wg = oo.get('oo_wg', None)
ff = dict(oo.get('ff', GLO.DEF_PLOT_FORMAT))
signal = oo.get('signal', None)
dd = signal['dd']
flag_plot_spectrogram = oo.get('flag_plot_spectrogram', True)
name_spectrogram = oo.get('name_spectrogram', 'spectrogram')
# to calculate relative spetrogram: w/w0
flag_rel_freq = oo.get('flag_rel_freq', False)
# to calculate spectrogram of a shifted signal:
# (data - data_postproc)
flag_data_shifted = oo.get('flag_data_shifted', False)
# post-processing has to be define for only one signal ->
# structure is [{}, {}, ...]
oo_postprocessing = oo.get('oo_postprocessing', None)
# parameters of nonlinear fitting
flag_stat = oo_wg.get('flag_stat', False)
sel_wg = oo_wg.get('sel_wg', 'wg-adv')
# define a name of the method used for w,g calculation
line_res_method = '_adv' if 'adv' in sel_wg else '_est'
line_res = 'naive'
if flag_stat:
line_res = 'stat'
line_res_method = ''
# define frequency label according to its normalization
_, _, line_norm_w, _ = mix.choose_wg_normalization(
oo_wg.get('sel_norm_wg', GLO.DEF_NORM_WG), dd
)
# read variable
dict_var = choose_vars(oo)[0]
data_init, t = dict_var['data'], dict_var['x']
# create time intervals:
oo_t = oo['oo_t']
tmin, tmax = oo_t['tmin'], oo_t['tmax']
t_ints = mix.create_consequent_time_intervals(oo_t)
nt = len(t_ints)
t_centers = [t_int[0] + (t_int[1] - t_int[0]) / 2. for t_int in t_ints]
# initial data (in a working domain between tmin and tmax)
data_init, t = mix.get_x_data_interval(
[tmin, tmax], t, data_init
)
# - post-processing -
data_post, t_post = ymath.post_processing(data_init, t, oo_postprocessing)
data_post = np.interp(t, t_post, data_post)
del t_post
# shifted signal:
data_shifted = (data_init - data_post) if flag_data_shifted \
else data_post
# --- PLOT TIME EVOLUTION OF SIGNALS ---
nsignals = 3 # original, treated, shifted
# signals:
ch_signals = GLO.create_signals_dds(
GLO.def_arbitrary_1d,
[dd] * nsignals,
flag_arbitrary=True,
xs=[t] * nsignals,
datas=[data_init, data_post, data_shifted],
)
# styling:
ff_x = dict(ff)
ff_x.update({
'legends': ['original', 'treated', 'original - treated'],
'title': dict_var['leg'],
'styles': ['-', ':', ':'],
'xlabel': dict_var['labx'],
'ylabel': 'original\ signal',
})
# plotting:
oo_plot_x = {
'signals': ch_signals,
'ff': ff_x,
'sel_norm_x': oo.get('sel_norm_x', None),
}
plot_vars_1d(oo_plot_x)
# --- PLOT FFT OF SIGNALS ---
# signals are the same
# styling
ff_x = dict(ff_x)
ff_x.update({
'title': 'FFT\ of\ ' + dict_var['leg'],
'xlabel': '\omega'
})
# postprocessing:
post_var = [dict(GLO.DEF_OPERATION_FFT_1D)]
oo_post_current = [post_var] * nsignals
# plotting:
oo_plot_x = {
'signals': ch_signals,
'ff': ff_x,
'sel_norm_x': None,
'oo_postprocessing': oo_post_current,
}
plot_vars_1d(oo_plot_x)
# --- CALCULATION of w(t) ---
ws, ws_err = np.zeros(nt), np.zeros(nt)
gs, gs_err = np.zeros(nt), np.zeros(nt)
ws[:], ws_err[:] = [np.nan]*2
for i_int in range(nt):
oo_wg.update({'t_work': t_ints[i_int]})
# signal
ch_signal = GLO.create_signals_dds(
GLO.def_arbitrary_1d, [dd],
flag_arbitrary=True,
datas=[data_shifted],
xs=[t]
)[0]
# styling
ff_wg = dict(GLO.DEF_PLOT_FORMAT)
ff_wg['flag_plot_print'] = False
# calculation
oo_calc = dict(oo)
oo_calc.update({
'signal': ch_signal,
'ff': ff_wg,
})
res_wg = calc_wg(oo_calc, oo_wg)
if flag_stat:
ws_err[i_int] = res_wg[line_res]['err_w']
gs_err[i_int] = res_wg[line_res]['err_g']
ws[i_int] = res_wg[line_res]['w' + line_res_method]
# --- PLOT SPECTROGRAM ---
data_w = ws if not flag_rel_freq else ws/ws[0]
data_w_err = ws_err if not flag_rel_freq else ws_err/ws[0]
line_w = '\omega' + line_norm_w if not flag_rel_freq \
else '\omega/\omega_{0}'
# signals:
ch_signals = GLO.create_signals_dds(
GLO.def_arbitrary_1d,
[dd],
flag_arbitrary=True,
xs=[t_centers],
datas=[data_w],
ys_err=[data_w_err],
)
# styling:
ff_x = dict(ff)
ff_x.update({
'legends': [name_spectrogram],
'title': dict_var['leg'],
'styles': ff.get('styles', ['o:']),
'xlabel': dict_var['labx'],
'ylabel': line_w,
})
# plotting:
oo_plot_x = {
'signals': ch_signals,
'ff': ff_x,
'sel_norm_x': oo.get('sel_norm_x', 'wc'),
'flag_plot': flag_plot_spectrogram,
}
curve_spectrogram = plot_vars_1d(oo_plot_x)
return curve_spectrogram
def calc_wg(oo, oo_wg):
# -------------------------------------------------------------------------------
# -> oo_var - dictionary to choose a variable
# (input dict. for the function choose_vars(...))
# -------------------------------------------------------------------------------
# -> oo_wg - dictionary with parameters to calculate frequency and dynamic rate:
# 't_work' - work time domain
# 'sel_wg' - line, name of a method to calculate frequency and rate:
# 'wg-adv', 'w-adv', 'g-adv', 'wg-est', 'w-est', 'g-est'
# 'flag_two_stages' = True:
# Firstly, one calculates gamma,
# then create a signal = initial_signal * exp(-gamma*t) and
# calculate the frequency
# False:
# calculate gamma and frequency from the initial_signal
# 'sel_norm': 'wc', 'vt', 'khz':
# output normalization
# ---
# 'flag_stat' = True:
# calculate errorbars
# 'n_samples' - integer:
# number of time interval variations
# 'min_n_peaks' - integer:
# minimum number of peaks in one time interval
# 'threshold_w' - float:
# relative difference between estimated (linear fitting) value of frequency
# (w_est) and
# frequency value found from NL fitting (w_adv),
# if |(w_adv - w_est)/w_est| <= threshold_w, then we are taking w_adv as
# a result frequency, otherwise we don't take any value
# 'threshold_g' - float:
# the same as threshold_w, but for the damping rate
# ---
# - FILTERING -
# -> If 'flag_two_stages' = True, there are three stages of the filtering:
# global, for gamma, for frequency;
# -> Globally filtered signal is a starting signal for the calculation of the
# both gamma and frequency;
# -> After that, globally filtered signal can be filtered separately
# before the calculation of the gamma and before the calc. of the frequency
# -> If 'flag_two_stages' = False, there is only global filtering
# 'filt_global' - dict. or [dict., dict., ...]:
# global filtering
# 'filt_gamma' - dict. or [dict., dict., ...]:
# additional filtering of the globally filtered signal
# before the calculation of the gamma
# 'filt_freq' - dict. or [dict., dict., ...]:
# additional filtering of the globally filtered signal
# before the calculation of the frequency
# -> For the description of these dictionaries, see the function ymath.filtering
# -------------------------------------------------------------------------------
# -> oo_plot - dictionary for plotting:
# 't_plot' - domain of plotting;
# 'flag_norm' = True: normalized plots;
# 'flag_semilogy' = True: Y-axis in logarithmic scale;
# 'flag_plot_print' = True: plot results and print values on screen
# -------------------------------------------------------------------------------
# - None-filter -
non_filt = GLO.NONE_FILTER
out_res = {}
# - FUNCTION: filtering at one stage -
def one_stage_filtering(x, y, oo_filt_loc):
oo_filts_res = []
if oo_filt_loc is None or len(oo_filt_loc) is 0:
oo_filts_res.append(non_filt)
elif isinstance(oo_filt_loc, dict):
oo_filts_res.append(oo_filt_loc)
else:
oo_filts_res = oo_filt_loc # array of filters
# apply one by one the filters in the array :
dict_loc = {'x': np.array(x), 'filt': np.array(y)}
count_filt = -1
for one_filt in oo_filts_res:
count_filt += 1
dict_loc = ymath.filtering(
dict_loc['x'], dict_loc['filt'], one_filt
)
return dict_loc
# - FUNCTION: get result -
def give_res(dict_wg_loc, name_method, name_value, coef_norm):
value_res, err_value = None, None
if dict_wg_loc[name_method] is not None:
value_res = dict_wg_loc[name_method][name_value]
err_value = dict_wg_loc[name_method][name_value + '_err']
# normalization:
if value_res is not None:
value_res *= coef_norm
if err_value is not None:
err_value *= coef_norm
line_value = 'None'
if value_res is not None:
line_value = '{:0.3e}'.format(value_res)
if err_value is not None:
line_value += ' +- {:0.3e}'.format(err_value)
return value_res, line_value
# - FUNCTION: different options of w and g measurement -
def find_wg(t, y, sel_wg, flag_print=True):
res_dict = {}
if sel_wg == 'wg-adv':
res_dict = ymath.advanced_wg(t, y, flag_print=flag_print)
elif sel_wg == 'w-adv':
res_dict = ymath.advanced_w(t, y, flag_print=flag_print)
elif sel_wg == 'g-adv':
res_dict = ymath.advanced_g(t, y, flag_print=flag_print)
elif sel_wg == 'wg-est':
res_dict = {
'est': ymath.estimate_wg(t, y),
'adv': None
}
elif sel_wg == 'w-est':
res_dict = {
'est': ymath.estimate_w(t, y),
'adv': None
}
elif sel_wg == 'g-est':
res_dict = {
'est': ymath.estimate_g(t, y),
'adv': None
}
else:
mix.error_mes('Wrong wg-selector: check oo_wg[''sel_wg'']')
return res_dict
# - project structure -
signal = oo.get('signal', None)
ff = dict(oo.get('ff', dict(GLO.DEF_PLOT_FORMAT)))
flag_plot_print = ff.get('flag_plot_print', True)
dd = signal['dd']
# seperate plots or subplots:
flag_subplots = oo.get('flag_subplots', False)
flag_plot_internal = not flag_subplots
# - choose a variable -
dict_var = choose_vars(oo)[0]