-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathforsims_sciserver.py
1939 lines (1647 loc) · 92.2 KB
/
forsims_sciserver.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
"""
Created on Wed Jul 21 17:35:34 2021
Revised Late Fall + Winter of 2021-2022 to work on SciServer
@author: rlmcclure/jhunt/cfilion
"""
#%%
#python 3.8
import datetime
from astropy.units import equivalencies
import numpy as np
import galpy
try:
from galpy.util import coords
except:
from galpy.util import bovy_coords as coords
import astropy.units as u
import matplotlib.pyplot as plt
import matplotlib
import pickle
import pandas as pd
from mpl_toolkits import mplot3d
import matplotlib.animation as animation
from matplotlib.animation import FuncAnimation
from matplotlib.gridspec import GridSpec
import os
import glob
from scipy.signal import find_peaks
plt.rcParams.update({'font.size': 22})
class SimHandler(object):
'''
Dev by R L McClure to interact with an perform analysis on J Hunt's 2021 simulations
This Class is designed to interact with the Bonsai simulation outputs.
Particles can be traced through the simulation and individual snaps can be loaded.
Some alterations by C. Filion to make it such that we can work with the data volume system
of sciserver.
There are also additional changes adapted from G.Lemson to speed up performance.
note - C. Filion also added re-centering function, adapted from J Hunt. This
is an optional flag when loading a whole snap, and is an additional function that one can
apply to a set of particle locations in time (an orbit). Note that to move into the bar frame,
the galaxy must be centered first.
Contact [email protected] and/or [email protected] for updates or problems or friendship.
###
For users of the original SimHandler class on the Flatiron cluster: C. Filion has
removed certain functionalities from the SimHandler that are more specialised
and related to R. McClure and C. Filion's projects, such that the SimHandler is
now a generic class for using the simulations.
When initializing the class, you pass in the simulation name - this will ensure you are loading the simulation
with the correct values for particle numbers etc
This class no longer automatically computes
cylindrical coordinates, which speeds up performance! As such, commondtype no longer includes cylindrical coordinates
###
'''
def __init__(self, sim, *args,**kwargs):
print('start init at: '+str(datetime.datetime.now()),flush=True)
self.verbose = 0 #default verbosity is zero but can go up to like 4 or 5
#path info defaults
self.path = '/home/idies/workspace/SMUDGE/'
self.db = 'data*'
self.sim = str(sim)
self.recenter = False
if self.sim == 'M1':
self.pointfpath = '/home/idies/workspace/SMUDGE/data11_03/M1pointers/' #path for pointer .npy files
#initial values as determined by BN-2 simulation
# there are 219,607,640 star particles in the disk, 21,960,680 in the bulge,
#and 153,599 in the dwarf satellite -- aka a total of 241,721,919 stars
# there are 878431120 dark particles in big galaxy, 2880684 in the satellite
self.ntot = 1123033723
self.ndark=881311804
self.nstar= 241721919
self.masscutoff = 400 #mass flag boundary between bulge and disk
if self.sim == 'M2':
self.pointfpath = '/home/idies/workspace/SMUDGE/data11_03/M2pointers/' #path for pointer .npy files - none yet
self.ntot = 1283033643
self.ndark=1006801964
self.nstar= 276231679
self.masscutoff = 400 #mass flag boundary between bulge and disk
if self.sim == 'D2':
self.pointfpath = '/home/idies/workspace/SMUDGE/data11_03/D2pointers/' #path for pointer .npy files
self.ntot = 1279999360
self.ndark=1003921280
self.nstar= 276078080
self.masscutoff = 400 #mass flag boundary between bulge and disk
if self.sim == 'D1':
self.pointfpath = '' #path for pointer .npy files
print('note - there are no pointers or pattern speed files for this simulation')
self.ntot = 1119999440
self.ndark=878431120
self.nstar= 241568320
self.masscutoff = 400 #mass flag boundary between bulge and disk
if self.sim != 'M1' and self.sim != 'M2' and self.sim != 'D2' and self.sim != 'D1':
print('Requested simulation is not in the list of hosted simulations (M1, M2, D1, or D2). No known',
'parameters on hand. Proceed at your own risk.',
'Numbers of particles will be computed on-the-fly. A pointer path must be specified')
self.pointfpath = None
#initial values as determined by BN-2 simulation
# there are 219,607,640 star particles in the disk, 21,960,680 in the bulge,
#and 153,599 in the dwarf satellite -- aka a total of 241,721,919 stars
# there are 878431120 dark particles in big galaxy, 2880684 in the satellite
self.ntot = None
self.ndark= None
self.nstar= None
self.masscutoff = 400 #mass flag boundary between bulge and disk
#set a string to be appended into save formats
self.savestr=''
#simulation data output info
self.ncores = None #number of cores the particles are spread between, M1 is 24, D2 is 32
#params for functions
self.targetangle = 0 #for the bar frame adjustment target
self.downsamplefrac = 0.00005 #fraction to downsample to
self.downsamplen = None #if this is set it will take priority over the downsample frac option
self.find_angle_rbounds = [1.5,2.5] #r bounds to compute the fft for determining the bar location, all in kpc
self.find_angle_m = 2#looking for the m=2 mode
#boolean loading type params
self.wdm = 0 #toggle in dark matter or not
self.barframe = 0 #default is to not load in the bar frame
self.kmpers = 1 #set params as km/s, there's really no reason to change this ever in my opinion
self.sort = 1 #sort in creating the pointers and assume that the pointers are sorted, you should never change this
#default bounds for grabbing particles or snaps
self.start = 0
self.finish = None
self.times = None #this will be made during the init
#load the pattern speeds for the array
self.patternspeeds = None
#data types
self.infodtype = [('time','d'),('n','i'),('ndim','i'),('ng','i'),('nd','i'),('ns','i'),('on','i')]
self.stellardtype = [('mass','f'), ('x','f'), ('y','f'), ('z','f'), ('vx','f'), ('vy','f'), ('vz','f'), ('metals','f'), ('tform','f'), ('ID','Q')]
self.dmdtype = [('mass','f'), ('x','f'), ('y','f'), ('z','f'), ('vx','f'), ('vy','f'), ('vz','f'), ('ID','Q')]
#data types for saving any snap or particle
#self.commondtype = [('t','d'),('x','f'), ('y','f'), ('z','f'), ('vx','f'), ('vy','f'), ('vz','f'), ('vr','f'), ('vphi','f'), ('vzz','f'), ('r','f'), ('phi','f'), ('zz','f'), ('mass','f'), ('idd','Q')]
self.commondtype = [('t','d'),('x','f'), ('y','f'), ('z','f'), ('vx','f'), ('vy','f'), ('vz','f'), ('mass','f'), ('idd','Q')]
#this one should never be accessed, there are a couple old files though that may be in this format -- if needed though it's here
self.oldsnapdtype = [('t','d'), ('idd','Q'),('x','f'), ('y','f'), ('z','f'), ('vx','f'), ('vy','f'), ('vz','f'), ('vr','f'), ('vphi','f'), ('vzz','f'), ('r','f'), ('phi','f'), ('zz','f'), ('mass','f')]
#data type for the pointer files that particle tracing functions use
self.pointdtype = [('idd','Q'),('core','H'), ('db1', 'H'),('db2', 'H'), ('seek','I')] ####need to add in which DB!
self.errrange = 200 #default range to look on either side of where something /should/ be in a pointer file
self.approxhalofrac = .1 #approximage halo fraction of the stellar population to speed up pointer file use
#if not(os.path.isdir('plots')):
# print('Making plots/ directory for output figures.', flush=True)
# os.path.mkdir('plots')
print('end at: '+str(datetime.datetime.now()),flush=True)
def gettimes(self, return_array=False):
path_01 = self.path + 'data01_01' + '/' + str(self.sim) + '/'
if self.times is None:
try:
self.times = sorted(glob.glob(path_01+'snapshot*-0')) #remember! glob is not sorted!
for ii,t in enumerate(self.times):
self.times[ii] = t.split('/')[-1]
except:
self.times = 'snapshot__00000.0000-0'
if return_array == True:
return self.times
def timestot(self,s):
return(float(s.split('-')[-2].split('_')[-1])*9.778145/1000.) #Gyr
def loadpatternspeeds(self):
#try to load the pattern speed array for this sim if it's available
if self.patternspeeds is None:
try:
self.patternspeeds = np.load(self.pointfpath+'patternspeed.npy')
except:
print('ATTN: Cannot load pattern speeds because file does not exist for this simulation at %s'%self.path, flush=True)
#%%
def printnow(self):
print('check: '+str(datetime.datetime.now()),flush=True)
#loaders
#% load one snapshot
def loader(self,filename,infoonly=0,forcedarkmatter=None):
"""
loads an individual time snapshot from an individual node
converts to physical units
Inputs
------------------
filename (str): path to file of snapshot
wdm (boolean): with dark matter toggle, will get stars and dark matter
Returns
------------------
cats (np.ndarray): stars [mass value for disk or bluge (float32), x position(float32),
y position (float32), z position (float32), vx x velocity(float32),
vy y velocity(float32), vz z velocity(float32), metals (float32),
tform (float), ID (uint64)]
if self.wdm==True:
returns tuple with (catd,cats,info) where catd (np.ndarray): dark matter particles [same as above]
"""
catd = []
cats = []
with open(filename, 'rb') as f:
if infoonly == True:
if self.verbose>1:
print(filename)
#file info
info= np.fromfile(f,dtype=self.infodtype,count=1)
infoBytes = f.tell()
if self.verbose>2:
print(infoBytes)
elif self.wdm == False:
if self.verbose>1:
print(filename)
#file info
info= np.fromfile(f,dtype=self.infodtype,count=1)
infoBytes = f.tell()
if self.verbose>2:
print(infoBytes)
#skip darkmatter
#read the first dm line
if self.verbose>2:
print(f.tell())
catd = np.fromfile(f,dtype=self.dmdtype, count=1)
#get the bytes location and subtract off the bytes location after loading info to get n bytes a line for dm
if self.verbose>2:
print(f.tell())
current = f.tell()
dmBytes = current-infoBytes
f.seek(dmBytes*(info['nd'][0]-1)+current)
if self.verbose>2:
print(f.tell())
# stars setup
cats= np.fromfile(f,dtype=self.stellardtype, count=info['ns'][0])
if self.verbose>2:
print('done')
else:
if self.verbose>1:
print(filename)
#file info
info= np.fromfile(f,dtype=self.infodtype,count=1)
if self.verbose>2:
print(f.tell())
#dark matter setup count is reading the number of rows
catd= np.fromfile(f,self.dmdtype, count=info['nd'][0])
if self.verbose>2:
print(f.tell())
# stars setup
cats= np.fromfile(f,dtype=self.stellardtype, count=info['ns'][0])
if self.verbose>2:
print('done')
if infoonly == False:
#convert to physical units as found in README.md
if self.wdm == True:
catd['mass']*=2.324876e9
if self.kmpers == 1:
catd['vx']*=100.
catd['vy']*=100.
catd['vz']*=100.
cats['mass']*=2.324876e9
if self.kmpers == True:
cats['vx']*=100.
cats['vy']*=100.
cats['vz']*=100.
if (self.wdm == True) or (forcedarkmatter==True):
return(catd,cats,info)
else:
return(cats,info)
#% load one whole timestep, load a single snap
def loadwholesnap(self,timestepid,forcebarframe=None,forcedarkmatter=None):
#check that times exists
self.gettimes()
if self.kmpers != 1:
print('ATTN: Enabled 100 km/s units instead of km/s for velocities.')
direcs = os.listdir(self.path)
c = 0
coreid_array = np.array([])
sim_direcs = np.array([])
for i in direcs:
if self.sim in os.listdir(self.path+str(i)):
c+=1
coreid = os.listdir(self.path+str(i)+'/'+str(self.sim))[0].split('-')[1]
coreid_array = np.append(coreid_array, coreid)
sim_direcs = np.append(sim_direcs, i)
#if the number of total, dark, and stellar particles are not set then determine
if self.ncores is None:
self.ncores = c
if self.ntot==None:
if self.verbose >0:
print('Loading to find nstars, ndark, and ntot'+self.path+str(sim_direcs[0])+self.times[timestepid][:-1]+str(coreid_array[0]), flush=True)
_,info=self.loader(self.path+ str(sim_direcs[0]) + '/' + str(self.sim) + '/' + self.times[timestepid][:-1]+str(coreid_array[0]),infoonly=1)
self.ntot=info['n']
self.ndark=info['nd']
self.nstar=info['ns']
if self.ncores is None:
self.ncores = c
for j in range(1,self.ncores): #loader will just load the info line and leave
coreid = coreid_array[j]
sim_path = sim_direcs[j]
print(sim_path)
if self.verbose >1:
print('Loading '+self.path+str(sim_path)+self.times[timestepid][:-1]+str(coreid), flush=True)
_,info=self.loader(self.path+str(sim_path)+'/'+str(self.sim)+'/'+self.times[timestepid][:-1]+str(coreid),infoonly=1)
self.ntot=self.ntot+info['n']
self.ndark=self.ndark+info['nd']
self.nstar=self.nstar+info['ns']
if self.verbose >2:
print('in length maker',self.ntot,self.ndark,self.nstar,info['n'],info['nd'],info['ns'],flush=True)
#now load the first core for information and to start filling the array
sim_path = sim_direcs[0] #first one
coreid = coreid_array[0]
if self.verbose > 1:
print('\nLoading (also to set info) ', self.path+str(sim_path)+'/'+str(self.sim)+'/'+self.times[timestepid][:-1]+str(coreid), flush=True)
if (self.wdm == True) or (forcedarkmatter==True):
catd,cats,info=self.loader(self.path+str(sim_path)+'/'+str(self.sim)+'/'+self.times[timestepid][:-1]+str(coreid),forcedarkmatter=forcedarkmatter)
else:
cats,info=self.loader(self.path+str(sim_path)+'/'+str(self.sim)+'/'+self.times[timestepid][:-1]+str(coreid))
if self.verbose > 1:
print(info['n'],info['ns'],info['nd'], flush=True)
if self.verbose > 2:
print(self.ntot,self.ndark,self.nstar, flush=True)
#allocate for the snap arrays
snaparr = np.empty(self.nstar,dtype=self.commondtype)
if (self.wdm == True) or (forcedarkmatter==True):
snaparr_dark = np.empty(self.ndark,dtype=self.commondtype)
tnstar=int(info['ns'])
if (self.wdm == True) or (forcedarkmatter==True):
tndark=int(info['nd'])
snaparr['x'][0:tnstar]=cats['x']
snaparr['y'][0:tnstar]=cats['y']
snaparr['z'][0:tnstar]=cats['z']
snaparr['vx'][0:tnstar]=cats['vx']
snaparr['vy'][0:tnstar]=cats['vy']
snaparr['vz'][0:tnstar]=cats['vz']
snaparr['mass'][0:tnstar]=cats['mass']
snaparr['idd'][0:tnstar]=cats['ID']
snaparr['t'][0:tnstar]=info['time']*9.778145/1000.
arrayindx=tnstar
if (self.wdm == True) or (forcedarkmatter==True):
snaparr_dark['x'][0:tndark]=catd['x']
snaparr_dark['y'][0:tndark]=catd['y']
snaparr_dark['z'][0:tndark]=catd['z']
snaparr_dark['vx'][0:tndark]=catd['vx']
snaparr_dark['vy'][0:tndark]=catd['vy']
snaparr_dark['vz'][0:tndark]=catd['vz']
snaparr_dark['mass'][0:tndark]=catd['mass']
snaparr_dark['idd'][0:tndark]=catd['ID']
snaparr_dark['t'][0:tndark]=info['time']*9.778145/1000.
arrayindx_dark = tndark
if self.verbose > 2:
print('stellar index is ',arrayindx, flush=True)
for j in range(1,self.ncores):
coreid = coreid_array[j]
sim_path = sim_direcs[j]
if self.verbose > 1:
print('Loading '+self.path+str(sim_path)+'/'+str(self.sim)+'/'+self.times[timestepid][:-1]+str(coreid), flush=True)
if (self.wdm == True) or (forcedarkmatter==True):
catd,cats,info=self.loader(self.path+str(sim_path)+'/'+str(self.sim)+'/'+self.times[timestepid][:-1]+str(coreid),forcedarkmatter=forcedarkmatter)
else:
cats,info=self.loader(self.path+str(sim_path)+'/'+str(self.sim)+'/'+self.times[timestepid][:-1]+str(coreid))
tnstar=int(info['ns'])
if (self.wdm == True) or (forcedarkmatter==True):
tndark = int(info['nd'])
if self.verbose > 2:
print(arrayindx,tnstar,arrayindx+tnstar, flush=True)
snaparr['x'][arrayindx:arrayindx+tnstar]=cats['x']
snaparr['y'][arrayindx:arrayindx+tnstar]=cats['y']
snaparr['z'][arrayindx:arrayindx+tnstar]=cats['z']
snaparr['vx'][arrayindx:arrayindx+tnstar]=cats['vx']
snaparr['vy'][arrayindx:arrayindx+tnstar]=cats['vy']
snaparr['vz'][arrayindx:arrayindx+tnstar]=cats['vz']
snaparr['idd'][arrayindx:arrayindx+tnstar]=cats['ID']
snaparr['mass'][arrayindx:arrayindx+tnstar]=cats['mass']
snaparr['t'][arrayindx:arrayindx+tnstar]=info['time']*9.778145/1000.
arrayindx=arrayindx+tnstar
if (self.wdm == True) or (forcedarkmatter==True):
snaparr_dark['x'][arrayindx_dark:arrayindx_dark+tndark]=catd['x']
snaparr_dark['y'][arrayindx_dark:arrayindx_dark+tndark]=catd['y']
snaparr_dark['z'][arrayindx_dark:arrayindx_dark+tndark]=catd['z']
snaparr_dark['vx'][arrayindx_dark:arrayindx_dark+tndark]=catd['vx']
snaparr_dark['vy'][arrayindx_dark:arrayindx_dark+tndark]=catd['vy']
snaparr_dark['vz'][arrayindx_dark:arrayindx_dark+tndark]=catd['vz']
snaparr_dark['idd'][arrayindx_dark:arrayindx_dark+tndark]=catd['ID']
snaparr_dark['mass'][arrayindx_dark:arrayindx_dark+tndark]=catd['mass']
snaparr_dark['t'][arrayindx_dark:arrayindx_dark+tndark]=info['time']*9.778145/1000.
arrayindx_dark=arrayindx_dark+tndark
#except:
# print(times[i]+'-'+str(j),'has no star particles', flush=True)
if self.recenter == True:
snaparr = self.apply_recen_snap(snaparr)
#move into bar frame if true
if (self.barframe == True) or (forcebarframe==True):
#check for path
if os.path.exists(self.pointfpath+'patternspeed.npy'):
snaparr = self.intobarframe(snaparr,frame=timestepid)
if (self.wdm == True) or (forcedarkmatter==True):
snaparr_dark = self.intobarframe(snaparr_dark,frame=timestepid)
else: #this is so inefficient never use it and intobarframe isnt set up for it -- okay but what about with the smaller sims?
print('ATTN: skipping moivng into bar pattern frame because speeds not computed yet')
# pspeed = getpatternspeed(path,timestepid,inputsnaparr=snaparr,verbose=verbose,withbarangle=1) #also in radperGyr
# snaparr = intobarframe(snaparr,timestepid)
if (self.wdm == True) or (forcedarkmatter==True):
return(snaparr,snaparr_dark)
else:
return(snaparr)
#% load whole pickle step
def loadstep(self,timestepid):
fstr = self.path+'step'+str(timestepid)+'.p'
#load the pickle
with open(fstr,'rb') as f:
idd,x,y,z,vx,vy,vz,mass = pickle.load(f)
return (idd,x,y,z,vx,vy,vz,mass)
def makepointerf(self):
#check that times exists
self.gettimes()
#ncores = len(glob.glob(self.path+'*'+self.times[0][:-1]+'*'))
######
direcs = os.listdir(self.path)
c = 0
coreid_array = np.array([])
sim_direcs = np.array([])
for i in direcs:
if self.sim in os.listdir(self.path+str(i)):
c+=1
coreid = os.listdir(self.path+str(i)+'/'+str(self.sim))[0].split('-')[1]
coreid_array = np.append(coreid_array, coreid)
sim_direcs = np.append(sim_direcs, i)
#if the number of total, dark, and stellar particles are not set then determine
if self.ncores is None:
self.ncores = c
#####
if self.verbose >0:
print('Loading to find nstars, ndark, and ntot'+self.path+self.times[0], flush=True)
#_,info=self.loader(self.path+self.times[0])
_,info=self.loader(self.path+ str(sim_direcs[0]) + '/' +
str(self.sim) + '/' +
self.times[0][:-1]+
str(coreid_array[0]))
self.ntot=info['n']
self.ndark=info['nd']
self.nstar=info['ns']
ncores = c
for j in range(1,ncores):
####
coreid = coreid_array[j]
sim_path = sim_direcs[j]
###
if self.verbose > 1:
print('Loading '+self.path+str(sim_path)+
self.times[0][:-1]+str(coreid), flush=True)
#_,info=self.loader(self.path+self.times[0][:-1]+str(j))
_,info=self.loader(self.path+str(sim_path)+'/'+
str(self.sim)+'/'+
self.times[0][:-1]+
str(coreid))
self.ntot=self.ntot+info['n']
self.ndark=self.ndark+info['nd']
self.nstar=self.nstar+info['ns']
if self.verbose > 1:
print('in length maker',self.ntot,self.ndark,self.nstar,info['n'],info['nd'],info['ns'],flush=True)
starti = len(glob.glob(self.pointfpath+'*stellar*'))
for ts,tt in enumerate(self.times[starti: self.pointfend]):
###this is a good spot to change this to a max time step -
#set file name for the timestep pointer file
tsstr = tt.split('-')[:-1][0]
#print('tsstr', tsstr)
if self.verbose >3:
print('tsstr', tsstr)
tsname = 'stellar_'+self.path.split('/')[-2]+'_'+tsstr
#print('tsname', tsname)
#?sort cause this could be used to make it faster later, cause they're unique we dont really need to do this
#initalize this file's stellar array
starpointarr = np.empty(self.nstar,dtype=self.pointdtype)
arrayindx = 0
for nc in range(0,ncores):
if self.verbose >2:
print('core '+str(nc), flush=True)
#load nth core of timestep/snapshot
sim_path = sim_direcs[nc]
core_id = coreid_array[nc]
print(sim_path, core_id)
fname = self.path+str(sim_path)+'/'+ str(self.sim)+'/'+str(tsstr)+'-'+str(core_id)
#+str(nc)
print(fname)
if self.verbose >1:
print('Loading '+fname, flush=True)
with open(fname, 'rb') as f:
# get byte lengths
info = np.fromfile(f,dtype=self.infodtype,count=1)
infoBytes = f.tell()
if self.verbose>2:
print('Info byte length is '+str(infoBytes), flush=True)
#read the first dm line
catd = np.fromfile(f,dtype= self.dmdtype, count=1)
current = f.tell()
dmBytes = current-infoBytes
if self.verbose>2:
print('DM byte length is '+str(dmBytes), flush=True)
#seek forward past rest of dm data
f.seek(dmBytes*(info['nd'][0]-1)+current)
if self.verbose>2:
print('Advanced through DM to '+str(f.tell()), flush=True)
#get star byte info
cats= np.fromfile(f,dtype=self.stellardtype, count=1)
current = f.tell()
print('cats', cats, cats.shape)
if self.verbose >2:
print(f.tell())
stBytes = current-dmBytes*(info['nd'][0])-infoBytes
if self.verbose>2:
print('Stellar byte length is '+str(stBytes), flush=True)
print(f.tell())
#seek back to start of stars
startofStellar = current-stBytes
f.seek(startofStellar)
if self.verbose>2:
print('Back to start of star '+str(f.tell()))
# stars setup
if self.verbose >1:
print('loading stellar')
self.printnow()
cats= np.fromfile(f,dtype=self.stellardtype, count=info['ns'][0])
afterStellar = f.tell()
print('after stars '+str(f.tell()))
print('info ns 0', info['ns'][0])
if info['ns'][0] > 0:
sim_path = str(sim_direcs[nc])
first_part = sim_path.split('data')[1][0:2]
second_part = sim_path.split('data')[1][3:5]
core_id = coreid_array[nc]
print('saving out idd, core, sim_direc, seek')
#print(core_id, sim_path, core_id.shape, 'simdirecs shape',
# sim_direcs[nc].shape)
starpointarr['idd'][arrayindx:arrayindx+info['ns'][0]] = cats['ID']
starpointarr['core'][arrayindx:arrayindx+info['ns'][0]] = core_id
#breaking sim_path into first number, second number & saving out
starpointarr['db1'][arrayindx:arrayindx+info['ns'][0]] = int(first_part)
starpointarr['db2'][arrayindx:arrayindx+info['ns'][0]] = int(second_part)
#
starpointarr['seek'][arrayindx:arrayindx+info['ns'][0]] = np.arange(startofStellar,afterStellar,stBytes)
print('sim_path[0], first part, second part', sim_path, first_part, int(first_part),
second_part, int(second_part))
else:
if self.verbose>1:
print('No stellar particles in '+fname, flush=True)
if self.verbose >1:
self.printnow()
print(arrayindx)
arrayindx += info['ns'][0]
print(arrayindx)
if self.verbose >1:
print('saving timestep '+tsname)
self.printnow()
#sort by idx so that the loc is the idd
if self.sort == 1: #this is an integral part of this function and should never be skipped unless the sim is very small
sortorder = np.argsort(starpointarr['idd'])
sortpointer = np.empty(len(starpointarr),dtype=self.pointdtype)
sortpointer['idd'] = starpointarr['idd'][sortorder]
sortpointer['core'] = starpointarr['core'][sortorder]
####added
sortpointer['db1'] = starpointarr['db1'][sortorder]
sortpointer['db2'] = starpointarr['db2'][sortorder]
sortpointer['seek'] = starpointarr['seek'][sortorder]
#save as a pickle .npy file cause it's wicked fast
print('up to save step!!')
np.save(self.pointfpath+tsname,sortpointer)
else:
print('up to save step!!')
#save as a pickle .npy file cause it's wicked fast
np.save(self.pointfpath+tsname,starpointarr)
if self.verbose >1:
print('finished saving timestep '+tsname)
self.printnow()
def downsamplesnap(self,snaparr,downsampmult=None):
startinginds = range(len(snaparr))
if self.downsamplen is None:
if downsampmult is None:
downsampleinds = np.random.choice(startinginds,
int(round(self.downsamplefrac*len(startinginds))),
replace=False)
else:
downsampleinds = np.random.choice(startinginds,
int(round(self.downsamplefrac*downsampmult*len(startinginds))),
replace=False)
else:
if downsampmult is None:
downsampleinds = np.random.choice(startinginds,int(self.downsamplen),replace=False)
else:
downsampleinds = np.random.choice(startinginds,int(self.downsamplen*downsampmult),replace=False)
return(snaparr[downsampleinds])
#%% load one particle over time
def loadonesource(self,idx,start=None,finish=None,forcebarframe=0):
'''
takes a path to the folder containing snapshots and an id
returns an array
dtype=[('t','f'),('x','f'), ('y','f'), ('z','f'),
('vx','f'), ('vy','f'), ('vz','f'),('mass','f'), ('idd','Q')]
set 'npypointerpath' to pointfpath
or 'loadall': loadall will toggle to itterate through and load all the arrays
npypointer will access .npy pointer files
'''
if self.kmpers != 1:
print('ATTN: Enabled 100 km/s units instead of km/s for velocities.')
idx = np.uint64(idx) #force this datatype
#get start and finish from params if none, allows for itterative loading
if start is None:
start = self.start
if finish is None:
finish = self.finish
#check for times
self.gettimes()
##fixed this
#if self.ncores == None:
# ncores = len(glob.glob(self.path+'*'+self.times[0][:-1]+'*'))
direcs = os.listdir(self.path)
c = 0
coreid_array = np.array([])
sim_direcs = np.array([])
for i in direcs:
if self.sim in os.listdir(self.path+str(i)):
c+=1
coreid = os.listdir(self.path+str(i)+'/'+str(self.sim))[0].split('-')[1]
coreid_array = np.append(coreid_array, coreid)
sim_direcs = np.append(sim_direcs, i)
#if the number of total, dark, and stellar particles are not set then determine
if self.ncores is None:
self.ncores = c
#set other params
if (finish == None) or (finish > len(self.times)):
print('ATTN: Setting finish tind as ', str(len(self.times)))
finish = len(self.times)
# let's allocate space for the finished final array for one source
tlen = len(range(start,finish))
sourcearr=np.empty(tlen,dtype=self.commondtype)
if self.pointfpath == None:
indvarrayindx=0
lastcore = 0
for i in range(start,finish):
#looping over times -
keepgoing = 1
if keepgoing > 0:
if self.verbose > 1:
#print('Loading starting from last core first '+self.path+self.times[i][:-1]+str(lastcore), flush=True)
print('loading ', self.path+ str(sim_direcs[0]) + '/' + str(self.sim) + '/' + self.times[i][:-1]+ str(coreid_array[0]))
if self.wdm == True:
_,cats, info=self.loader(self.path+ str(sim_direcs[0]) + '/' + str(self.sim) + '/' + self.times[i][:-1]+ str(coreid_array[0]))
# _,cats,info= self.loader(self.path+self.times[i][:-1]+str(lastcore))
else:
cats,info= self.loader(self.path+ str(sim_direcs[0]) + '/' + str(self.sim) + '/' + self.times[i][:-1]+str(coreid_array[0]))
#self.loader(self.path+self.times[i][:-1]+str(lastcore))
if np.where(np.isin(cats['ID'],idx,assume_unique=1))[0].size > 0:
j = lastcore
if self.verbose > 0:
print('Source found in '+self.path+self.times[i][:-1]+str(j), flush=True)
lastcore = j
if self.verbose > 1:
print('Last core is ',j)
foundid = np.argwhere(idx == cats['ID']).flatten()
if self.verbose >1:
print('printing cats[foundid]')
print(cats[foundid])
sourcearr['x'][indvarrayindx]=cats['x'][foundid]
sourcearr['y'][indvarrayindx]=cats['y'][foundid]
sourcearr['z'][indvarrayindx]=cats['z'][foundid]
sourcearr['vx'][indvarrayindx]=cats['vx'][foundid]
sourcearr['vy'][indvarrayindx]=cats['vy'][foundid]
sourcearr['vz'][indvarrayindx]=cats['vz'][foundid]
sourcearr['mass'][indvarrayindx]=cats['mass'][foundid]
sourcearr['idd'][indvarrayindx]=cats['ID'][foundid]
#sourcearr['vr'][indvarrayindx],sourcearr['vphi'][indvarrayindx],sourcearr['vzz'][indvarrayindx]=coords.rect_to_cyl_vec(cats['vx'][foundid],cats['vy'][foundid],cats['vz'][foundid],cats['x'][foundid],cats['y'][foundid],cats['z'][foundid])
#sourcearr['r'][indvarrayindx],sourcearr['phi'][indvarrayindx],sourcearr['zz'][indvarrayindx]=coords.rect_to_cyl(cats['x'][foundid],cats['y'][foundid],cats['z'][foundid])
sourcearr['t'][indvarrayindx]=info['time']*9.778145/1000.
keepgoing = 0
if keepgoing > 0:
for j in range(0,ncores):
if keepgoing > 0:
if self.verbose > 1:
print('Loading '+self.path+self.times[i][:-1]+str(j), flush=True)
print('actually loading', self.path+ str(sim_direcs[j]) + '/' + str(self.sim) + '/' + self.times[i][:-1]+str(coreid_array[j]))
if self.wdm == True:
_,cats,info= self.loader(self.path+ str(sim_direcs[j]) + '/' + str(self.sim) + '/' + self.times[i][:-1]+ str(coreid_array[j]))
#self.loader(self.path+self.times[i][:-1]+str(j))
else:
cats,info= self.loader(self.path+ str(sim_direcs[j]) + '/' + str(self.sim) + '/' + self.times[i][:-1]+ str(coreid_array[j]))
#self.loader(self.path+self.times[i][:-1]+str(j))
if np.where(np.isin(cats['ID'],idx,assume_unique=1))[0].size > 0:
if self.verbose > 0:
#print('Source found in '+self.path+self.times[i][:-1]+str(j), flush=True)
print('Source found in' + self.path+ str(sim_direcs[j]) + '/' + str(self.sim) + '/' + self.times[i][:-1]+str(coreid_array[j]))
lastcore = j
if self.verbose > 1:
print('Last core is ',j)
foundid = np.argwhere(idx == cats['ID']).flatten()
if self.verbose >1:
print('printing cats[\'x\'][foundid]')
print(cats['x'][foundid])
if self.verbose >1:
print('printing cats[\'ID\'][foundid]')
print(cats['ID'][foundid])
sourcearr['x'][indvarrayindx]=cats['x'][foundid]
sourcearr['y'][indvarrayindx]=cats['y'][foundid]
sourcearr['z'][indvarrayindx]=cats['z'][foundid]
sourcearr['vx'][indvarrayindx]=cats['vx'][foundid]
sourcearr['vy'][indvarrayindx]=cats['vy'][foundid]
sourcearr['vz'][indvarrayindx]=cats['vz'][foundid]
sourcearr['mass'][indvarrayindx]=cats['mass'][foundid]
sourcearr['idd'][indvarrayindx]=cats['ID'][foundid]
#sourcearr['vr'][indvarrayindx],sourcearr['vphi'][indvarrayindx],sourcearr['vzz'][indvarrayindx]=coords.rect_to_cyl_vec(cats['vx'][foundid],cats['vy'][foundid],cats['vz'][foundid],cats['x'][foundid],cats['y'][foundid],cats['z'][foundid])
#sourcearr['r'][indvarrayindx],sourcearr['phi'][indvarrayindx],sourcearr['zz'][indvarrayindx]=coords.rect_to_cyl(cats['x'][foundid],cats['y'][foundid],cats['z'][foundid])
sourcearr['t'][indvarrayindx]=info['time']*9.778145/1000.
keepgoing = 0
indvarrayindx+=1
#error out if cannot find the ID
if keepgoing > 0:
print('ID NOT FOUND in '+self.path+self.times[i][:-1])
break
else:
#check paths error
print('found pointer path')
if os.path.exists(self.pointfpath):
indvarrayindx=0
lspoint = os.listdir(self.pointfpath)
lspoint.sort(key=lambda s:s.split('_')[-1].split('.npy')[0])
#assumes that if patternspeed.npy is there, it will be the last file after sorting, could compare first and last item if this isnt always true
if lspoint[-1].find('patternspeed')>-1:
lspoint = lspoint[:-1]
for i in range(start,finish): #looping through time
pointerpath = self.pointfpath+lspoint[i]
#get pointer file
if self.verbose >2:
print('load pointer path: ',pointerpath)
self.printnow()
pointer = np.load(pointerpath,mmap_mode='r',allow_pickle=1)
if self.sort == 0:
bf = datetime.datetime.now()
found = pointer[pointer['idd']==idx]
if self.verbose > 2:
print('time for starpointarr[idx] is ',datetime.datetime.now()-bf)
print('found under sort', found)
else:
#offset application
if idx >10000000000000:
print('large idx!')
if self.verbose > 2:
bf = datetime.datetime.now()
try:
#grab sub array of region with halo particles
subr = pointer[-round(len(pointer)*self.approxhalofrac+self.errrange):]
found = subr[subr['idd']==idx]
if self.verbose >2:
print('time for subr[subr[\'idd\']==idx] is ',datetime.datetime.now()-bf)
except:
print('\n\nISSUE WITH FILE: ',pointerpath)
print('pointer[0]: ',pointer[0])
print('id is ', idx)
if pointer['idd'][0]==pointer['seek'][0]:
print('all zeros')
else:
if self.verbose > 2:
bf = datetime.datetime.now()
found=pointer[[idx]]
if self.verbose > 2:
print('found', found)
#catch when there's this weird offset of ~200 skipped IDs
if pointer[[idx]]['idd'][0]!=idx:
if self.verbose >1:
print('using error range to find local source')
#try except for end of array
try:
subarr = pointer[int(idx-self.errrange):int(idx+self.errrange)]
except:
subarr = pointer[int(idx-self.errrange):]
found = subarr[subarr['idd']==idx]
#print('found 2 ', found)
if len(found) <1:
if self.verbose >1:
print('expanding error range to find local source')
self.errrange *=2
try:
subarr = pointer[int(idx-self.errrange):int(idx+self.errrange)]
except:
subarr = pointer[int(idx-self.errrange):]
found = subarr[subarr['idd']==idx]
if len(found) <1:
print('\n\nthere\'s something wrong, error range expansion isn\'t enough to solve it')
if self.verbose > 2:
print('time for pointer[idx] is ',datetime.datetime.now()-bf)
#load the direct file
try:
if self.verbose > 0:
print('printing found under try', found)
print('Loading '+pointerpath, flush=True)
if self.verbose >2:
self.printnow()
#getting from DB1, DB2 to sim directory -
db1 = found['db1'][0]
db2 = found['db2'][0]
#if db1 is < 10, add zero in front of db1 bc file format is e.g. data05_02, data10_02
#db2 is always between 01 and 03
if db1 <= 9:
sim_loc = 'data0' + str(db1) + '_' + '0' + str(db2)
if db1 > 9:
sim_loc = 'data' + str(db1) + '_' + '0' + str(db2)
if db2 > 3:
print('uhoh, db2 is bigger than 3!')
filename = self.path+ str(sim_loc) + '/' + str(self.sim) + '/' + self.times[i][:-1]+ str(found['core'][0])
#self.path+ str(found['sim_direc'][0]) + '/' + str(self.sim) + '/' + self.times[i][:-1]+ str(found['core'][0])
#self.path+ str(sim_direcs[j]) + '/' + str(self.sim) + '/' + self.times[i][:-1]+ str(coreid_array[j])
#self.path+self.times[i][:-1]+str(found['core'][0])
if self.verbose>3:
print('filename', filename)
print('direc is', db1, db2, sim_loc)
print('core is ',found['core'][0])
with open(filename, 'rb') as f:
info= np.fromfile(f,dtype=self.infodtype,count=1)
if self.verbose>3:
print('seek to ',found['seek'][0])
f.seek(found['seek'][0])
cats= np.fromfile(f,dtype=self.stellardtype, count=1)
if self.verbose >2:
print('insert into indvarray')
self.printnow()
if self.verbose >1:
bf = datetime.datetime.now()
sourcearr['x'][indvarrayindx]=cats['x']
sourcearr['y'][indvarrayindx]=cats['y']
sourcearr['z'][indvarrayindx]=cats['z']
if self.kmpers == 1:
cats['vx']*=100.
cats['vy']*=100.
cats['vz']*=100.
sourcearr['vx'][indvarrayindx]=cats['vx']
sourcearr['vy'][indvarrayindx]=cats['vy']
sourcearr['vz'][indvarrayindx]=cats['vz']
sourcearr['mass'][indvarrayindx]=cats['mass'] * 2.324876e9 #converting to msun
sourcearr['idd'][indvarrayindx]=cats['ID']
if self.verbose >1:
print('time for plugging into array is ',datetime.datetime.now()-bf)
if self.verbose >2:
print('coords transf')
self.printnow()
if self.verbose >1:
bf = datetime.datetime.now()
#sourcearr['vr'][indvarrayindx],sourcearr['vphi'][indvarrayindx],sourcearr['vzz'][indvarrayindx]=coords.rect_to_cyl_vec(cats['vx'],cats['vy'],cats['vz'],cats['x'],cats['y'],cats['z'])
#sourcearr['r'][indvarrayindx],sourcearr['phi'][indvarrayindx],sourcearr['zz'][indvarrayindx]=coords.rect_to_cyl(cats['x'],cats['y'],cats['z'])
sourcearr['t'][indvarrayindx]=info['time']*9.778145/1000.
if self.verbose >1:
print('time for computing and plugging new vals into array is ',datetime.datetime.now()-bf)
if self.verbose >2:
print('onto the next loop')
self.printnow()
except:
print('\n\nISSUE WITH FILE: ',pointerpath,flush=True)
print('found[0]: ',found[0],flush=True)
indvarrayindx+=1
#move into bar frame if true
if (self.barframe == True) or (forcebarframe == True):
#check for path
if os.path.exists(self.pointfpath+'patternspeed.npy'):
sourcearr = self.intobarframe(sourcearr,start=start,finish=finish)
else: #this is so inefficient never use it and intobarframe isnt set up for it
print('ATTN: skipping moivng into bar pattern frame because speeds not computed yet', flush=True)
return(sourcearr)
def getperiapos(self,orbitarr,params=(['r','z']),returnperis=False,returnorbit=0,save=0,pathstr='',savestr=''):
#for an individual orbit, get the peri- and apo-centers in each direction of params
apos = []
if returnperis == True:
peris = []
if self.barframe == False and (params.count('x')+params.count('y'))>0:
print('ATTN: Cannot move forward with x or y as a param unless fixed in bar frame.', flush=True) #if in bar frame should be fine? -- check this
exit
#set data type to return the times and location of the parameter selected's peri/apo