-
Notifications
You must be signed in to change notification settings - Fork 1
/
f_strip.py
1590 lines (1344 loc) · 69.3 KB
/
f_strip.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
# -*- encoding: utf-8 -*-
# This file contains the main functions used in the bachelor thesis of Francesco Andreetto (2020)
# updated to be used on the new version of the pipeline for functional verification of LSPE-STRIP (2024)
# October 29th 2022, Brescia (Italy) - December 5th 2024, Bologna (Italy)
# Libraries & Modules
import h5py
import scipy.signal
import warnings
from astropy.time import Time, TimeDelta
from datetime import datetime
from matplotlib import pyplot as plt
from numba import njit
from pathlib import Path
from scipy.optimize import curve_fit
from striptease import DataFile, DataStorage
from typing import Dict, Any
import csv
import json
import logging
import numpy as np
import scipy.stats as scs
import scipy.ndimage as scn
def binning_func(data_array, bin_length: int):
"""
Operates a binning of the data_array by doing a mean of a number of samples equal to bin_length\n
Parameters:\n
- **data_array** (``list``): array-like object
- **bin_length** (``int``): number of elements on which the mean is calculated\n
"""
# Initialize a new list
new_data_array = []
# Check the dimension of the bin_length
if bin_length <= 1:
logging.warning("If bin_length < 1 it's not a binning operation")
return data_array
if bin_length >= len(data_array):
logging.warning("bin_length is too large for this array to bin.")
return data_array
# Operate the Binning
else:
chunk_n = int(len(data_array) / bin_length)
for i in range(chunk_n):
new_data_array.append(np.mean(data_array[i * bin_length:i * bin_length + bin_length]))
return new_data_array
def csv_to_json(csv_file_path: str, json_file_path):
"""
Convert a csv file into a json file.
Parameters:\n
- **csv_file_path** (``str``): path of the csv file that have to be converted
- **json_file_path** (``str``): path of the json file converted
"""
json_array = []
# read csv file
with open(csv_file_path, encoding='utf-8') as csv_file:
# load csv file data using csv library's dictionary reader
csvReader = csv.DictReader(csv_file)
# convert each csv row into python dict
for row in csvReader:
# add this python dict to json array
json_array.append(row)
# Check if the Json Path exists, if not it is created
# Note: 55 is the number of char of the name of the reports
logging.info(json_file_path)
json_dir = json_file_path[:-55]
logging.info(json_dir)
Path(json_dir).mkdir(parents=True, exist_ok=True)
# convert python json_array to JSON String and write to file
with open(json_file_path, 'w', encoding='utf-8') as json_file:
json_string = json.dumps(json_array, indent=4)
json_file.write(json_string)
def data_plot(pol_name: str,
dataset: dict,
timestamps: list,
start_datetime: str,
begin: int, end: int,
type: str,
even: str, odd: str, all: str,
demodulated: bool, rms: bool,
fft: bool, noise_level: bool,
window: int, smooth_len: int, nperseg: int,
output_plot_dir: str, output_report_dir: str,
show: bool):
"""
Generic function that create a Plot of the dataset provided.\n
Parameters:\n
- **pol_name** (``str``): name of the polarimeter we want to analyze
- **dataset** (``dict``): dictionary containing the dataset with the output of a polarimeter
- **timestamps** (``list``): list containing the Timestamps of the output of a polarimeter
- **start_datetime** (``str``): start time
- **begin**, **end** (``int``): interval of dataset that has to be considered\n
- **type** (``str``): defines the scientific output, *"DEM"* or *"PWR"*\n
- **even**, **odd**, **all** (int): used to set the transparency of the dataset (0=transparent, 1=visible)\n
- **demodulated** (``bool``): if true, demodulated data are computed, if false even-odd-all output are plotted
- **rms** (``bool``) if true, the rms are computed
- **fft** (``bool``) if true, the fft are computed
- **noise_level** (``bool``) if true, 1/f slope and white noise level are plotted on FFT plots computed;
- **window** (``int``): number of elements on which the RMS is calculated
- **smooth_len** (``int``): number of elements on which the mobile mean is calculated
- **nperseg** (``int``): number of elements of the array of scientific data on which the fft is calculated
- **output_plot_dir** (`str`): Path from the pipeline dir to the dir that contains the plots of the analysis
- **output_report_dir** (`str`): Path from the pipeline dir to the dir that contains the reports of the analysis
- **show** (``bool``): *True* -> show the plot and save the figure, *False* -> save the figure only
"""
# Initialize the plot directory
path_dir = ""
# Initialize the name of the plot
name_plot = f"{pol_name} "
# Initialize the marker size in the legend
marker_scale = 2.
# ------------------------------------------------------------------------------------------------------------------
# Step 1: define the operations: FFT, RMS, OUTPUT
# Calculate fft
if fft:
# Update the name of the plot
name_plot += " FFT"
# Update the name of the plot directory
path_dir += "/FFT"
if noise_level and demodulated:
name_plot += "+Noise_Level"
else:
pass
# Calculate rms
if rms:
# Update the name of the plot
name_plot += " RMS"
# Update the name of the plot directory
path_dir += "/RMS"
else:
pass
if not fft and not rms:
# Update the name of the plot directory
path_dir += "/SCIDATA" if demodulated else "/OUTPUT"
# ------------------------------------------------------------------------------------------------------------------
# Step 2: define type of data
# Demodulated Scientific Data vs Scientific Output
if type == "DEM":
# Update the name of the plot
name_plot += " DEMODULATED" if demodulated else f" {type} {EOA(even, odd, all)}"
# Update the name of the plot directory
path_dir += "/DEMODULATED" if demodulated else f"/{type}"
elif type == "PWR":
# Update the name of the plot
name_plot += " TOTPOWER" if demodulated else f" {type} {EOA(even, odd, all)}"
# Update the name of the plot directory
path_dir += "/TOTPOWER" if demodulated else f"/{type}"
else:
logging.error("Wrong type! Choose between DEM or PWR!")
raise SystemExit(1)
# ------------------------------------------------------------------------------------------------------------------
# Step 3: Creating the Plot
# Updating the start datatime for the plot title
begin_date = date_update(n_samples=begin, start_datetime=start_datetime, sampling_frequency=100)
# Creating the figure with the subplots
fig, axs = plt.subplots(nrows=2, ncols=4, constrained_layout=True, figsize=(20, 12))
# Title of the figure
fig.suptitle(f'POL {name_plot}\nDate: {begin_date}', fontsize=14)
logging.info(f"Plot of POL {name_plot}")
# The 4 plots are repeated on two rows (uniform Y-scale below)
for row in range(2):
col = 0 # type: int
for exit in ["Q1", "Q2", "U1", "U2"]:
# Plot Statistics
# Mean
m = ""
# Std deviation
std = ""
# Max Value
max_val = ""
# Min Value
min_val = ""
# Setting the Y-scale uniform on the 2nd row
if row == 1:
# Avoid UserWarning on y-axis log-scale
try:
# Set the y-axis of the current plot as the first of the raw
axs[row, col].sharey(axs[1, 0])
except ValueError as e:
logging.warning(f"{e} "
f"Negative data found in Spectral Analysis (FFT): impossible to use log scale.\n\n")
continue
except Exception as e:
logging.warning(f"{e} "
f"Negative data found in Spectral Analysis (FFT): impossible to use log scale.\n\n")
continue
# ----------------------------------------------------------------------------------------------------------
# Demodulation: Scientific Data
if demodulated:
# Avoid ValueError during Scientific Data Processing
try:
# Creating a dict with the Scientific Data of an exit of a specific type and their new timestamps
sci_data = demodulation(dataset=dataset, timestamps=timestamps,
type=type, exit=exit, begin=begin, end=end)
# --------------------------------------------------------------------------------------------------
# RMS Calculation
if rms:
# Calculate the RMS of the Scientific Data
rms_sd = RMS(sci_data["sci_data"], window=window, exit=exit, eoa=0, begin=begin, end=end)
# ----------------------------------------------------------------------------------------------
# Plot of FFT of the RMS of the SciData DEMODULATED/TOTPOWER
if fft:
# f, s = fourier_transformed(times, values, nperseg, f_max, f_min)
f, s = scipy.signal.welch(rms_sd, fs=50, nperseg=min(len(rms_sd), nperseg),
scaling="spectrum")
axs[row, col].plot(f[f < 25.], s[f < 25.],
linewidth=0.2, marker=".", markersize=2, color="mediumvioletred",
label=f"{name_plot[3:]}")
# ----------------------------------------------------------------------------------------------
# ----------------------------------------------------------------------------------------------
# Plot of RMS of the SciData DEMODULATED/TOTPOWER
else:
# Smoothing of the rms of the SciData. Smooth_len=1 -> No smoothing
rms_sd = mob_mean(rms_sd, smooth_len=smooth_len)
# Calculate Plot Statistics
# Mean
m = round(np.mean(rms_sd), 2)
# Std deviation
std = round(np.std(rms_sd), 2)
# Max value
max_val = round(max(rms_sd), 2)
# Min value
min_val = round(min(rms_sd), 2)
# Plot RMS
axs[row, col].plot(sci_data["times"][begin:len(rms_sd) + begin], rms_sd,
linewidth=0.2, marker=".", markersize=2,
color="mediumvioletred", label=f"{name_plot[3:]}")
# ----------------------------------------------------------------------------------------------
# --------------------------------------------------------------------------------------------------
# --------------------------------------------------------------------------------------------------
# Scientific Data Processing
else:
# Plot of the FFT of the SciData DEMODULATED/TOTPOWER ------------------------------------------
if fft:
f, s = fourier_transformed(times=sci_data["times"][begin:end],
values=sci_data["sci_data"][exit][begin:end],
nperseg=nperseg, f_max=25., f_min=0)
axs[row, col].plot(f, s,
linewidth=0.2, marker=".", markersize=2, color="mediumpurple",
label=f"{name_plot[3:]}")
# Computing Noise Level: WN + 1/f
if noise_level:
# Filter the fft to get the WN level
freq_fil, fft_fil = wn_filter_fft(f[50:], s[50:], mad_number=6.0)
# Create the WN array
wn = np.ones(len(f)) * np.median(fft_fil)
# Filtered the fft to get the 1/f noise curve
x_fil_data, y_fil_data = one_f_filter_fft(f, s)
# Get the fitted y values
y_fit, slope = get_y_fit_data(x_fil_data=x_fil_data, y_fil_data=y_fil_data)
# Get the knee frequency
knee_f = get_knee_freq(x=x_fil_data, y=y_fit, target_y=wn[0])
# Write info on the file only the 2nd time
if row == 1:
# Define the name of the noise report file
noise_report_name = dir_format(f"Noise_Report_{start_datetime}.txt")
# Write the info about the current polarimeter
with open(f"{output_report_dir}/{noise_report_name}", "a") as file:
file.write(f"{pol_name}\t{name_plot[20:]}\t{exit}\t"
f"{np.round(wn[0], 2)}\t"
f"{np.round(slope, 2)}\t"
f"{np.round(knee_f, 2)}\n")
# Plotting the WN and 1/f
# 1/f Fitted
axs[row, col].plot(x_fil_data, y_fit, color="limegreen",
label=f"1/f fitted data. Slope: {np.round(slope, 2)}")
# WN level
axs[row, col].plot(f, wn, color="orange",
label=f"WN level: {np.round(wn[0], 2)} ADU**2/Hz")
# Knee_freq
axs[row, col].plot(knee_f, wn[0], "*", color="black",
label=f"Knee Frequency = {np.round(knee_f, 2)}GHz")
# Set xy scale log
axs[row, col].set_xscale('log')
axs[row, col].set_yscale('log')
# Plot of the SciData DEMODULATED/TOTPOWER -----------------------------------------------------
elif not fft:
# Smoothing of the SciData Smooth_len=1 -> No smoothing
y = mob_mean(sci_data["sci_data"][exit][begin:end], smooth_len=smooth_len)
# Calculate Plot Statistics
# Mean
m = f"= {round(np.mean(y), 2)}"
# Std deviation
std = f"= {round(np.std(y), 2)}"
# Max value
max_val = round(max(y), 2)
# Min value
min_val = round(min(y), 2)
# Plot SciData
axs[row, col].plot(sci_data["times"][begin:len(y) + begin], y,
linewidth=0.2, marker=".", markersize=2,
color="mediumpurple", label=f"{name_plot[3:]}")
# --------------------------------------------------------------------------------------------------
except ValueError as e:
logging.warning(f"{e}. Impossible to process {name_plot}.\n\n")
pass
# ----------------------------------------------------------------------------------------------------------
# ----------------------------------------------------------------------------------------------------------
# Output
else:
# If even, odd, all are equal to 0
if not (even or odd or all):
# Do not plot anything
logging.error("No plot can be printed if even, odd, all values are all 0.")
raise SystemExit(1)
# When at least one in even, odd, all is different from 0
else:
# Avoid ValueError during Scientific Output Processing
try:
# ----------------------------------------------------------------------------------------------
# RMS Calculations
if rms:
rms_even = []
rms_odd = []
rms_all = []
# Calculate the RMS of the Scientific Output: Even, Odd, All
if even:
rms_even = RMS(dataset[type], window=window, exit=exit, eoa=2, begin=begin, end=end)
if odd:
rms_odd = RMS(dataset[type], window=window, exit=exit, eoa=1, begin=begin, end=end)
if all:
rms_all = RMS(dataset[type], window=window, exit=exit, eoa=0, begin=begin, end=end)
# ------------------------------------------------------------------------------------------
# Plot of FFT of the RMS of the Output DEM/PWR
if fft:
if even:
f, s = scipy.signal.welch(rms_even, fs=50, nperseg=min(len(rms_even), nperseg),
scaling="spectrum")
axs[row, col].plot(f[f < 25.], s[f < 25.], color="royalblue",
linewidth=0.2, marker=".", markersize=2,
alpha=even, label=f"Even samples")
if odd:
f, s = scipy.signal.welch(rms_odd, fs=50, nperseg=min(len(rms_odd), nperseg),
scaling="spectrum")
axs[row, col].plot(f[f < 25.], s[f < 25.], color="crimson",
linewidth=0.2, marker=".", markersize=2,
alpha=odd, label=f"Odd samples")
if all:
f, s = scipy.signal.welch(rms_all, fs=100, nperseg=min(len(rms_all), nperseg),
scaling="spectrum")
axs[row, col].plot(f[f < 25.], s[f < 25.], color="forestgreen",
linewidth=0.2, marker=".", markersize=2,
alpha=all, label="All samples")
# ------------------------------------------------------------------------------------------
# ------------------------------------------------------------------------------------------
# Plot of RMS of the Output DEM/PWR
else:
if even:
axs[row, col].plot(timestamps[begin:end - 1:2][:-window - smooth_len + 1],
mob_mean(rms_even, smooth_len=smooth_len)[:-1],
color="royalblue", linewidth=0.2, marker=".", markersize=2,
alpha=even, label="Even Output")
# Plot Statistics
# Mean
m += f"\nEven = {round(np.mean(rms_even), 2)}"
# Std deviation
std += f"\nEven = {round(np.std(rms_even), 2)}"
if odd:
axs[row, col].plot(timestamps[begin + 1:end:2][:-window - smooth_len + 1],
mob_mean(rms_odd, smooth_len=smooth_len)[:-1],
color="crimson", linewidth=0.2, marker=".", markersize=2,
alpha=odd, label="Odd Output")
# Plot Statistics
# Mean
m += f"\nOdd = {round(np.mean(rms_odd), 2)}"
# Std deviation
std += f"\nOdd = {round(np.std(rms_odd), 2)}"
if all != 0:
axs[row, col].plot(timestamps[begin:end][:-window - smooth_len + 1],
mob_mean(rms_all, smooth_len=smooth_len)[:-1],
linewidth=0.2, marker=".", markersize=2,
color="forestgreen", alpha=all, label="All Output")
# Plot Statistics
# Mean
m += f"\nAll = {round(np.mean(rms_all), 2)}"
# Std deviation
std += f"\nAll = {round(np.std(rms_all), 2)}"
# ------------------------------------------------------------------------------------------
# ----------------------------------------------------------------------------------------------
# ----------------------------------------------------------------------------------------------
# Scientific Output Processing
else:
# ------------------------------------------------------------------------------------------
# Plot of the FFT of the Output DEM/PWR
if fft:
if even:
f, s = fourier_transformed(times=timestamps[begin:end - 1:2],
values=dataset[type][exit][begin:end - 1:2],
nperseg=nperseg, f_max=25., f_min=0)
axs[row, col].plot(f, s,
color="royalblue", alpha=even,
linewidth=0.2, marker=".", markersize=2,
label="Even samples")
if odd:
f, s = fourier_transformed(times=timestamps[begin + 1:end:2],
values=dataset[type][exit][begin + 1:end:2],
nperseg=nperseg, f_max=25., f_min=0)
axs[row, col].plot(f, s,
color="crimson", alpha=odd,
linewidth=0.2, marker=".", markersize=2,
label="Odd samples")
if all:
f, s = fourier_transformed(times=timestamps[begin:end],
values=dataset[type][exit][begin:end],
nperseg=nperseg, f_max=25., f_min=0)
axs[row, col].plot(f, s,
color="forestgreen", alpha=all,
linewidth=0.2, marker=".", markersize=2,
label="All samples")
# ------------------------------------------------------------------------------------------
# ------------------------------------------------------------------------------------------
# Plot of the Output DEM/PWR
else:
if not rms:
if even != 0:
axs[row, col].plot(timestamps[begin:end - 1:2][:- smooth_len],
mob_mean(dataset[type][exit][begin:end - 1:2],
smooth_len=smooth_len)[:-1],
color="royalblue", alpha=even,
marker="*", markersize=0.005, linestyle=" ",
label="Even Output")
marker_scale = 1000.
# Plot Statistics
# Mean
m += f"\nEven = {round(np.mean(dataset[type][exit][begin:end - 1:2]), 2)}"
# Std deviation
std += f"\nEven = {round(np.std(dataset[type][exit][begin:end - 1:2]), 2)}"
if odd != 0:
axs[row, col].plot(timestamps[begin + 1:end:2][:- smooth_len],
mob_mean(dataset[type][exit][begin + 1:end:2],
smooth_len=smooth_len)[:-1],
color="crimson", alpha=odd,
marker="*", markersize=0.005, linestyle=" ",
label="Odd Output")
marker_scale = 1000.
# Plot Statistics
# Mean
m += f"\nOdd = {round(np.mean(dataset[type][exit][begin + 1:end:2]), 2)}"
# Std deviation
std += f"\nOdd = {round(np.std(dataset[type][exit][begin + 1:end:2]), 2)}"
if all != 0:
axs[row, col].plot(timestamps[begin:end][:- smooth_len],
mob_mean(dataset[type][exit][begin:end],
smooth_len=smooth_len)[:-1],
color="forestgreen", alpha=all,
marker="*", markersize=0.005, linestyle=" ",
label="All Output")
marker_scale = 1000.
# Plot Statistics
# Mean
m += f"\nAll = {round(np.mean(dataset[type][exit][begin:end]), 2)}"
# Std deviation
std += f"\nAll = {round(np.std(dataset[type][exit][begin:end]), 2)}"
# ------------------------------------------------------------------------------------------
# ----------------------------------------------------------------------------------------------
except ValueError as e:
logging.warning(f"{e}. Impossible to process {name_plot}.\n\n")
pass
# ----------------------------------------------------------------------------------------------------------
# ----------------------------------------------------------------------------------------------------------
# Subplots properties
# ----------------------------------------------------------------------------------------------------------
# Title subplot
title = f'{exit}'
if not fft:
title += f"\n$Mean$:{m}\n$STD$:{std}"
if demodulated:
title += f"\n$Min$={min_val}\n $Max$={max_val}"
axs[row, col].set_title(title, size=12)
# Treat UserWarning as errors to catch them
warnings.simplefilter("ignore", UserWarning)
# X-axis default label
x_label = "Time [s]"
# FFT Plots arrangements
if fft:
x_label = "Frequency [Hz]"
try:
axs[row, col].set_xscale('log')
except ValueError as e:
logging.warning(f"{e} "
f"Negative data found in Spectral Analysis (FFT): impossible to use log scale.\n\n")
continue
except Exception as e:
logging.warning(f"{e} "
f"Negative data found in Spectral Analysis (FFT): impossible to use log scale.\n\n")
continue
# X-axis label
axs[row, col].set_xlabel(f"{x_label}", size=10)
# Y-axis
y_label = "Output [ADU]"
if fft:
y_label = "Power Spectral Density [ADU**2/Hz]"
try:
axs[row, col].set_yscale('log')
except ValueError as e:
logging.warning(f"{e} "
f"Negative data found in Spectral Analysis (FFT): impossible to use log scale.\n\n")
continue
except Exception as e:
logging.warning(f"{e} "
f"Negative data found in Spectral Analysis (FFT): impossible to use log scale.\n\n")
continue
else:
if rms:
y_label = "RMS [ADU]"
# Y-Axis label
axs[row, col].set_ylabel(f"{y_label}", size=10)
# Legend
axs[row, col].legend(loc="lower left", markerscale=marker_scale, fontsize=10)
# Skipping to the following column of the subplot grid
col += 1
# ------------------------------------------------------------------------------------------------------------------
# ------------------------------------------------------------------------------------------------------------------
# Step 4: producing the png file in the correct dir
# Creating the name of the png file: introducing _ in place of white spaces
name_file = dir_format(name_plot)
logging.debug(f"Title plot: {name_plot}, name file: {name_file}, name dir: {path_dir}")
# Output dir path
path = f'{output_plot_dir}/{path_dir}/'
# Checking existence of the dir
Path(path).mkdir(parents=True, exist_ok=True)
try:
# Save the png figure
fig.savefig(f'{path}{name_file}.png')
except ValueError as e:
logging.warning(f"{e}. Impossible to save the pictures.\n\n")
pass
# If true, show the plot on video
if show:
plt.show()
plt.close(fig)
# ------------------------------------------------------------------------------------------------------------------
return 1
def datetime_check(date_str: str) -> bool:
"""
Check if the string is in datatime format "YYYY-MM-DD hh:mm:ss" or not.
Parameters:\n
- **date** (``str``): string with the datetime
"""
date_format = "%Y-%m-%d %H:%M:%S"
try:
datetime.strptime(date_str, date_format)
return True
except ValueError:
return False
def date_update(start_datetime: str, n_samples: int, sampling_frequency: int, ms=False) -> Time:
"""
Calculates and returns the new Gregorian date in which the analysis begins, given a number of samples that
must be skipped from the beginning of the dataset.
Parameters:\n
- **start_datetime** (``str``): start time of the dataset
- **n_samples** (``int``): number of samples that must be skipped\n
- **sampling_freq** (``int``): number of data collected per second
- **ms** (``bool``): if True the new Gregorian date has also milliseconds
"""
# Convert the str in a Time object: Julian Date MJD
jdate = Time(start_datetime).mjd
# A second expressed in days unit
s = 1 / 86_400
# Julian Date increased
jdate += s * (n_samples / sampling_frequency)
# New Gregorian Date
if not ms:
new_date = Time(jdate, format="mjd").to_datetime().strftime("%Y-%m-%d %H:%M:%S")
else:
new_date = Time(jdate, format="mjd").to_datetime().strftime("%Y-%m-%d %H:%M:%S.%f")[:-3]
return new_date
@njit
def diff_cons(v):
"""
Calculate consecutive difference between the elements of an array.\n
Parameters:\n
- **v** is an array-like object\n
The difference between each couple of samples of even-odd index is computed.
"""
n = (len(v) // 2) * 2
diff = (v[0:n:2] - v[1:n + 1:2])
return diff
def down_sampling(list1: [], list2: [], label1: str, label2: str) -> ():
"""
Create a new list operating the down-sampling (using median values) on the longest of the two arrays.\n
Parameters:\n
- **list1**, **list2** (``list``): array-like objects
- **label1**, **label2** (``str``): names of the dataset. Used for labels for future plots.
Return:\n
A tuple containing: the interpolated array, the long array and the two data labels.
"""
# Define the lengths of the arrays
l1 = len(list1)
l2 = len(list2)
# No down-sampling needed
if l1 == l2:
# Do nothing, return list1, list2, label1 and label2
return list1, list2, label1, label2
# Down-sampling procedure
else:
# Define the length of the down-sampled array
len_v = max(l1, l2)
# Points on which the median will be calculated
points_med = int(l1 / l2) if l1 > l2 else int(l2 / l1)
# Define the array that must be down-sampled
long_v, short_v = (list1, list2) if len(list1) > len(list2) else (list2, list1)
# Define the correct labels
long_label, short_label = (label1, label2) if len(list1) > len(list2) else (label2, label1)
# Down-sampling of the longest array
down_sampled_data = []
for i in range(0, len_v, points_med):
group = long_v[i:i + points_med]
down_sampled_data.append(np.median(group))
# Avoid length mismatch
down_sampled_data = down_sampled_data[:min(l1, l2)]
return down_sampled_data, short_v, long_label, short_label
def demodulate_array(array: list, type: str) -> list:
"""
Demodulation over an array\n
Calculate the double demodulation of the dataset.
Depending on the type provided, consecutive means or differences are computed.
Parameters:\n
- **array** (``list``): array-like dataset
- **type** (``str``) of data *"DEM"* or *"PWR"*
"""
data = []
# Calculate consecutive mean of PWR Outputs -> Get TOTAL POWER Scientific Data
if type == "PWR":
data = mean_cons(np.array(array))
# Calculate consecutive differences of DEM Outputs -> Get DEMODULATED Scientific Data
if type == "DEM":
data = diff_cons(np.array(array))
return data
def double_dem(dataset: list, type: str):
"""
Calculate the double demodulation of the dataset.
- **dataset** (``list``): numpy array
- **type** (``str``) of data *"DEM"* or *"PWR"*
If PWR calculates consecutive means, if DEM calculates consecutive differences
"""
if type == "PWR":
dataset = mean_cons(dataset)
# Calculate consecutive differences of DEM Outputs -> Get DEMODULATED Scientific Data
elif type == "DEM":
dataset = diff_cons(dataset)
else:
logging.error("No PWR or DEM detected")
return dataset
def demodulation(dataset: dict, timestamps: list, type: str, exit: str, begin=0, end=-1) -> Dict[str, Any]:
"""
Demodulation\n
Calculate the double demodulation of the dataset.
Depending on the type provided, consecutive means or differences are computed.\n
Timestamps are chosen as mean of the two consecutive times of the DEM/PWR data\n
Parameters:\n
- **dataset** (``dict``): dictionary ({}) containing the dataset with the output of a polarimeter
- **timestamps** (``list``): list ([]) containing the Timestamps of the output of a polarimeter
- **exit** (``str``) *"Q1"*, *"Q2"*, *"U1"*, *"U2"*\n
- **type** (``str``) of data *"DEM"* or *"PWR"*
- **begin**, **end** (``int``): interval of dataset that has to be considered
"""
# Calculate consecutive mean of the Timestamps
times = mean_cons(timestamps)
data = {}
# Calculate consecutive mean of PWR Outputs -> Get TOTAL POWER Scientific Data
if type == "PWR":
data[exit] = mean_cons(dataset[type][exit][begin:end])
# Calculate consecutive differences of DEM Outputs -> Get DEMODULATED Scientific Data
if type == "DEM":
data[exit] = diff_cons(dataset[type][exit][begin:end])
sci_data = {"sci_data": data, "times": times}
return sci_data
def delta_method(values: list):
"""
Compute the White Noise level from a dataset (from Nicole Grillo's Bachelor Thesis 2023).\n
- **values** (``list``): array-like objects containing the data from which compute the White Noise;
Return:\n
A floating point number representing the WN level
"""
# Calculate consecutive differences
delta_values = values[1:] - values[:-1]
# Consider only even values
delta_values_even = delta_values[::2]
# Delta Method Formula: median of the abs value of the difference between median and values
mean_abs_dev = np.median(np.abs(np.median(delta_values_even) - delta_values_even))
# Correction due to the propagation of errors
return mean_abs_dev / (0.67449 * np.sqrt(2))
def dir_format(old_string: str) -> str:
"""
Take a string and return a new string changing white spaces into underscores, ":" into "-" and removing ".000"\n
Parameters:\n
- **old_string** (``str``)
"""
new_string = old_string.replace(" ", "_")
new_string = new_string.replace(".000", "")
new_string = new_string.replace(":", "-")
return new_string
def EOA(even: int, odd: int, all: int) -> str:
"""
Parameters:\n
- **even**, **odd**, **all** (``int``)
If these variables are different from zero, this function returns a string with the corresponding letters:\n
- "E" for even (``int``)\n
- "O" for odd (``int``)\n
- "A" for all (``int``)\n
"""
eoa = ""
if even != 0:
eoa += "E"
if odd != 0:
eoa += "O"
if all != 0:
eoa += "A"
return eoa
def eoa_values(eoa_str: str) -> []:
"""
Return a list in which each element is a tuple of 3 values.
Those values can be 0 or 1 depending on the letters (e, o, a) provided.
Note: if a letter is present in the eoa_str, then that letter will assume both value 0 and 1. Only 0 otherwise.
Parameters:\n
- **eoa_str** (``str``): string of 0,1,2 or 3 letters from a combination of the letters e, o and a
"""
# Initialize a dictionary with 0 values for e,o,a keys
eoa_dict = {"E": [0], "O": [0], "A": [0]}
eoa_list = [char for char in eoa_str]
# If a letter appears also the value 1 is included in the dictionary
for key in eoa_dict.keys():
if key in eoa_list:
eoa_dict[key].append(1)
# Store the combinations of 0 and 1 depending on which letters were provided
eoa_combinations = [(val1, val2, val3)
for val1 in eoa_dict["E"]
for val2 in eoa_dict["O"]
for val3 in eoa_dict["A"]]
return eoa_combinations
def error_propagation_corr(cov, params: list, wn_level: float) -> float:
"""
Compute the value of the propagation of the errors (from Nicole Grillo's Bachelor Thesis 2023).\n
Parameters:\n
- **cov** (``Any``):
- **params** (``list``)
- **wn_level** (``float``)
Return:\n
A floating point value corresponding to the propagated error.
"""
one_alpha = 1 / params[1]
sig_c = (params[0] / wn_level) ** one_alpha
der_f = sig_c
der_sigma = one_alpha * sig_c * params[2] / wn_level
der_alpha = params[2] * sig_c * np.log(params[0] / wn_level) * one_alpha ** 2
return np.sqrt(
der_f ** 2 * cov[2, 2] + der_sigma ** 2 * cov[0, 0] + der_alpha ** 2 * cov[1, 1] +
2 * der_f * der_sigma * cov[2, 0] + 2 * der_f * der_alpha * cov[2, 1] + 2 * der_alpha * der_sigma * cov[0, 1])
def find_jump(v, exp_med: float, tolerance: float) -> {}:
"""
Find the 'jumps' in a given Time astropy object: the samples should be consequential with a fixed growth rate.
Hence, their consecutive differences should have an expected median within a certain tolerance.\n
Parameters:\n
- **v** is a Time object from astropy => i.e. Polarimeter.times\n
- **exp_med** (``float``) expected median (in seconds) of the TimeDelta between two consecutive values of v
- **tolerance** (``float``) threshold number of seconds over which a TimeDelta is considered as an error\n
Return:\n
- **jumps** a dictionary containing five keys:
- **n** (``int``) is the number of jumps found
- **idx** (``int``) index of the jump in the array
- **value** (``float``) is the value of the jump in JHD
- **s_value** (``float``) is the value of the jump in seconds
- **median_ok** (``bool``) True if there is no jump in the vector, False otherwise
"""
# Create a TimeDelta object from the Time object given in input
dt = (v[1:] - v[:-1]).sec # type: TimeDelta
# Calculate the median of the TimeDelta
med_dt = np.median(dt)
median_ok = True
# If the tolerance is overcome -> a warning message is produced
if np.abs(np.abs(med_dt) - np.abs(exp_med)) > tolerance:
msg = f"Median is out of range: {med_dt}, expected {exp_med}."
logging.warning(msg)
median_ok = False
# Discrepancy between dt and their median
err_t = dt - med_dt
# Initializing the lists with the information about time jumps
idx = []
value = []
s_value = []
n = 0
# Initializing the dict with the information about time jumps
jumps = {"n": n, "idx": idx, "value": value, "s_value": s_value,
"median": med_dt, "exp_med": exp_med, "tolerance": tolerance, "median_ok": median_ok,
"5per": np.percentile(dt, 5), "95per": np.percentile(dt, 95)}
# Store the info
for i, item in enumerate(err_t):
# logging.debug(f"Discrepancy value: {item}")
if np.abs(item) > tolerance:
jumps["n"] += 1
jumps["idx"].append(i)
# Convert the value in days
jumps["value"].append(dt[i] / 86400)
jumps["s_value"].append(dt[i])
return jumps
def find_spike(v, data_type: str, threshold=4.4, n_chunk=10) -> []:
"""
Look up for 'spikes' in a given array.\n
Calculate the median and the mad and uses those to discern spikes.\n
Parameters:\n
- **v** is an array-like object
- **type** (str): if "DEM" look for spikes in two sub arrays (even and odd output) if "FFT" select only spike up
- **threshold** (int): value used to discern what a spike is
- **n_chunk** (int): n of blocks in which v is divided. On every block the median is computed to find spikes.
"""
# Initialize a spike list to collect the indexes of the problematic samples
spike_idx = []
# Number of steps of the algorithm
steps = 1
# If DEM output look for spike on even and odd: two steps needed
if data_type == "DEM":
steps = 2
# Start spike algorithm
for i in range(steps):
# logging.debug(f"Step: {i+1}/{steps}.")
new_v = v[i:-1 - i:steps]
# Length of the new vector
l = len(new_v)
# Calculate the length of a chunk used to divide the array
len_chunk = l // n_chunk
# Repeat the research of the spikes on every chunk of data
for n_rip in range(n_chunk):
# Creating a sub array dividing the new_v in n_chunk
_v_ = new_v[n_rip * len_chunk:(n_rip + 1) * len_chunk - 1]
# Calculate the Median
med_v = scn.median(_v_) # type:float
# Calculate the Mean Absolute Deviation
mad_v = scs.median_abs_deviation(_v_)
for idx, item in enumerate(_v_):
if item > med_v + threshold * mad_v or item < med_v - threshold * mad_v:
s_idx = n_rip * len_chunk + idx
if data_type == "DEM":
s_idx = s_idx * 2 + i
spike_idx.append(s_idx)
# If the data_type is an FFT
if data_type == "FFT":
# Selecting local spikes UP: avoiding contour spikes
spike_idx = [i for i in spike_idx if v[i] > v[i - 1] and v[i] > v[i + 1]]
if len(spike_idx) > 0:
logging.warning(f"Found Spike in {data_type}!\n")
return spike_idx
def fourier_transformed(times: list, values: list, nperseg: int, f_max=25., f_min=0.):
"""
Compute the Fast Fourier Transformed of an array of data (update from Nicole Grillo's Bachelor Thesis 2023).
Parameters:\n
- **times** (``list``): array-like objects containing the timestamps of the data;
- **values** (``list``): array-like objects containing the data to transform;
- **nperseg** (``int``): number of elements of the array of scientific data on which the fft is calculated
Return:\n
- **freq** (``list``): array-like object containing the frequencies (x-axis in FFT plots);
- **fft** (``list``): array-like object containing the transformed data.
"""
freq, fft = scipy.signal.welch(values, fs=1 / np.median(times[1:] - times[:-1]),
nperseg=nperseg)
mask = (freq > f_min) & (freq <= f_max)
freq = freq[mask]
fft = fft[mask]