-
Notifications
You must be signed in to change notification settings - Fork 0
/
functions_giammi.py
1328 lines (1210 loc) · 65.2 KB
/
functions_giammi.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 itertools
from itertools import count
import math
import time
import warnings
import numpy as np
from numpy.core.defchararray import array
import pandas as pd
import matplotlib as mpl
import matplotlib.pyplot as plt
import matplotlib.colors
import matplotlib.ticker as mticker
from matplotlib import cm
import triangulation as tr
import scipy as sp
import scipy.ndimage
from scipy.spatial import Delaunay
from scipy import interpolate
from scipy.interpolate import griddata
from scipy.interpolate import interp2d
from scipy.ndimage import gaussian_filter
from pyntcloud import PyntCloud, structures
import plotly
import plotly.graph_objects as go
from plotly.subplots import make_subplots
# import uproot
# import uproot_methods
def avg_func(cosphi):
"""
Shifts an array by the average of the each step. It reduces the lenght of the input array by 1.
The input has to have a shape (13,7). Output (12,6).
"""
cosu=np.unique([col[0] for col in cosphi])
phiu=np.unique([col[1] for col in cosphi])
col1=[(a + b) / 2 for a, b in zip(cosu[::], cosu[1::])]
col2=[(a + b) / 2 for a, b in zip(phiu[::], phiu[1::])]
return np.around(np.array(list(itertools.product(col1,col2))),3)
def bin_ndarray(ndarray, new_shape, operation='mean'):
"""
Bins an ndarray in all axes based on the target shape, by summing or
averaging.
Number of output dimensions must match number of input dimensions and
new axes must divide old ones.
Example
-------
>>> m = np.arange(0,100,1).reshape((10,10))
>>> n = bin_ndarray(m, new_shape=(5,5), operation='sum')
>>> print(n)
[[ 22 30 38 46 54]
[102 110 118 126 134]
[182 190 198 206 214]
[262 270 278 286 294]
[342 350 358 366 374]]
"""
operation = operation.lower()
if not operation in ['sum', 'mean']:
raise ValueError("Operation not supported.")
if ndarray.ndim != len(new_shape):
raise ValueError("Shape mismatch: {} -> {}".format(ndarray.shape,
new_shape))
compression_pairs = [(d, c//d) for d,c in zip(new_shape,
ndarray.shape)]
flattened = [l for p in compression_pairs for l in p]
ndarray = ndarray.reshape(flattened)
for i in range(len(new_shape)):
op = getattr(ndarray, operation)
ndarray = op(-1*(i+1))
return ndarray
def clippedcolorbar(CS, **kwargs):
"""
use vmin and vmax in contour or and use there the keyword extend="both".
https://stackoverflow.com/questions/43150687/colorbar-limits-are-not-respecting-set-vmin-vmax-in-plt-contourf-how-can-i-more
"""
from matplotlib.cm import ScalarMappable
from numpy import arange, floor, ceil
fig = CS.ax.get_figure()
vmin = CS.get_clim()[0]
vmax = CS.get_clim()[1]
m = ScalarMappable(cmap=CS.get_cmap())
m.set_array(CS.get_array())
m.set_clim(CS.get_clim())
step = CS.levels[1] - CS.levels[0]
cliplower = CS.zmin<vmin
clipupper = CS.zmax>vmax
noextend = 'extend' in kwargs.keys() and kwargs['extend']=='neither'
# set the colorbar boundaries
boundaries = arange((floor(vmin/step)-1+1*(cliplower and noextend))*step, (ceil(vmax/step)+1-1*(clipupper and noextend))*step, step)
kwargs['boundaries'] = boundaries
# if the z-values are outside the colorbar range, add extend marker(s)
# This behavior can be disabled by providing extend='neither' to the function call
if not('extend' in kwargs.keys()) or kwargs['extend'] in ['min','max']:
extend_min = cliplower or ( 'extend' in kwargs.keys() and kwargs['extend']=='min' )
extend_max = clipupper or ( 'extend' in kwargs.keys() and kwargs['extend']=='max' )
if extend_min and extend_max:
kwargs['extend'] = 'both'
elif extend_min:
kwargs['extend'] = 'min'
elif extend_max:
kwargs['extend'] = 'max'
return fig.colorbar(m, **kwargs)
def cosphi_func(key,cosphi):
ctheta_nc = float((str(key).split("costheta_")[1]).split("_phi")[0])
phi_nc = float((str(key).split("phi_")[1]).split(";")[0])
# alternative method with import re
#ctheta_n=re.search("costheta_(.*)_phi", str(key)).group(1)
cosphi.append((ctheta_nc, phi_nc))
return cosphi
def create_gocoords(a=1,cos_lin=True,limits=[0,0,0,0], source=False):
"""
a=0 go coordiantes arragend according to ascending phi_photon, zigzag ctheta_photon,
a=1 (default) coordiantes arragend according to ascending ctheta_photon, zigzag phi_photon.
a=2 coordiantes arragend according to DESCENDING ctheta_photon, zigzag phi_photon.
a=3 coordiantes arragend according to DESCENDING ctheta_photon, zigzag phi_photon.
cos_lin=True photon coordiantes linear in cos(theta)
cos_lin=False (default) photon coordiants linear in theta
limits=[a,b,c,d] in the order from ctheta -1 to 1 and phi -180 to 180 OR EQUVALENTE ctheta np.pi to 0.
#NOTE: theta and cos(theta) are oppiste
according to automatic_72_CPR.f90 from philipp [1,6]: is from [0,P1] -> [cos(0), cos(PHI)] = [1,-1]
according to automatic_72_CPR.f90 from philipp [1,12]: is from [-PI,PI]
"""
#FULL range according to Philipp cos(theta)=[1,-1], phi=[-180,180]
#NOTE the SECOND element in the intertools is the one to which the array is sorted and goes FIRST column
if cos_lin and limits[0] == 0: #this matches the experimental values
print("STANDARD limits ph coord!")
cosphi_PHOTON_phi = np.around(np.array(list(itertools.product(np.linspace(-0.835,0.835,6).tolist(),np.linspace(-165,165,12).tolist()))),3)
cosphi_PHOTON_flipphi = np.around(np.array(list(itertools.product(np.linspace(0.835,-0.835,6).tolist(),np.linspace(-165,165,12).tolist()))),3)
phicos_PHOTON_cos = np.around(np.array(list(itertools.product(np.linspace(-165,165,12).tolist(),np.linspace(-0.835,0.835,6).tolist()))),3)
phicos_PHOTON_flipcos = np.around(np.array(list(itertools.product(np.linspace(-165,165,12).tolist(),np.linspace(0.835,-0.835,6).tolist()))),3)
elif cos_lin and limits[0] != 0:
print("Custom limits ph coord!")
cosphi_PHOTON_phi = np.around(np.array(list(itertools.product(np.linspace(limits[0],limits[1],6).tolist(),np.linspace(limits[2],limits[3],12).tolist()))),3)
cosphi_PHOTON_flipphi = np.around(np.array(list(itertools.product(np.linspace(limits[1],limits[0],6).tolist(),np.linspace(limits[2],limits[3],12).tolist()))),3)
phicos_PHOTON_cos = np.around(np.array(list(itertools.product(np.linspace(limits[2],limits[3],12).tolist(),np.linspace(limits[0],limits[1],6).tolist()))),3)
phicos_PHOTON_flipcos = np.around(np.array(list(itertools.product(np.linspace(limits[2],limits[3],12).tolist(),np.linspace(limits[1],limits[0],6).tolist()))),3)
elif cos_lin == False and limits[0] == 0:
print("STANDARD limits ph coord!")
cosphi_PHOTON_phi = np.around(np.array(list(itertools.product(np.cos(np.linspace(np.pi,0,6).tolist()),np.linspace(-180,180,12).tolist()))),3)
cosphi_PHOTON_flipphi = np.around(np.array(list(itertools.product(np.cos(np.linspace(0,np.pi,6).tolist()),np.linspace(-180,180,12).tolist()))),3)
phicos_PHOTON_cos = np.around(np.array(list(itertools.product(np.linspace(-180,180,12).tolist(),np.cos(np.linspace(np.pi,0,6).tolist())))),3)
phicos_PHOTON_flipcos = np.around(np.array(list(itertools.product(np.linspace(-180,180,12).tolist(),np.cos(np.linspace(0,np.pi,6).tolist())))),3)
elif cos_lin == False and limits[0] != 0:
print("Custom limits ph coord!")
cosphi_PHOTON_phi = np.around(np.array(list(itertools.product(np.cos(np.linspace(limits[0],limits[1],6).tolist()),np.linspace(limits[2],limits[3],12).tolist()))),3)
cosphi_PHOTON_flipphi = np.around(np.array(list(itertools.product(np.cos(np.linspace(limits[1],limits[0],6).tolist()),np.linspace(limits[2],limits[3],12).tolist()))),3)
phicos_PHOTON_cos = np.around(np.array(list(itertools.product(np.linspace(limits[2],limits[3],12).tolist(),np.cos(np.linspace(limits[0],limits[1],6).tolist())))),3)
phicos_PHOTON_flipcos = np.around(np.array(list(itertools.product(np.linspace(limits[2],limits[3],12).tolist(),np.cos(np.linspace(limits[1],limits[0],6).tolist())))),3)
#NOTE: x is always the 12 members array (phi)
# y is always the 6 members array (cos(theta))
if a==0:
xgo_phi=[col[0] for col in phicos_PHOTON_cos]
ygo_phi=[col[1] for col in phicos_PHOTON_cos]
if source:
return(xgo_phi,ygo_phi,np.flip(phicos_PHOTON_cos,axis=1))
else:
return(xgo_phi,ygo_phi)
elif a==1:
xgo_cos=[col[1] for col in cosphi_PHOTON_phi]
ygo_cos=[col[0] for col in cosphi_PHOTON_phi]
if source:
return(xgo_cos,ygo_cos,cosphi_PHOTON_phi)
else:
return(xgo_cos,ygo_cos)
elif a==2:
xgo_fcos=[col[1] for col in cosphi_PHOTON_flipphi]
ygo_fcos=[col[0] for col in cosphi_PHOTON_flipphi]
if source:
return(xgo_fcos,ygo_fcos,cosphi_PHOTON_flipphi)
else:
return(xgo_fcos,ygo_fcos)
if a==3:
xgo_fphi=[col[0] for col in phicos_PHOTON_flipcos]
ygo_fphi=[col[1] for col in phicos_PHOTON_flipcos]
if source:
return(xgo_fphi,ygo_fphi,np.flip(phicos_PHOTON_flipcos,axis=1))
else:
return(xgo_fphi,ygo_fphi)
else:
print("NO cooridnates loaded!")
return(0)
def customcmaps():
"""
It intriduces the cmap temperature to be consistent with Philipp graphs both for mpl and plotly.
Coverts seismic and magma into plotly format.
"""
########### plotly convertion ###########
magma_cmap = mpl.cm.get_cmap('magma')
seismic_cmap = mpl.cm.get_cmap('seismic')
magma_rgb = []
seismic_rgb = []
norm = mpl.colors.Normalize(vmin=0, vmax=255)
for i in range(0, 255):
k = mpl.colors.colorConverter.to_rgb(magma_cmap(norm(i)))
magma_rgb.append(k)
for i in range(0, 255):
k = mpl.colors.colorConverter.to_rgb(seismic_cmap(norm(i)))
seismic_rgb.append(k)
Magma_r = matplotlib_to_plotly(magma_cmap, 255)
Seismic_r = matplotlib_to_plotly(seismic_cmap, 255)
########### Temperautre ###########
colors = [[0, "blue"],
[0.5, "white"],
[0.75, "yellow"],
[1, "red"]]
cmap_temp = matplotlib.colors.LinearSegmentedColormap.from_list("temperature_philipp", colors)
cmap_temp_go = go.color_continuous_scale=[(0, "blue"), (0.5, "white"), (0.75, "yellow"), (1,"red")]
return(cmap_temp, cmap_temp_go, Magma_r, Seismic_r)
def error_calc(a,b,aerr=1,berr=1,error_type="PECD_S"):
"""
Performs the propagation of error for several operations. No covarience is taken into account.
keyword: PECD, PECD_S, SUM, DIFF, PROD, DIV.
NOTE: use all NON nomalized quantities; if the asymmetry in counts is low such as a~=b~=Ntot/2, than PECD can be simplified in PECD_S
William R. Leo - Techniques for Nuclear and Particle Physics Experiments_ A How-to Approach-Springer (1994)
https://faraday.physics.utoronto.ca/PVB/Harrison/ErrorAnalysis/Propagation.html
"""
if error_type == "PECD":
xsum=np.add(a,b)
xdiff=np.subtract(a,b)
sumerr=np.sqrt(aerr**2+berr**2)
return np.divide(xsum,np.fabs(xdiff))*np.sqrt((sumerr/xsum)**2+(sumerr/xdiff)**2)
elif error_type == "PECD_S":
return (np.add(a,b)**-0.5)
elif error_type == "SUM" or error_type == "DIFF":
return np.sqrt(a**2+b**2)
elif error_type == "PROD":
return np.multiply(a,b)*np.sqrt((aerr/a)**2+(berr/b)**2)
elif error_type == "DIV":
return np.divide(a,b)*np.sqrt((aerr/a)**2+(berr/b)**2)
def getamesh(x,y,z,d):
temp = pd.DataFrame(np.hstack((x[:,None], y[:,None], z[:,None])))
temp.columns = ["x", "y", "z"]
sph = PyntCloud(temp)
x, y, z = sph.points["x"], sph.points["y"], sph.points["z"]
pts = sph.points[['x', 'y', 'z']]
delaun = structures.Delaunay3D(pts)
delaun.compute()
mesh = delaun.get_mesh()
tri = mesh[['v1', 'v2', 'v3']].values
I, J, K = tri.T
return x,y,z,I,J,K
def import_TH1Dgeneric(file, loc, centre_bins=True):
"""
Loads a generic TH1D graph from a .root file.
"""
temp=np.array(file[loc].to_numpy(),dtype=object)
yvalues=temp[0]
if centre_bins: #! reduced of 1 dimension
xvalues_red=(temp[1][1:] + temp[1][:-1])/2
return np.array(xvalues_red), np.array(yvalues)
else:
xvalues = temp[1]
return np.array(xvalues), np.array(yvalues)
def import_TH2Dgeneric(file, loc, centre_bins=True):
"""
Loads a generic TH2D graph from a .root file.
"""
temp=np.array(file[loc].to_numpy(),dtype=object)
zvalues=temp[0]
if centre_bins: #! reduced of 1 dimension
xvalues_red=(temp[1][1:] + temp[1][:-1])/2
yvalues_red=(temp[2][1:] + temp[2][:-1])/2
return np.array(xvalues_red), np.array(yvalues_red), np.array(zvalues)
else:
xvalues = temp[1]
yvalues = temp[2]
return np.array(xvalues), np.array(yvalues), np.array(zvalues)
def import_TH3Dgeneric(file, loc, centre_bins=True):
"""
Loads a generic TH3D graph from a .root file.
"""
temp=np.array(file[loc].to_numpy(),dtype=object)
counts=temp[0]
if centre_bins: #! reduced of 1 dimension
xvalues_red=(temp[1][1:] + temp[1][:-1])/2
yvalues_red=(temp[2][1:] + temp[2][:-1])/2
zvalues_red=(temp[3][1:] + temp[3][:-1])/2
return np.array(xvalues_red), np.array(yvalues_red), np.array(zvalues_red), np.array(counts)
else:
xvalues = temp[1]
yvalues = temp[2]
zvalues = temp[3]
return np.array(xvalues), np.array(yvalues), np.array(zvalues), np.array(counts)
def import_MFPAD(file, loc, full=False, run_MFPAD=0, run_cos=0):
"""
Loads the 72 MFPADs and the cos(theta) from the .root files.
NOTE: MFPAD_xy and ctheta_c have originally +1 dimensions compare to the z values.
For the sake of iminiut, cos(theta) is centered on the middle of the bins.
The deprecation has been implemented to avoid slicing, and does not affect the output here.
"""
valueMFPAD=[];valuectheta=[];valuectheta_err=[]; #fundamental
cosphi_photon=[]; #important
xy_phicos_axisMFPAD=[];x_ctheta_axis=[];x_ctheta_axis_cred=[]; #just one
for key in file[loc].items():
#on linux and uproot4 concatenation of replace
if "MFPAD3D_engate_costheta_" in key[0]:
cosphi_photon=cosphi_func(key,cosphi_photon) #this function appends
#temp=np.array(file[filename].numpy()) #just .numpy for uproot3
temp=np.array(file[loc+key[0]].to_numpy(),dtype=object)
valueMFPAD.append(file[loc+key[0]].values()) # it is a list!
# valueMFPAD.append(temp[0]) # alterative way
if run_MFPAD == 0.:
#structure for uproot3
#xy_phicos_axisMFPAD.append((temp[1][0][0] , temp[1][0][1])) # phi cos(theta) from 2D
#structure for uproot4
xy_phicos_axisMFPAD.append((temp[1], temp[2])) # phi cos(theta) from 2D
run_MFPAD=1. #has to run just ones
elif "cos(theta)" in key[0]:
#temp=np.array(file[filename].numpy()) #just .numpy for uproot3
temp=np.array(file[loc+key[0]].to_numpy(),dtype=object)
valuectheta.append(file[loc+key[0]].values()) # it is a list!
valuectheta_err.append(file[loc+key[0]].errors()) # it is a list!
# valuectheta.append(temp[0]) # alterative way
if run_cos == 0.:
x_ctheta_axis.append(temp[1])
x_ctheta_axis_cred.append(np.array((x_ctheta_axis[0][1:] + x_ctheta_axis[0][:-1])/2)) #! reduced of 1 dimension
run_cos=1.
else:
continue
if full:
return np.array(valueMFPAD,dtype=float), np.array(valuectheta,dtype=float), np.array(valuectheta_err,dtype=float), \
np.array(cosphi_photon), np.array(xy_phicos_axisMFPAD), np.array(x_ctheta_axis,dtype=float), \
np.array(x_ctheta_axis_cred,dtype=float)
else:
return np.array(valueMFPAD,dtype=float), np.array(valuectheta,dtype=float), np.array(valuectheta_err,dtype=float)
def import_MFPAD3D(file, loc):
"""
Loads a single MFPAD and the cos(theta) from the 3D root file.
It excrats cosphi photon as number of MFPAD, phi and cos electron axis
NOTE: the final shape is (72,18,36), theroefore each of the 72 MPFAD is transposed comapre to the single inputs
The deprecation has been implemented to avoid slicing, and does not affect the output here.
"""
valueMFPAD=[]
for key in file[loc].items():
if "MFPAD_Mathematica" in key[0]:
valueMFPAD=np.array(file[loc+key[0]].values(),dtype=float) # it is a list!
else:
continue
#has to be transposed to match the sum
return np.array(valueMFPAD.T,dtype=float)
#TODO combine PECD3D with PECD3D_cos: the second should be just an option of selecting reduced and polarization planes.
#TODO substitute the functions in diatomic_ALLCH
#TODO a=a should be removed!
def import_PECD3D(file, loc, a, full=False, run_MFPAD=0, run_cos=0):
"""
Loads 2DMFPADs (cos(theta) el. ejection vs. cos(beta) mol. orientation) and the cos(theta) from the diatomic .root files.
For the sake of iminiut, cos(theta) is centered on the middle of the bins.
"""
valuePECD=[];valuePECD3D=[]; #fundamental
valuectheta=[];valuectheta_err=[]; #fundamental
xy_phicos_axisMFPAD=[];x_ctheta_axis=[];x_ctheta_axis_cred=[]; #just one
for key in file[loc].items():
if "_en" in key[0]:
valuePECD3D=(file[loc+key[0]].values()) # it is a list!
elif "redPHI_"+str(a) in key[0]:
temp=np.array(file[loc+key[0]].to_numpy(),dtype=object)
valuePECD=file[loc+key[0]].values() # it is a list!
if run_MFPAD == 0.:
xy_phicos_axisMFPAD=(temp[1], temp[2]) # phi cos(theta) from 2D
run_MFPAD=1. #has to run just ones
elif "cos(theta)_e[0]_" in key[0]:
temp=np.array(file[loc+key[0]].to_numpy(),dtype=object)
valuectheta=file[loc+key[0]].values() # it is a list!
valuectheta_err=file[loc+key[0]].errors() # it is a list!
if run_cos == 0.:
x_ctheta_axis=temp[1]
x_ctheta_axis_cred=np.array((x_ctheta_axis[1:] + x_ctheta_axis[:-1])/2) #! reduced of 1 dimension
run_cos=1.
else:
continue
if full:
return np.array(valuePECD,dtype=float), np.array(valuePECD3D,dtype=float), np.array(valuectheta,dtype=float), \
np.array(valuectheta_err,dtype=float), np.array(xy_phicos_axisMFPAD), np.array(x_ctheta_axis,dtype=float), \
np.array(x_ctheta_axis_cred)
else:
return np.array(valuePECD,dtype=float), np.array(valuePECD3D,dtype=float), np.array(valuectheta,dtype=float), \
np.array(valuectheta_err,dtype=float)
def import_PECD3D_cos(file, loc, full=False, run_MFPAD=0, run_cos=0):
"""
Loads MFPAD and the cos(theta) from the diatomic .root files.
For the sake of iminiut, cos(theta) is centered on the middle of the bins.
"""
valuePECD=[];valuePECD3D=[]; #fundamental
valuectheta=[];valuectheta_err=[]; #fundamental
valuectheta_pol=[];valuectheta_pol_err=[]; #fundamental
xy_phicos_axisMFPAD=[];x_ctheta_axis=[];x_ctheta_axis_cred=[]; #just one
for key in file[loc].items():
if "_en" in key[0]:
valuePECD3D=(file[loc+key[0]].values()) # it is a list!
elif "PECD_LF_red" in key[0]:
temp=np.array(file[loc+key[0]].to_numpy(),dtype=object)
valuePECD=file[loc+key[0]].values() # it is a list!
if run_MFPAD == 0.:
xy_phicos_axisMFPAD=(temp[1], temp[2]) # phi cos(theta) from 2D
run_MFPAD=1. #has to run just ones
elif "cos(theta)_e[0]_pol_red" in key[0]:
temp=np.array(file[loc+key[0]].to_numpy(),dtype=object)
valuectheta_pol=file[loc+key[0]].values() # it is a list!
valuectheta_pol_err=file[loc+key[0]].errors() # it is a list!
# elif "cos(theta)_e[0]_redphi" in filename.lower():
elif "cos(theta)_e[0];" in key[0]:
# elif "cos(theta)_e[0]_prop" in key[0]:
temp=np.array(file[loc+key[0]].to_numpy(),dtype=object)
valuectheta=file[loc+key[0]].values() # it is a list!
valuectheta_err=file[loc+key[0]].errors() # it is a list!
if run_cos == 0.:
x_ctheta_axis=temp[1]
x_ctheta_axis_cred=np.array((x_ctheta_axis[1:] + x_ctheta_axis[:-1])/2) #! reduced of 1 dimension
run_cos=1.
else:
continue
if full:
return np.array(valuePECD,dtype=float), np.array(valuePECD3D,dtype=float), np.array(valuectheta,dtype=float), \
np.array(valuectheta_err,dtype=float), np.array(valuectheta_pol,dtype=float), np.array(valuectheta_pol_err,dtype=float), \
np.array(xy_phicos_axisMFPAD,dtype=float), np.array(x_ctheta_axis,dtype=float), np.array(x_ctheta_axis_cred,dtype=float)
else:
return np.array(valuePECD,dtype=float), np.array(valuePECD3D,dtype=float), np.array(valuectheta,dtype=float), np.array(valuectheta_err,dtype=float), \
np.array(valuectheta_pol,dtype=float), np.array(valuectheta_pol_err,dtype=float)
def import_2DPECD(file, loc, run_MFPAD=0, run_cos=0, full=False, redpol=False, en=False, cos=False, cdad=False, res_PECD=0):
"""
Loads MFPAD and the cos(theta) from the diatomic .root files.
For the sake of iminiut, cos(theta) is centered on the middle of the bins.
run_MFPAD to load cos(thte) and phi coordiantes.
redpol is reduced polarization and identifies the the redPHI (NOTE: fore CDAD has to be be False)
res is present just in the diatomic files and outputs JUST 2DPECD_res.
en is True for PECD function of energy.
In general 2DPECD from diatomic and polyatomic should differ.
"""
valuePECD=[];valuePECD3D=[]; #fundamental
valuectheta=[];valuectheta_err=[]; #fundamental
xy_phicos_axisMFPAD=[];xy_phicos_axisMFPAD_red=[];x_ctheta_axis=[];x_ctheta_axis_cred=[]; #just one
reslist = [0, 16, 36, 72]
if res_PECD not in reslist:
raise ValueError("Invalid resolution! Expected one of: %s" % res_PECD)
if res_PECD == 0:
for key in file[loc].items():
if redpol:
if ("PECD_LF_redPHI_en" in key[0]) and en:
# print("PECD_redPHI")
temp=np.array(file[loc+key[0]].to_numpy(),dtype=object)
valuePECD3D=(file[loc+key[0]].values()) # it is a list!
if run_MFPAD == 0.:
xy_phicos_axisMFPAD=(temp[1], temp[2], temp[3]) # cos(beta) cos(theta) energy from 2§
run_MFPAD=1. #has to run just ones
return np.array(valuePECD3D,dtype=float), np.array(xy_phicos_axisMFPAD,dtype=object)
elif ("PECD_LF_redPHI" in key[0]) and en==False:
temp=np.array(file[loc+key[0]].to_numpy(),dtype=object)
valuePECD=file[loc+key[0]].values() # it is a list!
if run_MFPAD == 0.:
xy_phicos_axisMFPAD=(temp[1], temp[2]) # cos(beta) cos(theta) from 2D
xy_phicos_axisMFPAD_red=(np.array((temp[1][1:] + temp[1][:-1])/2), np.array((temp[2][1:] + temp[2][:-1])/2)) # cos(beta) cos(theta) from 2D
run_MFPAD=1. #has to run just ones
if full:
return np.array(valuePECD,dtype=float), np.array(xy_phicos_axisMFPAD,dtype=float)
else:
return np.array(valuePECD,dtype=float), np.array(xy_phicos_axisMFPAD_red,dtype=float)
elif "cos(theta)_e[0]_pol_red" in key[0] and cos:
temp=np.array(file[loc+key[0]].to_numpy(),dtype=object)
valuectheta=file[loc+key[0]].values() # it is a list!
valuectheta_err=file[loc+key[0]].errors() # it is a list!
if run_cos == 0.:
x_ctheta_axis=temp[1]
x_ctheta_axis_cred=np.array((x_ctheta_axis[1:] + x_ctheta_axis[:-1])/2) #! reduced of 1 dimension
run_cos=1.
if full:
return np.array(valuectheta,dtype=float), np.array(valuectheta_err,dtype=float), np.array(x_ctheta_axis,dtype=float), np.array(x_ctheta_axis_cred,dtype=float)
else:
return np.array(valuectheta,dtype=float), np.array(valuectheta_err,dtype=float)
else:
if ("PECD_LF_en" in key[0]) and en:
# print("PECD")
temp=np.array(file[loc+key[0]].to_numpy(),dtype=object)
valuePECD3D=(file[loc+key[0]].values()) # it is a list!
if run_MFPAD == 0.:
xy_phicos_axisMFPAD=(temp[1], temp[2], temp[3]) # cos(beta) cos(theta) energy from 2§
run_MFPAD=1. #has to run just ones
return np.array(valuePECD3D,dtype=float), np.array(xy_phicos_axisMFPADdtype=object)
elif ("PECD_LF" in key[0]) and en==False:
temp=np.array(file[loc+key[0]].to_numpy(),dtype=object)
valuePECD=file[loc+key[0]].values() # it is a list!
if run_MFPAD == 0.:
xy_phicos_axisMFPAD=(temp[1], temp[2]) # cos(beta) cos(theta) from 2D
xy_phicos_axisMFPAD_red=(np.array((temp[1][1:] + temp[1][:-1])/2), np.array((temp[2][1:] + temp[2][:-1])/2)) # cos(beta) cos(theta) from 2D
run_MFPAD=1. #has to run just ones
if full:
return np.array(valuePECD,dtype=float), np.array(xy_phicos_axisMFPAD,dtype=float)
else:
return np.array(valuePECD,dtype=float), np.array(xy_phicos_axisMFPAD_red,dtype=float)
elif ("CDAD_LF" in key[0]) and en==False and cdad:
temp=np.array(file[loc+key[0]].to_numpy(),dtype=object)
valueCDAD=file[loc+key[0]].values() # it is a list!
if run_MFPAD == 0.:
xy_phicos_axisMFPAD=(temp[1], temp[2]) # cos(beta) cos(theta) from 2D
xy_phicos_axisMFPAD_red=(np.array((temp[1][1:] + temp[1][:-1])/2), np.array((temp[2][1:] + temp[2][:-1])/2)) # cos(beta) cos(theta) from 2D
run_MFPAD=1. #has to run just ones
if full:
return np.array(valueCDAD,dtype=float), np.array(xy_phicos_axisMFPAD,dtype=float)
else:
return np.array(valuePECD,dtype=float), np.array(xy_phicos_axisMFPAD_red,dtype=float)
elif ("cos(theta)_e[0];" in key[0]) and cos:
temp=np.array(file[loc+key[0]].to_numpy(),dtype=object)
valuectheta=file[loc+key[0]].values() # it is a list!
valuectheta_err=file[loc+key[0]].errors() # it is a list!
if run_cos == 0.:
x_ctheta_axis=temp[1]
x_ctheta_axis_cred=np.array((x_ctheta_axis[1:] + x_ctheta_axis[:-1])/2) #! reduced of 1 dimension
run_cos=1.
if full:
return np.array(valuectheta,dtype=float), np.array(valuectheta_err,dtype=float), np.array(x_ctheta_axis,dtype=float), np.array(x_ctheta_axis_cred,dtype=float)
else:
return np.array(valuectheta,dtype=float), np.array(valuectheta_err,dtype=float)
else:
continue
else:
for key in file[loc].items():
if redpol:
if "PECD_LF_redPHI_"+str(res_PECD) in key[0]:
# print("PECD_LF_redPHI_"+str(res_PECD))
temp=np.array(file[loc+key[0]].to_numpy(),dtype=object)
valuePECD=file[loc+key[0]].values() # it is a list!
if run_MFPAD == 0.:
xy_phicos_axisMFPAD=(temp[1], temp[2]) # cos(beta) cos(theta) from 2D
xy_phicos_axisMFPAD_red=(np.array((temp[1][1:] + temp[1][:-1])/2), np.array((temp[2][1:] + temp[2][:-1])/2)) # cos(beta) cos(theta) from 2D
run_MFPAD=1. #has to run just ones
if full:
return np.array(valuePECD,dtype=float), np.array(xy_phicos_axisMFPAD,dtype=float)
else:
return np.array(valuePECD,dtype=float), np.array(xy_phicos_axisMFPAD_red,dtype=float)
else:
continue
else:
if "PECD_LF_"+str(res_PECD) in key[0]:
temp=np.array(file[loc+key[0]].to_numpy(),dtype=object)
valuePECD=file[loc+key[0]].values() # it is a list!
if run_MFPAD == 0.:
xy_phicos_axisMFPAD=(temp[1], temp[2]) # cos(beta) cos(theta) from 2D
xy_phicos_axisMFPAD_red=(np.array((temp[1][1:] + temp[1][:-1])/2), np.array((temp[2][1:] + temp[2][:-1])/2)) # cos(beta) cos(theta) from 2D
run_MFPAD=1. #has to run just ones
if full:
return np.array(valuePECD,dtype=float), np.array(xy_phicos_axisMFPAD,dtype=float)
else:
return np.array(valuePECD,dtype=float), np.array(xy_phicos_axisMFPAD_red,dtype=float)
else:
continue
def mag(vector):
"""
Return the magnitude of a vector (array) as the square root of the sum of the squares of its components.
"""
return math.sqrt(sum(pow(element, 2) for element in vector))
def makeamesh (x,y,z,d):
points2d_trace=go.Scatter(x=x, y=y, mode='markers', marker_color='red', marker_size=6)
point_trace=go.Scatter(x=x, y=y,
mode='markers',
name='points',
marker_color='red',
marker_size=6)
pts2d=np.array([x,y]).T
tri=Delaunay(pts2d)
delaunay_tri = tr.triangulation_edges(pts2d, tri.simplices, linewidth=1)
i, j, k = tri.simplices.T
my_mesh3d = go.Mesh3d(
x = x,
y = y,
z = z,
i=i, j=j, k=k,
colorscale='deep_r',
colorbar_thickness=25,
intensity=d,
flatshading=True)
points3d=np.array([x,y,z]).T
delaun_tri3d=tr.triangulation_edges(points3d, tri.simplices)
return delaunay_tri, point_trace, my_mesh3d, delaun_tri3d
def matplotlib_to_plotly(cmap, pl_entries):
"""
To be used in cmaptep
"""
h = 1.0/(pl_entries-1)
pl_colorscale = []
for k in range(pl_entries):
C = list(map(np.uint8, np.array(cmap(k*h)[:3])*255))
pl_colorscale.append([k*h, 'rgb'+str((C[0], C[1], C[2]))])
return pl_colorscale
def normalise_with_err(a,err=0,normtype=2,nancorr=False):
"""
It normalises a [n,m] matrix.
normtype 0 is a coefficient of variation along the rows.
normtype 1 is a vector normalization along the rows.
normtype 2 is a coefficient of variation, results proportional to the total counts (integral).
normtype 3 is a min max feature scaling, results between 0 - 1.
err: if non integer, it introduce the calculation of errors
nancorr: substitutes 0 with NaN.
For errors: if I normalize using the integral sum, the standard error SE has to be divided by the same quantity.
NOTE it is likely that error shouldn´t be normalized in the approximation.
https://faraday.physics.utoronto.ca/PVB/Harrison/ErrorAnalysis/Propagation.html
"""
new_matrix=[]
new_err=[]
if type(err) == int:
if len(np.array(a).shape) == 3:
if normtype==0:
for el in a:
new_matrix.append(el/np.sum(el,axis=1)[:, np.newaxis])
elif normtype==1:
for el in a:
new_matrix.append(el/np.linalg.norm(el,axis=1)[:, np.newaxis])
elif normtype==2:
for el in a:
new_matrix.append(el/np.sum(el))
elif normtype==3:
for el in a:
new_matrix.append((el-el.min())/(el.max()-el.min()))
else:
print("Failed to normalise!")
return 0
else:
if normtype==0:
row_sums = np.sum(a,axis=1)
new_matrix = a / row_sums[:, np.newaxis]
elif normtype==1:
row_sums = np.linalg.norm(a,axis=1)
new_matrix = a / row_sums[:, np.newaxis]
elif normtype==2:
new_matrix = a / np.sum(a)
elif normtype==3:
new_matrix = (a - a.min()) /(a.max()-a.min())
else:
print("Failed to normalise!")
return 0
if nancorr:
return np.array(np.nan_to_num(new_matrix))
else:
return np.array(new_matrix)
else:
if len(np.array(a).shape) == 3:
if normtype==0:
for el,elr in zip(a,err):
new_matrix.append(el/np.sum(el,axis=1)[:, np.newaxis])
new_err.append(elr/np.sum(el,axis=1)[:, np.newaxis])
elif normtype==1:
for el,elr in zip(a,err):
new_matrix.append(el/np.linalg.norm(el,axis=1)[:, np.newaxis])
new_err.append(elr/np.linalg.norm(el,axis=1)[:, np.newaxis])
elif normtype==2:
for el,elr in zip(a,err):
new_matrix.append(el/np.sum(el))
new_err.append(elr/np.sum(el))
elif normtype==3:
for el,elr in zip(a,err):
new_matrix.append((el-el.min())/(el.max()-el.min()))
new_err.append(elr/(el.max()-el.min()))
else:
print("Failed to normalise!")
return 0
else:
if normtype==0:
row_sums = np.sum(a,axis=1)
new_matrix = a / row_sums[:, np.newaxis]
new_err = err / row_sums[:, np.newaxis]
elif normtype==1:
row_sums = np.linalg.norm(a,axis=1)
new_matrix = a / row_sums[:, np.newaxis]
new_err = err / row_sums[:, np.newaxis]
elif normtype==2:
new_matrix = a / np.sum(a)
new_err = err / np.sum(a)
elif normtype==3:
new_matrix = (a - a.min()) /(a.max()-a.min())
new_err = err / (a.max()-a.min())
else:
print("Failed to normalise!")
return 0
if nancorr:
return np.array(np.nan_to_num(new_matrix)),np.array(np.nan_to_num(new_err))
else:
return np.array(new_matrix), np.array(new_err)
def overlaygraph(fig, title="",original=True, paper=False, wspace=0.08, hspace=0.08):
"""
Overlays the typical graphs with photon coordiantes x=phi, y=cos(theta).
Set the space in between the subplots via fig.
Original = True is the new stardar according to the way of filling the histograms
with np.flip for phi
"""
# fig.tight_layout() #NOTE goes in conflict with subplots_adjust
fig.subplots_adjust(wspace=wspace, hspace=hspace)
fig.suptitle(title) #,fontsize=20)
newax = fig.add_subplot()
newax.patch.set_visible(False)
newax.minorticks_off()
newax.tick_params(which="both", direction='out', right=False, labelright=False, labelsize=18)
newax.spines['bottom'].set_position(('outward', 45))
newax.spines['left'].set_position(('outward', 50))
newax.spines['right'].set_visible(False)
newax.spines['top'].set_visible(False)
newax.xaxis.set_ticks_position('bottom')
newax.xaxis.set_label_position('bottom')
newax.set_xticks(np.arange(-180,180.1,30, dtype=int))
newax.set_xlim([-180,180])
if paper:
newax.set_xlabel('\u03C6°$_{ph}$',loc='center',fontsize=26)
newax.set_ylabel('cos\u03D1$_{ph}$',loc='center',fontsize=26)
else:
newax.set_xlabel('\u03C6$_{ph}$ [DEG]')
newax.set_ylabel('cos\u03D1$_{ph}$ [adm]')
# newax.set_yticks(np.arange(0,180.1,20, dtype=int))
# newax.set_ylim([-181,180])
if original:
newax.set_ylim([-1,1])
else:
newax.set_ylim([1,-1])
return(newax)
def overlaycbar(fig,cs,axes,MFPAD=True, minmaxth=False, minmaxexp=False):
"""
Overlays the colorbar to the 72 plots
with MFPAD=True the lable is shown in contrast, otherwise in min max absolute counts
"""
cbar = fig.colorbar(cs, ax=axes.ravel().tolist(), ticks=mticker.MultipleLocator(10), anchor=(1.5,1), pad=-2.5)
if MFPAD and minmaxth==False and minmaxexp==False:
contrast=cs.get_array().max()/cs.get_array().min()
cbar.set_ticks([cs.get_array().min(),cs.get_array().max()])
cbar.set_ticklabels([1,f"{contrast:.2f}"])
cbar.ax.set_ylabel('contrast')
elif minmaxth:
cbar.set_ticks([cs.get_array().min(),cs.get_array().max()])
cbar.set_ticklabels(['min', 'max'])
cbar.ax.set_ylabel('normalised intesity',loc='center')
elif minmaxexp:
cbar.set_ticks([cs.get_array().min(),cs.get_array().max()])
cbar.set_ticklabels(['min', 'max'])
cbar.ax.set_ylabel('normalised counts',loc='center')
else:
cbar.set_ticks([cs.get_array().min(),cs.get_array().max()])
cbar.ax.set_ylabel('normalised counts')
return(cbar)
def plot_interpolation (x, y, z, ax, cmap="viridis", limits=False, xstep=1, ystep=.001, cont=True, nnorm=False, kind="cubic", gaussian=0, after=True, n=15, s_test=0, upscale=False):
"""
Interpolates MFPAD and b1 with the unique x and y. Draws with pcolormesh with contour.
FOR MFPADS(100,200) it is usually .T to match the dimension of phiM(100,) and cosM(200,)
IF x (m,) y (n,) z (n,m) e.g. for b1 (12,) (6,) (12,6).T for xx_phi sortings
IF x (m,) y (n,) z (n,m) e.g. for b1 (12,) (6,) (6,12) for xx_cos sortings
https://docs.scipy.org/doc/scipy/reference/generated/scipy.interpolate.interp2d.html
limits can be a boolean (computes the min and max of the input), or an array of floats [min,max]
suggested gaussian value for MFPAD is 5 or more
"""
# maybe a more elegant way would be using mgrid. NOTE the use of cosphi_adj_cos!
# grid_x, grid_y = np.mgrid[-0.835:0.835:100j, -165:165:200j]
# grid_z2 = griddata(cosphi_adj_cos, param_matrix_cos[:,0,0], (grid_x, grid_y), method='cubic')
#!NOTE warning are set off because s or m in inter2d cannot be tuned and bisplrep doesn't fit well!
warnings.filterwarnings("ignore", category=RuntimeWarning)
if limits == True:
limits=[1]
elif limits == False:
limits=[]
if len(z.shape)<2:
z=z.reshape(len(y),-1)
xnew = np.arange(x.min(), x.max(), xstep)
ynew = np.arange(y.min(), y.max(), ystep)
Xn, Yn = np.meshgrid(xnew, ynew)
#Smoothing before the interpolation
if gaussian>0 and after==True:
# print("Gaussian filter applied before interpolation..")
z=gaussian_filter(z, sigma=gaussian)
if len(x.shape) == 1:
f = interp2d(x, y, z, kind=kind)
Zn = f(Xn[0,:], Yn[:,0])
elif s_test != 0:
f = interpolate.bisplrep(x.reshape(-1), y.reshape(-1), z.reshape(-1), s=s_test)
Zn = interpolate.bisplev(Xn[0,:], Yn[:,0],f).T
else:
f = interp2d(x.reshape(-1), y.reshape(-1), z.reshape(-1), kind=kind)
Zn = f(Xn[0,:], Yn[:,0])
#Smoothing after the interpolation
if gaussian>0 and after==False:
# print("Gaussian filter applied after interpolation..")
Zn=gaussian_filter(Zn, sigma=gaussian)
if upscale:
return (Xn[0,:], Yn[:,0], Zn)
if nnorm:
if len(limits)==1:
cs=ax.pcolormesh(Xn, Yn, Zn, vmin=Zn.min(), vmax=Zn.max(), shading='gouraud', cmap=cmap, norm=nnorm)
# print("test_norm")
elif len(limits)==2:
cs=ax.pcolormesh(Xn, Yn, Zn, vmin=limits[0], vmax=limits[1], shading='gouraud', cmap=cmap, norm=nnorm)
# print("test1_norm")
else:
cs=ax.pcolormesh(Xn, Yn, Zn, shading='gouraud', cmap=cmap, norm=nnorm)
print("test2_norm")
else:
if len(limits)==1:
cs=ax.pcolormesh(Xn, Yn, Zn, vmin=Zn.min(), vmax=Zn.max(), shading='gouraud', cmap=cmap)
# print("test")
elif len(limits)==2:
cs=ax.pcolormesh(Xn, Yn, Zn, vmin=limits[0], vmax=limits[1], shading='gouraud', cmap=cmap)
# print("test1")
else:
cs=ax.pcolormesh(Xn, Yn, Zn, shading='gouraud', cmap=cmap)
# print("test2")
if cont:
ax.contour(Xn, Yn, gaussian_filter(Zn, sigma=4.), n, colors='k', alpha=0.15)
return(cs,ax)
def plotgo_single(param_matrix, xgo, ygo, name, limits=[]):
"""
limits=[min,max,size]
"""
ch_en=str(name).split("_")
cmap_temp, cmap_temp_go, Magma_r, Seismic_r = customcmaps()
#takes in account the shape of the input
if len(param_matrix.shape)>2:
z=param_matrix[:,0,0]
else:
z=param_matrix
fig = go.Figure()
if len(limits)>0:
fig.add_trace(go.Contour(z=z, x=xgo, y=ygo, line_smoothing=0.75, colorscale=cmap_temp_go,contours=dict(start=limits[0], end=limits[1], size=limits[2])))
else:
fig.add_trace(go.Contour(z=z, x=xgo, y=ygo, line_smoothing=0.75, colorscale=cmap_temp_go))
fig.update_layout(
title={
'text': "b1 map "+ch_en[-2],'y':0.98,'x':0.5,'xanchor': 'center','yanchor': 'top'},
xaxis_title='\u03C6$_{ph}$ [DEG]',
yaxis_title='cos\u03D1$_{ph}$ [adm]',
# legend_title="Legend Title",
showlegend=False,
# autosize=False,
width=560,
height=500,
margin=dict(l=10,r=10,b=10,t=35)
)
fig.write_image("../PYTHON_graphs/OUTPUTS/plotly/"+name+".png")
fig.write_html("../PYTHON_graphs/OUTPUTS/plotly/"+name+".html")
return(fig)
def plotgo_multiple(param_matrix, xgo, ygo, name, limits=[], tweak=False):
"""
limits=[min,max,size]
try pto substitute colorscale with contours_coloring for smooth graphs: more similar to imshow
"""
ch_en=str(name).split("_")
cmap_temp, cmap_temp_go, Magma_r, Seismic_r = customcmaps()
fig = go.Figure()
fig = make_subplots(rows=6, cols=1, shared_xaxes=True, vertical_spacing=0.015)
if len(limits)>0:
for i in range(6):
if tweak:
if i==1 or i==3:
fig.add_trace(go.Contour(z=param_matrix[:,i,0], x=xgo, y=ygo, line_smoothing=0.5, colorscale=cmap_temp_go,
colorbar=dict(len=0.15, y=0.92-i*0.17), contours=dict(start=limits[0][0], end=limits[0][1], size=limits[0][2])), i+1, 1)
else:
fig.add_trace(go.Contour(z=param_matrix[:,i,0], x=xgo, y=ygo, line_smoothing=0.5, colorscale=cmap_temp_go,
colorbar=dict(len=0.15, y=0.92-i*0.17), contours=dict(start=limits[1][0], end=limits[1][1], size=limits[1][2])), i+1, 1)
else:
if i==1 or i==3 or i==5:
fig.add_trace(go.Contour(z=param_matrix[:,i,0], x=xgo, y=ygo, line_smoothing=0.5, colorscale=cmap_temp_go,
colorbar=dict(len=0.15, y=0.92-i*0.17), contours=dict(start=limits[0][0], end=limits[0][1], size=limits[0][2])), i+1, 1)
else:
fig.add_trace(go.Contour(z=param_matrix[:,i,0], x=xgo, y=ygo, line_smoothing=0.5, colorscale=cmap_temp_go,
colorbar=dict(len=0.15, y=0.92-i*0.17), contours=dict(start=limits[1][0], end=limits[1][1], size=limits[1][2])), i+1, 1)
else:
for i in range(6):
if tweak:
if i==1 or i==3:
fig.add_trace(go.Contour(z=param_matrix[:,i,0], x=xgo, y=ygo, line_smoothing=0.5, colorscale=cmap_temp_go,
colorbar=dict(len=0.15, y=0.92-i*0.17)), i+1, 1)
else:
fig.add_trace(go.Contour(z=param_matrix[:,i,0], x=xgo, y=ygo, line_smoothing=0.5, colorscale=cmap_temp_go,
colorbar=dict(len=0.15, y=0.92-i*0.17)), i+1, 1)
else:
if i==1 or i==3 or i==5:
fig.add_trace(go.Contour(z=param_matrix[:,i,0], x=xgo, y=ygo, line_smoothing=0.5, colorscale=cmap_temp_go,
colorbar=dict(len=0.15, y=0.92-i*0.17)), i+1, 1)
else:
fig.add_trace(go.Contour(z=param_matrix[:,i,0], x=xgo, y=ygo, line_smoothing=0.5, colorscale=cmap_temp_go,
colorbar=dict(len=0.15, y=0.92-i*0.17)), i+1, 1)
fig.update_layout(
title={'text': "b1-6 parameters maps "+ch_en[-2],'y':0.99,'x':0.5,'xanchor': 'center','yanchor': 'top'},
# xaxis_title='phi_photon [DEG]',
# coloraxis=dict(colorscale=Seismic_r),
# showlegend=False,
autosize=False,
width=420,
height=1500,
margin=dict(l=10,r=10,b=10,t=45)
)
fig.update_xaxes(title_text='\u03C6$_{ph}$ [DEG]', row=6, col=1)
fig.update_yaxes(title_text='cos\u03D1$_{ph}$ [adm]', row=3, col=1)
fig.write_image("../PYTHON_graphs/OUTPUTS/plotly/"+name+".png")
fig.write_html("../PYTHON_graphs/OUTPUTS/plotly/"+name+".html")
return(fig)
def projection(MFPAD, alongaxis):
"""
Return the sum along the chosen axis:
axis=0 means along lines, therefore returns cos(theta)_el
axis=1 means along columns, therefore returns phi_el.
Boths cased of MFPAD tensor and matrix are covered.
"""
projected=[]
if len(np.array(MFPAD).shape)>2:
for j,el in enumerate(MFPAD):
projected.append(el.sum(axis=alongaxis))
else:
projected=(MFPAD.sum(axis=alongaxis))
return np.array(projected)
def remap(b,lim1_low,lim1_high,lim2_low=0,lim2_high=0, rounding=False):
"""
Remaps the np.array b of tuples [(col1,col2)] to the new interval [lim_low,lim_high] for both columns.
It rounds the numbers to the third decimals.
"""
if len(b.shape)>1:
col1=np.array([col[0] for col in b])
col2=np.array([col[1] for col in b])
col1 = lim1_low + np.divide(lim1_high-lim1_low , np.amax(col1)-np.amin(col1)) * (col1-np.amin(col1))
col2 = lim2_low + np.divide(lim2_high-lim2_low , np.amax(col2)-np.amin(col2)) * (col2-np.amin(col2))
out=list(zip(col1,col2))
if rounding:
out=np.around(b,3)
else:
out = lim1_low + np.divide(lim1_high-lim1_low , np.amax(b)-np.amin(b)) * (b-np.amin(b))
if rounding:
out=np.around(b,3)
return out
def rot3d(alpha,beta,gamma,convention=1):