/
frontend.py
912 lines (819 loc) · 31.3 KB
/
frontend.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
import numpy as np
import healpy as hp
from numpy import zeros_like, zeros
from .kernel import *
from .octree import *
from .dynamic_tree import *
from .treewalk import *
from .bruteforce import *
from .misc import *
def valueTestMethod(method):
methods = ["adaptive", "bruteforce", "tree"]
## check if method is a str
if type(method) != str:
raise TypeError("Invalid method type %s, must be str" % type(method))
## check if method is a valid method
if method not in methods:
raise ValueError(
"Invalid method %s. Must be one of: %s" % (method, str(methods))
)
def ConstructTree(
pos,
m=None,
softening=None,
quadrupole=False,
vel=None,
compute_moments=True,
morton_order=True,
):
"""Builds a tree containing particle data, for subsequent potential/field evaluation
Parameters
----------
pos: array_like
shape (N,3) array of particle positions
m: array_like or None, optional
shape (N,) array of particle masses - if None then zeros will be used (e.g. if all you need the tree for is spatial algorithms)
softening: array_like or None, optional
shape (N,) array of particle softening lengths - these give the radius of compact support of the M4 cubic spline mass distribution of each particle
quadrupole: bool, optional
Whether to store quadrupole moments (default False)
vel: bool, optional
Whether to store node velocities in the tree (default False)
Returns
-------
tree: octree
Octree instance built from particle data
"""
if m is None:
m = zeros(len(pos))
compute_moments = False
if softening is None:
softening = zeros_like(m)
if not (
np.all(np.isfinite(pos))
and np.all(np.isfinite(m))
and np.all(np.isfinite(softening))
):
print(
"Invalid input detected - aborting treebuild to avoid going into an infinite loop!"
)
raise
if vel is None:
return Octree(
pos,
m,
softening,
quadrupole=quadrupole,
compute_moments=compute_moments,
morton_order=morton_order,
)
else:
return DynamicOctree(pos, m, softening, vel, quadrupole=quadrupole)
def Potential(
pos,
m,
softening=None,
G=1.0,
theta=0.7,
tree=None,
return_tree=False,
parallel=False,
method="adaptive",
quadrupole=False,
):
"""Gravitational potential calculation
Returns the gravitational potential for a set of particles with positions x and masses m, at the positions of those particles, using either brute force or tree-based methods depending on the number of particles.
Parameters
----------
pos: array_like
shape (N,3) array of particle positions
m: array_like
shape (N,) array of particle masses
G: float, optional
gravitational constant (default 1.0)
softening: None or array_like, optional
shape (N,) array containing kernel support radii for gravitational softening - - these give the radius of compact support of the M4 cubic spline mass distribution - set to 0 by default
theta: float, optional
cell opening angle used to control force accuracy; smaller is slower (runtime ~ theta^-3) but more accurate. (default 0.7, gives ~1% accuracy)
parallel: bool, optional
If True, will parallelize the force summation over all available cores. (default False)
tree: Octree, optional
optional pre-generated Octree: this can contain any set of particles, not necessarily the target particles at pos (default None)
return_tree: bool, optional
return the tree used for future use (default False)
method: str, optional
Which summation method to use: 'adaptive', 'tree', or 'bruteforce' (default adaptive tries to pick the faster choice)
quadrupole: bool, optional
Whether to use quadrupole moments in tree summation (default False)
Returns
-------
phi: array_like
shape (N,) array of potentials at the particle positions
"""
## test if method is correct, otherwise raise a ValueError
valueTestMethod(method)
if softening is None:
softening = np.zeros_like(m)
# figure out which method to use
if method == "adaptive":
if len(pos) > 1000:
method = "tree"
else:
method = "bruteforce"
if method == "bruteforce": # we're using brute force
if parallel:
phi = Potential_bruteforce_parallel(pos, m, softening, G=G)
else:
phi = Potential_bruteforce(pos, m, softening, G=G)
if return_tree:
tree = None
else: # we're using the tree algorithm
if tree is None:
tree = ConstructTree(
np.float64(pos),
np.float64(m),
np.float64(softening),
quadrupole=quadrupole,
) # build the tree if needed
idx = tree.TreewalkIndices
# sort by the order they appear in the treewalk to improve access pattern efficiency
pos_sorted = np.take(pos, idx, axis=0)
h_sorted = np.take(softening, idx)
if parallel:
phi = PotentialTarget_tree_parallel(
pos_sorted, h_sorted, tree, theta=theta, G=G, quadrupole=quadrupole
)
else:
phi = PotentialTarget_tree(
pos_sorted, h_sorted, tree, theta=theta, G=G, quadrupole=quadrupole
)
# now reorder phi back to the order of the input positions
phi = np.take(phi, idx.argsort())
if return_tree:
return phi, tree
else:
return phi
def PotentialTarget(
pos_target,
pos_source,
m_source,
softening_target=None,
softening_source=None,
G=1.0,
theta=0.7,
tree=None,
return_tree=False,
parallel=False,
method="adaptive",
quadrupole=False,
):
"""Gravitational potential calculation for general N+M body case
Returns the gravitational potential for a set of M particles with positions x_source and masses m_source, at the positions of a set of N particles that need not be the same.
Parameters
----------
pos_target: array_like
shape (N,3) array of target particle positions where you want to know the potential
pos_source: array_like
shape (M,3) array of source particle positions (positions of particles sourcing the gravitational field)
m_source: array_like
shape (M,) array of source particle masses
softening_target: array_like or None, optional
shape (N,) array of target particle softening radii - these give the radius of compact support of the M4 cubic spline mass distribution
softening_source: array_like or None, optional
shape (M,) array of source particle radii - these give the radius of compact support of the M4 cubic spline mass distribution
G: float, optional
gravitational constant (default 1.0)
theta: float, optional
cell opening angle used to control force accuracy; smaller is slower (runtime ~ theta^-3) but more accurate. (default 0.7, gives ~1% accuracy)
parallel: bool, optional
If True, will parallelize the force summation over all available cores. (default False)
tree: Octree, optional
optional pre-generated Octree: this can contain any set of particles, not necessarily the target particles at pos (default None)
return_tree: bool, optional
return the tree used for future use (default False)
method: str, optional
Which summation method to use: 'adaptive', 'tree', or 'bruteforce' (default adaptive tries to pick the faster choice)
quadrupole: bool, optional
Whether to use quadrupole moments in tree summation (default False)
Returns
-------
phi: array_like
shape (N,) array of potentials at the target positions
"""
## test if method is correct, otherwise raise a ValueError
valueTestMethod(method)
## allow user to pass in tree without passing in source pos and m
## but catch if they don't pass in the tree.
if tree is None and (pos_source is None or m_source is None):
raise ValueError("Must pass either pos_source & m_source or source tree.")
if softening_target is None:
softening_target = zeros(len(pos_target))
if softening_source is None and pos_source is not None:
softening_source = zeros(len(pos_source))
# figure out which method to use
if method == "adaptive":
if pos_source is None or len(pos_target) * len(pos_source) > 10**6:
method = "tree"
else:
method = "bruteforce"
if method == "bruteforce": # we're using brute force
if parallel:
phi = PotentialTarget_bruteforce_parallel(
pos_target,
softening_target,
pos_source,
m_source,
softening_source,
G=G,
)
else:
phi = PotentialTarget_bruteforce(
pos_target,
softening_target,
pos_source,
m_source,
softening_source,
G=G,
)
if return_tree:
tree = None
else: # we're using the tree algorithm
if tree is None:
tree = ConstructTree(
np.float64(pos_source),
np.float64(m_source),
np.float64(softening_source),
quadrupole=quadrupole,
) # build the tree if needed
if parallel:
phi = PotentialTarget_tree_parallel(
pos_target,
softening_target,
tree,
theta=theta,
G=G,
quadrupole=quadrupole,
)
else:
phi = PotentialTarget_tree(
pos_target,
softening_target,
tree,
theta=theta,
G=G,
quadrupole=quadrupole,
)
if return_tree:
return phi, tree
else:
return phi
def Accel(
pos,
m,
softening=None,
G=1.0,
theta=0.7,
tree=None,
return_tree=False,
parallel=False,
method="adaptive",
quadrupole=False,
):
"""Gravitational acceleration calculation
Returns the gravitational acceleration for a set of particles with positions x and masses m, at the positions of those particles, using either brute force or tree-based methods depending on the number of particles.
Parameters
----------
pos: array_like
shape (N,3) array of particle positions
m: array_like
shape (N,) array of particle masses
G: float, optional
gravitational constant (default 1.0)
softening: None or array_like, optional
shape (N,) array containing kernel support radii for gravitational softening - these give the radius of compact support of the M4 cubic spline mass distribution - set to 0 by default
theta: float, optional
cell opening angle used to control force accuracy; smaller is slower (runtime ~ theta^-3) but more accurate. (default 0.7, gives ~1% accuracy)
parallel: bool, optional
If True, will parallelize the force summation over all available cores. (default False)
tree: Octree, optional
optional pre-generated Octree: this can contain any set of particles, not necessarily the target particles at pos (default None)
return_tree: bool, optional
return the tree used for future use (default False)
method: str, optional
Which summation method to use: 'adaptive', 'tree', or 'bruteforce' (default adaptive tries to pick the faster choice)
quadrupole: bool, optional
Whether to use quadrupole moments in tree summation (default False)
Returns
-------
g: array_like
shape (N,3) array of acceleration vectors at the particle positions
"""
## test if method is correct, otherwise raise a ValueError
valueTestMethod(method)
if softening is None:
softening = np.zeros_like(m)
# figure out which method to use
if method == "adaptive":
if len(pos) > 1000:
method = "tree"
else:
method = "bruteforce"
if method == "bruteforce": # we're using brute force
if parallel:
g = Accel_bruteforce_parallel(pos, m, softening, G=G)
else:
g = Accel_bruteforce(pos, m, softening, G=G)
if return_tree:
tree = None
else: # we're using the tree algorithm
if tree is None:
tree = ConstructTree(
np.float64(pos),
np.float64(m),
np.float64(softening),
quadrupole=quadrupole,
) # build the tree if needed
idx = tree.TreewalkIndices
# sort by the order they appear in the treewalk to improve access pattern efficiency
pos_sorted = np.take(pos, idx, axis=0)
h_sorted = np.take(softening, idx)
if parallel:
g = AccelTarget_tree_parallel(
pos_sorted, h_sorted, tree, theta=theta, G=G, quadrupole=quadrupole
)
else:
g = AccelTarget_tree(
pos_sorted, h_sorted, tree, theta=theta, G=G, quadrupole=quadrupole
)
# now g is in the tree-order: reorder it back to the original order
g = np.take(g, idx.argsort(), axis=0)
if return_tree:
return g, tree
else:
return g
def AccelTarget(
pos_target,
pos_source,
m_source,
softening_target=None,
softening_source=None,
G=1.0,
theta=0.7,
tree=None,
return_tree=False,
parallel=False,
method="adaptive",
quadrupole=False,
):
"""Gravitational acceleration calculation for general N+M body case
Returns the gravitational acceleration for a set of M particles with positions x_source and masses m_source, at the positions of a set of N particles that need not be the same.
Parameters
----------
pos_target: array_like
shape (N,3) array of target particle positions where you want to know the acceleration
pos_source: array_like
shape (M,3) array of source particle positions (positions of particles sourcing the gravitational field)
m_source: array_like
shape (M,) array of source particle masses
softening_target: array_like or None, optional
shape (N,) array of target particle softening radii - these give the radius of compact support of the M4 cubic spline mass distribution
softening_source: array_like or None, optional
shape (M,) array of source particle radii - these give the radius of compact support of the M4 cubic spline mass distribution
G: float, optional
gravitational constant (default 1.0)
theta: float, optional
cell opening angle used to control force accuracy; smaller is slower (runtime ~ theta^-3) but more accurate. (default 0.7, gives ~1% accuracy)
parallel: bool, optional
If True, will parallelize the force summation over all available cores. (default False)
tree: Octree, optional
optional pre-generated Octree: this can contain any set of particles, not necessarily the target particles at pos (default None)
return_tree: bool, optional
return the tree used for future use (default False)
method: str, optional
Which summation method to use: 'adaptive', 'tree', or 'bruteforce' (default adaptive tries to pick the faster choice)
quadrupole: bool, optional
Whether to use quadrupole moments in tree summation (default False)
Returns
-------
phi: array_like
shape (N,3) array of accelerations at the target positions
"""
## test if method is correct, otherwise raise a ValueError
valueTestMethod(method)
## allow user to pass in tree without passing in source pos and m
## but catch if they don't pass in the tree.
if tree is None and (pos_source is None or m_source is None):
raise ValueError("Must pass either pos_source & m_source or source tree.")
if softening_target is None:
softening_target = zeros(len(pos_target))
if softening_source is None and pos_source is not None:
softening_source = zeros(len(pos_source))
# figure out which method to use
if method == "adaptive":
if pos_source is None or len(pos_target) * len(pos_source) > 10**6:
method = "tree"
else:
method = "bruteforce"
if method == "bruteforce": # we're using brute force
if parallel:
g = AccelTarget_bruteforce_parallel(
pos_target,
softening_target,
pos_source,
m_source,
softening_source,
G=G,
)
else:
g = AccelTarget_bruteforce(
pos_target,
softening_target,
pos_source,
m_source,
softening_source,
G=G,
)
if return_tree:
tree = None
else: # we're using the tree algorithm
if tree is None:
tree = ConstructTree(
np.float64(pos_source),
np.float64(m_source),
np.float64(softening_source),
quadrupole=quadrupole,
) # build the tree if needed
if parallel:
g = AccelTarget_tree_parallel(
pos_target,
softening_target,
tree,
theta=theta,
G=G,
quadrupole=quadrupole,
)
else:
g = AccelTarget_tree(
pos_target,
softening_target,
tree,
theta=theta,
G=G,
quadrupole=quadrupole,
)
if return_tree:
return g, tree
else:
return g
def DensityCorrFunc(
pos,
m,
rbins=None,
max_bin_size_ratio=100,
theta=1.0,
tree=None,
return_tree=False,
parallel=False,
boxsize=0,
weighted_binning=False,
):
"""Computes the average amount of mass in radial bin [r,r+dr] around a point, provided a set of radial bins.
Parameters
----------
pos: array_like
shape (N,3) array of particle positions
m: array_like
shape (N,) array of particle masses
rbins: array_like or None, optional
1D array of radial bin edges - if None will use heuristics to determine sensible bins. Otherwise MUST BE LOGARITHMICALLY SPACED (default None)
max_bin_size_ratio: float, optional
controls the accuracy of the binning - tree nodes are subdivided until their side length is at most this factor * the radial bin width (default 100)
theta: float, optional
cell opening angle used to control accuracy; smaller is slower (runtime ~ theta^-3) but more accurate. (default 1.0)
parallel: bool, optional
If True, will parallelize the correlation function computation over all available cores. (default False)
tree: Octree, optional
optional pre-generated Octree: this can contain any set of particles, not necessarily the target particles at pos (default None)
return_tree: bool, optional
if True will return the generated or used tree for future use (default False)
boxsize: float, optional
finite periodic box size, if periodic boundary conditions are to be used (default 0)
weighted_binning: bool, optional
(experimental) if True will distribute mass among radial bings with a weighted kernel (default False)
Returns
-------
rbins: array_like
array containing radial bin edges
mbins: array_like
array containing mean mass in radial bins, averaged over all points
"""
if rbins is None:
r = np.sort(np.sqrt(np.sum((pos - np.median(pos, axis=0)) ** 2, axis=1)))
rbins = 10 ** np.linspace(
np.log10(r[10]), np.log10(r[-1]), int(len(r) ** (1.0 / 3))
)
if tree is None:
softening = np.zeros_like(m)
tree = ConstructTree(
np.float64(pos), np.float64(m), np.float64(softening)
) # build the tree if needed
idx = tree.TreewalkIndices
# sort by the order they appear in the treewalk to improve access pattern efficiency
pos_sorted = np.take(pos, idx, axis=0)
if parallel:
mbins = DensityCorrFunc_tree_parallel(
pos_sorted,
tree,
rbins,
max_bin_size_ratio=max_bin_size_ratio,
theta=theta,
boxsize=boxsize,
weighted_binning=weighted_binning,
)
else:
mbins = DensityCorrFunc_tree(
pos_sorted,
tree,
rbins,
max_bin_size_ratio=max_bin_size_ratio,
theta=theta,
boxsize=boxsize,
weighted_binning=weighted_binning,
)
if return_tree:
return rbins, mbins, tree
else:
return rbins, mbins
def VelocityCorrFunc(
pos,
m,
v,
rbins=None,
max_bin_size_ratio=100,
theta=1.0,
tree=None,
return_tree=False,
parallel=False,
boxsize=0,
weighted_binning=False,
):
"""Computes the weighted average product v(x).v(x+r), for a vector field v, in radial bins
Parameters
----------
pos: array_like
shape (N,3) array of particle positions
m: array_like
shape (N,) array of particle masses
v: array_like
shape (N,3) of vector quantity (e.g. velocity, magnetic field, etc)
rbins: array_like or None, optional
1D array of radial bin edges - if None will use heuristics to determine sensible bins. Otherwise MUST BE LOGARITHMICALLY SPACED (default None)
max_bin_size_ratio: float, optional
controls the accuracy of the binning - tree nodes are subdivided until their side length is at most this factor * the radial bin width (default 100)
theta: float, optional
cell opening angle used to control accuracy; smaller is slower (runtime ~ theta^-3) but more accurate. (default 1.0)
parallel: bool, optional
If True, will parallelize the correlation function computation over all available cores. (default False)
tree: Octree, optional
optional pre-generated Octree: this can contain any set of particles, not necessarily the target particles at pos (default None)
return_tree: bool, optional
if True will return the generated or used tree for future use (default False)
boxsize: float, optional
finite periodic box size, if periodic boundary conditions are to be used (default 0)
weighted_binning: bool, optional
(experimental) if True will distribute mass among radial bings with a weighted kernel (default False)
Returns
-------
rbins: array_like
array containing radial bin edges
corr: array_like
array containing correlation function values in radial bins
"""
if rbins is None:
r = np.sort(np.sqrt(np.sum((pos - np.median(pos, axis=0)) ** 2, axis=1)))
rbins = 10 ** np.linspace(
np.log10(r[10]), np.log10(r[-1]), int(len(r) ** (1.0 / 3))
)
if tree is None:
softening = np.zeros_like(m)
tree = ConstructTree(
np.float64(pos), np.float64(m), np.float64(softening), vel=v
) # build the tree if needed
idx = tree.TreewalkIndices
# sort by the order they appear in the treewalk to improve access pattern efficiency
pos_sorted = np.take(pos, idx, axis=0)
v_sorted = np.take(v, idx, axis=0)
wt_sorted = np.take(m, idx, axis=0)
if parallel:
corr = VelocityCorrFunc_tree_parallel(
pos_sorted,
v_sorted,
wt_sorted,
tree,
rbins,
max_bin_size_ratio=max_bin_size_ratio,
theta=theta,
boxsize=boxsize,
weighted_binning=weighted_binning,
)
else:
corr = VelocityCorrFunc_tree(
pos_sorted,
v_sorted,
wt_sorted,
tree,
rbins,
max_bin_size_ratio=max_bin_size_ratio,
theta=theta,
boxsize=boxsize,
weighted_binning=weighted_binning,
)
if return_tree:
return rbins, corr, tree
else:
return rbins, corr
def VelocityStructFunc(
pos,
m,
v,
rbins=None,
max_bin_size_ratio=100,
theta=1.0,
tree=None,
return_tree=False,
parallel=False,
boxsize=0,
weighted_binning=False,
):
"""Computes the structure function for a vector field: the average value of |v(x)-v(x+r)|^2, in radial bins for r
Parameters
----------
pos: array_like
shape (N,3) array of particle positions
m: array_like
shape (N,) array of particle masses
v: array_like
shape (N,3) of vector quantity (e.g. velocity, magnetic field, etc)
rbins: array_like or None, optional
1D array of radial bin edges - if None will use heuristics to determine sensible bins. Otherwise MUST BE LOGARITHMICALLY SPACED (default None)
max_bin_size_ratio: float, optional
controls the accuracy of the binning - tree nodes are subdivided until their side length is at most this factor * the radial bin width (default 100)
theta: float, optional
cell opening angle used to control accuracy; smaller is slower (runtime ~ theta^-3) but more accurate. (default 1.0)
parallel: bool, optional
If True, will parallelize the correlation function computation over all available cores. (default False)
tree: Octree, optional
optional pre-generated Octree: this can contain any set of particles, not necessarily the target particles at pos (default None)
return_tree: bool, optional
if True will return the generated or used tree for future use (default False)
boxsize: float, optional
finite periodic box size, if periodic boundary conditions are to be used (default 0)
weighted_binning: bool, optional
(experimental) if True will distribute mass among radial bings with a weighted kernel (default False)
Returns
-------
rbins: array_like
array containing radial bin edges
Sv: array_like
array containing structure function values
"""
if rbins is None:
r = np.sort(np.sqrt(np.sum((pos - np.median(pos, axis=0)) ** 2, axis=1)))
rbins = 10 ** np.linspace(
np.log10(r[10]), np.log10(r[-1]), int(len(r) ** (1.0 / 3))
)
if tree is None:
softening = np.zeros_like(m)
tree = ConstructTree(
np.float64(pos), np.float64(m), np.float64(softening), vel=v
) # build the tree if needed
idx = tree.TreewalkIndices
# sort by the order they appear in the treewalk to improve access pattern efficiency
pos_sorted = np.take(pos, idx, axis=0)
v_sorted = np.take(v, idx, axis=0)
wt_sorted = np.take(m, idx, axis=0)
if parallel:
Sv = VelocityStructFunc_tree_parallel(
pos_sorted,
v_sorted,
wt_sorted,
tree,
rbins,
max_bin_size_ratio=max_bin_size_ratio,
theta=theta,
boxsize=boxsize,
weighted_binning=weighted_binning,
)
else:
Sv = VelocityStructFunc_tree(
pos_sorted,
v_sorted,
wt_sorted,
tree,
rbins,
max_bin_size_ratio=max_bin_size_ratio,
theta=theta,
boxsize=boxsize,
weighted_binning=weighted_binning,
)
if return_tree:
return rbins, Sv, tree
else:
return rbins, Sv
def ColumnDensity(
pos,
m,
radii,
rays=None,
randomize_rays=False,
healpix=False,
tree=None,
theta=0.5,
return_tree=False,
parallel=False,
):
"""Ray-traced or angle-binned column density calculation.
Returns an estimate of the column density from the position of each particle
integrated to infinity, assuming the particles are represented by uniform spheres. Note
that optical depth can be obtained by supplying "sigma = opacity * mass" in
place of mass, useful in situations where opacity is highly variable.
Parameters
----------
pos: array_like
shape (N,3) array of particle positions
m: array_like
shape (N,) array of particle masses
radii: array_like
shape (N,) array containing particle radii of the uniform spheres that
we use to model the particles' mass distribution
rays: optional
Which ray directions to raytrace the columns.
None: use the angular-binned column density method with 6 bins on the sky
OPTION 2: Integer number: use this many rays, with 6 using the standard
6-ray grid and other numbers sampling random directions
OPTION 3: Give a (N_rays,3) array of vectors specifying the
directions, which will be automatically normalized.
healpix: int, optional
Use healpix ray grid with specified resolution level NSIDE
randomize_rays: bool, optional
Randomize the orientation of the ray-grid *for each particle*
parallel: bool, optional
If True, will parallelize the column density over all available cores.
(default False)
tree: Octree, optional
optional pre-generated Octree: this can contain any set of particles,
not necessarily the target particles at pos (default None)
theta: float, optional
Opening angle for beam-traced angular bin estimator
return_tree: bool, optional
return the tree used for future use (default False)
Returns
-------
columns: array_like
shape (N,N_rays) float array of column densities from particle
centers integrated along the rays
"""
if tree is None:
tree = ConstructTree(
np.float64(pos),
np.float64(m),
np.float64(radii),
) # build the tree if needed
idx = tree.TreewalkIndices
pos_sorted = np.take(pos, idx, axis=0)
if type(rays) == int:
if rays == 6:
rays = np.vstack([np.eye(3), -np.eye(3)]) # 6-ray grid
else:
# generate a random grid of ray directions
rays = np.random.normal(size=(rays, 3)) # normalize later
elif type(rays) == np.ndarray:
# check that the shape is correct
if not len(rays.shape) == 2:
raise Exception("rays array argument must be 2D.")
elif rays.shape[1] != 3:
raise Exception("rays array argument is not an array of 3D vectors.")
rays = np.copy(rays) # so that we don't overwrite the argument
elif rays is not None:
raise Exception("rays argument type is not supported")
if healpix:
nside = healpix
npix = hp.nside2npix(nside)
rays = np.array(hp.pix2vec(nside, np.arange(npix))).T
if rays is not None:
rays /= np.sqrt((rays * rays).sum(1))[:, None] # normalize the ray vectors
if parallel:
columns = ColumnDensity_tree_parallel(
pos_sorted, tree, rays, randomize_rays=randomize_rays, theta=theta
)
else:
columns = ColumnDensity_tree(
pos_sorted, tree, rays, randomize_rays=randomize_rays, theta=theta
)
if np.any(np.isnan(columns)):
print("WARNING some column densities are NaN!")
columns = np.take(columns, idx.argsort(), axis=0)
if return_tree:
return columns, tree
else:
return columns