/
streamgapdf.py
2077 lines (1953 loc) · 81.5 KB
/
streamgapdf.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
# The DF of a gap in a tidal stream
import copy
import multiprocessing
import warnings
from functools import wraps
import numpy
from scipy import integrate, interpolate, special
from ..orbit import Orbit
from ..potential import MovingObjectPotential, PlummerPotential, evaluateRforces
from ..potential import flatten as flatten_potential
from ..util import _rotate_to_arbitrary_vector, conversion, coords, galpyWarning, multi
from ..util.conversion import physical_conversion
from . import streamdf
from .df import df
from .streamdf import _determine_stream_track_single
def impact_check_range(func):
"""Decorator to check the range of interpolated kicks"""
@wraps(func)
def impact_wrapper(*args, **kwargs):
if isinstance(args[1], numpy.ndarray):
out = numpy.zeros(len(args[1]))
goodIndx = (args[1] < args[0]._deltaAngleTrackImpact) * (args[1] > 0.0)
out[goodIndx] = func(args[0], args[1][goodIndx])
return out
elif args[1] >= args[0]._deltaAngleTrackImpact or args[1] <= 0.0:
return 0.0
else:
return func(*args, **kwargs)
return impact_wrapper
class streamgapdf(streamdf.streamdf):
"""The DF of a gap in a tidal stream"""
def __init__(self, *args, **kwargs):
"""
Initialize the DF of a gap in a stellar stream
Parameters
----------
sigv : float or Quantity
Radial velocity dispersion of the progenitor.
progenitor : galpy.orbit.Orbit
Progenitor orbit as Orbit instance (will be re-integrated, so don't bother integrating the orbit before).
pot : galpy.potential.Potential or list thereof, optional
Potential instance or list thereof.
aA : actionAngle instance
ActionAngle instance used to convert (x,v) to actions. Generally a actionAngleIsochroneApprox instance.
useTM : bool, optional
If set to an actionAngleTorus instance, use this to speed up calculations.
tdisrupt : float or Quantity, optional
Time since start of disruption (default: 5 Gyr).
sigMeanOffset : float, optional
Offset between the mean of the frequencies and the progenitor, in units of the largest eigenvalue of the frequency covariance matrix (along the largest eigenvector), should be positive; to model the trailing part, set leading=False (default: 6.0).
leading : bool, optional
If True, model the leading part of the stream; if False, model the trailing part (default: True).
sigangle : float or Quantity, optional
Estimate of the angle spread of the debris initially (default: sigv/122/[1km/s]=1.8sigv in natural coordinates).
deltaAngleTrack : float or Quantity, optional
Angle to estimate the stream track over (rad; or can be Quantity) (default: None).
nTrackChunks : int, optional
Number of chunks to divide the progenitor track in (default: floor(deltaAngleTrack/0.15)+1).
nTrackIterations : int, optional
Number of iterations to perform when establishing the track; each iteration starts from a previous approximation to the track in (x,v) and calculates a new track based on the deviation between the previous track and the desired track in action-angle coordinates; if not set, an appropriate value is determined based on the magnitude of the misalignment between stream and orbit, with larger numbers of iterations for larger misalignments (default: None).
progIsTrack : bool, optional
If True, then the progenitor (x,v) is actually the (x,v) of the stream track at zero angle separation; useful when initializing with an orbit fit; the progenitor's position will be calculated (default: False).
ro : float or Quantity, optional
Distance scale for translation into internal units (default from configuration file).
vo : float or Quantity, optional
Velocity scale for translation into internal units (default from configuration file).
Vnorm : float or Quantity, optional
Deprecated. Use vo instead (default: None).
Rnorm : float or Quantity, optional
Deprecated. Use ro instead (default: None).
R0 : float or Quantity, optional
Galactocentric radius of the Sun (kpc) (can be different from ro) (default: 8.0).
Zsun : float or Quantity, optional
Sun's height above the plane (kpc) (default: 0.0208).
vsun : numpy.ndarray or Quantity, optional
Sun's motion in cylindrical coordinates (vR positive away from center) (can be Quantity array, but not a list of Quantities) (default: [-11.1, 8.0 * 30.24, 7.25]).
multi : int, optional
If set, use multi-processing (default: None).
interpTrack : bool, optional
Interpolate the stream track while setting up the instance (can be done by hand by calling self._interpolate_stream_track() and self._interpolate_stream_track_aA()) (default: _INTERPDURINGSETUP).
useInterp : bool, optional
Use interpolation by default when calculating approximated frequencies and angles (default: _USEINTERP).
nosetup : bool, optional
If True, don't setup the stream track and anything else that is expensive (default: False).
nospreadsetup : bool, optional
If True, don't setup the spread around the stream track (only for nosetup is False) (default: False).
approxConstTrackFreq : bool, optional
If True, approximate the stream assuming that the frequency is constant along the stream (only works with useTM, for which this leads to a significant speed-up) (default: False).
useTMHessian : bool, optional
If True, compute the basic Hessian dO/dJ_prog using TM; otherwise use aA (default: False).
custom_transform : numpy.ndarray, optional
Matrix implementing the rotation from (ra,dec) to a custom set of sky coordinates (default: None).
impactb : float or Quantity, optional
Impact parameter (can be Quantity) (default: 1.0).
subhalovel : numpy.ndarray or Quantity, optional
Velocity of the subhalo shape=(3) (default: [0.0, 1.0, 0.0]).
timpact : float or Quantity, optional
Time since impact (can be Quantity) (default: 1.0).
impact_angle : float or Quantity, optional
Angle offset from progenitor at which the impact occurred (rad) (can be Quantity) (default: 1.0).
GM : float or Quantity, optional
Mass of the subhalo when using a Plummer or Hernquist model.
rs : float or Quantity, optional
Scale parameter of the subhalo when using a Plummer or Hernquist model.
hernquist : bool, optional
If True, use Hernquist kicks for GM/rs (default: False --> Plummer).
subhalopot : Potential or list thereof, optional
Gravitational potential of the subhalo (alternative to specifying GM and rs)
deltaAngleTrackImpact : float or Quantity, optional
Angle to estimate the stream track over to determine the effect of the impact [similar to deltaAngleTrack] (rad) (default: None).
nTrackChunksImpact : int, optional
Number of chunks to divide the progenitor track in near the impact [similar to nTrackChunks] (default: floor(deltaAngleTrack/0.15)+1).
nKickPoints : int, optional
Number of points along the stream to compute the kicks at (kicks are then interpolated); '30' chosen such that higherorderTrack can be set to False and get calculations accurate to > 99% (default: 30xnTrackChunksImpact).
nokicksetup : bool, optional
If True, only run as far as setting up the coordinate transformation at the time of impact (useful when using this in streampepperdf) (default: False).
spline_order : int, optional
Order of the spline to interpolate the kicks with (default: 3).
higherorderTrack : bool, optional
If True, calculate the track using higher-order terms (default: False).
nTrackChunks : int, optional
Number of chunks to divide the progenitor track into (default: 8).
interpTrack : bool, optional
If True, interpolate the track (default: True).
useInterp : bool, optional
If True, use the interpolated track to calculate actions and angles (default: True).
Notes
-----
- Parameters above up to impactb are streamdf parameters used to setup the underlying smooth stream.
- 2015-06-02 - Started - Bovy (IAS)
"""
df.__init__(self, ro=kwargs.get("ro", None), vo=kwargs.get("vo", None))
# Parse kwargs
impactb = conversion.parse_length(kwargs.pop("impactb", 1.0), ro=self._ro)
subhalovel = conversion.parse_velocity(
kwargs.pop("subhalovel", numpy.array([0.0, 1.0, 0.0])), vo=self._vo
)
hernquist = kwargs.pop("hernquist", False)
GM = kwargs.pop("GM", None)
if not GM is None:
GM = conversion.parse_mass(GM, ro=self._ro, vo=self._vo)
rs = kwargs.pop("rs", None)
if not rs is None:
rs = conversion.parse_length(rs, ro=self._ro)
subhalopot = kwargs.pop("subhalopot", None)
timpact = conversion.parse_time(
kwargs.pop("timpact", 1.0), ro=self._ro, vo=self._vo
)
impact_angle = conversion.parse_angle(kwargs.pop("impact_angle", 1.0))
nokicksetup = kwargs.pop("nokicksetup", False)
deltaAngleTrackImpact = kwargs.pop("deltaAngleTrackImpact", None)
nTrackChunksImpact = kwargs.pop("nTrackChunksImpact", None)
nKickPoints = kwargs.pop("nKickPoints", None)
spline_order = kwargs.pop("spline_order", 3)
higherorderTrack = kwargs.pop("higherorderTrack", False)
# For setup later
nTrackChunks = kwargs.pop("nTrackChunks", None)
interpTrack = kwargs.pop("interpTrack", streamdf._INTERPDURINGSETUP)
useInterp = kwargs.pop("useInterp", streamdf._USEINTERP)
# Analytical Plummer or general potential?
self._general_kick = GM is None or rs is None
if self._general_kick and subhalopot is None:
raise OSError(
"One of (GM=, rs=) or subhalopot= needs to be set to specify the subhalo's structure"
)
# Now run the regular streamdf setup, but without calculating the
# stream track (nosetup=True)
kwargs["nosetup"] = True
super().__init__(*args, **kwargs)
# Setup the machinery to go between (x,v) and (Omega,theta)
# near the impact
self._determine_nTrackIterations(kwargs.get("nTrackIterations", None))
self._determine_deltaAngleTrackImpact(deltaAngleTrackImpact, timpact)
self._determine_impact_coordtransform(
self._deltaAngleTrackImpact, nTrackChunksImpact, timpact, impact_angle
)
# Set nKickPoints
if nKickPoints is None:
self._nKickPoints = 30 * self._nTrackChunksImpact
else:
self._nKickPoints = nKickPoints
if nokicksetup: # pragma: no cover
return None
# Compute \Delta Omega ( \Delta \theta_perp) and \Delta theta,
# setup interpolating function
self._determine_deltav_kick(
impact_angle,
impactb,
subhalovel,
GM,
rs,
subhalopot,
spline_order,
hernquist,
)
self._determine_deltaOmegaTheta_kick(spline_order)
# Then pass everything to the normal streamdf setup
self.nInterpolatedTrackChunks = 201 # more expensive now
self._higherorderTrack = higherorderTrack
super()._determine_stream_track(nTrackChunks)
self._useInterp = useInterp
if interpTrack or self._useInterp:
super()._interpolate_stream_track()
super()._interpolate_stream_track_aA()
super().calc_stream_lb()
return None
def pOparapar(self, Opar, apar):
"""
Return the probability of a given parallel (frequency,angle) offset pair.
Parameters
----------
Opar : numpy.ndarray or Quantity
Parallel frequency offset.
apar : float or Quantity
Parallel angle offset along the stream.
Returns
-------
numpy.ndarray
Probability of a given parallel (frequency,angle) offset pair.
Notes
-----
- 2015-11-17 - Written - Bovy (UofT).
"""
Opar = conversion.parse_frequency(Opar, ro=self._ro, vo=self._vo)
apar = conversion.parse_angle(apar)
Opar = numpy.array(Opar)
out = numpy.zeros_like(Opar)
# Compute ts and where they were at impact for all
ts = apar / Opar
apar_impact = apar - Opar * self._timpact
dOpar_impact = self._kick_interpdOpar(apar_impact)
Opar_b4impact = Opar - dOpar_impact
# Evaluate the smooth model in the two regimes:
# stripped before or after impact
afterIndx = (ts < self._timpact) * (ts >= 0.0)
out[afterIndx] = super().pOparapar(Opar[afterIndx], apar)
out[True ^ afterIndx] = super().pOparapar(
Opar_b4impact[True ^ afterIndx],
apar_impact[True ^ afterIndx],
tdisrupt=self._tdisrupt - self._timpact,
)
return out
def _density_par(self, dangle, tdisrupt=None, approx=True, higherorder=None):
"""The raw density as a function of parallel angle,
approx= use faster method that directly integrates the spline
representation"""
if higherorder is None:
higherorder = self._higherorderTrack
if tdisrupt is None:
tdisrupt = self._tdisrupt
if approx:
return self._density_par_approx(dangle, tdisrupt, higherorder=higherorder)
else:
return integrate.quad(
lambda T: numpy.sqrt(self._sortedSigOEig[2])
* (1 + T * T)
/ (1 - T * T) ** 2.0
* self.pOparapar(
T / (1 - T * T) * numpy.sqrt(self._sortedSigOEig[2]) + self._meandO,
dangle,
),
-1.0,
1.0,
)[0]
def _density_par_approx(
self, dangle, tdisrupt, _return_array=False, higherorder=False
):
"""Compute the density as a function of parallel angle using the
spline representation + approximations"""
# First construct the breakpoints for this dangle
Oparb = (dangle - self._kick_interpdOpar_poly.x) / self._timpact
# Find the lower limit of the integration in the pw-linear-kick approx.
lowbindx, lowx = self.minOpar(dangle, tdisrupt, _return_raw=True)
lowbindx = numpy.arange(len(Oparb) - 1)[lowbindx]
Oparb[lowbindx + 1] = Oparb[lowbindx] - lowx
# Now integrate between breakpoints
out = (
0.5
/ (1.0 + self._kick_interpdOpar_poly.c[-2] * self._timpact)
* (
special.erf(
1.0
/ numpy.sqrt(2.0 * self._sortedSigOEig[2])
* (Oparb[:-1] - self._kick_interpdOpar_poly.c[-1] - self._meandO)
)
- special.erf(
1.0
/ numpy.sqrt(2.0 * self._sortedSigOEig[2])
* (
numpy.roll(Oparb, -1)[:-1]
- self._kick_interpdOpar_poly.c[-1]
- self._meandO
- self._kick_interpdOpar_poly.c[-2]
* self._timpact
* (Oparb - numpy.roll(Oparb, -1))[:-1]
)
)
)
)
if _return_array:
return out
out = numpy.sum(out[: lowbindx + 1])
if higherorder:
# Add higher-order contribution
out += self._density_par_approx_higherorder(Oparb, lowbindx)
# Add integration to infinity
out += 0.5 * (
1.0
+ special.erf(
(self._meandO - Oparb[0]) / numpy.sqrt(2.0 * self._sortedSigOEig[2])
)
)
return out
def _density_par_approx_higherorder(
self, Oparb, lowbindx, _return_array=False, gaussxpolyInt=None
):
"""Contribution from non-linear spline terms"""
spline_order = self._kick_interpdOpar_raw._eval_args[2]
if spline_order == 1: # pragma: no cover
return 0.0
# Form all Gaussian-like integrals necessary
ll = (
numpy.roll(Oparb, -1)[:-1]
- self._kick_interpdOpar_poly.c[-1]
- self._meandO
- self._kick_interpdOpar_poly.c[-2]
* self._timpact
* (Oparb - numpy.roll(Oparb, -1))[:-1]
) / numpy.sqrt(2.0 * self._sortedSigOEig[2])
ul = (
Oparb[:-1] - self._kick_interpdOpar_poly.c[-1] - self._meandO
) / numpy.sqrt(2.0 * self._sortedSigOEig[2])
if gaussxpolyInt is None:
gaussxpolyInt = self._densMoments_approx_higherorder_gaussxpolyInts(
ll, ul, spline_order + 1
)
# Now multiply in the coefficients for each order
powers = numpy.tile(numpy.arange(spline_order + 1)[::-1], (len(ul), 1)).T
gaussxpolyInt *= (
-0.5
* (-numpy.sqrt(2.0)) ** (powers + 1)
* self._sortedSigOEig[2] ** (0.5 * (powers - 1))
)
powers = numpy.tile(numpy.arange(spline_order + 1)[::-1][:-2], (len(ul), 1)).T
for jj in range(spline_order + 1):
gaussxpolyInt[-jj - 1] *= numpy.sum(
self._kick_interpdOpar_poly.c[:-2]
* self._timpact**powers
/ (1.0 + self._kick_interpdOpar_poly.c[-2] * self._timpact)
** (powers + 1)
* special.binom(powers, jj)
* (Oparb[:-1] - self._kick_interpdOpar_poly.c[-1] - self._meandO)
** (powers - jj),
axis=0,
)
if _return_array:
return numpy.sum(gaussxpolyInt, axis=0)
else:
return numpy.sum(gaussxpolyInt[:, : lowbindx + 1])
def _densMoments_approx_higherorder_gaussxpolyInts(self, ll, ul, maxj):
"""Calculate all of the polynomial x Gaussian integrals occurring
in the higher-order terms, recursively"""
gaussxpolyInt = numpy.zeros((maxj, len(ul)))
gaussxpolyInt[-1] = (
1.0 / numpy.sqrt(numpy.pi) * (numpy.exp(-(ll**2.0)) - numpy.exp(-(ul**2.0)))
)
gaussxpolyInt[-2] = 1.0 / numpy.sqrt(numpy.pi) * (
numpy.exp(-(ll**2.0)) * ll - numpy.exp(-(ul**2.0)) * ul
) + 0.5 * (special.erf(ul) - special.erf(ll))
for jj in range(maxj - 2):
gaussxpolyInt[-jj - 3] = (
1.0
/ numpy.sqrt(numpy.pi)
* (
numpy.exp(-(ll**2.0)) * ll ** (jj + 2)
- numpy.exp(-(ul**2.0)) * ul ** (jj + 2)
)
+ 0.5 * (jj + 2) * gaussxpolyInt[-jj - 1]
)
return gaussxpolyInt
def minOpar(self, dangle, tdisrupt=None, _return_raw=False):
"""
Return the approximate minimum parallel frequency at a given angle
Parameters
----------
dangle : float
Parallel angle
tdisrupt : float, optional
Disruption time (default is the value passed at initialization)
_return_raw : bool, optional
If True, return the index of the minimum frequency and the value of the minimum frequency (default is False)
Returns
-------
float or tuple
Minimum frequency that gets to this parallel angle or a tuple with the index of the minimum frequency and the value of the minimum frequency
Notes
-----
- 2015-12-28 - Written - Bovy (UofT)
"""
if tdisrupt is None:
tdisrupt = self._tdisrupt
# First construct the breakpoints for this dangle
Oparb = (dangle - self._kick_interpdOpar_poly.x[:-1]) / self._timpact
# Find the lower limit of the integration in the pw-linear-kick approx.
lowx = (
(Oparb - self._kick_interpdOpar_poly.c[-1]) * (tdisrupt - self._timpact)
+ Oparb * self._timpact
- dangle
) / (
(tdisrupt - self._timpact)
* (1.0 + self._kick_interpdOpar_poly.c[-2] * self._timpact)
+ self._timpact
)
lowx[lowx < 0.0] = numpy.inf
lowbindx = numpy.argmin(lowx)
if _return_raw:
return (lowbindx, lowx[lowbindx])
else:
return Oparb[lowbindx] - lowx[lowbindx]
@physical_conversion("frequency", pop=True)
def meanOmega(
self, dangle, oned=False, tdisrupt=None, approx=True, higherorder=None
):
"""
Calculate the mean frequency as a function of angle, assuming a uniform time distribution up to a maximum time.
Parameters
----------
dangle : float
Angle offset.
oned : bool, optional
If True, return the 1D offset from the progenitor (along the direction of disruption). Default is False.
tdisrupt : float, optional
Maximum time. Default is None.
approx : bool, optional
If True, compute the mean Omega by direct integration of the spline representation. Default is True.
higherorder : object, optional
Higher-order spline terms in the approximate computation. Default is object-wide default higherorderTrack.
Returns
-------
float
Mean Omega.
Notes
-----
- 2015-11-17 - Written - Bovy (UofT)
"""
if higherorder is None:
higherorder = self._higherorderTrack
if tdisrupt is None:
tdisrupt = self._tdisrupt
if approx:
num = self._meanOmega_num_approx(dangle, tdisrupt, higherorder=higherorder)
else:
num = integrate.quad(
lambda T: (
T / (1 - T * T) * numpy.sqrt(self._sortedSigOEig[2]) + self._meandO
)
* numpy.sqrt(self._sortedSigOEig[2])
* (1 + T * T)
/ (1 - T * T) ** 2.0
* self.pOparapar(
T / (1 - T * T) * numpy.sqrt(self._sortedSigOEig[2]) + self._meandO,
dangle,
),
-1.0,
1.0,
)[0]
denom = self._density_par(
dangle, tdisrupt=tdisrupt, approx=approx, higherorder=higherorder
)
dO1D = num / denom
if oned:
return dO1D
else:
return (
self._progenitor_Omega
+ dO1D * self._dsigomeanProgDirection * self._sigMeanSign
)
def _meanOmega_num_approx(self, dangle, tdisrupt, higherorder=False):
"""Compute the numerator going into meanOmega using the direct integration of the spline representation"""
# First construct the breakpoints for this dangle
Oparb = (dangle - self._kick_interpdOpar_poly.x) / self._timpact
# Find the lower limit of the integration in the pw-linear-kick approx.
lowbindx, lowx = self.minOpar(dangle, tdisrupt, _return_raw=True)
lowbindx = numpy.arange(len(Oparb) - 1)[lowbindx]
Oparb[lowbindx + 1] = Oparb[lowbindx] - lowx
# Now integrate between breakpoints
out = numpy.sum(
(
(
Oparb[:-1]
+ (self._meandO + self._kick_interpdOpar_poly.c[-1] - Oparb[:-1])
/ (1.0 + self._kick_interpdOpar_poly.c[-2] * self._timpact)
)
* self._density_par_approx(dangle, tdisrupt, _return_array=True)
+ numpy.sqrt(self._sortedSigOEig[2] / 2.0 / numpy.pi)
/ (1.0 + self._kick_interpdOpar_poly.c[-2] * self._timpact) ** 2.0
* (
numpy.exp(
-0.5
* (
Oparb[:-1]
- self._kick_interpdOpar_poly.c[-1]
- (1.0 + self._kick_interpdOpar_poly.c[-2] * self._timpact)
* (Oparb - numpy.roll(Oparb, -1))[:-1]
- self._meandO
)
** 2.0
/ self._sortedSigOEig[2]
)
- numpy.exp(
-0.5
* (
Oparb[:-1]
- self._kick_interpdOpar_poly.c[-1]
- self._meandO
)
** 2.0
/ self._sortedSigOEig[2]
)
)
)[: lowbindx + 1]
)
if higherorder:
# Add higher-order contribution
out += self._meanOmega_num_approx_higherorder(Oparb, lowbindx)
# Add integration to infinity
out += 0.5 * (
numpy.sqrt(2.0 / numpy.pi)
* numpy.sqrt(self._sortedSigOEig[2])
* numpy.exp(
-0.5 * (self._meandO - Oparb[0]) ** 2.0 / self._sortedSigOEig[2]
)
+ self._meandO
* (
1.0
+ special.erf(
(self._meandO - Oparb[0]) / numpy.sqrt(2.0 * self._sortedSigOEig[2])
)
)
)
return out
def _meanOmega_num_approx_higherorder(self, Oparb, lowbindx):
"""Contribution from non-linear spline terms"""
spline_order = self._kick_interpdOpar_raw._eval_args[2]
if spline_order == 1: # pragma: no cover
return 0.0
# Form all Gaussian-like integrals necessary
ll = (
numpy.roll(Oparb, -1)[:-1]
- self._kick_interpdOpar_poly.c[-1]
- self._meandO
- self._kick_interpdOpar_poly.c[-2]
* self._timpact
* (Oparb - numpy.roll(Oparb, -1))[:-1]
) / numpy.sqrt(2.0 * self._sortedSigOEig[2])
ul = (
Oparb[:-1] - self._kick_interpdOpar_poly.c[-1] - self._meandO
) / numpy.sqrt(2.0 * self._sortedSigOEig[2])
gaussxpolyInt = self._densMoments_approx_higherorder_gaussxpolyInts(
ll, ul, spline_order + 2
)
firstTerm = Oparb[:-1] * self._density_par_approx_higherorder(
Oparb,
lowbindx,
_return_array=True,
gaussxpolyInt=copy.copy(gaussxpolyInt[1:]),
)
# Now multiply in the coefficients for each order
powers = numpy.tile(numpy.arange(spline_order + 2)[::-1], (len(ul), 1)).T
gaussxpolyInt *= (
-0.5
* (-numpy.sqrt(2.0)) ** (powers + 1)
* self._sortedSigOEig[2] ** (0.5 * (powers - 1))
)
powers = numpy.tile(numpy.arange(spline_order + 1)[::-1][:-2], (len(ul), 1)).T
for jj in range(spline_order + 2):
gaussxpolyInt[-jj - 1] *= numpy.sum(
self._kick_interpdOpar_poly.c[:-2]
* self._timpact**powers
/ (1.0 + self._kick_interpdOpar_poly.c[-2] * self._timpact)
** (powers + 2)
* special.binom(powers + 1, jj)
* (Oparb[:-1] - self._kick_interpdOpar_poly.c[-1] - self._meandO)
** (powers - jj + 1),
axis=0,
)
out = numpy.sum(gaussxpolyInt, axis=0)
out += firstTerm
return numpy.sum(out[: lowbindx + 1])
def _determine_deltav_kick(
self,
impact_angle,
impactb,
subhalovel,
GM,
rs,
subhalopot,
spline_order,
hernquist,
):
# Store some impact parameters
self._impactb = impactb
self._subhalovel = subhalovel
# Sign of delta angle tells us whether the impact happens to the
# leading or trailing arm, self._sigMeanSign contains this info;
# Checked before, but check it again in case impact_angle has changed
if impact_angle > 0.0:
self._gap_leading = True
else:
self._gap_leading = False
if (self._gap_leading and not self._leading) or (
not self._gap_leading and self._leading
):
raise ValueError(
"Modeling leading (trailing) impact for trailing (leading) arm; this is not allowed because it is nonsensical in this framework"
)
self._impact_angle = numpy.fabs(impact_angle)
# Interpolate the track near the gap in (x,v) at the kick_thetas
self._interpolate_stream_track_kick()
self._interpolate_stream_track_kick_aA()
# Then compute delta v along the track
if self._general_kick:
self._kick_deltav = impulse_deltav_general_curvedstream(
self._kick_interpolatedObsTrackXY[:, 3:],
self._kick_interpolatedObsTrackXY[:, :3],
self._impactb,
self._subhalovel,
self._kick_ObsTrackXY_closest[:3],
self._kick_ObsTrackXY_closest[3:],
subhalopot,
)
else:
if hernquist:
deltav_func = impulse_deltav_hernquist_curvedstream
else:
deltav_func = impulse_deltav_plummer_curvedstream
self._kick_deltav = deltav_func(
self._kick_interpolatedObsTrackXY[:, 3:],
self._kick_interpolatedObsTrackXY[:, :3],
self._impactb,
self._subhalovel,
self._kick_ObsTrackXY_closest[:3],
self._kick_ObsTrackXY_closest[3:],
GM,
rs,
)
return None
def _determine_deltaOmegaTheta_kick(self, spline_order):
# Propagate deltav(angle) -> delta (Omega,theta) [angle]
# Cylindrical coordinates of the perturbed points
vXp = self._kick_interpolatedObsTrackXY[:, 3] + self._kick_deltav[:, 0]
vYp = self._kick_interpolatedObsTrackXY[:, 4] + self._kick_deltav[:, 1]
vZp = self._kick_interpolatedObsTrackXY[:, 5] + self._kick_deltav[:, 2]
vRp, vTp, vZp = coords.rect_to_cyl_vec(
vXp,
vYp,
vZp,
self._kick_interpolatedObsTrack[:, 0],
self._kick_interpolatedObsTrack[:, 5],
self._kick_interpolatedObsTrack[:, 3],
cyl=True,
)
# We will abuse streamdf functions for doing the (O,a) -> (R,vR)
# coordinate transformation, to do this, we assign some of the
# attributes related to the track near the impact to the equivalent
# attributes related to the track at the present time, carefully
# removing this again to avoid confusion (as much as possible)
self._interpolatedObsTrack = self._kick_interpolatedObsTrack
self._ObsTrack = self._gap_ObsTrack
self._interpolatedObsTrackXY = self._kick_interpolatedObsTrackXY
self._ObsTrackXY = self._gap_ObsTrackXY
self._alljacsTrack = self._gap_alljacsTrack
self._interpolatedObsTrackAA = self._kick_interpolatedObsTrackAA
self._ObsTrackAA = self._gap_ObsTrackAA
self._nTrackChunks = self._nTrackChunksImpact
Oap = self._approxaA(
self._kick_interpolatedObsTrack[:, 0],
vRp,
vTp,
self._kick_interpolatedObsTrack[:, 3],
vZp,
self._kick_interpolatedObsTrack[:, 5],
interp=True,
cindx=range(len(self._kick_interpolatedObsTrackAA)),
)
# Remove attributes again to avoid confusion later
delattr(self, "_interpolatedObsTrack")
delattr(self, "_ObsTrack")
delattr(self, "_interpolatedObsTrackXY")
delattr(self, "_ObsTrackXY")
delattr(self, "_alljacsTrack")
delattr(self, "_interpolatedObsTrackAA")
delattr(self, "_ObsTrackAA")
delattr(self, "_nTrackChunks")
# Generate (dO,da)[angle_offset] and interpolate (raw here, see below
# for form that checks range)
self._kick_dOap = Oap.T - self._kick_interpolatedObsTrackAA
self._kick_interpdOr_raw = interpolate.InterpolatedUnivariateSpline(
self._kick_interpolatedThetasTrack, self._kick_dOap[:, 0], k=spline_order
)
self._kick_interpdOp_raw = interpolate.InterpolatedUnivariateSpline(
self._kick_interpolatedThetasTrack, self._kick_dOap[:, 1], k=spline_order
)
self._kick_interpdOz_raw = interpolate.InterpolatedUnivariateSpline(
self._kick_interpolatedThetasTrack, self._kick_dOap[:, 2], k=spline_order
)
self._kick_interpdar_raw = interpolate.InterpolatedUnivariateSpline(
self._kick_interpolatedThetasTrack, self._kick_dOap[:, 3], k=spline_order
)
self._kick_interpdap_raw = interpolate.InterpolatedUnivariateSpline(
self._kick_interpolatedThetasTrack, self._kick_dOap[:, 4], k=spline_order
)
self._kick_interpdaz_raw = interpolate.InterpolatedUnivariateSpline(
self._kick_interpolatedThetasTrack, self._kick_dOap[:, 5], k=spline_order
)
# Also interpolate parallel and perpendicular frequencies
self._kick_dOaparperp = numpy.dot(
self._kick_dOap[:, :3],
self._sigomatrixEig[1][:, self._sigomatrixEigsortIndx],
)
self._kick_dOaparperp[:, 2] *= self._sigMeanSign
self._kick_interpdOpar_raw = interpolate.InterpolatedUnivariateSpline(
self._kick_interpolatedThetasTrack,
numpy.dot(self._kick_dOap[:, :3], self._dsigomeanProgDirection)
* self._sigMeanSign,
k=spline_order,
) # to get zeros with sproot
self._kick_interpdOperp0_raw = interpolate.InterpolatedUnivariateSpline(
self._kick_interpolatedThetasTrack,
self._kick_dOaparperp[:, 0],
k=spline_order,
)
self._kick_interpdOperp1_raw = interpolate.InterpolatedUnivariateSpline(
self._kick_interpolatedThetasTrack,
self._kick_dOaparperp[:, 1],
k=spline_order,
)
# Also construct derivative of dOpar
self._kick_interpdOpar_dapar = self._kick_interpdOpar_raw.derivative(1)
# Also construct piecewise-polynomial representation of dOpar,
# removing intervals at the start and end with zero range
ppoly = interpolate.PPoly.from_spline(self._kick_interpdOpar_raw._eval_args)
nzIndx = numpy.nonzero(
(numpy.roll(ppoly.x, -1) - ppoly.x > 0)
* (numpy.arange(len(ppoly.x)) < len(ppoly.x) // 2)
+ (ppoly.x - numpy.roll(ppoly.x, 1) > 0)
* (numpy.arange(len(ppoly.x)) >= len(ppoly.x) // 2)
)
self._kick_interpdOpar_poly = interpolate.PPoly(
ppoly.c[:, nzIndx[0][:-1]], ppoly.x[nzIndx[0]]
)
return None
# Functions that evaluate the interpolated kicks, but also check the range
@impact_check_range
def _kick_interpdOpar(self, da):
return self._kick_interpdOpar_raw(da)
@impact_check_range
def _kick_interpdOperp0(self, da):
return self._kick_interpdOperp0_raw(da)
@impact_check_range
def _kick_interpdOperp1(self, da):
return self._kick_interpdOperp1_raw(da)
@impact_check_range
def _kick_interpdOr(self, da):
return self._kick_interpdOr_raw(da)
@impact_check_range
def _kick_interpdOp(self, da):
return self._kick_interpdOp_raw(da)
@impact_check_range
def _kick_interpdOz(self, da):
return self._kick_interpdOz_raw(da)
@impact_check_range
def _kick_interpdar(self, da):
return self._kick_interpdar_raw(da)
@impact_check_range
def _kick_interpdap(self, da):
return self._kick_interpdap_raw(da)
@impact_check_range
def _kick_interpdaz(self, da):
return self._kick_interpdaz_raw(da)
def _interpolate_stream_track_kick(self):
"""Build interpolations of the stream track near the kick"""
if hasattr(self, "_kick_interpolatedThetasTrack"): # pragma: no cover
self._store_closest()
return None # Already did this
# Setup the trackpoints where the kick will be computed, covering the
# full length of the stream
self._kick_interpolatedThetasTrack = numpy.linspace(
self._gap_thetasTrack[0], self._gap_thetasTrack[-1], self._nKickPoints
)
TrackX = self._gap_ObsTrack[:, 0] * numpy.cos(self._gap_ObsTrack[:, 5])
TrackY = self._gap_ObsTrack[:, 0] * numpy.sin(self._gap_ObsTrack[:, 5])
TrackZ = self._gap_ObsTrack[:, 3]
TrackvX, TrackvY, TrackvZ = coords.cyl_to_rect_vec(
self._gap_ObsTrack[:, 1],
self._gap_ObsTrack[:, 2],
self._gap_ObsTrack[:, 4],
self._gap_ObsTrack[:, 5],
)
# Interpolate
self._kick_interpTrackX = interpolate.InterpolatedUnivariateSpline(
self._gap_thetasTrack, TrackX, k=3
)
self._kick_interpTrackY = interpolate.InterpolatedUnivariateSpline(
self._gap_thetasTrack, TrackY, k=3
)
self._kick_interpTrackZ = interpolate.InterpolatedUnivariateSpline(
self._gap_thetasTrack, TrackZ, k=3
)
self._kick_interpTrackvX = interpolate.InterpolatedUnivariateSpline(
self._gap_thetasTrack, TrackvX, k=3
)
self._kick_interpTrackvY = interpolate.InterpolatedUnivariateSpline(
self._gap_thetasTrack, TrackvY, k=3
)
self._kick_interpTrackvZ = interpolate.InterpolatedUnivariateSpline(
self._gap_thetasTrack, TrackvZ, k=3
)
# Now store an interpolated version of the stream track
self._kick_interpolatedObsTrackXY = numpy.empty(
(len(self._kick_interpolatedThetasTrack), 6)
)
self._kick_interpolatedObsTrackXY[:, 0] = self._kick_interpTrackX(
self._kick_interpolatedThetasTrack
)
self._kick_interpolatedObsTrackXY[:, 1] = self._kick_interpTrackY(
self._kick_interpolatedThetasTrack
)
self._kick_interpolatedObsTrackXY[:, 2] = self._kick_interpTrackZ(
self._kick_interpolatedThetasTrack
)
self._kick_interpolatedObsTrackXY[:, 3] = self._kick_interpTrackvX(
self._kick_interpolatedThetasTrack
)
self._kick_interpolatedObsTrackXY[:, 4] = self._kick_interpTrackvY(
self._kick_interpolatedThetasTrack
)
self._kick_interpolatedObsTrackXY[:, 5] = self._kick_interpTrackvZ(
self._kick_interpolatedThetasTrack
)
# Also in cylindrical coordinates
self._kick_interpolatedObsTrack = numpy.empty(
(len(self._kick_interpolatedThetasTrack), 6)
)
tR, tphi, tZ = coords.rect_to_cyl(
self._kick_interpolatedObsTrackXY[:, 0],
self._kick_interpolatedObsTrackXY[:, 1],
self._kick_interpolatedObsTrackXY[:, 2],
)
tvR, tvT, tvZ = coords.rect_to_cyl_vec(
self._kick_interpolatedObsTrackXY[:, 3],
self._kick_interpolatedObsTrackXY[:, 4],
self._kick_interpolatedObsTrackXY[:, 5],
tR,
tphi,
tZ,
cyl=True,
)
self._kick_interpolatedObsTrack[:, 0] = tR
self._kick_interpolatedObsTrack[:, 1] = tvR
self._kick_interpolatedObsTrack[:, 2] = tvT
self._kick_interpolatedObsTrack[:, 3] = tZ
self._kick_interpolatedObsTrack[:, 4] = tvZ
self._kick_interpolatedObsTrack[:, 5] = tphi
self._store_closest()
return None
def _store_closest(self):
# Also store (x,v) for the point of closest approach
self._kick_ObsTrackXY_closest = numpy.array(
[
self._kick_interpTrackX(self._impact_angle),
self._kick_interpTrackY(self._impact_angle),
self._kick_interpTrackZ(self._impact_angle),
self._kick_interpTrackvX(self._impact_angle),
self._kick_interpTrackvY(self._impact_angle),
self._kick_interpTrackvZ(self._impact_angle),
]
)
return None
def _interpolate_stream_track_kick_aA(self):
"""Build interpolations of the stream track near the impact in action-angle coordinates"""
if hasattr(self, "_kick_interpolatedObsTrackAA"): # pragma: no cover
return None # Already did this
# Calculate 1D meanOmega on a fine grid in angle and interpolate
dmOs = numpy.array(
[
super(streamgapdf, self).meanOmega(
da,
oned=True,
tdisrupt=self._tdisrupt - self._timpact,
use_physical=False,
)
for da in self._kick_interpolatedThetasTrack
]
)
self._kick_interpTrackAAdmeanOmegaOneD = (
interpolate.InterpolatedUnivariateSpline(
self._kick_interpolatedThetasTrack, dmOs, k=3
)
)
# Build the interpolated AA
self._kick_interpolatedObsTrackAA = numpy.empty(
(len(self._kick_interpolatedThetasTrack), 6)
)
for ii in range(len(self._kick_interpolatedThetasTrack)):
self._kick_interpolatedObsTrackAA[ii, :3] = (
self._progenitor_Omega
+ dmOs[ii] * self._dsigomeanProgDirection * self._gap_sigMeanSign
)
self._kick_interpolatedObsTrackAA[ii, 3:] = (
self._progenitor_angle
+ self._kick_interpolatedThetasTrack[ii]
* self._dsigomeanProgDirection
* self._gap_sigMeanSign
- self._timpact * self._progenitor_Omega
)
self._kick_interpolatedObsTrackAA[ii, 3:] = numpy.mod(
self._kick_interpolatedObsTrackAA[ii, 3:], 2.0 * numpy.pi
)
return None
def _determine_deltaAngleTrackImpact(self, deltaAngleTrackImpact, timpact):
self._timpact = timpact
deltaAngleTrackLim = (
(self._sigMeanOffset + 4.0)
* numpy.sqrt(self._sortedSigOEig[2])
* (self._tdisrupt - self._timpact)
)
if deltaAngleTrackImpact is None:
deltaAngleTrackImpact = deltaAngleTrackLim
else:
if deltaAngleTrackImpact > deltaAngleTrackLim:
warnings.warn(
"WARNING: deltaAngleTrackImpact angle range large compared to plausible value",
galpyWarning,
)
self._deltaAngleTrackImpact = deltaAngleTrackImpact
return None
def _determine_impact_coordtransform(
self, deltaAngleTrackImpact, nTrackChunksImpact, timpact, impact_angle
):
"""Function that sets up the transformation between (x,v) and (O,theta)"""
# Integrate the progenitor backward to the time of impact
self._gap_progenitor_setup()
# Sign of delta angle tells us whether the impact happens to the
# leading or trailing arm, self._sigMeanSign contains this info
if impact_angle > 0.0:
self._gap_leading = True
else:
self._gap_leading = False
if (self._gap_leading and not self._leading) or (
not self._gap_leading and self._leading
):