-
Notifications
You must be signed in to change notification settings - Fork 95
/
test_potential.py
2603 lines (2528 loc) · 143 KB
/
test_potential.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
############################TESTS ON POTENTIALS################################
from __future__ import print_function, division
import os
import sys
from nose.tools import raises, assert_raises
import numpy
import pynbody
from galpy import potential
from galpy.util import bovy_coords
_TRAVIS= bool(os.getenv('TRAVIS'))
#Test whether the normalization of the potential works
def test_normalize_potential():
#Grab all of the potentials
pots= [p for p in dir(potential)
if ('Potential' in p and not 'plot' in p and not 'RZTo' in p
and not 'FullTo' in p and not 'toPlanar' in p
and not 'evaluate' in p)]
pots.append('mockTwoPowerIntegerSphericalPotential')
pots.append('specialTwoPowerSphericalPotential')
pots.append('HernquistTwoPowerIntegerSphericalPotential')
pots.append('JaffeTwoPowerIntegerSphericalPotential')
pots.append('NFWTwoPowerIntegerSphericalPotential')
pots.append('specialMiyamotoNagaiPotential')
pots.append('specialPowerSphericalPotential')
pots.append('specialFlattenedPowerPotential')
pots.append('specialMN3ExponentialDiskPotentialPD')
pots.append('specialMN3ExponentialDiskPotentialSECH')
rmpots= ['Potential','MWPotential','MWPotential2014',
'MovingObjectPotential',
'interpRZPotential', 'linearPotential', 'planarAxiPotential',
'planarPotential', 'verticalPotential','PotentialError',
'SnapshotRZPotential','InterpSnapshotRZPotential']
if False: #_TRAVIS: #travis CI
rmpots.append('DoubleExponentialDiskPotential')
rmpots.append('RazorThinExponentialDiskPotential')
for p in rmpots:
pots.remove(p)
for p in pots:
#if not 'NFW' in p: continue #For testing the test
#Setup instance of potential
try:
tclass= getattr(potential,p)
except AttributeError:
tclass= getattr(sys.modules[__name__],p)
tp= tclass()
if hasattr(tp,'isNonAxi') and tp.isNonAxi:
continue # skip, bc vcirc not well defined
if not hasattr(tp,'normalize'): continue
tp.normalize(1.)
assert (tp.Rforce(1.,0.)+1.)**2. < 10.**-16., \
"Normalization of %s potential fails" % p
assert (tp.vcirc(1.)**2.-1.)**2. < 10.**-16., \
"Normalization of %s potential fails" % p
tp.normalize(.5)
if hasattr(tp,'toPlanar'):
ptp= tp.toPlanar()
else:
ptp= tp
assert (ptp.Rforce(1.,0.)+.5)**2. < 10.**-16., \
"Normalization of %s potential fails" % p
assert (ptp.vcirc(1.)**2.-0.5)**2. < 10.**-16., \
"Normalization of %s potential fails" % p
#Test whether the derivative of the potential is minus the force
def test_forceAsDeriv_potential():
#Grab all of the potentials
pots= [p for p in dir(potential)
if ('Potential' in p and not 'plot' in p and not 'RZTo' in p
and not 'FullTo' in p and not 'toPlanar' in p
and not 'evaluate' in p)]
pots.append('mockTwoPowerIntegerSphericalPotential')
pots.append('specialTwoPowerSphericalPotential')
pots.append('HernquistTwoPowerIntegerSphericalPotential')
pots.append('JaffeTwoPowerIntegerSphericalPotential')
pots.append('NFWTwoPowerIntegerSphericalPotential')
pots.append('specialMiyamotoNagaiPotential')
pots.append('specialMN3ExponentialDiskPotentialPD')
pots.append('specialMN3ExponentialDiskPotentialSECH')
pots.append('specialPowerSphericalPotential')
pots.append('specialFlattenedPowerPotential')
pots.append('testMWPotential')
pots.append('testplanarMWPotential')
pots.append('testlinearMWPotential')
pots.append('mockInterpRZPotential')
pots.append('mockSnapshotRZPotential')
pots.append('mockInterpSnapshotRZPotential')
pots.append('mockCosmphiDiskPotentialT1')
pots.append('mockCosmphiDiskPotentialTm1')
pots.append('mockCosmphiDiskPotentialTm5')
pots.append('mockDehnenBarPotentialT1')
pots.append('mockDehnenBarPotentialTm1')
pots.append('mockDehnenBarPotentialTm5')
pots.append('mockEllipticalDiskPotentialT1')
pots.append('mockEllipticalDiskPotentialTm1')
pots.append('mockEllipticalDiskPotentialTm5')
pots.append('mockSteadyLogSpiralPotentialT1')
pots.append('mockSteadyLogSpiralPotentialTm1')
pots.append('mockSteadyLogSpiralPotentialTm5')
pots.append('mockTransientLogSpiralPotential')
pots.append('mockFlatEllipticalDiskPotential') #for evaluate w/ nonaxi lists
pots.append('mockMovingObjectPotential')
pots.append('mockMovingObjectExplSoftPotential')
pots.append('oblateHernquistPotential')
pots.append('oblateNFWPotential')
pots.append('oblatenoGLNFWPotential')
pots.append('oblateJaffePotential')
pots.append('prolateHernquistPotential')
pots.append('prolateNFWPotential')
pots.append('prolateJaffePotential')
pots.append('triaxialHernquistPotential')
pots.append('triaxialNFWPotential')
pots.append('triaxialJaffePotential')
pots.append('zRotatedTriaxialNFWPotential')
pots.append('yRotatedTriaxialNFWPotential')
pots.append('fullyRotatedTriaxialNFWPotential')
pots.append('fullyRotatednoGLTriaxialNFWPotential')
pots.append('HernquistTwoPowerTriaxialPotential')
pots.append('NFWTwoPowerTriaxialPotential')
pots.append('JaffeTwoPowerTriaxialPotential')
pots.append('mockSCFZeeuwPotential')
pots.append('mockSCFNFWPotential')
pots.append('mockSCFAxiDensity1Potential')
pots.append('mockSCFAxiDensity2Potential')
pots.append('mockSCFDensityPotential')
pots.append('mockAxisymmetricFerrersPotential')
pots.append('sech2DiskSCFPotential')
pots.append('expwholeDiskSCFPotential')
pots.append('nonaxiDiskSCFPotential')
rmpots= ['Potential','MWPotential','MWPotential2014',
'MovingObjectPotential',
'interpRZPotential', 'linearPotential', 'planarAxiPotential',
'planarPotential', 'verticalPotential','PotentialError',
'SnapshotRZPotential','InterpSnapshotRZPotential']
if False: #_TRAVIS: #travis CI
rmpots.append('DoubleExponentialDiskPotential')
rmpots.append('RazorThinExponentialDiskPotential')
for p in rmpots:
pots.remove(p)
Rs= numpy.array([0.5,1.,2.])
Zs= numpy.array([0.,.125,-.125,0.25,-0.25])
phis= numpy.array([0.,0.5,-0.5,1.,-1.,
numpy.pi,0.5+numpy.pi,
1.+numpy.pi])
#tolerances in log10
tol= {}
tol['default']= -8.
tol['DoubleExponentialDiskPotential']= -6. #these are more difficult
tol['RazorThinExponentialDiskPotential']= -6.
tol['mockInterpRZPotential']= -4.
for p in pots:
#if not 'NFW' in p: continue #For testing the test
#Setup instance of potential
try:
tclass= getattr(potential,p)
except AttributeError:
tclass= getattr(sys.modules[__name__],p)
tp= tclass()
if hasattr(tp,'normalize'): tp.normalize(1.)
#Set tolerance
if p in list(tol.keys()): ttol= tol[p]
else: ttol= tol['default']
#Radial force
for ii in range(len(Rs)):
for jj in range(len(Zs)):
dr= 10.**-8.
newR= Rs[ii]+dr
dr= newR-Rs[ii] #Representable number
if isinstance(tp,potential.linearPotential):
mpotderivR= (potential.evaluatelinearPotentials(tp,Rs[ii])
-potential.evaluatelinearPotentials(tp,Rs[ii]+dr))/dr
tRforce= potential.evaluatelinearForces(tp,Rs[ii])
elif isinstance(tp,potential.planarPotential):
mpotderivR= (potential.evaluateplanarPotentials(tp,Rs[ii],phi=Zs[jj])-potential.evaluateplanarPotentials(tp,Rs[ii]+dr,phi=Zs[jj]))/dr
tRforce= potential.evaluateplanarRforces(tp,Rs[ii],
phi=Zs[jj])
else:
mpotderivR= (potential.evaluatePotentials(tp,Rs[ii],Zs[jj],phi=0.)
-potential.evaluatePotentials(tp,Rs[ii]+dr,Zs[jj],phi=0.))/dr
tRforce= potential.evaluateRforces(tp,Rs[ii],Zs[jj],phi=0.)
if tRforce**2. < 10.**ttol:
assert mpotderivR**2. < 10.**ttol, \
"Calculation of the Radial force as the Radial derivative of the %s potential fails at (R,Z) = (%.3f,%.3f); diff = %e, rel. diff = %e" % (p,Rs[ii],Zs[jj],numpy.fabs(tRforce-mpotderivR), numpy.fabs((tRforce-mpotderivR)/tRforce))
else:
assert (tRforce-mpotderivR)**2./tRforce**2. < 10.**ttol, \
"Calculation of the Radial force as the Radial derivative of the %s potential fails at (R,Z) = (%.3f,%.3f); diff = %e, rel. diff = %e" % (p,Rs[ii],Zs[jj],numpy.fabs(tRforce-mpotderivR), numpy.fabs((tRforce-mpotderivR)/tRforce))
#Azimuthal force, if it exists
if isinstance(tp,potential.linearPotential): continue
for ii in range(len(Rs)):
for jj in range(len(phis)):
dphi= 10.**-8.
newphi= phis[jj]+dphi
dphi= newphi-phis[jj] #Representable number
if isinstance(tp,potential.planarPotential):
mpotderivphi= (tp(Rs[ii],phi=phis[jj])-tp(Rs[ii],phi=phis[jj]+dphi))/dphi
tphiforce= potential.evaluateplanarphiforces(tp,Rs[ii],
phi=phis[jj])
else:
mpotderivphi= (tp(Rs[ii],0.05,phi=phis[jj])-tp(Rs[ii],0.05,phi=phis[jj]+dphi))/dphi
tphiforce= potential.evaluatephiforces(tp,Rs[ii],0.05,
phi=phis[jj])
try:
if tphiforce**2. < 10.**ttol:
assert(mpotderivphi**2. < 10.**ttol)
else:
assert((tphiforce-mpotderivphi)**2./tphiforce**2. < 10.**ttol)
except AssertionError:
if isinstance(tp,potential.planarPotential):
raise AssertionError("Calculation of the azimuthal force as the azimuthal derivative of the %s potential fails at (R,phi) = (%.3f,%.3f); diff = %e, rel. diff = %e" % (p,Rs[ii],phis[jj],numpy.fabs(tphiforce-mpotderivphi),numpy.fabs((tphiforce-mpotderivphi)/tphiforce)))
else:
raise AssertionError("Calculation of the azimuthal force as the azimuthal derivative of the %s potential fails at (R,Z,phi) = (%.3f,0.05,%.3f); diff = %e, rel. diff = %e" % (p,Rs[ii],phis[jj],numpy.fabs(tphiforce-mpotderivphi),numpy.fabs((tphiforce-mpotderivphi)/tphiforce)))
#Vertical force, if it exists
if isinstance(tp,potential.planarPotential) \
or isinstance(tp,potential.linearPotential): continue
for ii in range(len(Rs)):
for jj in range(len(Zs)):
##Excluding KuzminDiskPotential when z = 0
if Zs[jj]==0 and isinstance(tp,potential.KuzminDiskPotential):
continue
dz= 10.**-8.
newZ= Zs[jj]+dz
dz= newZ-Zs[jj] #Representable number
mpotderivz= (tp(Rs[ii],Zs[jj])-tp(Rs[ii],Zs[jj]+dz,phi=0.))/dz
tzforce= potential.evaluatezforces(tp,Rs[ii],Zs[jj],phi=0.)
if tzforce**2. < 10.**ttol:
assert mpotderivz**2. < 10.**ttol, \
"Calculation of the vertical force as the vertical derivative of the %s potential fails at (R,Z) = (%.3f,%.3f); diff = %e, rel. diff = %e" % (p,Rs[ii],Zs[jj],numpy.fabs(mpotderivz),numpy.fabs((tzforce-mpotderivz)/tzforce))
else:
assert (tzforce-mpotderivz)**2./tzforce**2. < 10.**ttol, \
"Calculation of the vertical force as the vertical derivative of the %s potential fails at (R,Z) = (%.3f,%.3f); diff = %e, rel. diff = %e" % (p,Rs[ii],Zs[jj],numpy.fabs(mpotderivz),numpy.fabs((tzforce-mpotderivz)/tzforce))
#Test whether the second derivative of the potential is minus the derivative of the force
def test_2ndDeriv_potential():
#Grab all of the potentials
pots= [p for p in dir(potential)
if ('Potential' in p and not 'plot' in p and not 'RZTo' in p
and not 'FullTo' in p and not 'toPlanar' in p
and not 'evaluate' in p)]
pots.append('mockTwoPowerIntegerSphericalPotential')
pots.append('specialTwoPowerSphericalPotential')
pots.append('HernquistTwoPowerIntegerSphericalPotential')
pots.append('JaffeTwoPowerIntegerSphericalPotential')
pots.append('NFWTwoPowerIntegerSphericalPotential')
pots.append('specialMiyamotoNagaiPotential')
pots.append('specialMN3ExponentialDiskPotentialPD')
pots.append('specialMN3ExponentialDiskPotentialSECH')
pots.append('specialPowerSphericalPotential')
pots.append('specialFlattenedPowerPotential')
pots.append('testMWPotential')
pots.append('testplanarMWPotential')
pots.append('testlinearMWPotential')
pots.append('mockInterpRZPotential')
pots.append('mockCosmphiDiskPotentialT1')
pots.append('mockCosmphiDiskPotentialTm1')
pots.append('mockCosmphiDiskPotentialTm5')
pots.append('mockDehnenBarPotentialT1')
pots.append('mockDehnenBarPotentialTm1')
pots.append('mockDehnenBarPotentialTm5')
pots.append('mockEllipticalDiskPotentialT1')
pots.append('mockEllipticalDiskPotentialTm1')
pots.append('mockEllipticalDiskPotentialTm5')
pots.append('mockSteadyLogSpiralPotentialT1')
pots.append('mockSteadyLogSpiralPotentialTm1')
pots.append('mockSteadyLogSpiralPotentialTm5')
pots.append('mockTransientLogSpiralPotential')
pots.append('mockFlatEllipticalDiskPotential') #for evaluate w/ nonaxi lists
pots.append('oblateHernquistPotential') # in case these are ever implemented
pots.append('oblateNFWPotential')
pots.append('oblatenoGLNFWPotential')
pots.append('oblateJaffePotential')
pots.append('prolateHernquistPotential')
pots.append('prolateNFWPotential')
pots.append('prolateJaffePotential')
pots.append('triaxialHernquistPotential')
pots.append('triaxialNFWPotential')
pots.append('triaxialJaffePotential')
pots.append('HernquistTwoPowerTriaxialPotential')
pots.append('NFWTwoPowerTriaxialPotential')
pots.append('JaffeTwoPowerTriaxialPotential')
pots.append('mockAxisymmetricFerrersPotential')
rmpots= ['Potential','MWPotential','MWPotential2014',
'MovingObjectPotential',
'interpRZPotential', 'linearPotential', 'planarAxiPotential',
'planarPotential', 'verticalPotential','PotentialError',
'SnapshotRZPotential','InterpSnapshotRZPotential']
if False: #_TRAVIS: #travis CI
rmpots.append('DoubleExponentialDiskPotential')
rmpots.append('RazorThinExponentialDiskPotential')
rmpots.append('DiskSCFPotential') # 2nd derivs not implemented yet, but placeholders exist
for p in rmpots:
pots.remove(p)
Rs= numpy.array([0.5,1.,2.])
Zs= numpy.array([0.,.125,-.125,0.25,-0.25])
phis= numpy.array([0.,0.5,-0.5,1.,-1.,
numpy.pi,0.5+numpy.pi,
1.+numpy.pi])
#tolerances in log10
tol= {}
tol['default']= -8.
tol['DoubleExponentialDiskPotential']= -3. #these are more difficult
tol['RazorThinExponentialDiskPotential']= -6.
tol['mockInterpRZPotential']= -4.
for p in pots:
#if not 'NFW' in p: continue #For testing the test
#Setup instance of potential
try:
tclass= getattr(potential,p)
except AttributeError:
tclass= getattr(sys.modules[__name__],p)
tp= tclass()
if hasattr(tp,'normalize'): tp.normalize(1.)
#Set tolerance
if p in list(tol.keys()): ttol= tol[p]
else: ttol= tol['default']
#2nd radial
if hasattr(tp,'_R2deriv'):
for ii in range(len(Rs)):
for jj in range(len(Zs)):
if p == 'RazorThinExponentialDiskPotential' and numpy.fabs(Zs[jj]) > 0.: continue #Not implemented
dr= 10.**-8.
newR= Rs[ii]+dr
dr= newR-Rs[ii] #Representable number
if isinstance(tp,potential.linearPotential):
mRforcederivR= (tp.Rforce(Rs[ii])-tp.Rforce(Rs[ii]+dr))/dr
tR2deriv= tp.R2deriv(Rs[ii])
elif isinstance(tp,potential.planarPotential):
mRforcederivR= (tp.Rforce(Rs[ii],Zs[jj])-tp.Rforce(Rs[ii]+dr,Zs[jj]))/dr
tR2deriv= potential.evaluateplanarR2derivs(tp,Rs[ii],
phi=Zs[jj])
else:
mRforcederivR= (tp.Rforce(Rs[ii],Zs[jj])-tp.Rforce(Rs[ii]+dr,Zs[jj]))/dr
tR2deriv= potential.evaluateR2derivs(tp,Rs[ii],Zs[jj],phi=0.)
if tR2deriv**2. < 10.**ttol:
assert mRforcederivR**2. < 10.**ttol, \
"Calculation of the second Radial derivative of the potential as the Radial derivative of the %s Radial force fails at (R,Z) = (%.3f,%.3f); diff = %e, rel. diff = %e" % (p,Rs[ii],Zs[jj],numpy.fabs(tR2deriv-mRforcederivR), numpy.fabs((tR2deriv-mRforcederivR)/tR2deriv))
else:
assert (tR2deriv-mRforcederivR)**2./tR2deriv**2. < 10.**ttol, \
"Calculation of the second Radial derivative of the potential as the Radial derivative of the %s Radial force fails at (R,Z) = (%.3f,%.3f); diff = %e, rel. diff = %e" % (p,Rs[ii],Zs[jj],numpy.fabs(tR2deriv-mRforcederivR), numpy.fabs((tR2deriv-mRforcederivR)/tR2deriv))
#2nd azimuthal
if not isinstance(tp,potential.linearPotential) \
and hasattr(tp,'_phi2deriv'):
for ii in range(len(Rs)):
for jj in range(len(phis)):
dphi= 10.**-8.
newphi= phis[jj]+dphi
dphi= newphi-phis[jj] #Representable number
if isinstance(tp,potential.planarPotential):
mphiforcederivphi= (tp.phiforce(Rs[ii],phi=phis[jj])-tp.phiforce(Rs[ii],phi=phis[jj]+dphi))/dphi
tphi2deriv= tp.phi2deriv(Rs[ii],phi=phis[jj])
else:
mphiforcederivphi= (tp.phiforce(Rs[ii],0.05,phi=phis[jj])-tp.phiforce(Rs[ii],0.05,phi=phis[jj]+dphi))/dphi
tphi2deriv= tp.phi2deriv(Rs[ii],0.05,phi=phis[jj])
try:
if tphi2deriv**2. < 10.**ttol:
assert(mphiforcederivphi**2. < 10.**ttol)
else:
assert((tphi2deriv-mphiforcederivphi)**2./tphi2deriv**2. < 10.**ttol)
except AssertionError:
if isinstance(tp,potential.planarPotential):
raise AssertionError("Calculation of the second azimuthal derivative of the potential as the azimuthal derivative of the %s azimuthal force fails at (R,phi) = (%.3f,%.3f); diff = %e, rel. diff = %e" % (p,Rs[ii],phis[jj],numpy.fabs(tphi2deriv-mphiforcederivphi), numpy.fabs((tphi2deriv-mphiforcederivphi)/tphi2deriv)))
else:
raise AssertionError("Calculation of the second azimuthal derivative of the potential as the azimuthal derivative of the %s azimuthal force fails at (R,Z,phi) = (%.3f,0.05,%.3f); diff = %e, rel. diff = %e" % (p,Rs[ii],phis[jj],numpy.fabs(tphi2deriv-mphiforcederivphi), numpy.fabs((tphi2deriv-mphiforcederivphi)/tphi2deriv)))
#mixed radial azimuthal: Isn't this the same as what's below??
if not isinstance(tp,potential.linearPotential) \
and hasattr(tp,'_Rphideriv'):
for ii in range(len(Rs)):
for jj in range(len(phis)):
dphi= 10.**-8.
newphi= phis[jj]+dphi
dphi= newphi-phis[jj] #Representable number
if isinstance(tp,potential.planarPotential):
mRforcederivphi= (tp.Rforce(Rs[ii],phi=phis[jj])-tp.Rforce(Rs[ii],phi=phis[jj]+dphi))/dphi
tRphideriv= tp.Rphideriv(Rs[ii],phi=phis[jj])
else:
mRforcederivphi= (tp.Rforce(Rs[ii],0.05,phi=phis[jj])-tp.Rforce(Rs[ii],0.05,phi=phis[jj]+dphi))/dphi
tRphideriv= tp.Rphideriv(Rs[ii],0.05,phi=phis[jj])
try:
if tRphideriv**2. < 10.**ttol:
assert(mRforcederivphi**2. < 10.**ttol)
else:
assert((tRphideriv-mRforcederivphi)**2./tRphideriv**2. < 10.**ttol)
except AssertionError:
if isinstance(tp,potential.planarPotential):
raise AssertionError("Calculation of the mixed radial, azimuthal derivative of the potential as the azimuthal derivative of the %s Radial force fails at (R,phi) = (%.3f,%.3f); diff = %e, rel. diff = %e" % (p,Rs[ii],phis[jj],numpy.fabs(tRphideriv-mRforcederivphi), numpy.fabs((tRphideriv-mRforcederivphi)/tRphideriv)))
else:
raise AssertionError("Calculation of the second azimuthal derivative of the potential as the azimuthal derivative of the %s azimuthal force fails at (R,Z,phi) = (%.3f,0.05,%.3f); diff = %e, rel. diff = %e" % (p,Rs[ii],phis[jj],numpy.fabs(tphi2deriv-mphiforcederivphi), numpy.fabs((tphi2deriv-mphiforcederivphi)/tphi2deriv)))
#2nd vertical
if not isinstance(tp,potential.planarPotential) \
and not isinstance(tp,potential.linearPotential) \
and hasattr(tp,'_z2deriv'):
for ii in range(len(Rs)):
for jj in range(len(Zs)):
if p == 'RazorThinExponentialDiskPotential': continue #Not implemented, or badly defined
if p == 'TwoPowerSphericalPotential': continue #Not implemented, or badly defined
if p == 'mockTwoPowerIntegerSphericalPotential': continue #Not implemented, or badly defined
if p == 'specialTwoPowerSphericalPotential': continue #Not implemented, or badly defined
if p == 'HernquistTwoPowerIntegerSphericalPotential': continue #Not implemented, or badly defined
if p == 'JaffeTwoPowerIntegerSphericalPotential': continue #Not implemented, or badly defined
if p == 'NFWTwoPowerIntegerSphericalPotential': continue #Not implemented, or badly defined
#Excluding KuzminDiskPotential at z = 0
if p == 'KuzminDiskPotential' and Zs[jj] == 0: continue
dz= 10.**-8.
newz= Zs[jj]+dz
dz= newz-Zs[jj] #Representable number
mzforcederivz= (tp.zforce(Rs[ii],Zs[jj])-tp.zforce(Rs[ii],Zs[jj]+dz))/dz
tz2deriv= potential.evaluatez2derivs(tp,Rs[ii],Zs[jj],phi=0.)
if tz2deriv**2. < 10.**ttol:
assert mzforcederivz**2. < 10.**ttol, \
"Calculation of the second vertical derivative of the potential as the vertical derivative of the %s vertical force fails at (R,Z) = (%.3f,%.3f); diff = %e, rel. diff = %e" % (p,Rs[ii],Zs[jj],numpy.fabs(tz2deriv-mzforcederivz), numpy.fabs((tz2deriv-mzforcederivz)/tz2deriv))
else:
assert (tz2deriv-mzforcederivz)**2./tz2deriv**2. < 10.**ttol, \
"Calculation of the second vertical derivative of the potential as the vertical derivative of the %s vertical force fails at (R,Z) = (%.3f,%.3f); diff = %e, rel. diff = %e" % (p,Rs[ii],Zs[jj],numpy.fabs(tz2deriv-mzforcederivz), numpy.fabs((tz2deriv-mzforcederivz)/tz2deriv))
#mixed radial vertical
if not isinstance(tp,potential.planarPotential) \
and not isinstance(tp,potential.linearPotential) \
and hasattr(tp,'_Rzderiv'):
for ii in range(len(Rs)):
for jj in range(len(Zs)):
#Excluding KuzminDiskPotential at z = 0
if p == 'KuzminDiskPotential' and Zs[jj] == 0: continue
# if p == 'RazorThinExponentialDiskPotential': continue #Not implemented, or badly defined
dz= 10.**-8.
newz= Zs[jj]+dz
dz= newz-Zs[jj] #Representable number
mRforcederivz= (tp.Rforce(Rs[ii],Zs[jj])-tp.Rforce(Rs[ii],Zs[jj]+dz))/dz
tRzderiv= potential.evaluateRzderivs(tp,Rs[ii],Zs[jj],phi=0.)
if tRzderiv**2. < 10.**ttol:
assert mRforcederivz**2. < 10.**ttol, \
"Calculation of the mixed radial vertical derivative of the potential as the vertical derivative of the %s radial force fails at (R,Z) = (%.3f,%.3f); diff = %e, rel. diff = %e" % (p,Rs[ii],Zs[jj],numpy.fabs(tRzderiv-mRforcederivz), numpy.fabs((tRzderiv-mRforcederivz)/tRzderiv))
else:
assert (tRzderiv-mRforcederivz)**2./tRzderiv**2. < 10.**ttol, \
"Calculation of the mixed radial vertical derivative of the potential as the vertical derivative of the %s radial force fails at (R,Z) = (%.3f,%.3f); diff = %e, rel. diff = %e" % (p,Rs[ii],Zs[jj],numpy.fabs(tRzderiv-mRforcederivz), numpy.fabs((tRzderiv-mRforcederivz)/tRzderiv))
#mixed radial, azimuthal
if not isinstance(tp,potential.linearPotential) \
and hasattr(tp,'_Rphideriv'):
for ii in range(len(Rs)):
for jj in range(len(phis)):
# if p == 'RazorThinExponentialDiskPotential': continue #Not implemented, or badly defined
dphi= 10.**-8.
newphi= phis[jj]+dphi
dphi= newphi-phis[jj] #Representable number
if isinstance(tp,potential.planarPotential):
mRforcederivphi= (tp.Rforce(Rs[ii],phi=phis[jj])\
-tp.Rforce(Rs[ii],phi=phis[jj]+dphi))/dphi
tRphideriv= potential.evaluateplanarPotentials(tp,Rs[ii],
phi=phis[jj],dR=1,dphi=1)
else:
mRforcederivphi= (tp.Rforce(Rs[ii],0.1,phi=phis[jj])\
-tp.Rforce(Rs[ii],0.1,phi=phis[jj]+dphi))/dphi
tRphideriv= potential.evaluatePotentials(tp,Rs[ii],0.1,
phi=phis[jj],dR=1,dphi=1)
if tRphideriv**2. < 10.**ttol:
assert mRforcederivphi**2. < 10.**ttol, \
"Calculation of the mixed radial azimuthal derivative of the potential as the azimuthal derivative of the %s radial force fails at (R,phi) = (%.3f,%.3f); diff = %e, rel. diff = %e" % (p,Rs[ii],phis[jj],numpy.fabs(tRphideriv-mRforcederivphi), numpy.fabs((tRphideriv-mRforcederivphi)/tRphideriv))
else:
assert (tRphideriv-mRforcederivphi)**2./tRphideriv**2. < 10.**ttol, \
"Calculation of the mixed radial azimuthal derivative of the potential as the azimuthal derivative of the %s radial force fails at (R,phi) = (%.3f,%.3f); diff = %e, rel. diff = %e" % (p,Rs[ii],phis[jj],numpy.fabs(tRphideriv-mRforcederivphi), numpy.fabs((tRphideriv-mRforcederivphi)/tRphideriv))
#Test whether the Poisson equation is satisfied if _dens and the relevant second derivatives are implemented
def test_poisson_potential():
#Grab all of the potentials
pots= [p for p in dir(potential)
if ('Potential' in p and not 'plot' in p and not 'RZTo' in p
and not 'FullTo' in p and not 'toPlanar' in p
and not 'evaluate' in p)]
pots.append('mockTwoPowerIntegerSphericalPotential')
pots.append('specialTwoPowerSphericalPotential')
pots.append('HernquistTwoPowerIntegerSphericalPotential')
pots.append('JaffeTwoPowerIntegerSphericalPotential')
pots.append('NFWTwoPowerIntegerSphericalPotential')
pots.append('specialMiyamotoNagaiPotential')
pots.append('specialMN3ExponentialDiskPotentialPD')
pots.append('specialMN3ExponentialDiskPotentialSECH')
pots.append('specialFlattenedPowerPotential')
pots.append('specialPowerSphericalPotential')
pots.append('testMWPotential')
pots.append('testplanarMWPotential')
pots.append('testlinearMWPotential')
pots.append('oblateHernquistPotential') # in cae these are ever implemented
pots.append('oblateNFWPotential')
pots.append('oblateJaffePotential')
pots.append('prolateHernquistPotential')
pots.append('prolateNFWPotential')
pots.append('prolateJaffePotential')
pots.append('triaxialHernquistPotential')
pots.append('triaxialNFWPotential')
pots.append('triaxialJaffePotential')
pots.append('HernquistTwoPowerTriaxialPotential')
pots.append('NFWTwoPowerTriaxialPotential')
pots.append('JaffeTwoPowerTriaxialPotential')
rmpots= ['Potential','MWPotential','MWPotential2014',
'MovingObjectPotential',
'interpRZPotential', 'linearPotential', 'planarAxiPotential',
'planarPotential', 'verticalPotential','PotentialError',
'SnapshotRZPotential','InterpSnapshotRZPotential']
if False: #_TRAVIS: #travis CI
rmpots.append('DoubleExponentialDiskPotential')
rmpots.append('RazorThinExponentialDiskPotential')
rmpots.append('DiskSCFPotential') # 2nd derivs not implemented yet, but placeholders exist
for p in rmpots:
pots.remove(p)
Rs= numpy.array([0.5,1.,2.])
Zs= numpy.array([0.,.125,-.125,0.25,-0.25])
phis= numpy.array([0.,0.5,-0.5,1.,-1.,
numpy.pi,0.5+numpy.pi,
1.+numpy.pi])
#tolerances in log10
tol= {}
tol['default']= -8.
tol['DoubleExponentialDiskPotential']= -3. #these are more difficult
#tol['RazorThinExponentialDiskPotential']= -6.
for p in pots:
#if not 'NFW' in p: continue #For testing the test
#if 'Isochrone' in p: continue #For testing the test
#Setup instance of potential
try:
tclass= getattr(potential,p)
except AttributeError:
tclass= getattr(sys.modules[__name__],p)
tp= tclass()
if hasattr(tp,'normalize'): tp.normalize(1.)
#Set tolerance
if p in list(tol.keys()): ttol= tol[p]
else: ttol= tol['default']
#2nd radial
if not hasattr(tp,'_dens') or not hasattr(tp,'_R2deriv') \
or not hasattr(tp,'_Rforce') or not hasattr(tp,'phi2deriv') \
or not hasattr(tp,'_z2deriv'):
continue
for ii in range(len(Rs)):
for jj in range(len(Zs)):
for kk in range(len(phis)):
tpoissondens= tp.dens(Rs[ii],Zs[jj],phi=phis[kk],
forcepoisson=True)
tdens= potential.evaluateDensities(tp,Rs[ii],Zs[jj],
phi=phis[kk],
forcepoisson=False)
if tdens**2. < 10.**ttol:
assert tpoissondens**2. < 10.**ttol, \
"Poisson equation relation between the derivatives of the potential and the implemented density is not satisfied for the %s potential at (R,Z,phi) = (%.3f,%.3f,%.3f); diff = %e, rel. diff = %e" % (p,Rs[ii],Zs[jj],phis[kk],numpy.fabs(tdens-tpoissondens), numpy.fabs((tdens-tpoissondens)/tdens))
else:
assert (tpoissondens-tdens)**2./tdens**2. < 10.**ttol, \
"Poisson equation relation between the derivatives of the potential and the implemented density is not satisfied for the %s potential at (R,Z,phi) = (%.3f,%.3f,%.3f); diff = %e, rel. diff = %e" % (p,Rs[ii],Zs[jj],phis[kk],numpy.fabs(tdens-tpoissondens), numpy.fabs((tdens-tpoissondens)/tdens))
return None
#Test whether the _evaluate function is correctly implemented in specifying derivatives
def test_evaluateAndDerivs_potential():
#Grab all of the potentials
pots= [p for p in dir(potential)
if ('Potential' in p and not 'plot' in p and not 'RZTo' in p
and not 'FullTo' in p and not 'toPlanar' in p
and not 'evaluate' in p)]
pots.append('mockTwoPowerIntegerSphericalPotential')
pots.append('specialTwoPowerSphericalPotential')
pots.append('HernquistTwoPowerIntegerSphericalPotential')
pots.append('JaffeTwoPowerIntegerSphericalPotential')
pots.append('NFWTwoPowerIntegerSphericalPotential')
pots.append('specialMiyamotoNagaiPotential')
pots.append('specialMN3ExponentialDiskPotentialPD')
pots.append('specialMN3ExponentialDiskPotentialSECH')
pots.append('specialFlattenedPowerPotential')
pots.append('specialPowerSphericalPotential')
pots.append('mockCosmphiDiskPotentialT1')
pots.append('mockCosmphiDiskPotentialTm1')
pots.append('mockCosmphiDiskPotentialTm5')
pots.append('mockDehnenBarPotentialT1')
pots.append('mockDehnenBarPotentialTm1')
pots.append('mockDehnenBarPotentialTm5')
pots.append('mockEllipticalDiskPotentialT1')
pots.append('mockEllipticalDiskPotentialTm1')
pots.append('mockEllipticalDiskPotentialTm5')
pots.append('mockSteadyLogSpiralPotentialT1')
pots.append('mockSteadyLogSpiralPotentialTm1')
pots.append('mockSteadyLogSpiralPotentialTm5')
pots.append('mockTransientLogSpiralPotential')
pots.append('mockMovingObjectPotential')
pots.append('oblateHernquistPotential') # in cae these are ever implemented
pots.append('oblateNFWPotential')
pots.append('oblateJaffePotential')
pots.append('prolateHernquistPotential')
pots.append('prolateNFWPotential')
pots.append('prolateJaffePotential')
pots.append('triaxialHernquistPotential')
pots.append('triaxialNFWPotential')
pots.append('triaxialJaffePotential')
pots.append('mockSCFZeeuwPotential')
pots.append('mockSCFNFWPotential')
pots.append('mockSCFAxiDensity1Potential')
pots.append('mockSCFAxiDensity2Potential')
pots.append('mockSCFDensityPotential')
pots.append('sech2DiskSCFPotential')
pots.append('expwholeDiskSCFPotential')
pots.append('nonaxiDiskSCFPotential')
rmpots= ['Potential','MWPotential','MWPotential2014',
'MovingObjectPotential',
'interpRZPotential', 'linearPotential', 'planarAxiPotential',
'planarPotential', 'verticalPotential','PotentialError',
'SnapshotRZPotential','InterpSnapshotRZPotential']
if False: #_TRAVIS: #travis CI
rmpots.append('DoubleExponentialDiskPotential')
rmpots.append('RazorThinExponentialDiskPotential')
for p in rmpots:
pots.remove(p)
#tolerances in log10
tol= {}
tol['default']= -12.
#tol['DoubleExponentialDiskPotential']= -3. #these are more difficult
#tol['RazorThinExponentialDiskPotential']= -6.
for p in pots:
#if 'Isochrone' in p: continue #For testing the test
#Setup instance of potential
try:
tclass= getattr(potential,p)
except AttributeError:
tclass= getattr(sys.modules[__name__],p)
tp= tclass()
if hasattr(tp,'normalize'): tp.normalize(1.)
#Set tolerance
if p in list(tol.keys()): ttol= tol[p]
else: ttol= tol['default']
#1st radial
if isinstance(tp,potential.linearPotential):
continue
elif isinstance(tp,potential.planarPotential):
tevaldr= tp(1.2,phi=0.1,dR=1)
trforce= tp.Rforce(1.2,phi=0.1)
else:
tevaldr= tp(1.2,0.1,phi=0.1,dR=1)
trforce= tp.Rforce(1.2,0.1,phi=0.1)
if not tevaldr is None:
if tevaldr**2. < 10.**ttol:
assert trforce**2. < 10.**ttol, \
"Calculation of radial derivative through _evaluate and Rforce inconsistent for the %s potential" % p
else:
assert (tevaldr+trforce)**2./tevaldr**2. < 10.**ttol, \
"Calculation of radial derivative through _evaluate and Rforce inconsistent for the %s potential" % p
#2nd radial
hasR2= True
from galpy.potential import PotentialError
if 'RazorThin' in p: R2z= 0.
else: R2z= 0.1
try:
if isinstance(tp,potential.planarPotential):
tp.R2deriv(1.2)
else:
tp.R2deriv(1.2,R2z)
except PotentialError:
hasR2= False
if hasR2:
if isinstance(tp,potential.planarPotential):
tevaldr2= tp(1.2,phi=0.1,dR=2)
tr2deriv= tp.R2deriv(1.2,phi=0.1)
else:
tevaldr2= tp(1.2,R2z,phi=0.1,dR=2)
tr2deriv= tp.R2deriv(1.2,R2z,phi=0.1)
if not tevaldr2 is None:
if tevaldr2**2. < 10.**ttol:
assert tr2deriv*2. < 10.**ttol, \
"Calculation of 2nd radial derivative through _evaluate and R2deriv inconsistent for the %s potential" % p
else:
assert (tevaldr2-tr2deriv)**2./tevaldr2**2. < 10.**ttol, \
"Calculation of 2nd radial derivative through _evaluate and R2deriv inconsistent for the %s potential" % p
#1st phi
if isinstance(tp,potential.planarPotential):
tevaldphi= tp(1.2,phi=0.1,dphi=1)
tphiforce= tp.phiforce(1.2,phi=0.1)
else:
tevaldphi= tp(1.2,0.1,phi=0.1,dphi=1)
tphiforce= tp.phiforce(1.2,0.1,phi=0.1)
if not tevaldphi is None:
if tevaldphi**2. < 10.**ttol:
assert tphiforce**2. < 10.**ttol, \
"Calculation of azimuthal derivative through _evaluate and phiforce inconsistent for the %s potential" % p
else:
assert (tevaldphi+tphiforce)**2./tevaldphi**2. < 10.**ttol, \
"Calculation of azimuthal derivative through _evaluate and phiforce inconsistent for the %s potential" % p
#2nd phi
hasphi2= True
try:
if isinstance(tp,potential.planarPotential):
tp.phi2deriv(1.2,phi=0.1)
else:
tp.phi2deriv(1.2,0.1,phi=0.1)
except (PotentialError,AttributeError):
hasphi2= False
if hasphi2 and hasattr(tp,'_phi2deriv'):
if isinstance(tp,potential.planarPotential):
tevaldphi2= tp(1.2,phi=0.1,dphi=2)
tphi2deriv= tp.phi2deriv(1.2,phi=0.1)
else:
tevaldphi2= tp(1.2,0.1,phi=0.1,dphi=2)
tphi2deriv= tp.phi2deriv(1.2,0.1,phi=0.1)
if not tevaldphi2 is None:
if tevaldphi2**2. < 10.**ttol:
assert tphi2deriv*2. < 10.**ttol, \
"Calculation of 2nd azimuthal derivative through _evaluate and phi2deriv inconsistent for the %s potential" % p
else:
assert (tevaldphi2-tphi2deriv)**2./tevaldphi2**2. < 10.**ttol, \
"Calculation of 2nd azimuthal derivative through _evaluate and phi2deriv inconsistent for the %s potential" % p
continue
#mixed radial,vertical
if isinstance(tp,potential.planarPotential):
tevaldrz= tp(1.2,0.1,phi=0.1,dR=1,dz=1)
trzderiv= tp.Rzderiv(1.2,0.1,phi=0.1)
else:
tevaldrz= tp(1.2,0.1,phi=0.1,dR=1,dz=1)
trzderiv= tp.Rzderiv(1.2,0.1,phi=0.1)
if not tevaldrz is None:
if tevaldrz**2. < 10.**ttol:
assert trzderiv*2. < 10.**ttol, \
"Calculation of mixed radial,vertical derivative through _evaluate and z2deriv inconsistent for the %s potential" % p
else:
assert (tevaldrz-trzderiv)**2./tevaldrz**2. < 10.**ttol, \
"Calculation of mixed radial,vertical derivative through _evaluate and z2deriv inconsistent for the %s potential" % p
#Finally test that much higher derivatives are not implemented
try: tp(1.2,0.1,dR=4,dphi=10)
except NotImplementedError: pass
else: raise AssertionError('Higher-order derivative request in potential __call__ does not raise NotImplementedError')
return None
# Test that the spherically radial force is correct
def test_rforce():
# Spherical potentials: Rforce = rforce x R / r; zforce = rforce x z /r
pp= potential.PlummerPotential(amp=2.,b=2.)
R,z= 1.3, 0.4
r= numpy.sqrt(R*R+z*z)
assert numpy.fabs(pp.Rforce(R,z)*r/R-pp.rforce(R,z)) < 10.**-10., 'rforce does not behave as expected for spherical potentials'
assert numpy.fabs(potential.evaluateRforces(pp,R,z)*r/R-potential.evaluaterforces(pp,R,z)) < 10.**-10., 'evaluaterforces does not behave as expected for spherical potentials'
return None
# Check that the masses are calculated correctly for spherical potentials
def test_mass_spher():
#PowerPotential close to Kepler should be very steep
pp= potential.PowerSphericalPotential(amp=2.,alpha=2.999)
kp= potential.KeplerPotential(amp=2.)
assert numpy.fabs((((3.-2.999)/(4.*numpy.pi)*pp.mass(10.)-kp.mass(10.)))/kp.mass(10.)) < 10.**-2., "Mass for PowerSphericalPotential close to KeplerPotential is not close to KeplerPotential's mass"
pp= potential.PowerSphericalPotential(amp=2.)
#mass = amp x r^(3-alpha)
tR= 1.
assert numpy.fabs(pp.mass(tR,forceint=True)-pp._amp*tR**(3.-pp.alpha)) < 10.**-10., 'Mass for PowerSphericalPotential not as expected'
tR= 2.
assert numpy.fabs(pp.mass(tR,forceint=True)-pp._amp*tR**(3.-pp.alpha)) < 10.**-10., 'Mass for PowerSphericalPotential not as expected'
tR= 20.
assert numpy.fabs(pp.mass(tR,forceint=True)-pp._amp*tR**(3.-pp.alpha)) < 10.**-10., 'Mass for PowerSphericalPotential not as expected'
#Test that for a cut-off potential, the mass far beyond the cut-off is
# 2pi rc^(3-alpha) gamma(1.5-alpha/2)
pp= potential.PowerSphericalPotentialwCutoff(amp=2.)
from scipy import special
expecMass= 2.*pp._amp*numpy.pi*pp.rc**(3.-pp.alpha)*special.gamma(1.5-pp.alpha/2.)
tR= 5.
assert numpy.fabs((pp.mass(tR,forceint=True)-expecMass)/expecMass) < 10.**-6., 'Mass of PowerSphericalPotentialwCutoff far beyond the cut-off not as expected'
tR= 15.
assert numpy.fabs((pp.mass(tR,forceint=True)-expecMass)/expecMass) < 10.**-6., 'Mass of PowerSphericalPotentialwCutoff far beyond the cut-off not as expected'
tR= 50.
assert numpy.fabs((pp.mass(tR,forceint=True)-expecMass)/expecMass) < 10.**-6., 'Mass of PowerSphericalPotentialwCutoff far beyond the cut-off not as expected'
#Jaffe and Hernquist both have finite masses, NFW diverges logarithmically
jp= potential.JaffePotential(amp=2.,a=0.1)
hp= potential.HernquistPotential(amp=2.,a=0.1)
np= potential.NFWPotential(amp=2.,a=0.1)
tR= 10.
# Limiting behavior
jaffemass= jp._amp*(1.-jp.a/tR)
hernmass= hp._amp/2.*(1.-2.*hp.a/tR)
nfwmass= np._amp*(numpy.log(tR/np.a)-1.+np.a/tR)
assert numpy.fabs((jp.mass(tR,forceint=True)-jaffemass)/jaffemass) < 10.**-3., 'Limit mass for Jaffe potential not as expected'
assert numpy.fabs((hp.mass(tR,forceint=True)-hernmass)/hernmass) < 10.**-3., 'Limit mass for Jaffe potential not as expected'
assert numpy.fabs((np.mass(tR,forceint=True)-nfwmass)/nfwmass) < 10.**-2., 'Limit mass for NFW potential not as expected'
tR= 200.
# Limiting behavior, add z, to test that too
jaffemass= jp._amp*(1.-jp.a/tR)
hernmass= hp._amp/2.*(1.-2.*hp.a/tR)
nfwmass= np._amp*(numpy.log(tR/np.a)-1.+np.a/tR)
assert numpy.fabs((jp.mass(tR,forceint=True)-jaffemass)/jaffemass) < 10.**-6., 'Limit mass for Jaffe potential not as expected'
assert numpy.fabs((hp.mass(tR,forceint=True)-hernmass)/hernmass) < 10.**-6., 'Limit mass for Jaffe potential not as expected'
assert numpy.fabs((np.mass(tR,forceint=True)-nfwmass)/nfwmass) < 10.**-4., 'Limit mass for NFW potential not as expected'
tR, tz= 200., 10.
tr= numpy.sqrt(tR**2.+tz**2.)
# Limiting behavior, add z, to test that too
jaffemass= jp._amp*(1.-jp.a/tr)
hernmass= hp._amp/2.*(1.-2.*hp.a/tr)
nfwmass= np._amp*(numpy.log(tr/np.a)-1.+np.a/tr)
assert numpy.fabs((jp.mass(tR,z=tz,forceint=False)-jaffemass)/jaffemass) < 10.**-6., 'Limit mass for Jaffe potential not as expected'
assert numpy.fabs((hp.mass(tR,z=tz,forceint=False)-hernmass)/hernmass) < 10.**-6., 'Limit mass for Jaffe potential not as expected'
assert numpy.fabs((np.mass(tR,z=tz,forceint=False)-nfwmass)/nfwmass) < 10.**-4., 'Limit mass for NFW potential not as expected'
return None
# Check that the masses are implemented correctly for spherical potentials
def test_mass_spher_analytic():
#TwoPowerSphericalPotentials all have explicitly implemented masses
jp= potential.JaffePotential(amp=2.)
hp= potential.HernquistPotential(amp=2.)
np= potential.NFWPotential(amp=2.)
tp= potential.TwoPowerSphericalPotential(amp=2.)
tR= 2.
assert numpy.fabs(jp.mass(tR,forceint=True)-jp.mass(tR)) < 10.**-10., 'Explicit mass does not agree with integral of the density for Jaffe potential'
assert numpy.fabs(hp.mass(tR,forceint=True)-hp.mass(tR)) < 10.**-10., 'Explicit mass does not agree with integral of the density for Hernquist potential'
assert numpy.fabs(np.mass(tR,forceint=True)-np.mass(tR)) < 10.**-10., 'Explicit mass does not agree with integral of the density for NFW potential'
assert numpy.fabs(tp.mass(tR,forceint=True)-tp.mass(tR)) < 10.**-10., 'Explicit mass does not agree with integral of the density for TwoPowerSpherical potential'
assert numpy.fabs(tp.mass(tR,forceint=True)-tp.mass(numpy.sqrt(tR**2.-1**2.),z=1.)) < 10.**-10., 'Explicit mass does not agree with integral of the density for TwoPowerSpherical potential, for not z is None'
return None
# Check that the masses are calculated correctly for axisymmetric potentials
def test_mass_axi():
#For Miyamoto-Nagai, we know that mass integrated over everything should be equal to amp, so
mp= potential.MiyamotoNagaiPotential(amp=1.)
assert numpy.fabs(mp.mass(200.,20.)-1.) < 0.01, 'Total mass of Miyamoto-Nagai potential w/ amp=1 is not equal to 1'
#For a double-exponential disk potential, the
# mass(R,z) = amp x hR^2 x hz x (1-(1+R/hR)xe^(-R/hR)) x (1-e^(-Z/hz)
dp= potential.DoubleExponentialDiskPotential(amp=2.)
def dblexpmass(r,z,dp):
return 4.*numpy.pi*dp._amp*dp._hr**2.*dp._hz*(1.-(1.+r/dp._hr)*numpy.exp(-r/dp._hr))*(1.-numpy.exp(-z/dp._hz))
tR,tz= 0.01,0.01
assert numpy.fabs((dp.mass(tR,tz,forceint=True)-dblexpmass(tR,tz,dp))/dblexpmass(tR,tz,dp)) < 10.**-10., 'Mass for DoubleExponentialDiskPotential incorrect'
tR,tz= 0.1,0.05
assert numpy.fabs((dp.mass(tR,tz,forceint=True)-dblexpmass(tR,tz,dp))/dblexpmass(tR,tz,dp)) < 10.**-10., 'Mass for DoubleExponentialDiskPotential incorrect'
tR,tz= 1.,0.1
assert numpy.fabs((dp.mass(tR,tz,forceint=True)-dblexpmass(tR,tz,dp))/dblexpmass(tR,tz,dp)) < 10.**-10., 'Mass for DoubleExponentialDiskPotential incorrect'
tR,tz= 5.,0.1
assert numpy.fabs((dp.mass(tR,tz,forceint=True)-dblexpmass(tR,tz,dp))/dblexpmass(tR,tz,dp)) < 10.**-10., 'Mass for DoubleExponentialDiskPotential incorrect'
tR,tz= 5.,1.
assert numpy.fabs((dp.mass(tR,tz,forceint=True)-dblexpmass(tR,tz,dp))/dblexpmass(tR,tz,dp)) < 10.**-10., 'Mass for DoubleExponentialDiskPotential incorrect'
tR,tz= 100.,100.
assert numpy.fabs((dp.mass(tR,tz,forceint=True)-dblexpmass(tR,tz,dp))/dblexpmass(tR,tz,dp)) < 10.**-6., 'Mass for DoubleExponentialDiskPotential incorrect'
#Test that nonAxi raises error
from galpy.orbit import Orbit
mop= potential.MovingObjectPotential(Orbit([1.,0.1,1.1,0.1,0.,0.]))
try: mop.mass(1.,0.)
except NotImplementedError: pass
else: raise AssertionError('mass for non-axisymmetric potential should have raised NotImplementedError, but did not')
return None
# Check that toVertical and toPlanar work
def test_toVertical_toPlanar():
#Grab all of the potentials
pots= [p for p in dir(potential)
if ('Potential' in p and not 'plot' in p and not 'RZTo' in p
and not 'FullTo' in p and not 'toPlanar' in p
and not 'evaluate' in p)]
rmpots= ['Potential','MWPotential','MWPotential2014',
'MovingObjectPotential',
'interpRZPotential', 'linearPotential', 'planarAxiPotential',
'planarPotential', 'verticalPotential','PotentialError',
'SnapshotRZPotential','InterpSnapshotRZPotential']
if False: #_TRAVIS: #travis CI
rmpots.append('DoubleExponentialDiskPotential')
rmpots.append('RazorThinExponentialDiskPotential')
for p in rmpots:
pots.remove(p)
for p in pots:
#Setup instance of potential
try:
tclass= getattr(potential,p)
except AttributeError:
tclass= getattr(sys.modules[__name__],p)
tp= tclass()
if not hasattr(tp,'normalize'): continue #skip these
tp.normalize(1.)
if isinstance(tp,potential.linearPotential) or \
isinstance(tp,potential.planarPotential):
continue
tpp= tp.toPlanar()
assert isinstance(tpp,potential.planarPotential), \
"Conversion into planar potential of potential %s fails" % p
tlp= tp.toVertical(1.)
assert isinstance(tlp,potential.linearPotential), \
"Conversion into linear potential of potential %s fails" % p
def test_RZToplanarPotential():
lp= potential.LogarithmicHaloPotential(normalize=1.)
plp= potential.RZToplanarPotential(lp)
assert isinstance(plp,potential.planarPotential), 'Running an RZPotential through RZToplanarPotential does not produce a planarPotential'
#Check that a planarPotential through RZToplanarPotential is still planar
pplp= potential.RZToplanarPotential(lp)
assert isinstance(pplp,potential.planarPotential), 'Running a planarPotential through RZToplanarPotential does not produce a planarPotential'
try:
plp= potential.RZToplanarPotential('something else')
except potential.PotentialError:
pass
else:
raise AssertionError('Using RZToplanarPotential with a string rather than an RZPotential or a planarPotential did not raise PotentialError')
return None
def test_toPlanarPotential():
tnp= potential.TriaxialNFWPotential(normalize=1.,b=0.5)
ptnp= potential.toPlanarPotential(tnp)
assert isinstance(ptnp,potential.planarPotential), 'Running a non-axisymmetric Potential through toPlanarPotential does not produce a planarPotential'
# Also for list
ptnp= potential.toPlanarPotential([tnp])
assert isinstance(ptnp[0],potential.planarPotential), 'Running a non-axisymmetric Potential through toPlanarPotential does not produce a planarPotential'
#Check that a planarPotential through toPlanarPotential is still planar
pptnp= potential.toPlanarPotential(tnp)
assert isinstance(pptnp,potential.planarPotential), 'Running a planarPotential through toPlanarPotential does not produce a planarPotential'
try:
ptnp= potential.toPlanarPotential('something else')
except potential.PotentialError:
pass
else:
raise AssertionError('Using toPlanarPotential with a string rather than an Potential or a planarPotential did not raise PotentialError')
return None
# Sanity check the derivative of the rotation curve and the frequencies in the plane
def test_dvcircdR_omegac_epifreq_rl_vesc():
#Derivative of rotation curve
#LogarithmicHaloPotential: rotation everywhere flat
lp= potential.LogarithmicHaloPotential(normalize=1.)
assert lp.dvcircdR(1.)**2. < 10.**-16., \
"LogarithmicHaloPotential's rotation curve is not flat at R=1"
assert lp.dvcircdR(0.5)**2. < 10.**-16., \
"LogarithmicHaloPotential's rotation curve is not flat at R=0.5"
assert lp.dvcircdR(2.)**2. < 10.**-16., \
"LogarithmicHaloPotential's rotation curve is not flat at R=2"
#Kepler potential, vc = vc_0(R/R0)^-0.5 -> dvcdR= -0.5 vc_0 (R/R0)**-1.5
kp= potential.KeplerPotential(normalize=1.)
assert (kp.dvcircdR(1.)+0.5)**2. < 10.**-16., \
"KeplerPotential's rotation curve is not what it should be at R=1"
assert (kp.dvcircdR(0.5)+0.5**-0.5)**2. < 10.**-16., \
"KeplerPotential's rotation curve is not what it should be at R=0.5"
assert (kp.dvcircdR(2.)+0.5**2.5)**2. < 10.**-16., \
"KeplerPotential's rotation curve is not what it should be at R=2"
#Rotational frequency
assert (lp.omegac(1.)-1.)**2. < 10.**-16., \
"LogarithmicHalo's rotational frequency is off at R=1"
assert (lp.omegac(0.5)-2.)**2. < 10.**-16., \
"LogarithmicHalo's rotational frequency is off at R=0.5"
assert (lp.omegac(2.)-0.5)**2. < 10.**-16., \
"LogarithmicHalo's rotational frequency is off at R=2"
assert (lp.toPlanar().omegac(2.)-0.5)**2. < 10.**-16., \
"LogarithmicHalo's rotational frequency is off at R=2 through planarPotential"
#Epicycle frequency, flat rotation curve
assert (lp.epifreq(1.)-numpy.sqrt(2.)*lp.omegac(1.))**2. < 10.**-16., \
"LogarithmicHalo's epicycle and rotational frequency are inconsistent with kappa = sqrt(2) Omega at R=1"
assert (lp.epifreq(0.5)-numpy.sqrt(2.)*lp.omegac(0.5))**2. < 10.**-16., \
"LogarithmicHalo's epicycle and rotational frequency are inconsistent with kappa = sqrt(2) Omega at R=0.5"
assert (lp.epifreq(2.0)-numpy.sqrt(2.)*lp.omegac(2.0))**2. < 10.**-16., \
"LogarithmicHalo's epicycle and rotational frequency are inconsistent with kappa = sqrt(2) Omega at R=2"
assert (lp.toPlanar().epifreq(2.0)-numpy.sqrt(2.)*lp.omegac(2.0))**2. < 10.**-16., \
"LogarithmicHalo's epicycle and rotational frequency are inconsistent with kappa = sqrt(2) Omega at R=, through planar2"
#Epicycle frequency, Kepler
assert (kp.epifreq(1.)-kp.omegac(1.))**2. < 10.**-16., \
"KeplerPotential's epicycle and rotational frequency are inconsistent with kappa = Omega at R=1"
assert (kp.epifreq(0.5)-kp.omegac(0.5))**2. < 10.**-16., \
"KeplerPotential's epicycle and rotational frequency are inconsistent with kappa = Omega at R=0.5"
assert (kp.epifreq(2.)-kp.omegac(2.))**2. < 10.**-16., \
"KeplerPotential's epicycle and rotational frequency are inconsistent with kappa = Omega at R=2"
#Check radius of circular orbit, Kepler
assert (kp.rl(1.)-1.)**2. < 10.**-16., \
"KeplerPotential's radius of a circular orbit is wrong at Lz=1."
assert (kp.rl(0.5)-1./4.)**2. < 10.**-16., \
"KeplerPotential's radius of a circular orbit is wrong at Lz=0.5"
assert (kp.rl(2.)-4.)**2. < 10.**-16., \
"KeplerPotential's radius of a circular orbit is wrong at Lz=2."
#Check radius of circular orbit, PowerSphericalPotential with close-to-flat rotation curve
pp= potential.PowerSphericalPotential(alpha=1.8,normalize=1.)
assert (pp.rl(1.)-1.)**2. < 10.**-16., \
"PowerSphericalPotential's radius of a circular orbit is wrong at Lz=1."
assert (pp.rl(0.5)-0.5**(10./11.))**2. < 10.**-16., \
"PowerSphericalPotential's radius of a circular orbit is wrong at Lz=0.5"
assert (pp.rl(2.)-2.**(10./11.))**2. < 10.**-16., \
"PowerSphericalPotential's radius of a circular orbit is wrong at Lz=2."
#Check radius of circular orbit, PowerSphericalPotential with steeper rotation curve
pp= potential.PowerSphericalPotential(alpha=0.5,normalize=1.)
assert (pp.rl(1.)-1.)**2. < 10.**-16., \
"PowerSphericalPotential's radius of a circular orbit is wrong at Lz=1."
assert (pp.rl(0.0625)-0.0625**(4./7.))**2. < 10.**-16., \
"PowerSphericalPotential's radius of a circular orbit is wrong at Lz=0.0625"
assert (pp.rl(16.)-16.**(4./7.))**2. < 10.**-16., \
"PowerSphericalPotential's radius of a circular orbit is wrong at Lz=16."
#Escape velocity of Kepler potential
assert (kp.vesc(1.)**2.-2.)**2. < 10.**-16., \
"KeplerPotential's escape velocity is wrong at R=1"
assert (kp.vesc(0.5)**2.-2.*kp.vcirc(0.5)**2.)**2. < 10.**-16., \
"KeplerPotential's escape velocity is wrong at R=0.5"
assert (kp.vesc(2.)**2.-2.*kp.vcirc(2.)**2.)**2. < 10.**-16., \
"KeplerPotential's escape velocity is wrong at R=2"
assert (kp.toPlanar().vesc(2.)**2.-2.*kp.vcirc(2.)**2.)**2. < 10.**-16., \
"KeplerPotential's escape velocity is wrong at R=2, through planar"
# W/ different interface
assert (kp.vcirc(1.)-potential.vcirc(kp,1.))**2. < 10.**-16., \
"KeplerPotential's circular velocity does not agree between kp.vcirc and vcirc(kp)"
assert (kp.vcirc(1.)-potential.vcirc(kp.toPlanar(),1.))**2. < 10.**-16., \
"KeplerPotential's circular velocity does not agree between kp.vcirc and vcirc(kp.toPlanar)"
assert (kp.vesc(1.)-potential.vesc(kp,1.))**2. < 10.**-16., \
"KeplerPotential's escape velocity does not agree between kp.vesc and vesc(kp)"
assert (kp.vesc(1.)-potential.vesc(kp.toPlanar(),1.))**2. < 10.**-16., \
"KeplerPotential's escape velocity does not agree between kp.vesc and vesc(kp.toPlanar)"
return None
def test_vcirc_phi_axi():
# Test that giving phi to vcirc for an axisymmetric potential doesn't
# affect the answer
kp= potential.KeplerPotential(normalize=1.)
phis= numpy.linspace(0.,numpy.pi,101)
vcs= numpy.array([kp.vcirc(1.,phi) for phi in phis])
assert numpy.all(numpy.fabs(vcs-1.) < 10.**-8.), 'Setting phi= in vcirc for axisymmetric potential gives different answers for different phi'
# One at a different radius
R= 0.5
vcs= numpy.array([kp.vcirc(R,phi) for phi in phis])
assert numpy.all(numpy.fabs(vcs-kp.vcirc(R)) < 10.**-8.), 'Setting phi= in vcirc for axisymmetric potential gives different answers for different phi'