-
Notifications
You must be signed in to change notification settings - Fork 0
/
caterpillaranalysis.py
1107 lines (1055 loc) · 49.1 KB
/
caterpillaranalysis.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 numpy as np
import pylab as plt
import os,subprocess,sys,time
import asciitable
import readsnapshots.readsnapHDF5_greg as rsg
import haloutils
import scipy.optimize as optimize
from scipy import interpolate
import profilefit
class PluginBase(object):
"""
When extending this class, make sure to define the following variables in __init__:
Data: filename
Plotting: xmin, xmax, ymin, ymax, xlog, ylog, xlabel, ylabel
n_xmin, n_xmax, n_ymin, n_ymax, n_xlabel, n_ylabel (for normtohost)
Figure name (for haloplot): autofigname
Define the following methods:
_analyze(self,hpath)
compute relevant quantities, save in hpath/OUTPUTFOLDERNAME
_read(self,hpath)
read the data computed/saved with _analyze(), return data
_plot(self,hpath,data,ax,lx=None,labelon=False,normtohost=False,**kwargs)
take data from _read() and plot in ax.
lx input is used when stacking multiple LX's on same plot (see convergeplot)
labelon calls self.label_plot in convergeplot, or you can define a custom labeling function
normtohost should normalize quantities to host halo (e.g. r/rvir, v/vvir, m/mvir) or z=0
or whatever other quantity makes sense to remove the effect of host mass
**kwargs should be used for plotting functions
"""
colordict = {11:'b',12:'r',13:'g',14:'m'}
OUTPUTFOLDERNAME = 'analysis'
def __init__(self):
self.filename=None
self.allhalos=True
self.radius=None
self.verbose=False
self.xmin=None; self.n_xmin=None
self.xmax=None; self.n_xmax=None
self.ymin=None; self.n_ymin=None
self.ymax=None; self.n_ymax=None
self.xlog=None
self.ylog=None
self.xlabel=''; self.n_xlabel=''
self.ylabel=''; self.n_ylabel=''
self.autofigname=None
def get_outfname(self,hpath):
""" Use this function in _analysis to generate the data filename """
analysispath = hpath+'/'+self.OUTPUTFOLDERNAME
subprocess.call("mkdir -p "+analysispath,shell=True)
thisgroup = subprocess.check_output(["stat", "-c", "'%G'", analysispath]).strip()[1:-1]
if thisgroup != 'annaproj' and thisgroup != 'nobody':
subprocess.call("chgrp annaproj "+analysispath,shell=True)
return hpath+'/'+self.OUTPUTFOLDERNAME+'/'+self.filename
def get_filename(self,hpath):
""" Use this function in _read to obtain the data filename """
assert hpath != None
assert self.filename != None
fname = hpath+'/'+self.OUTPUTFOLDERNAME+'/'+self.filename
if not os.path.exists(fname): raise IOError
return fname
def file_exists(self,hpath):
""" Use this function to check if the data file is already created """
if hpath==None: return False
try:
fname = self.get_filename(hpath)
return True
except IOError:
return False
### Analysis
def _analyze(hpath):
""" Implemented by plugins """
raise NotImplementedError
def analyze(self,hpath,recalc=False):
"""
Calculate this plugin's analysis on a given halo path.
Will not recalculate data files unless asked.
@param hpath: what halo to analyze
@param recalc: if true, force recalculation of the analysis (default False)
"""
if hpath==None: return
if recalc: self._analyze(hpath)
else:
if self.file_exists(hpath):
if self.verbose: print "Already analyzed: "+haloutils.get_foldername(hpath)
else: self._analyze(hpath)
### Reading data generated by analyze()
def _read(self,hpath):
""" Implemented by plugins """
raise NotImplementedError
def read(self,hpath,autocalc=True,recalc=False,stop_on_error=False):
"""
Read data associated with halo path.
@param hpath: which halo's data to read
@param autocalc: if true, automatically calls analyze() when data is missing (default True)
@param recalc: if true, force recalculation of the analysis (default False).
Can also pass in list of halo IDs to recalculate (useful if e.g. fixing one halo)
"""
if hpath==None: return None
if type(recalc) is list or type(recalc) is np.ndarray:
## if list of haloids, check if current hid is in that list
# TODO allow specifying LX
assert autocalc==True
recalcids = [haloutils.hidint(hid) for hid in recalc]
thishid = haloutils.get_parent_hid(hpath)
recalc = (thishid in recalcids)
if not recalc and self.file_exists(hpath):
try:
return self._read(hpath)
except Exception as e:
print "READ ERROR: {0}".format(hpath)
print sys.exc_info()
return None
elif autocalc:
start = time.time()
print "Automatically analyzing "+haloutils.get_foldername(hpath)+"..."+self.filename
if stop_on_error:
self.analyze(hpath,recalc=recalc)
else:
try:
self.analyze(hpath,recalc=recalc)
except Exception as e:
print "Automatic analysis failed..."
print sys.exc_info()
return None
print "Done! %.1f sec" % (time.time()-start)
return self._read(hpath) # if it crashes here, you have an error in your plugin code
else:
return None
### Plotting using output of read()
def _plot(self,hpath,data,ax,lx=None,labelon=False,normtohost=False,**kwargs):
""" Implemented by plugins """
raise NotImplementedError
def plot(self,hpath,ax,lx=None,labelon=False,normtohost=False,autocalc=True,recalc=False,stop_on_error=False,formatonly=False,usehaloname=False,**kwargs):
"""
Creates a plot of the data in hpath. Automatically calls analyze() if data missing.
@param hpath: which halo to plot
@param ax: axis object to create the plot in
@param lx: used for lxplot()
@param labelon: if True, label axis with the halo ID
@param autocalc: if True, automatically analyze data if missing
@param recalc: if true, force recalculation of the analysis (default False)
Can also pass in list of halo IDs to recalculate (useful if e.g. fixing one halo)
@param formatonly: if true, only format the plot (default False)
@param usehaloname: if true, label with the halo's name instead of ID number
@param **kwargs: keyword arguments (intended for plotting parameters)
"""
if usehaloname: label='catnum'
else: label=None
if formatonly: #TODO this isn't very elegant
self.format_plot(ax,normtohost=normtohost)
if labelon: self.label_plot(hpath,ax,normtohost=normtohost,label=label)
return
data = self.read(hpath,autocalc=autocalc,recalc=recalc,stop_on_error=stop_on_error)
try:
baddata = data==None
except TypeError:
baddata = False
if baddata:
self.format_plot(ax,normtohost=normtohost)
if labelon: self.label_plot(hpath,ax,normtohost=normtohost,label=label)
return
self._plot(hpath,data,ax,lx=lx,labelon=labelon,normtohost=normtohost,**kwargs)
if labelon: self.label_plot(hpath,ax,normtohost=normtohost,label=label)
self.format_plot(ax,normtohost=normtohost)
def lxplot(self,hid,ax,whichlx=[11,12,13,14],**kwargs):
lxlist = haloutils.get_lxlist(hid)
hpaths = haloutils.get_lxlist(hid,gethpaths=True)
for lx,hpath in zip(lxlist,hpaths):
formatonly = (lx not in whichlx)
self.plot(hpath,ax,lx=lx,labelon=True,formatonly=formatonly,**kwargs)
def customplot(self,ax,*args,**kwargs):
raise NotImplementedError
### Default plotting formatting
def get_plot_params(self,normtohost):
if normtohost:
assert self.n_xmin != None and self.n_xmax != None and self.n_xmax > self.n_xmin
assert self.n_ymin != None and self.n_ymax != None and self.n_ymax > self.n_ymin
xmin = self.n_xmin; xmax = self.n_xmax; ymin = self.n_ymin; ymax = self.n_ymax
xlabel = self.n_xlabel; ylabel = self.n_ylabel
else:
assert self.xmin != None and self.xmax != None and self.xmax > self.xmin
assert self.ymin != None and self.ymax != None and self.ymax > self.ymin
xmin = self.xmin; xmax = self.xmax; ymin = self.ymin; ymax = self.ymax
xlabel = self.xlabel; ylabel = self.ylabel
assert self.xlog != None and self.ylog != None
return xmin,xmax,ymin,ymax,self.xlog,self.ylog,xlabel,ylabel
def format_plot(self,ax,normtohost=False):
xmin,xmax,ymin,ymax,xlog,ylog,xlabel,ylabel = self.get_plot_params(normtohost)
ax.set_xlim((xmin,xmax))
ax.set_ylim((ymin,ymax))
ax.set_xlabel(xlabel)
ax.set_ylabel(ylabel)
if xlog: ax.set_xscale('log')
if ylog: ax.set_yscale('log')
def label_plot(self,hpath,ax,label=None,normtohost=False,dx=.05,dy=.1,fontsize='medium',**kwargs):
if label==None:
label = r'$\rm{'+haloutils.hidstr(haloutils.get_parent_hid(hpath))+r'}$'
elif label=='catnum':
label = r'$\rm{'+haloutils.hpath_name(hpath)+r'}$'
xmin,xmax,ymin,ymax,xlog,ylog,xlabel,ylabel = self.get_plot_params(normtohost)
if xlog:
logxoff = np.log10(xmax/xmin)*dx
xlabel = xmin * 10**logxoff
else:
xoff = (xmax-xmin)*dx
xlabel = xmin + xoff
if ylog:
logyoff = np.log10(ymax/ymin)*dy
ylabel = ymax * 10**(-logyoff)
else:
yoff = (ymax-ymin)*dy
ylabel = ymax - yoff
ax.text(xlabel,ylabel,label,color='black',fontsize=fontsize,**kwargs)
### Helper methods for analysis
def get_rssubs(self,rscat,zoomid):
if self.allhalos:
return rscat.get_all_subhalos_within_halo(zoomid,radius=self.radius)
else:
return rscat.get_subhalos_within_halo(zoomid,radius=self.radius)
## Adapted from Greg's BestMethods.py
def distance(self,posA,posB,boxsize=None):
dist = abs(posA-posB)
if boxsize != None:
tmp = dist > boxsize/2.0
dist[tmp] = boxsize-dist[tmp]
return np.sqrt(np.sum(dist**2,axis=1))
def row_magnitude(self,matrix):
"""
Find magnitude of each row.
@ param matrix: m x n matrix.
@ return: m x 1 column vector of magnitudes.
"""
return np.sqrt(sum((matrix**2).T))[:,np.newaxis]
def row_norm(self,matrix):
magnitude = self.row_magnitude(matrix)
matrix = matrix.astype('d') #make sure array is all floats
return np.nan_to_num(matrix/magnitude)
def row_dot(self,a,b):
return sum((a*b).T)[:,np.newaxis]
## Contour Plots
def find_confidence_interval(self,x, pdf, confidence_level):
return pdf[pdf > x].sum() - confidence_level
def density_contour(self,xdata, ydata, nbins_x, nbins_y):
""" Create a density contour plot.
xdata : numpy.ndarray
ydata : numpy.ndarray
nbins_x : int
Number of bins along x dimension
nbins_y : int
Number of bins along y dimension
"""
H, xedges, yedges = np.histogram2d(xdata, ydata, bins=(nbins_x,nbins_y), normed=True)
x_bin_sizes = (xedges[1:] - xedges[:-1]).reshape((1,nbins_x))
y_bin_sizes = (yedges[1:] - yedges[:-1]).reshape((nbins_y,1))
pdf = (H.T*(x_bin_sizes*y_bin_sizes))
one_sigma = optimize.brentq(self.find_confidence_interval, 0., 1., args=(pdf, 0.68))
two_sigma = optimize.brentq(self.find_confidence_interval, 0., 1., args=(pdf, 0.954))
three_sigma = optimize.brentq(self.find_confidence_interval, 0., 1., args=(pdf, 0.997))
levels = [one_sigma, two_sigma, three_sigma]
X, Y = 0.5*(xedges[1:]+xedges[:-1]), 0.5*(yedges[1:]+yedges[:-1])
Z = pdf
return X,Y,Z,levels
class MultiPlugin(PluginBase):
"""
When extending this class, make sure to define the following variables in __init__:
Plotting: xmin, xmax, ymin, ymax, xlog, ylog, xlabel, ylabel
Figure name (for haloplot): autofigname
Also make sure to call super(xxx,self).__init__(pluglist)
Define the following methods:
_plot(self,hpath,datalist,ax,lx=None,labelon=False,normtohost=False,**kwargs)
take datalist (order is the same as pluglist) and plot in ax.
lx input is used when stacking multiple LX's on same plot (see convergeplot)
**kwargs should be used for plotting functions
"""
def __init__(self,pluglist):
super(MultiPlugin,self).__init__()
self.nplugs = len(pluglist)
self.pluglist = pluglist
for plug in self.pluglist:
assert isinstance(plug,PluginBase), 'plugs in pluglist must be of type PluginBase'
def get_outfname(self,hpath):
""" Use this function in _analysis to generate the data filename """
subprocess.call("mkdir -p "+hpath+'/'+self.OUTPUTFOLDERNAME,shell=True)
return [hpath+'/'+self.OUTPUTFOLDERNAME+'/'+plug.filename for plug in self.pluglist]
def get_filename(self,hpath):
""" Use this function in _read to obtain the data filename """
assert hpath != None
for plug in self.pluglist: assert plug.filename != None
fnames = [hpath+'/'+self.OUTPUTFOLDERNAME+'/'+plug.filename for plug in self.pluglist]
for fname in fnames:
if not os.path.exists(fname): raise IOError
return fnames
def file_exists(self,hpath):
""" Use this function to check if the data file is already created """
if hpath==None: return False
try:
fnames = self.get_filename(hpath)
return True
except IOError:
return False
### Analysis
def analyze(self,hpath,recalc=False):
"""
Calculate this plugin's analysis on a given halo path.
Will not recalculate data files unless asked.
@param hpath: what halo to analyze
@param recalc: if true, force recalculation of the analysis (default False)
"""
if hpath==None: return
for plug in self.pluglist:
plug.analyze(hpath,recalc=recalc)
### Reading data generated by analyze()
def read(self,hpath,autocalc=True,recalc=False,stop_on_error=False):
"""
Read data associated with halo path.
@param hpath: which halo's data to read
@param autocalc: if true, automatically calls analyze() when data is missing (default True)
@param recalc: if true, force recalculation of the analysis (default False)
"""
if hpath==None: return None
datalist = []
for plug in self.pluglist:
datalist.append(plug.read(hpath,autocalc=autocalc,recalc=recalc,stop_on_error=stop_on_error))
nonetest = False
for data in datalist:
if data==None: nonetest=True
if nonetest: return None
else: return datalist
### No need to redefine plot() as long as _plot is defined properly.
def _plot(self,hpath,datalist,ax,lx=None,labelon=False,normtohost=False,**kwargs):
""" Implemented by plugins """
raise NotImplementedError
class NvmaxPlugin(PluginBase):
def __init__(self,vmin=0.3,vmax=100,Nmin=1,Nmax=10**4.9):
super(NvmaxPlugin,self).__init__()
self.filename='Nvmax.dat'
self.logvmin = -1.
self.logvmax = 3.
self.dlogv = 0.05
self.vmaxbins = 10.**np.arange(self.logvmin,self.logvmax+self.dlogv,self.dlogv)
self.xmin = vmin; self.xmax = vmax
self.ymin = Nmin; self.ymax = Nmax
self.xlabel = r'$V_{\rm max}\ (km/s)$'
self.ylabel = r'$N(>V_{\rm max})$'
self.n_xmin = 10**-2.9; self.n_xmax = 10**0.1
self.n_ymin = self.ymin; self.n_ymax = self.ymax
self.n_xlabel = r'$V_{\rm max}/V_{\rm vir}$'
self.n_ylabel = self.ylabel
self.xlog = True; self.ylog = True
self.autofigname='Nvmax'
def calcNvmax(self,vmax):
h,x = np.histogram(vmax,bins=self.vmaxbins)
return np.cumsum(h[::-1])[::-1]
def _analyze(self,hpath):
if not haloutils.check_last_rockstar_exists(hpath):
raise IOError("No rockstar")
numsnaps = haloutils.get_numsnaps(hpath)
rscat = haloutils.load_rscat(hpath,numsnaps-1)
zoomid = haloutils.load_zoomid(hpath)
eps = 1000*haloutils.load_soft(hpath)
subs = self.get_rssubs(rscat,zoomid)
svmax = np.array(subs['vmax'])
srmax = np.array(subs['rvmax'])
svmaxp = svmax * np.sqrt(1+(eps/srmax)**2)
Nvmax = self.calcNvmax(svmax)
Nvmaxp = self.calcNvmax(svmaxp)
try:
scat = haloutils.load_scat(hpath)
bestgroup = 0
ssvmax = scat.sub_vmax[0:scat.group_nsubs[0]]
ssrmax = scat.sub_vmaxrad[0:scat.group_nsubs[0]]
ssvmaxp = ssvmax*np.sqrt(1+((eps/1000.)/ssrmax)**2)
sNvmax = self.calcNvmax(ssvmax)
sNvmaxp = self.calcNvmax(ssvmaxp)
except IOError: #No Subfind
ssvmax = 0
sNvmax = np.zeros(len(Nvmax))
sNvmaxp = np.zeros(len(Nvmax))
with open(self.get_outfname(hpath),'w') as f:
f.write(str(np.min(svmax))+" "+str(np.min(ssvmax))+'\n')
for v,N,sN,Np,sNp in zip(self.vmaxbins[1:],Nvmax,sNvmax,Nvmaxp,sNvmaxp):
f.write(str(v)+" "+str(N)+" "+str(sN)+" "+str(Np)+" "+str(sNp)+'\n')
def _read(self,hpath):
thisfilename = self.get_filename(hpath)
data = asciitable.read(thisfilename,delimiter=' ',data_start=1)
v = data['col1']
N = data['col2']
sN = data['col3']
Np = data['col4']
sNp= data['col5']
with open(thisfilename,'r') as f:
split = f.readline().split(" ")
minv = float(split[0])
sminv= float(split[1])
return v,N,minv,sN,sminv,Np,sNp
def _plot(self,hpath,data,ax,lx=None,labelon=False,normtohost=False,**kwargs):
v,N,minv,sN,sminv,Np,sNp = data
ii = v >= minv
if normtohost:
mvir,rvir,vvir=haloutils.load_haloprops(hpath)
v = v/vvir
if lx != None:
ax.plot(v[ii],N[ii],color=self.colordict[lx],**kwargs)
else:
ax.plot(v[ii],N[ii],**kwargs)
class SHMFPlugin(PluginBase):
def __init__(self,Mmin=10**4.5,Mmax=10**10.6,ymin=10**1.5,ymax=10**12.0):
super(SHMFPlugin,self).__init__()
self.filename='SHMF.dat'
self.histrange = np.arange(4.0,10.5,0.2)
self.xmin = Mmin; self.xmax = Mmax
self.ymin = ymin; self.ymax = ymax
self.xlabel = r'$M_{\rm sub} (M_\odot)$'
self.ylabel = r'$M_{\rm vir} dN/dM_{\rm sub}$'
self.n_xmin = Mmin/10**12; self.n_xmax = Mmax/10**12
self.n_ymin = ymin; self.n_ymax = ymax
self.n_xlabel = r'$M_{\rm sub}/M_{\rm vir}$'
self.n_ylabel = self.ylabel
self.xlog = True; self.ylog = True
self.autofigname = 'SHMF'
def _analyze(self,hpath):
if not haloutils.check_last_rockstar_exists(hpath):
raise IOError("No rockstar")
numsnaps = haloutils.get_numsnaps(hpath)
rscat = haloutils.load_rscat(hpath,numsnaps-1)
zoomid = haloutils.load_zoomid(hpath)
subs = self.get_rssubs(rscat,zoomid)
subM = np.array(subs['mvir'])/rscat.h0
x,y = self.MassFunc_dNdM(subM,self.histrange)
boundM = np.array(subs['mgrav'])/rscat.h0
bx,by = self.MassFunc_dNdM(boundM,self.histrange)
try:
scat = haloutils.load_scat(hpath)
bestgroup = 0
ssubM = scat.sub_mass[0:scat.group_nsubs[0]]*10**10/rscat.h0
sx,sy = self.MassFunc_dNdM(ssubM,self.histrange)
except IOError: #No Subfind
sx = np.zeros(len(x))
sy = np.zeros(len(y))
with open(self.get_outfname(hpath),'w') as f:
for a,b,sa,sb,ba,bb in zip(x,y,sx,sy,bx,by):
f.write(str(a)+' '+str(b)+' '+str(sa)+' '+str(sb)+' '+str(ba)+' '+str(bb)+'\n')
def MassFunc_dNdM(self,masses,histrange):
"""
Adapted from Greg's MassFunctions code
"""
numbins = len(histrange) - 1
hist, r_array = np.histogram(np.log10(masses), bins=histrange)
x_array = self._getMidpoints(r_array)
dM = 10.**r_array[1:]-10.**r_array[0:numbins] #Mass size of bins in non-log space
dNdM = hist/dM
return 10**x_array, dNdM
def _getMidpoints(self,bins):
spacing = bins[1:]-bins[:-1]
return bins[:-1]+spacing/2.0
def _read(self,hpath):
thisfilename = self.get_filename(hpath)
data = asciitable.read(thisfilename,delimiter=' ')
#don't return mvir, only mgrav
return data['col5'],data['col6'],data['col3'],data['col4']
def _plot(self,hpath,data,ax,lx=None,labelon=False,normtohost=False,**kwargs):
x,y,sx,sy = data
mvir,rvir,vvir=haloutils.load_haloprops(hpath)
y = y*mvir
if normtohost: x = x/mvir
if lx != None:
ax.plot(x,y,color=self.colordict[lx],**kwargs)
else:
ax.plot(x,y,**kwargs)
class IntegrableSHMFPlugin(SHMFPlugin):
def __init__(self):
super(IntegrableSHMFPlugin,self).__init__()
self.xmin = self.n_xmin; self.xmax = self.n_xmax
self.ymin = 0; self.ymax = 1.1
self.n_ymin = 0; self.n_ymax = 1.1
self.xlabel = self.n_xlabel
self.ylabel = r'$normed\ dN/dlogM_{\rm sub}$'
self.ylog=False #this way you can visually integrate
self.autofigname = 'integrableSHMF'
def _plot(self,hpath,data,ax,lx=None,labelon=False,normtohost=False,**kwargs):
if normtohost:
raise NotImplementedError
x,y,sx,sy = data
mvir,rvir,vvir=haloutils.load_haloprops(hpath)
x = x/mvir; y = y*mvir
y = y/np.max(y)
if lx != None:
ax.plot(x,y,color=self.colordict[lx],**kwargs)
else:
ax.plot(x,y,**kwargs)
class ProfilePlugin(PluginBase):
def __init__(self,rmin=10**-2,rmax=10**3,ymin=10**0.5,ymax=10**10.5):
super(ProfilePlugin,self).__init__()
self.filename='rsprofile.dat'
self.useallpart=True
self.xmin = rmin; self.xmax = rmax
self.ymin = ymin; self.ymax = ymax
self.xlabel = r'$r\ (kpc)$'
self.ylabel = r'$\rho(r)\ (M_\odot\ \rm{kpc}^{-3})$'
self.xlog = True; self.ylog = True
self.autofigname = 'rho'
def _analyze(self,hpath):
if not haloutils.check_last_rockstar_exists(hpath):
raise IOError("No rockstar")
snap = haloutils.get_numsnaps(hpath)-1
rscat = haloutils.load_rscat(hpath,snap)
haloid = haloutils.get_parent_hid(hpath)
ictype,lx,nv = haloutils.get_zoom_params(hpath)
zoomid = haloutils.load_zoomid(hpath)
snapstr = str(snap).zfill(3)
snapfile = hpath+'/outputs/snapdir_'+snapstr+'/snap_'+snapstr
header = rsg.snapshot_header(snapfile+'.0')
rvir = (rscat.ix[zoomid]['rvir'])/header.hubble
rarr = self.get_rarr(rvir)
rarr,mltrarr,p03rmin,halorvir,r200c,halomass = self.compute_one_profile(rarr,hpath,rscat,zoomid,snap,header,useallpart=self.useallpart)
rbin = np.concatenate(([0],rarr))*1000. #kpc
rhoarr = self.mltr_to_rho(rarr*1000.,mltrarr) #Msun/kpc^3
rs = float(rscat.ix[zoomid]['rs'])
try:
NFW0,NFW1 = profilefit.fitNFW(rbin,rhoarr,[rs,9],minr=p03rmin,maxr=halorvir)
except RuntimeError as e:
print e
NFW0=None;NFW1=None
try:
EIN0,EIN1,EIN2 = profilefit.fitEIN(rbin,rhoarr,[rs,6.5,.17],minr=p03rmin,maxr=halorvir)
except RuntimeError as e:
print e
EIN0=None;EIN1=None;EIN2=None
with open(self.get_outfname(hpath),'w') as f:
f.write(" ".join([str(p03rmin),str(halorvir),str(r200c),str(halomass),
str(NFW0),str(NFW1),str(EIN0),str(EIN1),str(EIN2)+"\n"]))
for r,mltr in zip(rarr,mltrarr):
f.write(str(r)+" "+str(mltr)+"\n")
def get_rarr(self,rvir): #rvir in kpc
return (rvir/1000.)*np.logspace(np.log10(1.5e-4),np.log10(3),50)
#return np.logspace(-5,0,50)
def compute_one_profile(self,rarr,hpath,rscat,rsid,snap,header,
calcp03r=True,calcr200=True,retdr=False,useallpart=False):
halopos = np.array(rscat.ix[rsid][['posX','posY','posZ']])
halorvir = float(rscat.ix[rsid]['rvir']) / header.hubble #kpc
halomass = rscat.ix[rsid]['mvir']/header.hubble
if useallpart: #use all particles within 3x rvir
rbins = np.concatenate(([0],rarr))
all_h_r = np.zeros(len(rarr))
all_m_r = np.zeros(len(rarr))
for parttype in range(1,5+1):
partpos = haloutils.load_partblock(hpath,snap,"POS ",parttype=parttype)
dr = self.distance(partpos,halopos)/header.hubble #Mpc
ii = dr*1000. < 3*halorvir
if parttype==5:
if np.sum(ii) > 0:
raise RuntimeError("Forced to use parttype 5 particles, this halo may be bad (stopping)!")
break
if np.sum(ii) == 0: continue
dr = dr[ii]
mpart = header.massarr[parttype]*10**10/header.hubble
h_r, x_r = np.histogram(dr,bins=rbins)
all_h_r += h_r
all_m_r += mpart*h_r
N_lt_r = np.cumsum(all_h_r)
mltrarr = np.cumsum(all_m_r)
p03rmin,r200c = self.calc_extra_radii(header,N_lt_r,mltrarr,rarr,calcp03r=calcp03r,calcr200=calcr200)
else: #use only bound particles
haloparts = rscat.get_all_particles_from_halo(rsid)
try:
haloparts = np.sort(haloparts)
partpos = haloutils.load_partblock(hpath,snap,"POS ",parttype=1,ids=haloparts)
except IndexError as e:
print e
raise RuntimeError("Contamination in halo")
dr = self.distance(partpos,halopos)/header.hubble #Mpc
mltrarr,p03rmin,r200c = self.calc_mltr_radii(rarr,dr,header,haloparts,
calcp03r=calcp03r,calcr200=calcr200)
if retdr: return rarr,mltrarr,p03rmin,halorvir,r200c,halomass,dr #all in physical units
return rarr,mltrarr,p03rmin,halorvir,r200c,halomass #all in physical units
def calc_mltr_radii(self,rarr,dr,header,haloparts,calcp03r=True,calcr200=True,verbose=False):
parttype=1 # Only works if no contamination
mpart = header.massarr[parttype]*10**10/header.hubble #Msun
if verbose:
print " Particle type",parttype
if len(dr) != 0:
print " dr range=",dr.min(),dr.max()
if dr.max()>rarr[-1]:
nout = np.sum(dr > rarr[-1])
print " densityprofile warning:",nout,"particles lie outside max(rarr)"
h_r, x_r = np.histogram(dr, bins=np.concatenate(([0],rarr)))
N_lt_r = np.cumsum(h_r)
#m_of_r = h_r*mpart
m_lt_r = N_lt_r*mpart #Msun
p03rmin,r200c = self.calc_extra_radii(header,N_lt_r,m_lt_r,rarr,calcp03r=calcp03r,calcr200=calcr200)
return m_lt_r,p03rmin,r200c
def calc_extra_radii(self,header,N_lt_r,m_lt_r,rarr,calcp03r=True,calcr200=True):
if calcp03r or calcr200:
rhocrit = 2.776e11 * (header.hubble)**2 #Msun/Mpc^3
rhobar = m_lt_r/(4*np.pi/3 * rarr**3) #Msun/Mpc^3
if calcp03r:
try:
p03 = np.sqrt(200)/8.0 * N_lt_r/np.log(N_lt_r) / np.sqrt(rhobar/rhocrit)
p03rmin = rarr[np.min(np.where(np.logical_and(p03>=1,np.isfinite(p03)))[0])]*1000 #kpc
except ValueError:
p03rmin = None
else: p03rmin = None
if calcr200:
tck = interpolate.splrep(rarr,rhobar)
def func(r):
return interpolate.splev(r,tck) - 200*rhocrit
r200c = optimize.fsolve(func,.02)[0]*1000 #kpc
else: r200c = None
return p03rmin,r200c
def mltr_to_rho(self,rarr,mltr):
""" rarr in Mpc (including h), mltr in Msun (including h), return Msun/Mpc^3 """
#tck = interpolate.splrep(rarr,mltr)
#return interpolate.splev(rarr,tck,der=1)/(4*np.pi*rarr**2)
rarr = np.concatenate(([0],rarr))
Marr = self.mltr_to_Marr(mltr)
Varr = 4*np.pi/3 * (rarr[1:]**3-rarr[:-1]**3)
return Marr/Varr
def mltr_to_vcirc(self,rarr,mltr):
""" rarr in Mpc (including h), mltr in Msun (including h), return km/s """
const = 6.67e-17*1.988e30*3.241e-23 #G * Msun->kg * m->Mpc to km/s
v2 = const*mltr/rarr
return np.sqrt(v2)
def mltr_to_Marr(self,mltr):
return np.diff(np.concatenate(([0],mltr)))
def _read(self,hpath):
thisfilename = self.get_filename(hpath)
data = np.array(asciitable.read(thisfilename,delimiter=" ",data_start=1))
r = data['col1'] #Mpc
mltr = data['col2'] #Msun
f = open(thisfilename,'r')
p03r,rvir,r200c,halomass,NFW0,NFW1,EIN0,EIN1,EIN2 = f.readline().split(" ")
p03r = float(p03r); rvir = float(rvir); r200c = float(r200c) #all in kpc
NFW0 = float(NFW0); NFW1 = float(NFW1); EIN0 = float(EIN0); EIN1 = float(EIN1); EIN2 = float(EIN2);
pNFW = [NFW0,NFW1]; pEIN = [EIN0,EIN1,EIN2]
return r,mltr,p03r,rvir,r200c,pNFW,pEIN
def _plot(self,hpath,data,ax,lx=None,labelon=False,normtohost=False,lw=3,**kwargs):
if normtohost:
raise NotImplementedError
r,mltr,p03r,rvir,r200c,pNFW,pEIN = data
rho = self.mltr_to_rho(r,mltr)
r = r*1000. # kpc
rho = rho/1.e9 #Msun/Mpc^3 to Msun/kpc^3
eps = 1000*haloutils.load_soft(hpath)
rbin=np.concatenate(([0],r))
rmid = 10**((np.log10(rbin[1:])+np.log10(rbin[:-1]))/2.)
ii1 = rmid >= eps
ii2 = rmid >= p03r
if lx != None:
color = self.colordict[lx]
ax.plot(rmid[ii1], rho[ii1], color=color, lw=1, **kwargs)
ax.plot(rmid[ii2], rho[ii2], color=color, lw=lw, **kwargs)
#ax.plot(r,profilefit.NFWprofile(r,pNFW[0],pNFW[1]),':',color=color,lw=1,**kwargs)
ax.plot(rmid,profilefit.EINprofile(rmid,pEIN[0],pEIN[1],pEIN[2]),':',color=color,lw=1,**kwargs)
else:
ax.plot(rmid[ii1], rho[ii1], lw=1, **kwargs)
ax.plot(rmid[ii2], rho[ii2], lw=lw, **kwargs)
#ax.plot(r,profilefit.NFWprofile(r,pNFW[0],pNFW[1]),':',color=color,lw=1,**kwargs)
ax.plot(rmid,profilefit.EINprofile(rmid,pEIN[0],pEIN[1],pEIN[2]),':',lw=1,**kwargs)
class R2ProfilePlugin(ProfilePlugin):
def __init__(self,rmin=10**-2,rmax=10**3,ymin=10**-1.5,ymax=10**2.5):
super(ProfilePlugin,self).__init__()
self.filename='rsprofile.dat'
self.useallpart=True
self.xmin = rmin; self.xmax = rmax
self.ymin = ymin; self.ymax = ymax
self.xlabel = r'$r\ (kpc)$' #$h^{-1}$
self.ylabel = r'$r^2 \rho(r)\ (10^{10}\ M_\odot\ Mpc^{-1})$'
self.xlog = True; self.ylog = True
self.autofigname = 'rhor2'
def _plot(self,hpath,data,ax,lx=None,labelon=False,normtohost=False,plotEIN=False,labelalpha=False,**kwargs):
if normtohost:
raise NotImplementedError
r,mltr,p03r,rvir,r200c,pNFW,pEIN = data
rho = self.mltr_to_rho(r,mltr)
r = r*1000. # kpc
rho = rho/10**10 #10^10 Msun/Mpc^3
eps = 1000*haloutils.load_soft(hpath)
rbin=np.concatenate(([0],r))
rmid = 10**((np.log10(rbin[1:])+np.log10(rbin[:-1]))/2.)
ii1 = rmid >= eps
ii2 = rmid >= p03r
r2,rho2,alpha = pEIN
if lx != None:
color = self.colordict[lx]
ax.plot(rmid[ii1], (rmid[ii1]/1000.)**2 * rho[ii1], color=color, lw=1, **kwargs)
ax.plot(rmid[ii2], (rmid[ii2]/1000.)**2 * rho[ii2], color=color, lw=3, **kwargs)
if plotEIN:
ax.plot(rmid,rmid**2 * profilefit.EINprofile(rmid,pEIN[0],pEIN[1],pEIN[2])*10**-7,':',color=color,lw=1,**kwargs)
if labelalpha: self._label_alpha(ax,pEIN,normtohost)
else:
ax.plot(rmid[ii1], (rmid[ii1]/1000.)**2 * rho[ii1], lw=1, **kwargs)
ax.plot(rmid[ii2], (rmid[ii2]/1000.)**2 * rho[ii2], lw=3, **kwargs)
if plotEIN:
ax.plot(rmid,rmid**2 * profilefit.EINprofile(rmid,pEIN[0],pEIN[1],pEIN[2])*10**-7,':',lw=1,**kwargs)
if labelalpha: self._label_alpha(ax,pEIN,normtohost)
def _label_alpha(self,ax,pEIN,normtohost):
xmin,xmax,ymin,ymax,xlog,ylog,xlabel,ylabel = self.get_plot_params(normtohost)
logxoff = np.log10(xmax/xmin)*.05
xlabel = xmax * 10**(-logxoff)
logyoff = np.log10(ymax/ymin)*.1
ylabel = ymin * 10**(logyoff)
ax.text(xlabel,ylabel,"{0:.3f}".format(pEIN[2]),ha='right')
class BoundProfilePlugin(ProfilePlugin):
def __init__(self,rmin=10**-2,rmax=10**3,ymin=10**0.5,ymax=10**10.5):
super(BoundProfilePlugin,self).__init__()
self.filename='brsprofile.dat'
self.useallpart=False
self.xmin = rmin; self.xmax = rmax
self.ymin = ymin; self.ymax = ymax
self.xlabel = r'$r\ (kpc)$'
self.ylabel = r'$\rho(r)\ (M_\odot\ \rm{kpc}^{-3})$'
self.xlog = True; self.ylog = True
self.autofigname = 'brho'
class BoundR2ProfilePlugin(BoundProfilePlugin):
def __init__(self,rmin=10**-2,rmax=10**3,ymin=10**-1.5,ymax=10**2.5):
super(BoundR2ProfilePlugin,self).__init__()
self.filename='brsprofile.dat'
self.useallpart=False
self.xmin = rmin; self.xmax = rmax
self.ymin = ymin; self.ymax = ymax
self.xlabel = r'$r\ (kpc)$' #$h^{-1}$
self.ylabel = r'$r^2 \rho(r)\ (10^{10}\ M_\odot\ Mpc^{-1})$'
self.xlog = True; self.ylog = True
self.autofigname = 'brhor2'
def _plot(self,hpath,data,ax,lx=None,labelon=False,normtohost=False,plotEIN=False,**kwargs):
if normtohost:
raise NotImplementedError
r,mltr,p03r,rvir,r200c,pNFW,pEIN = data
rho = self.mltr_to_rho(r,mltr)
r = r*1000. # kpc
rho = rho/10**10 #10^10 Msun/Mpc^3
eps = 1000*haloutils.load_soft(hpath)
rbin=np.concatenate(([0],r))
rmid = 10**((np.log10(rbin[1:])+np.log10(rbin[:-1]))/2.)
ii1 = rmid >= eps
ii2 = rmid >= p03r
r2,rho2,alpha = pEIN
if lx != None:
color = self.colordict[lx]
ax.plot(rmid[ii1], (rmid[ii1]/1000.)**2 * rho[ii1], color=color, lw=1, **kwargs)
ax.plot(rmid[ii2], (rmid[ii2]/1000.)**2 * rho[ii2], color=color, lw=3, **kwargs)
if plotEIN:
ax.plot(rmid,rmid**2 * profilefit.EINprofile(rmid,pEIN[0],pEIN[1],pEIN[2])*10**-7,':',color=color,lw=1,**kwargs)
else:
ax.plot(rmid[ii1], (rmid[ii1]/1000.)**2 * rho[ii1], lw=1, **kwargs)
ax.plot(rmid[ii2], (rmid[ii2]/1000.)**2 * rho[ii2], lw=3, **kwargs)
if plotEIN:
ax.plot(rmid,rmid**2 * profilefit.EINprofile(rmid,pEIN[0],pEIN[1],pEIN[2])*10**-7,':',lw=1,**kwargs)
class VelocityProfilePlugin(ProfilePlugin):
def __init__(self,rmin=10**-2,rmax=10**3,vmin=10**1,vmax=10**2.5):
super(VelocityProfilePlugin,self).__init__()
self.xmin = rmin; self.xmax = rmax
self.ymin = vmin; self.ymax = vmax
self.xlabel = r'$r\ (kpc)$'
self.ylabel = r'$v_{\rm circ} (km/s)$'
self.n_xmin = rmin/10**2.5; self.n_xmax = rmax/10**2.5
self.n_ymin = vmin/10**2.0; self.n_ymax = vmax/10**2.0
self.n_xlabel = r'$r/r_{\rm vir}$'
self.n_ylabel = r'$v_{\rm circ}/v_{\rm vir}$'
self.xlog = True; self.ylog = True
self.autofigname = 'vcirc'
def _read(self,hpath):
thisfilename = self.get_filename(hpath)
data = np.array(asciitable.read(thisfilename,delimiter=" ",data_start=1))
r = data['col1'] #Mpc
mltr = data['col2'] #Msun
vcirc = self.mltr_to_vcirc(r,mltr) #km/s
f = open(thisfilename,'r')
p03r,rvir,r200c,halomass,NFW0,NFW1,EIN0,EIN1,EIN2 = f.readline().split(" ")
p03r = 1000.*float(p03r); rvir = float(rvir); r200c = float(r200c) #all in kpc
#NFW0 = float(NFW0); NFW1 = float(NFW1); EIN0 = float(EIN0); EIN1 = float(EIN1); EIN2 = float(EIN2);
#pNFW = [NFW0,NFW1]; pEIN = [EIN0,EIN1,EIN2]
return r,vcirc,p03r,rvir,r200c
def _plot(self,hpath,data,ax,lx=None,labelon=False,normtohost=False,**kwargs):
r,vcirc,p03r,rvir,r200c = data
r = r*1000. # kpc
eps = 1000*haloutils.load_soft(hpath)
ii1 = r >= eps
ii2 = r >= p03r
if normtohost:
mvir,rvir,vvir=haloutils.load_haloprops(hpath)
r = r/rvir
vcirc = vcirc/vvir
if lx != None:
color = self.colordict[lx]
ax.plot(r[ii1], vcirc[ii1], color=color, lw=1, **kwargs)
ax.plot(r[ii2], vcirc[ii2], color=color, lw=3, **kwargs)
else:
ax.plot(r[ii1], vcirc[ii1], lw=1, **kwargs)
ax.plot(r[ii2], vcirc[ii2], lw=3, **kwargs)
class SubProfilePlugin(ProfilePlugin):
def __init__(self,rmin=10**-2,rmax=10**3,ymin=10**-1.5,ymax=10**2.5):
super(SubProfilePlugin,self).__init__(rmin=rmin,rmax=rmax,ymin=ymin,ymax=ymax)
self.filename='subprofile.dat'
self.nr = 50
self.profilenames = ['mltr'+str(i).zfill(2) for i in xrange(self.nr)]
self.mmin = 10**8 #Msun
self.xmin = rmin; self.xmax = rmax
self.ymin = ymin; self.ymax = ymax
self.xlabel = r'$r\ (kpc)$' #$h^{-1}$
self.ylabel = r'$r^2 \rho(r)\ [10^{10}\ M_\odot\ Mpc^{-1}]$'
self.xlog = True; self.ylog = True
self.autofigname = 'subrhor2'
def get_scaled_rarr(self,rvir):
""" rvir in kpc, return Mpc """
out = 3*rvir.reshape(-1,1)/1000.*np.logspace(-5,0,self.nr).reshape(1,-1)
if out.shape[0]==1: return out[0]
return out
def _analyze(self,hpath):
if not haloutils.check_last_rockstar_exists(hpath):
raise IOError("No rockstar")
zoomid = haloutils.load_zoomid(hpath)
rscat = haloutils.load_rscat(hpath,haloutils.get_numsnaps(hpath)-1)
subs = rscat.get_subhalos_within_halo(zoomid) #no subsubhalos
subs = subs[subs['mgrav']/rscat.h0 > self.mmin]
subids = np.array(subs['id'])
nsubs = len(subs)
nr = self.nr
rvirarr = np.zeros(nsubs)
mgravarr = np.zeros(nsubs)
allmltrarr = np.zeros((nsubs,nr))
snap = haloutils.get_numsnaps(hpath)-1
snapstr = str(snap).zfill(3)
snapfile = hpath+'/outputs/snapdir_'+snapstr+'/snap_'+snapstr
header = rsg.snapshot_header(snapfile+'.0')
for i,subid in enumerate(subids):
thismgrav = float(subs.ix[subid]['mgrav'])/header.hubble
thisrvir = float(subs.ix[subid]['rvir'])/header.hubble
rarr = self.get_scaled_rarr(thisrvir)
rarr,mltr,p03rmin,halorvir,r200c,halomass = self.compute_one_profile(rarr,hpath,rscat,subid,snap,header,calcp03r=False,calcr200=False)
rvirarr[i] = halorvir
mgravarr[i] = thismgrav
allmltrarr[i,:] = mltr
#p03rarr[i] = p03rmin
#r200carr[i]= r200c
names = ['rsid','rvir','mgrav']+self.profilenames
outdict = {'rsid':subids,'rvir':rvirarr,'mgrav':mgravarr}
for col in range(nr):
outdict[self.profilenames[col]] = allmltrarr[:,col]
asciitable.write(outdict,self.get_outfname(hpath),names=names)
def _read(self,hpath):
thisfilename = self.get_filename(hpath)
data = asciitable.read(thisfilename,header_start=0)
rsid = data['rsid']
rvir = data['rvir']
mltrarr = data[self.profilenames]
mltrarr = mltrarr.view(np.float).reshape(mltrarr.shape+(-1,))
rarr = self.get_scaled_rarr(rvir)
return rsid,rarr,rvir,mltrarr
def _plot(self,hpath,data,ax,lx=None,labelon=False,normtohost=False,alpha=.2,color='k',**kwargs):
if normtohost:
raise NotImplementedError
rsid,rarr,rvir,mltrarr = data
rhoarr = np.zeros(mltrarr.shape)
for i in range(len(rsid)):
rhoarr[i,:] = self.mltr_to_rho(rarr[i],mltrarr[i,:])
rhoarr = rhoarr/10**10 #10^10 Msun/Mpc^3
rarr = rarr*1000 #kpc
plotqty = (rarr/1000.)**2 * rhoarr #Msun/Mpc
eps = 1000*haloutils.load_soft(hpath)
if lx != None:
color = self.colordict[lx]
for i in xrange(len(rsid)):
ii = rarr[i,:] >= eps
if np.sum(ii) == 0: continue
ax.plot(rarr[i,ii], plotqty[i,ii], color=color, lw=2, alpha=alpha, **kwargs)
class SubVelocityProfilePlugin(SubProfilePlugin):
def __init__(self,rmin=10**-1.5,rmax=10**3,vmin=10**0,vmax=10**2.3):
super(SubVelocityProfilePlugin,self).__init__()
self.xmin = rmin; self.xmax = rmax
self.ymin = vmin; self.ymax = vmax
self.xlabel = r'$r\ (kpc)$'
self.ylabel = r'$v_{circ}\ (km/s)$'
self.n_xmin = 10**-3.9; self.n_xmax = 10**0.5
self.n_ymin = 10**-2.0; self.n_ymax = 10**0.2
self.n_xlabel = r'$r/r_{\rm vir,host}$'
self.n_ylabel = r'$v_{\rm circ}/v_{\rm vir,host}$'
self.xlog = True; self.ylog = True
self.autofigname = 'subvcirc'
def _read(self,hpath):
thisfilename = self.get_filename(hpath)
data = asciitable.read(thisfilename,header_start=0)
rsid = data['rsid']
rvir = data['rvir']
mltrarr = data[self.profilenames]
mltrarr = mltrarr.view(np.float).reshape(mltrarr.shape+(-1,))
rarr = self.get_scaled_rarr(rvir)
vcircarr = np.zeros(mltrarr.shape)
for i in range(len(rsid)):
vcircarr[i,:] = self.mltr_to_vcirc(rarr[i],mltrarr[i,:])
return rsid,rarr,rvir,vcircarr
def _plot(self,hpath,data,ax,lx=None,labelon=False,normtohost=False,alpha=.2,color='k',**kwargs):
rsid,rarr,rvir,vcircarr = data
rarr = rarr*1000 #kpc
eps = 1000*haloutils.load_soft(hpath)
if normtohost:
mvir,rvir,vvir=haloutils.load_haloprops(hpath)
rarr = rarr/rvir
vcircarr = vcircarr/vvir
eps = eps/rvir
if lx != None:
color = self.colordict[lx]
for i in xrange(len(rsid)):
ii = rarr[i,:] >= eps
if np.sum(ii) == 0: continue
ax.plot(rarr[i,ii], vcircarr[i,ii], color=color, lw=2, alpha=alpha, **kwargs)
class MassAccrPlugin(PluginBase):
## Important note: the results of this are used in load_zoomid for snaps < 255
def __init__(self,Mmin=10**4.5,Mmax=10**10.6,ymin=10**-10,ymax=10**-1.0):
super(MassAccrPlugin,self).__init__()
self.filename='massaccr.dat'
self.xmin = 0; self.xmax = 1
self.ymin = 10**6; self.ymax = 10**13
self.xlabel = r'$\rm{scale\ factor}$'
self.ylabel = r'$M\ (M_\odot)$'
self.n_xmin = 0; self.n_xmax = 1
self.n_ymin = 10**-6.5; self.n_ymax = 10**0.5
self.n_xlabel = r'$\rm{scale\ factor}$'
self.n_ylabel = r'$M/M(a=1)$'
self.xlog = False; self.ylog = True
self.autofigname = 'massaccr'
def _analyze(self,hpath):
if not haloutils.check_mergertree_exists(hpath,autoconvert=True):
raise IOError("No Merger Tree")
zoomid = haloutils.load_zoomid(hpath)
rscat = haloutils.load_rscat(hpath,haloutils.get_numsnaps(hpath)-1)
mtc = haloutils.load_mtc(hpath,haloids=[zoomid])
mt = mtc[0]
mb = mt.getMainBranch()
scale = mb['scale'][::-1]
snap = mb['snap'][::-1]
phantom = mb['phantom'][::-1]
mvir = mb['mvir'][::-1]/rscat.h0
rvir = mb['rvir'][::-1]/rscat.h0
sammvir = mb['sam_mvir'][::-1]/rscat.h0
vmax = mb['vmax'][::-1]
vrms = mb['vrms'][::-1]
TU = mb['T/|U|'][::-1]
scaleMM = mb['scale_of_last_MM'][::-1]
x = mb['posX'][::-1]
y = mb['posY'][::-1]
z = mb['posZ'][::-1]
vx = mb['pecVX'][::-1]
vy = mb['pecVY'][::-1]
vz = mb['pecVZ'][::-1]
Jx = mb['Jx'][::-1]
Jy = mb['Jy'][::-1]
Jz = mb['Jz'][::-1]
spin = mb['spin'][::-1]
spinbullock = mb['spin_bullock'][::-1]
origid = mb['origid'][::-1]
b_to_a = mb['b_to_a(500c)'][::-1]