/
Force.py
309 lines (266 loc) · 10 KB
/
Force.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
###############################################################################
# Force.py: top-level class for a 3D force, conservative (Potential) or
# not (DissipativeForce)
#
###############################################################################
import copy
import numpy
from ..util import config, conversion
from ..util._optional_deps import _APY_LOADED
from ..util.conversion import (
physical_compatible,
physical_conversion,
potential_physical_input,
)
if _APY_LOADED:
from astropy import units
class Force:
"""Top-level class for any force, conservative or dissipative"""
def __init__(self, amp=1.0, ro=None, vo=None, amp_units=None):
"""
Initialize Force.
Parameters
----------
amp : float, optional
Amplitude to be applied when evaluating the potential and its forces.
ro : float or Quantity, optional
Physical distance scale (in kpc or as Quantity). Default is from the configuration file.
vo : float or Quantity, optional
Physical velocity scale (in km/s or as Quantity). Default is from the configuration file.
amp_units : str, optional
Type of units that `amp` should have if it has units. Must be one of
'mass', 'velocity2', or 'density'.
Notes
-----
- 2018-03-18 - Written to generalize Potential to force that may or may not be conservative - Bovy (UofT)
"""
self._amp = amp
# Parse ro and vo
if ro is None:
self._ro = config.__config__.getfloat("normalization", "ro")
self._roSet = False
else:
self._ro = conversion.parse_length_kpc(ro)
self._roSet = True
if vo is None:
self._vo = config.__config__.getfloat("normalization", "vo")
self._voSet = False
else:
self._vo = conversion.parse_velocity_kms(vo)
self._voSet = True
# Parse amp if it has units
if _APY_LOADED and isinstance(self._amp, units.Quantity):
# Try a bunch of possible units
unitFound = False
# velocity^2
try:
self._amp = conversion.parse_energy(self._amp, vo=self._vo)
except units.UnitConversionError:
pass
else:
unitFound = True
if not amp_units == "velocity2":
raise units.UnitConversionError(
f"amp= parameter of {type(self).__name__} should have units of {amp_units}, but has units of velocity2 instead"
)
if not unitFound:
# mass
try:
self._amp = conversion.parse_mass(
self._amp, ro=self._ro, vo=self._vo
)
except units.UnitConversionError:
pass
else:
unitFound = True
if not amp_units == "mass":
raise units.UnitConversionError(
f"amp= parameter of {type(self).__name__} should have units of {amp_units}, but has units of mass instead"
)
if not unitFound:
# density
try:
self._amp = conversion.parse_dens(
self._amp, ro=self._ro, vo=self._vo
)
except units.UnitConversionError:
pass
else:
unitFound = True
if not amp_units == "density":
raise units.UnitConversionError(
f"amp= parameter of {type(self).__name__} should have units of {amp_units}, but has units of density instead"
)
if not unitFound:
# surface density
try:
self._amp = conversion.parse_surfdens(
self._amp, ro=self._ro, vo=self._vo
)
except units.UnitConversionError:
pass
else:
unitFound = True
if not amp_units == "surfacedensity":
raise units.UnitConversionError(
f"amp= parameter of {type(self).__name__} should have units of {amp_units}, but has units of surface density instead"
)
if not unitFound:
raise units.UnitConversionError(
f"amp= parameter of {type(self).__name__} should have units of {amp_units}; given units are not understood"
)
else:
# When amplitude is given with units, turn on physical output
self._roSet = True
self._voSet = True
return None
def __mul__(self, b):
"""
Multiply a Force or Potential's amplitude by a number
Parameters
----------
b : int or float
Number to multiply the amplitude with.
Returns
-------
Force or Potential instance
New instance with amplitude = (old amplitude) x b.
Notes
-----
- 2019-01-27 - Written - Bovy (UofT)
"""
if not isinstance(b, (int, float)):
raise TypeError(
"Can only multiply a Force or Potential instance with a number"
)
out = copy.deepcopy(self)
out._amp *= b
return out
# Similar functions
__rmul__ = __mul__
def __div__(self, b):
return self.__mul__(1.0 / b)
__truediv__ = __div__
def __add__(self, b):
"""
Add Force or Potential instances together to create a multi-component potential (e.g., pot= pot1+pot2+pot3)
Parameters
----------
b : Force or Potential instance or a list thereof
Returns
-------
list of Force or Potential instances
Represents the combined potential
Notes
-----
- 2019-01-27 - Written - Bovy (UofT)
- 2020-04-22 - Added check that unit systems of combined potentials are compatible - Bovy (UofT)
"""
from ..potential import flatten as flatten_pot
from ..potential import planarPotential
if not isinstance(flatten_pot([b])[0], (Force, planarPotential)):
raise TypeError(
"""Can only combine galpy Force objects with """
"""other Force objects or lists thereof"""
)
assert physical_compatible(self, b), (
"""Physical unit conversion parameters (ro,vo) are not """
"""compatible between potentials to be combined"""
)
if isinstance(b, list):
return [self] + b
else:
return [self, b]
# Define separately to keep order
def __radd__(self, b):
from ..potential import flatten as flatten_pot
from ..potential import planarPotential
if not isinstance(flatten_pot([b])[0], (Force, planarPotential)):
raise TypeError(
"""Can only combine galpy Force objects with """
"""other Force objects or lists thereof"""
)
assert physical_compatible(self, b), (
"""Physical unit conversion parameters (ro,vo) are not """
"""compatible between potentials to be combined"""
)
# If we get here, b has to be a list
return b + [self]
def turn_physical_off(self):
"""
Turn off automatic returning of outputs in physical units.
Returns
-------
None
Notes
-----
- 2016-01-30 - Written - Bovy (UofT)
"""
self._roSet = False
self._voSet = False
return None
def turn_physical_on(self, ro=None, vo=None):
"""
Turn on automatic returning of outputs in physical units.
Parameters
----------
ro : float or Quantity, optional
Reference distance in kpc. Default is None.
vo : float or Quantity, optional
Reference velocity in km/s. Default is None.
Returns
-------
None
Notes
-----
- 2016-01-30 - Written - Bovy (UofT)
- 2020-04-22 - Don't turn on a parameter when it is False - Bovy (UofT)
"""
if not ro is False:
self._roSet = True
ro = conversion.parse_length_kpc(ro)
if not ro is None:
self._ro = ro
if not vo is False:
self._voSet = True
vo = conversion.parse_velocity_kms(vo)
if not vo is None:
self._vo = vo
return None
@potential_physical_input
@physical_conversion("force", pop=True)
def rforce(self, R, z, **kwargs):
"""
Evaluate the spherical radial force F_r (R,z).
Parameters
----------
R : float or Quantity
Cylindrical Galactocentric radius.
z : float or Quantity
Vertical height.
phi : float or Quantity, optional
Azimuth. Default is None.
t : float or Quantity, optional
Time. Default is 0.0.
v : float or Quantity, optional
Current velocity in cylindrical coordinates. Required when including dissipative forces. Default is None.
Returns
-------
F_r : float or Quantity
The spherical radial force F_r (R,z).
Notes
-----
- 2016-06-20 - Written - Bovy (UofT)
"""
r = numpy.sqrt(R**2.0 + z**2.0)
kwargs["use_physical"] = False
return self.Rforce(R, z, **kwargs) * R / r + self.zforce(R, z, **kwargs) * z / r
def toPlanar(self):
"""
Convert a 3D potential into a planar potential in the mid-plane.
Returns
-------
planarPotential, planarAxiPotential, or planarDissipativeForce instance
"""
from ..potential import toPlanarPotential
return toPlanarPotential(self)