-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathCOSIpy_tools.py
More file actions
2885 lines (2392 loc) · 124 KB
/
COSIpy_tools.py
File metadata and controls
2885 lines (2392 loc) · 124 KB
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 numpy as np
from astropy.io import fits
import matplotlib.pyplot as plt
plt.style.use('thomas')
import astropy.units as u
import sys
import time
import scipy.interpolate as interpol
import matplotlib
from matplotlib import ticker, cm
from scipy.ndimage import gaussian_filter
from tqdm import tqdm_notebook as tqdm
import os, glob
import pandas as pd
from model_definitions import *
# import ROOT/MEGAlib to work with python
import ROOT as M
# Load MEGAlib into ROOT
M.gSystem.Load("$(MEGAlib)/lib/libMEGAlib.so")
# Initialize MEGAlib
G = M.MGlobal()
G.Initialize()
def minmin(x):
"""
Return array shifted to zero
:param: x Input array
"""
return x - x.min()
def maxmax(x):
"""
Return array shifted to maximum
:param: x Input array
"""
return x.max() - x
def minmax(x):
"""
Return minimum and maximum of array
:param: x Input array
"""
return np.array([x.min(),x.max()])
def find_nearest(array, value):
"""
Find nearest index for value in array (where for non-existent values)
:param: array Input array
:param: value value to search for
"""
array = np.asarray(array)
idx = (np.abs(array - value)).argmin()
return idx
def verb(q,text):
"""
Print text of q is True
:param: q (boolean)
:param: text
"""
if q:
print(text)
def polar2cart(ra,dec):
"""
Coordinate transformation of ra/dec (lon/lat) [phi/theta] polar/spherical coordinates
into cartesian coordinates
:param: ra angle in deg
:param: dec angle in deg
"""
x = np.cos(np.deg2rad(ra)) * np.cos(np.deg2rad(dec))
y = np.sin(np.deg2rad(ra)) * np.cos(np.deg2rad(dec))
z = np.sin(np.deg2rad(dec))
return np.array([x,y,z])
def cart2polar(vector):
"""
Coordinate transformation of cartesian x/y/z values into spherical (deg)
:param: vector vector of x/y/z values
"""
ra = np.arctan2(vector[1],vector[0])
dec = np.arcsin(vector[2])
return np.rad2deg(ra), np.rad2deg(dec)
def construct_scy(scx_l, scx_b, scz_l, scz_b):
"""
Construct y-coordinate of spacecraft/balloon given x and z directions
Note that here, z is the optical axis
:param: scx_l longitude of x direction
:param: scx_b latitude of x direction
:param: scz_l longitude of z direction
:param: scz_b latitude of z direction
"""
x = polar2cart(scx_l, scx_b)
z = polar2cart(scz_l, scz_b)
return cart2polar(np.cross(z,x,axis=0))
def read_COSI_DataSet(dor):
"""
Reads in all MEGAlib .tra (or .tra.gz) files in given directory 'dor'
If full flight/mission data set is read in, e.g. from /FlightData_Processed_v4/ with standard names,
the data set is split up into days and hours of observations. Otherwise, everything is lumped together.
Returns COSI data set as a dictionary of the form
COSI_DataSet = {'Day':trafiles[i][StrBeg:StrBeg+StrLen],
'Energies':erg,
'TimeTags':tt,
'Xpointings':np.array([lonX,latX]).T,
'Ypointings':np.array([lonY,latY]).T,
'Zpointings':np.array([lonZ,latZ]).T,
'Phi':phi,
'Chi local':chi_loc,
'Psi local':psi_loc,
'Distance':dist,
'Chi galactic':chi_gal,
'Psi galactic':psi_gal}
:param: dor Path of directory in which data set is stored
"""
# Search for files in directory
trafiles = []
for dirpath, subdirs, files in os.walk(dor):
for file in files:
if glob.fnmatch.fnmatch(file,"*.tra*"):
trafiles.append(os.path.join(dirpath, file))
# sort files (only with standard names)
trafiles = sorted(trafiles)
# string lengths to get day as key
StrBeg = len(dor)+len('OP_')
StrLen = 6
# read COSI data
COSI_Data = []
# loop over all tra files
for i in tqdm(range(len(trafiles))):
Reader = M.MFileEventsTra()
if Reader.Open(M.MString(trafiles[i])) == False:
print("Unable to open file " + trafiles[i] + ". Aborting!")
quit()
erg = [] # Compton energy
tt = [] # Time tag
et = [] # Event Type
latX = [] # latitude of X direction of spacecraft
lonX = [] # lontitude of X direction of spacecraft
latZ = [] # latitude of Z direction of spacecraft
lonZ = [] # longitude of Z direction of spacecraft
phi = [] # Compton scattering angle
chi_loc = [] # measured data space angle chi
psi_loc = [] # measured data space angle psi
dist = [] # First lever arm
chi_gal = [] # measured gal angle chi (lon direction)
psi_gal = [] # measured gal angle psi (lat direction)
while True:
Event = Reader.GetNextEvent()
if not Event:
break
if Event.GetEventType() == M.MPhysicalEvent.c_Compton:
# all calculations and definitions taken from /MEGAlib/src/response/src/MResponseImagingBinnedMode.cxx
erg.append(Event.Ei()) # Total Compton Energy
tt.append(Event.GetTime().GetAsSeconds()) # Time tag in seconds since ...
et.append(Event.GetEventType()) # Event type (0 = Compton, 4 = Photo)
latX.append(Event.GetGalacticPointingXAxisLatitude()) # x axis of space craft pointing at GAL latitude
lonX.append(Event.GetGalacticPointingXAxisLongitude()) # x axis of space craft pointing at GAL longitude
latZ.append(Event.GetGalacticPointingZAxisLatitude()) # z axis of space craft pointing at GAL latitude
lonZ.append(Event.GetGalacticPointingZAxisLongitude()) # z axis of space craft pointing at GAL longitude
phi.append(Event.Phi()) # Compton scattering angle
chi_loc.append((-Event.Dg()).Phi())
psi_loc.append((-Event.Dg()).Theta())
dist.append(Event.FirstLeverArm())
chi_gal.append((Event.GetGalacticPointingRotationMatrix()*Event.Dg()).Phi())
psi_gal.append((Event.GetGalacticPointingRotationMatrix()*Event.Dg()).Theta())
erg = np.array(erg)
tt = np.array(tt)
et = np.array(et)
latX = np.array(latX)
lonX = np.array(lonX)
lonX[lonX > np.pi] -= 2*np.pi
latZ = np.array(latZ)
lonZ = np.array(lonZ)
lonZ[lonZ > np.pi] -= 2*np.pi
phi = np.array(phi)
chi_loc = np.array(chi_loc)
chi_loc[chi_loc < 0] += 2*np.pi ### TS: MIGHT BE WRONG!
psi_loc = np.array(psi_loc)
dist = np.array(dist)
chi_gal = np.array(chi_gal)
psi_gal = np.array(psi_gal)
# construct Y direction from X and Z direction
lonlatY = construct_scy(np.rad2deg(lonX),np.rad2deg(latX),np.rad2deg(lonZ),np.rad2deg(latZ))
lonY = np.deg2rad(lonlatY[0])
latY = np.deg2rad(lonlatY[1])
# avoid negative zeros
chi_loc[np.where(chi_loc == 0.0)] = np.abs(chi_loc[np.where(chi_loc == 0.0)])
# make observation dictionary
COSI_DataSet = {'Day':trafiles[i][StrBeg:StrBeg+StrLen],
'Energies':erg,
'TimeTags':tt,
'Xpointings':np.array([lonX,latX]).T,
'Ypointings':np.array([lonY,latY]).T,
'Zpointings':np.array([lonZ,latZ]).T,
'Phi':phi,
'Chi local':chi_loc,
'Psi local':psi_loc,
'Distance':dist,
'Chi galactic':chi_gal,
'Psi galactic':psi_gal}
COSI_Data.append(COSI_DataSet)
return COSI_Data
def read_COSI_DataSet_PE(dor):
"""
Reads in all MEGAlib .tra (or .tra.gz) files in given directory 'dor'
If full flight/mission data set is read in, e.g. from /FlightData_Processed_v4/ with standard names,
the data set is split up into days and hours of observations. Otherwise, everything is lumped together.
Returns COSI data set as a dictionary of the form
COSI_DataSet = {'Day':trafiles[i][StrBeg:StrBeg+StrLen],
'Energies':erg,
'TimeTags':tt,
'Xpointings':np.array([lonX,latX]).T,
'Ypointings':np.array([lonY,latY]).T,
'Zpointings':np.array([lonZ,latZ]).T,
'Phi':phi,
'Chi local':chi_loc,
'Psi local':psi_loc,
'Distance':dist,
'Chi galactic':chi_gal,
'Psi galactic':psi_gal}
:param: dor Path of directory in which data set is stored
"""
# Search for files in directory
trafiles = []
for dirpath, subdirs, files in os.walk(dor):
for file in files:
if glob.fnmatch.fnmatch(file,"*.tra*"):
trafiles.append(os.path.join(dirpath, file))
# sort files (only with standard names)
trafiles = sorted(trafiles)
# string lengths to get day as key
StrBeg = len(dor)+len('OP_')
StrLen = 6
# read COSI data
COSI_Data = []
# loop over all tra files
for i in tqdm(range(len(trafiles))):
Reader = M.MFileEventsTra()
if Reader.Open(M.MString(trafiles[i])) == False:
print("Unable to open file " + trafiles[i] + ". Aborting!")
quit()
erg = [] # Photo energy
tt = [] # Time tag
et = [] # Event Type
latX = [] # latitude of X direction of spacecraft
lonX = [] # lontitude of X direction of spacecraft
latZ = [] # latitude of Z direction of spacecraft
lonZ = [] # longitude of Z direction of spacecraft
phi = [] # Compton scattering angle
chi_loc = [] # measured data space angle chi
psi_loc = [] # measured data space angle psi
dist = [] # First lever arm
chi_gal = [] # measured gal angle chi (lon direction)
psi_gal = [] # measured gal angle psi (lat direction)
while True:
Event = Reader.GetNextEvent()
if not Event:
break
# read all photo events # !!! if Event.GetEventType() == M.MPhysicalEvent.:
# all calculations and definitions taken from /MEGAlib/src/response/src/MResponseImagingBinnedMode.cxx
erg.append(Event.Ei()) # Total Compton Energy
tt.append(Event.GetTime().GetAsSeconds()) # Time tag in seconds since ...
et.append(Event.GetEventType()) # Event type (0 = Compton, 4 = Photo)
latX.append(Event.GetGalacticPointingXAxisLatitude()) # x axis of space craft pointing at GAL latitude
lonX.append(Event.GetGalacticPointingXAxisLongitude()) # x axis of space craft pointing at GAL longitude
latZ.append(Event.GetGalacticPointingZAxisLatitude()) # z axis of space craft pointing at GAL latitude
lonZ.append(Event.GetGalacticPointingZAxisLongitude()) # z axis of space craft pointing at GAL longitude
erg = np.array(erg)
tt = np.array(tt)
et = np.array(et)
latX = np.array(latX)
lonX = np.array(lonX)
lonX[lonX > np.pi] -= 2*np.pi
latZ = np.array(latZ)
lonZ = np.array(lonZ)
lonZ[lonZ > np.pi] -= 2*np.pi
phi = np.array(phi)
chi_loc = np.array(chi_loc)
chi_loc[chi_loc < 0] += 2*np.pi ### TS: MIGHT BE WRONG!
psi_loc = np.array(psi_loc)
dist = np.array(dist)
chi_gal = np.array(chi_gal)
psi_gal = np.array(psi_gal)
# construct Y direction from X and Z direction
lonlatY = construct_scy(np.rad2deg(lonX),np.rad2deg(latX),np.rad2deg(lonZ),np.rad2deg(latZ))
lonY = np.deg2rad(lonlatY[0])
latY = np.deg2rad(lonlatY[1])
# avoid negative zeros
chi_loc[np.where(chi_loc == 0.0)] = np.abs(chi_loc[np.where(chi_loc == 0.0)])
# make observation dictionary
COSI_DataSet = {'Day':trafiles[i][StrBeg:StrBeg+StrLen],
'Energies':erg,
'TimeTags':tt,
'Xpointings':np.array([lonX,latX]).T,
'Ypointings':np.array([lonY,latY]).T,
'Zpointings':np.array([lonZ,latZ]).T,
'Phi':phi,
'Chi local':chi_loc,
'Psi local':psi_loc,
'Distance':dist,
'Chi galactic':chi_gal,
'Psi galactic':psi_gal}
COSI_Data.append(COSI_DataSet)
return COSI_Data
def hourly_tags(COSI_Data,n_hours=24):
"""
Get COSI data reformatted to one data set per hour in each day of the observation
(Basically only useful if not single observations are used)
Output is a dictionary of the form:
data = {'Day':COSI_Data[i]['Day'],
'Hour':h,
'Indices':tdx}
:param: COSI_Data dictionary from read_COSI_DataSet
"""
# time conversions
s2d = 1./86400
s2h = 1./3600
# number of hours per day
#n_hours = 24 # TS: by default 24, otherwise set according to data set
# fill data
data = []
for i in range(len(COSI_Data)):
for h in range(n_hours):
tdx = np.where( (minmin(COSI_Data[i]['TimeTags'])*s2h >= h) &
(minmin(COSI_Data[i]['TimeTags'])*s2h <= h+1) )
tmp_data = {'Day':COSI_Data[i]['Day'],
'Hour':h,
'Indices':tdx}
data.append(tmp_data)
return data
def hourly_binning(COSI_Data):
"""
Get total times, counts, and average observations per hour of observation
(Note that the mean of different angles over time doesnt make sense, and should only be used for illustration purpose!)
Output is a dictionary of the form:
data = {'Times':times,
'Counts':counts,
'GLons':glons,
'GLats':glats}
:param: COSI_Data dictionary from read_COSI_DataSet
"""
# initialise sequential binning
tmp = np.histogram(COSI_Data[0]['TimeTags'],bins=24)
times = tmp[1][0:-1]
counts = tmp[0]
# add nonsense start array (remove later)
gcoords = np.array([[-99],[-99]])
# loop over hours
for t in range(len(tmp[0])):
gcoords = np.concatenate([gcoords,
np.nanmean(COSI_Data[0]['Zpointings'][np.where((COSI_Data[0]['TimeTags'] >= tmp[1][t]) &
(COSI_Data[0]['TimeTags'] <= tmp[1][t+1]))[0],:],
axis=0).reshape(2,1)],axis=1)
glons = gcoords[0,:]
glats = gcoords[1,:]
glons = np.delete(glons,0) # get rid of -99
glats = np.delete(glats,0) # get rid of -99
# loop over remaining days
for i in range(len(COSI_Data)-1):
# check for unexpected time tags
bad_idx = np.where(COSI_Data[i+1]['TimeTags'] < COSI_Data[i]['TimeTags'][-1])
if len(bad_idx[0]) > 0:
for key in COSI_Data[i+1].keys():
if key != 'Day':
COSI_Data[i+1][key] = np.delete(COSI_Data[i+1][key],bad_idx,axis=0)
# continue as before
tmp = np.histogram(COSI_Data[i+1]['TimeTags'],bins=24)
times = np.concatenate((times,tmp[1][0:-1]))
counts = np.concatenate((counts,tmp[0]))
gcoords = np.array([[-99],[-99]])
for t in range(len(tmp[0])):
gcoords = np.concatenate([gcoords,
np.nanmean(COSI_Data[i+1]['Zpointings'][np.where((COSI_Data[i+1]['TimeTags'] >= tmp[1][t]) &
(COSI_Data[i+1]['TimeTags'] <= tmp[1][t+1]))[0],:],
axis=0).reshape(2,1)],axis=1)
glons_tmp = gcoords[0,:]
glats_tmp = gcoords[1,:]
glons_tmp = np.delete(glons_tmp,0)
glats_tmp = np.delete(glats_tmp,0)
glons = np.concatenate([glons,glons_tmp])
glats = np.concatenate([glats,glats_tmp])
data = {'Times':times,
'Counts':counts,
'GLons':glons,
'GLats':glats}
return data
def FISBEL(n_bins,lon_shift,verbose=False):
"""
MEGAlib's FISBEL spherical axis binning
/MEGAlib/src/global/misc/src/MBinnerFISBEL.cxx
Used to make images with more information (pixels) in the centre, and less at higher latitudes
// CASEBALL - Constant area, squares at equator, borders along latitude & longitude
// Rules:
// (1) constant area
// (2) squarish at equator
// (3) All borders along latitude & longitude lines
// (4) latitude distance close to equal
Don't know where "lon_shift" is actually required, keeping it for the moment
:param: n_bins number of bins to populate the sky (typically 1650 (~5 deg) or 4583 (~3 deg))
:param: lon_shift ???
:option: verbose True = more verbose output
Returns CoordinatePairs and respective Binsizes
"""
# if only one bin, full sky in one bin
if (n_bins == 1):
LatitudeBinEdges = [0,np.pi]
LongitudeBins = [1]
else:
FixBinArea = 4*np.pi/n_bins
SquareLength = np.sqrt(FixBinArea)
n_collars = np.int((np.pi/SquareLength-1)+0.5) + 2
# -1 for half one top AND Bottom, 0.5 to round to next integer
# +2 for the half on top and bottom
verb(verbose,'Number of bins: %4i' % n_bins)
verb(verbose,'Fix bin area: %6.3f' % FixBinArea)
verb(verbose,'Square length: %6.3f' % SquareLength)
verb(verbose,'Number of collars: %4i' % n_collars)
LongitudeBins = np.zeros(n_collars)
LatitudeBinEdges = np.zeros(n_collars+1)
# Top and bottom first
LatitudeBinEdges[0] = 0
LatitudeBinEdges[n_collars] = np.pi
# Start on top and bottom with a circular region:
LongitudeBins[0] = 1
LongitudeBins[n_collars - 1] = LongitudeBins[0]
LatitudeBinEdges[1] = np.arccos(1 - 2.0/n_bins)
LatitudeBinEdges[n_collars - 1] = np.pi - LatitudeBinEdges[1]
# now iterate over remaining bins
for collar in range(1,np.int(np.ceil(n_collars/2))):
UnusedLatitude = LatitudeBinEdges[n_collars-collar] - LatitudeBinEdges[collar]
UnusedCollars = n_collars - 2*collar
NextEdgeEstimate = LatitudeBinEdges[collar] + UnusedLatitude/UnusedCollars
NextBinsEstimate = 2*np.pi * (np.cos(LatitudeBinEdges[collar]) - np.cos(NextEdgeEstimate)) / FixBinArea
# roundgind
NextBins = np.int(NextBinsEstimate+0.5)
NextEdge = np.arccos(np.cos(LatitudeBinEdges[collar]) - NextBins*FixBinArea/2/np.pi)
# insert at correct position
LongitudeBins[collar] = NextBins
if (collar != n_collars/2):
LatitudeBinEdges[collar+1] = NextEdge
LongitudeBins[n_collars-collar-1] = NextBins
if (collar != n_collars/2):
LatitudeBinEdges[n_collars-collar-1] = np.pi - NextEdge
LongitudeBinEdges = []
for nl in LongitudeBins:
if (nl == 1):
LongitudeBinEdges.append(np.array([0,2*np.pi]))
else:
n_lon_edges = nl+1
LongitudeBinEdges.append(np.linspace(0,2*np.pi,n_lon_edges))
#verb(verbose,'LatitudeBins: %4i' % n_collars)
#verb(verbose,'LatitudeBinEdges: %6.3f' % LatitudeBinEdges)
#verb(verbose,'LongitudeBins: %4i' % LongitudeBins)
#verb(verbose,'LongitudeBinEdges: %6.3f' % np.array(LongitudeBinEdges))
CoordinatePairs = []
Binsizes = []
for c in range(n_collars):
for l in range(np.int(LongitudeBins[c])):
CoordinatePairs.append([np.mean(LatitudeBinEdges[c:c+2]),np.mean(LongitudeBinEdges[c][l:l+2])])
Binsizes.append([np.diff(LatitudeBinEdges[c:c+2]),np.diff(LongitudeBinEdges[c][l:l+2])])
return CoordinatePairs,Binsizes
def get_binned_data(COSI_Data,tdx,pp,bb,ll,dpp,dbb,dll):
"""
Re-format COSI data set into phi, psi, and chi (last two FISBELed) bins.
Here assuming full data set with 47 days and 24 hours, requires FISBEL and phi bins and edges
to be set up with COSIpy_tools.FISBEL()
:param: COSI_Data COSI data set dictionary from read_COSI_DataSet()
:param: tdx Time tag indices as hourly binned dictionary from hourly_tags()
:param: pp PHI bins from FISBEL
:param: bb PSI bins from FISBEL
:param: ll CHI bins from FISBEL
:param: dpp PHI bin sizes
:param: dbb PSI bin sizes
:param: dll CHI bin sizes
Returns 4D array of shape (47,24,36,1650) with 47 days, 24 hours, 36 PHI, abd 1650 FISBEL bins
"""
# init data array
binned_data = np.zeros((47,24,36,1650))
# not really used now; played with tolerance for bin edges (now np.around >> very slow)
tol = 1e-6
# loop over days, hours, phi, psi-chi-fisbel
for d in tqdm(range(47)):
for h in range(24):
for p in range(len(pp)):
for c in range(len(ll)):
binned_data[d,h,p,c] = len(np.where((COSI_Data[d]['Phi'][tdx[d,h]['Indices']] >= np.around(pp[p]-dpp[p]/2,6)) &
(COSI_Data[d]['Phi'][tdx[d,h]['Indices']] < np.around(pp[p]+dpp[p]/2,6)) &
(COSI_Data[d]['Psi local'][tdx[d,h]['Indices']] >= np.around(bb[c]-dbb[c]/2,6)) &
(COSI_Data[d]['Psi local'][tdx[d,h]['Indices']] < np.around(bb[c]+dbb[c]/2,6)) &
(COSI_Data[d]['Chi local'][tdx[d,h]['Indices']] >= np.around(ll[c]-dll[c]/2,6)) &
(COSI_Data[d]['Chi local'][tdx[d,h]['Indices']] < np.around(ll[c]+dll[c]/2,6)))[0])
#might be faster with some tools, don't know yet
return binned_data
def get_binned_data_complete(COSI_Data,pp,bb,ll,dpp,dbb,dll):
"""
Same as get_binned_data() but for data set without separate time information (everything lumped together)
:param: COSI_Data COSI data set dictionary from read_COSI_DataSet()
:param: pp PHI bins from FISBEL
:param: bb PSI bins from FISBEL
:param: ll CHI bins from FISBEL
:param: dpp PHI bin sizes
:param: dbb PSI bin sizes
:param: dll CHI bin sizes
Returns 2D array of shape (36,1650) with 36 PHI, abd 1650 FISBEL bins
"""
# init data array
binned_data = np.zeros((36,1650))
# loop over phi and psi-chi-fisbel
for p in range(len(pp)):
for c in range(len(ll)):
# darn np.around
idx = np.where((COSI_Data[0]['Phi'] >= np.around(pp[p]-dpp[p]/2,6)) &
(COSI_Data[0]['Phi'] < np.around(pp[p]+dpp[p]/2,6)) &
(COSI_Data[0]['Psi local'] >= np.around(bb[c]-dbb[c]/2,6)) &
(COSI_Data[0]['Psi local'] < np.around(bb[c]+dbb[c]/2,6)) &
(COSI_Data[0]['Chi local'] >= np.around(ll[c]-dll[c]/2,6)) &
(COSI_Data[0]['Chi local'] < np.around(ll[c]+dll[c]/2,6)))[0]
binned_data[p,c] = len(idx)
return binned_data
def get_binned_data_oneday(COSI_Data,tdx,pp,bb,ll,dpp,dbb,dll):
"""
Same as get_binned_data() but for data set with only one day (24 hours)
:param: COSI_Data COSI data set dictionary from read_COSI_DataSet()
:param: tdx Time tag indices as hourly binned dictionary from hourly_tags() as (1,24) array
:param: pp PHI bins from FISBEL
:param: bb PSI bins from FISBEL
:param: ll CHI bins from FISBEL
:param: dpp PHI bin sizes
:param: dbb PSI bin sizes
:param: dll CHI bin sizes
Returns 3D array of shape (24,36,1650) with 36 PHI, abd 1650 FISBEL bins
"""
# init data array
binned_data = np.zeros((24,36,1650))
# same as above
tol = 1e-6
# loops as above
for h in tqdm(range(24)):
for p in range(len(pp)):
for c in range(len(ll)):
binned_data[h,p,c] = len(np.where((COSI_Data[0]['Phi'][tdx[0,h]['Indices']] >= np.around(pp[p]-dpp[p]/2,6)) &
(COSI_Data[0]['Phi'][tdx[0,h]['Indices']] < np.around(pp[p]+dpp[p]/2,6)) &
(COSI_Data[0]['Psi local'][tdx[0,h]['Indices']] >= np.around(bb[c]-dbb[c]/2,6)) &
(COSI_Data[0]['Psi local'][tdx[0,h]['Indices']] < np.around(bb[c]+dbb[c]/2,6)) &
(COSI_Data[0]['Chi local'][tdx[0,h]['Indices']] >= np.around(ll[c]-dll[c]/2,6)) &
(COSI_Data[0]['Chi local'][tdx[0,h]['Indices']] < np.around(ll[c]+dll[c]/2,6)))[0])
return binned_data
def get_binned_data_hourly(COSI_Data,tdx,pp,bb,ll,dpp,dbb,dll,n_hours):
"""
Same as get_binned_data() but for data set with n_hours hours
:param: COSI_Data COSI data set dictionary from read_COSI_DataSet()
:param: tdx Time tag indices as hourly binned dictionary from hourly_tags() as (1,n_hours) array
:param: pp PHI bins from FISBEL
:param: bb PSI bins from FISBEL
:param: ll CHI bins from FISBEL
:param: dpp PHI bin sizes
:param: dbb PSI bin sizes
:param: dll CHI bin sizes
:param: n_hours Number of hours in data set to bin to
Returns 3D array of shape (n_hours,36,1650) with 36 PHI, 1650 FISBEL bins
"""
# init data array
binned_data = np.zeros((n_hours,36,1650))
# tolerance of binning (strange effects when binning in angle space)
tol = 6 #1e-6
phimin_r = np.around(pp-dpp/2,tol)
phimax_r = np.around(pp+dpp/2,tol)
psimin_r = np.around(bb-dbb/2,tol)
psimax_r = np.around(bb+dbb/2,tol)
chimin_r = np.around(ll-dll/2,tol)
chimax_r = np.around(ll+dll/2,tol)
# loops as above
for h in tqdm(range(n_hours)):
phis = COSI_Data[0]['Phi'][tdx[0,h]['Indices']]
psis = COSI_Data[0]['Psi local'][tdx[0,h]['Indices']]
chis = COSI_Data[0]['Chi local'][tdx[0,h]['Indices']]
for p in range(len(pp)):
for c in range(len(ll)):
binned_data[h,p,c] = len(np.where((phis >= phimin_r[p]) &
(phis < phimax_r[p]) &
(psis >= psimin_r[c]) &
(psis < psimax_r[c]) &
(chis >= chimin_r[c]) &
(chis < chimax_r[c]))[0])
return binned_data
# def get_binned_data_hourly(COSI_Data,tdx,pp,bb,ll,dpp,dbb,dll,n_hours=24):
# """
# Same as get_binned_data() but for data set with only one day (24 hours)
# :param: COSI_Data COSI data set dictionary from read_COSI_DataSet()
# :param: tdx Time tag indices as hourly binned dictionary from hourly_tags() as (1,24) array
# :param: pp PHI bins from FISBEL
# :param: bb PSI bins from FISBEL
# :param: ll CHI bins from FISBEL
# :param: dpp PHI bin sizes
# :param: dbb PSI bin sizes
# :param: dll CHI bin sizes
# Returns 3D array of shape (n_hours,36,1650) with 36 PHI, abd 1650 FISBEL bins
# """
# # init data array
# binned_data = np.zeros((n_hours,36,1650))
# # same as above
# tol = 1e-6
# # loops as above
# for h in tqdm(range(n_hours)):
# for p in range(len(pp)):
# for c in range(len(ll)):
# binned_data[h,p,c] = len(np.where((COSI_Data[0]['Phi'][tdx[0,h]['Indices']] >= np.around(pp[p]-dpp[p]/2,6)) &
# (COSI_Data[0]['Phi'][tdx[0,h]['Indices']] < np.around(pp[p]+dpp[p]/2,6)) &
# (COSI_Data[0]['Psi local'][tdx[0,h]['Indices']] >= np.around(bb[c]-dbb[c]/2,6)) &
# (COSI_Data[0]['Psi local'][tdx[0,h]['Indices']] < np.around(bb[c]+dbb[c]/2,6)) &
# (COSI_Data[0]['Chi local'][tdx[0,h]['Indices']] >= np.around(ll[c]-dll[c]/2,6)) &
# (COSI_Data[0]['Chi local'][tdx[0,h]['Indices']] < np.around(ll[c]+dll[c]/2,6)))[0])
# return binned_data
def get_binned_data_oneday_halfhourwise(COSI_Data,tdx,pp,bb,ll,dpp,dbb,dll):
"""
Same as get_binned_data() but for data set with only one day (48 half-hours)
:param: COSI_Data COSI data set dictionary from read_COSI_DataSet()
:param: tdx Time tag indices as hourly binned dictionary from hourly_tags() as (1,48) array
:param: pp PHI bins from FISBEL
:param: bb PSI bins from FISBEL
:param: ll CHI bins from FISBEL
:param: dpp PHI bin sizes
:param: dbb PSI bin sizes
:param: dll CHI bin sizes
Returns 3D array of shape (48,36,1650) with 36 PHI, abd 1650 FISBEL bins
"""
# init data array
binned_data = np.zeros((48,36,1650))
# same as above
tol = 1e-6
# loops as above
for h in tqdm(range(48)):
for p in range(len(pp)):
for c in range(len(ll)):
binned_data[h,p,c] = len(np.where((COSI_Data[0]['Phi'][tdx[0,h]['Indices']] >= np.around(pp[p]-dpp[p]/2,6)) &
(COSI_Data[0]['Phi'][tdx[0,h]['Indices']] < np.around(pp[p]+dpp[p]/2,6)) &
(COSI_Data[0]['Psi local'][tdx[0,h]['Indices']] >= np.around(bb[c]-dbb[c]/2,6)) &
(COSI_Data[0]['Psi local'][tdx[0,h]['Indices']] < np.around(bb[c]+dbb[c]/2,6)) &
(COSI_Data[0]['Chi local'][tdx[0,h]['Indices']] >= np.around(ll[c]-dll[c]/2,6)) &
(COSI_Data[0]['Chi local'][tdx[0,h]['Indices']] < np.around(ll[c]+dll[c]/2,6)))[0])
return binned_data
def get_binned_data_oneday_energy(COSI_Data,tdx,pp,bb,ll,ee,dpp,dbb,dll,dee):
"""
Same as get_binned_data() but for data set with only one day (24 hours)
:param: COSI_Data COSI data set dictionary from read_COSI_DataSet()
:param: tdx Time tag indices as hourly binned dictionary from hourly_tags() as (1,24) array
:param: pp PHI bins from FISBEL
:param: bb PSI bins from FISBEL
:param: ll CHI bins from FISBEL
:param: ee ENERGIES bin centre (self-defined)
:param: dpp PHI bin sizes
:param: dbb PSI bin sizes
:param: dll CHI bin sizes
:param: dee ENERGY bin widths (consistently defined with ee)
Returns 3D array of shape (n_e,24,36,1650) with 36 PHI, 1650 FISBEL bins, and n_e ENERGY bins
"""
# init data array
n_e = len(ee)
binned_data = np.zeros((n_e,24,36,1650))
# same as above
tol = 1e-6
# loops as above
for e in tqdm(range(n_e)):
for h in tqdm(range(24)):
for p in range(len(pp)):
for c in range(len(ll)):
binned_data[e,h,p,c] = len(np.where((COSI_Data[0]['Energies'][tdx[0,h]['Indices']] >= (ee[e]-dee[e]/2)) &
(COSI_Data[0]['Energies'][tdx[0,h]['Indices']] < (ee[e]+dee[e]/2)) &
(COSI_Data[0]['Phi'][tdx[0,h]['Indices']] >= np.around(pp[p]-dpp[p]/2,6)) &
(COSI_Data[0]['Phi'][tdx[0,h]['Indices']] < np.around(pp[p]+dpp[p]/2,6)) &
(COSI_Data[0]['Psi local'][tdx[0,h]['Indices']] >= np.around(bb[c]-dbb[c]/2,6)) &
(COSI_Data[0]['Psi local'][tdx[0,h]['Indices']] < np.around(bb[c]+dbb[c]/2,6)) &
(COSI_Data[0]['Chi local'][tdx[0,h]['Indices']] >= np.around(ll[c]-dll[c]/2,6)) &
(COSI_Data[0]['Chi local'][tdx[0,h]['Indices']] < np.around(ll[c]+dll[c]/2,6)))[0])
return binned_data
def plot_FISBEL(ll,bb_in,dll,dbb,values,colorbar=False,projection=False):
"""
Plot FISBEL-binned data given the definition of FISBEL bins and the corresponding 1D array of values
:param: ll azimuth,longitude,psi bin centers
:param: bb_in zenith,latitude,theta bin centers
:param: dll azimuth,longitude,psi bin sizes
:param: dbb zenith,latitude,theta bin sizes
:param: values array of values to plot as color (3rd dimension)
:option: colorbar True = add colorbar to plot
"""
# change initial FISBEL definition of bb to avoid random graphic issues (mainly in projection)
bb = bb_in - np.pi
bb = np.abs(bb)
# set up figure
plt.figure(figsize=(16,9))
if projection:
plt.subplot(projection=projection)
bb -= np.pi/2
# make colorbar in viridis according to entry values
tmp_data = values
cmap = plt.cm.viridis
norm = matplotlib.colors.Normalize(vmin=tmp_data.min(), vmax=tmp_data.max())
# plot points only
fig = plt.scatter(ll,bb,s=0.5,zorder=3000,c=tmp_data)
if colorbar==True:
plt.colorbar()
plt.scatter(ll,bb,s=0.5,zorder=3001)
# loop over FISBEL bins to add coloured tiles
for i in range(len(bb)):
# no idea how to makes this more efficient, but takes for ever
plt.fill_between((ll[i]+np.array([-dll[i],+dll[i],+dll[i],-dll[i],-dll[i]])/2.),
(bb[i]+np.array([-dbb[i],-dbb[i],+dbb[i],+dbb[i],-dbb[i]])/2.),
color=cmap(norm(tmp_data[i])),zorder=i)
# add lines around each tile
plt.plot((ll[i]+np.array([-dll[i],+dll[i],+dll[i],-dll[i],-dll[i]])/2.),
(bb[i]+np.array([-dbb[i],-dbb[i],+dbb[i],+dbb[i],-dbb[i]])/2.),
color='black',linewidth=1,zorder=1000+i)
# add standard labels
plt.xlabel('Azimuth')
plt.ylabel('Zenith')
# use these limits
#plt.xlim(-np.pi,np.pi)
#plt.ylim(0,np.pi)
# not
def zero_func(x,y,grid=False):
"""Returns an array of zeros for any given input array (or scalar) x.
:param: x Input array (or scalar, tuple, list)
:param: y Optional second array or value
:option: grid Standard keyword to work with RectBivarSpline
"""
if isinstance(x, (list, tuple, np.ndarray)):
return np.zeros(len(x))
else:
return 0.
def one_func(x,y,grid=False):
"""Returns an array of ones for any given input array (or scalar) x.
:param: x Input array (or scalar, tuple, list)
:param: y Optional second array or value
:option: grid Standard keyword to work with RectBivarSpline
"""
if isinstance(x, (list, tuple, np.ndarray)):
return np.ones(len(x))
else:
return 1.
def get_response(Response,zenith,azimuth,deg=False,cut=65):
"""
Calculate response for a given zenith/azimuth position up to a certain threshold cut in zenith.
:param: Response List(!) of response function to be looped over in 1D
:param: zenith Zenith position of source with respect to instrument (in rad)
:param: azimuth Azimuth position of source with respect to instrument (in rad)
:option: deg Default False, if True, degree angles are converted into radians
:option: cut Default 65 deg, range up to which response is calculated (COSI FoV ~ 60 deg)
"""
# check for rad input
if deg == True:
zenith, azimuth = np.deg2rad(zenith), np.deg2rad(azimuth)
# loop over response list
val = np.array([Response[r](zenith,azimuth,grid=False) for r in range(len(Response))])
# check that values are strictly non-negative (may have happened during RectBivarSpline interpolation)
val[val<0] = 0.
# zero out values beyond the cut (and if negative zeniths happened)
val[:,(zenith < 0) | (zenith > np.deg2rad(cut))] = 0
# make everything finite
val[np.isnan(val)] = 0.
return val
def get_response_with_weights(Response,zenith,azimuth,deg=True,binsize=5,cut=60.0):
"""
Calculate response at given zenith/azimuth position of a source relative to COSI,
using the angular distance to the 4 neighbouring pixels that overlap using a
certain binsize.
Note that this also introduces some smoothing of the response as zeniths/azimuths
on the edges or corners of pixels will not be weighted equally but still get
contributions from the remaining pixels.
:param: Response Response grid with regular sky pixel dimension (zenith x azimuth)
and unfolded 1D phi-psi-chi dimension.
:param: zenith Zenith positions of the source with respect to the instrument (in deg)
:param: azimuth Azimuth positions of the source with respect to the instrument (in deg)
:option: deg Default True, (right now not checked for any purpose)
:option: binsize Default 5 deg (matching the sky dimension of the response). If set
differently, make sure it matches the sky dimension as otherwise,
false results may be returned
:option: cut Threshold to cut the response calculation after a certain zenith angle.
Default 60 deg (~ COSI FoV)
Returns an array of length equal the response that is input.
"""
# calculate the weighting for neighbouring pixels using their angular distance
# also returns the indices of which pixels to be used for response averaging
widx = get_response_weights_vector(zenith,azimuth,binsize,cut=cut)
# This is a vectorised function so that each entry gets its own weighting
# at the correct positions of the input angles ([:, None] is the same as
# column-vector multiplcation of a lot of ones)
rsp0 = Response[widx[0][0,1,:],widx[0][0,0,:],:]*widx[1][0,:][:, None]
rsp1 = Response[widx[0][1,1,:],widx[0][1,0,:],:]*widx[1][1,:][:, None]
rsp2 = Response[widx[0][2,1,:],widx[0][2,0,:],:]*widx[1][2,:][:, None]
rsp3 = Response[widx[0][3,1,:],widx[0][3,0,:],:]*widx[1][3,:][:, None]
# add together
rsp_mean = rsp0 + rsp1 + rsp2 + rsp3
return rsp_mean
def get_response_weights_vector(zenith,azimuth,binsize=5,cut=57.4):
"""
Get Compton response pixel weights (four nearest neighbours),
weighted by angular distance to zenith/azimuth vector(!) input.
Binsize determines regular(!!!) sky coordinate grid in degrees.
For single zenith/azimuth pairs use get_response_weights()
:param: zenith Zenith positions of the source with respect to the instrument (in deg)
:param: azimuth Azimuth positions of the source with respect to the instrument (in deg)
:option: binsize Default 5 deg (matching the sky dimension of the response). If set
differently, make sure it matches the sky dimension as otherwise,
false results may be returned
:option: cut Threshold to cut the response calculation after a certain zenith angle.
Default 57.4 deg (0.1 deg before last pixel reaching beyon 60 deg)
"""
# assuming useful input:
# azimuthal angle is periodic in the range [0,360[
# zenith ranges from [0,180[
# check which pixel (index) was hit on regular grid
hit_pixel_zi = np.floor(zenith/binsize)
hit_pixel_ai = np.floor(azimuth/binsize)
# and which pixel centre
hit_pixel_z = (hit_pixel_zi+0.5)*binsize
hit_pixel_a = (hit_pixel_ai+0.5)*binsize
# check which zeniths are beyond threshold
bad_idx = np.where(hit_pixel_z > cut)
# calculate nearest neighbour pixels indices
za_idx = np.array([[np.floor(azimuth/binsize+0.5),np.floor(zenith/binsize+0.5)],
[np.floor(azimuth/binsize+0.5),np.floor(zenith/binsize-0.5)],
[np.floor(azimuth/binsize-0.5),np.floor(zenith/binsize+0.5)],
[np.floor(azimuth/binsize-0.5),np.floor(zenith/binsize-0.5)]]).astype(int)
# take care of bounds at zenith (azimuth is allowed to be -1!)
(za_idx[:,1,:])[np.where(za_idx[:,1,:] < 0)] += 1
(za_idx[:,1,:])[np.where(za_idx[:,1,:] >= 180/binsize)] = int(180/binsize-1)
# but azimuth may not be larger than range [0,360/binsize[
(za_idx[:,0,:])[np.where(za_idx[:,0,:] >= 360/binsize)] = 0
# and pixel centres of neighbours
azimuth_neighbours = (za_idx[:,0]+0.5)*binsize
zenith_neighbours = (za_idx[:,1]+0.5)*binsize
# calculate angular distances to neighbours
dists = angular_distance(azimuth_neighbours,zenith_neighbours,azimuth,zenith)
# inverse weighting to get impact of neighbouring pixels
n_in = len(zenith)
weights = (1/dists)/np.sum(1/dists,axis=0).repeat(4).reshape(n_in,4).T
# if pixel is hit directly, set weight to 1.0
weights[np.isnan(weights)] = 1
# set beyond threshold weights to zero
weights[:,bad_idx] = 0
return za_idx,weights