EinsteinPy - Making Einstein possible in Python¶

EinsteinPy is an open source pure Python package dedicated to problems arising in General Relativity and gravitational physics, such as goedesics plotting for Schwarzschild, Kerr and Kerr Newman space-time model, calculation of Schwarzschild radius, calculation of Event Horizon and Ergosphere for Kerr space-time. Symbolic Manipulations of various tensors like Metric, Riemann, Ricci and Christoffel Symbols is also possible using the library. EinsteinPy also features Hypersurface Embedding of Schwarzschild space-time, which will soon lead to modelling of Gravitational Lensing! It is released under the MIT license.
View source code of EinsteinPy!
Key features of EinsteinPy are:
Geometry analysis and trajectory calculation in vacuum solutions of Einstein’s field equations
Schwarzschild space-time
Kerr space-time
Kerr-Newman space-time
Various utilities related to above geometry models
Schwarzschild Radius
Event horizon and ergosphere for Kerr black hole
Maxwell Tensor and electromagnetic potential in Kerr-Newman space-time
And much more!
Symbolic Calculation of various quantities
Christoffel Symbols
Riemann Curvature Tensor
Ricci Tensor
Index uppering and lowering!
Simplification of symbolic expressions
Geodesic Plotting
Static Plotting using Matplotlib
Interactive 2D plotting
Environment aware plotting!
Coordinate conversion with unit handling
Spherical/Cartesian Coordinates
Boyer-Lindquist/Cartesian Coordinates
Hypersurface Embedding of Schwarzschild Space-Time
Shadow cast by an thin emission disk around a Schwarzschild Black Hole
And more to come!
Einsteinpy is developed by an open community. Release announcements and general discussion take place on our mailing list and chat.
The source code, issue tracker and wiki are hosted on GitHub, and all contributions and feedback are more than welcome. You can test EinsteinPy in your browser using binder, a cloud Jupyter notebook server:
EinsteinPy works on recent versions of Python and is released under the MIT license, hence allowing commercial use of the library.
from einsteinpy.plotting import GeodesicPlotter
from einsteinpy.examples import perihelion
a = GeodesicPlotter()
a.plot(perihelion)
a.show()

Contents¶
Getting started¶
Overview¶
EinsteinPy is a easy-to-use python library which provides a user-friendly interface for supporting numerical relativity and relativistic astrophysics research. The library is an attempt to provide programming and numerical environment for a lot of numerical relativity problems like geodesics plotter, gravitational lensing and ray tracing, solving and simulating relativistic hydrodynamical equations, plotting of black hole event horizons, solving Einstein’s field equations and simulating various dynamical systems like binary merger etc.
Who can use?¶
Most of the numerical relativity platforms currently available in the gravitational physics research community demands a heavy programming experience in languages like C, C++ or their wrappers on some other non popular platforms. Many of the people working in the field of gravitational physics have theoretical background and does not have any or have little programming experience and they find using these libraries mind-boggling. EinsteinPy is motivated by this problem and provide a high level of abstraction that shed away from user all the programming and algorithmic view of the implemented numerical methods and enables anyone to simulate complicated system like binary merger with just 20-25 lines of python code.
Even people who does not know any python programming can also follow up with the help of tutorials and documentation given for the library. We aim to provide all steps, from setting up your library environment to running your first geodesic plotter with example jupyter notebooks.
So now you are motivated enough so let’s first start with installing the library.
Installation¶
It’s as easy as running one command!¶
Stable Versions:¶
For installation of the latest stable
version of EinsteinPy:
Using pip:
$ pip install einsteinpy
Using conda:
$ conda install -c conda-forge einsteinpy
Latest Versions¶
For installing the development version, you can do two things:
Installation from clone:
$ git clone https://github.com/einsteinpy/einsteinpy.git $ cd einsteinpy/ $ pip install .
Install using pip:
$ pip install git+https://github.com/einsteinpy/einsteinpy.git
Contribute¶
EinsteinPy is an open source library which is under heavy development. To contribute kindly do visit :
https://github.com/einsteinpy/einsteinpy/
and also check out current posted issues and help us expand this awesome library.
User guide¶
Defining the geometry: metric
objects¶
EinsteinPy provides a way to define the background geometry on which the code would deal with the dynamics. These geometry has a central operating quantity known as metric tensor and encapsulate all the geometrical and topological information about the 4d spacetime in them.
The central quantity required to simulate trajectory of a particle in a gravitational field is christoffel symbols.
EinsteinPy provides an easy to use interface to calculate these symbols.
Schwarzschild metric¶
EinsteinPy provides an easy interface for calculating time-like geodesics in Schwarzschild Geometry.
First of all, we import all the relevant modules and classes :
import numpy as np from astropy import units as u from einsteinpy.coordinates import SphericalDifferential, CartesianDifferential from einsteinpy.metric import Schwarzschild
From position and velocity in Spherical Coordinates¶
There are several methods available to create Schwarzschild
objects. For example, if we have the position and velocity vectors we can use from_spherical()
:
M = 5.972e24 * u.kg sph_coord = SphericalDifferential(306.0 * u.m, np.pi/2 * u.rad, -np.pi/6*u.rad, 0*u.m/u.s, 0*u.rad/u.s, 1900*u.rad/u.s) obj = Schwarzschild.from_coords(sph_coord, M , 0* u.s)
From position and velocity in Cartesian Coordinates¶
For initializing with Cartesian Coordinates, we can use from_cartesian
:
cartsn_coord = CartesianDifferential(.265003774 * u.km, -153.000000e-03 * u.km, 0 * u.km, 145.45557 * u.km/u.s, 251.93643748389 * u.km/u.s, 0 * u.km/u.s) obj = Schwarzschild.from_coords(cartsn_coord, M , 0* u.s)
Calculating Trajectory/Time-like Geodesics¶
After creating the object we can call calculate_trajectory
end_tau = 0.01 # approximately equal to coordinate time stepsize = 0.3e-6 ans = obj.calculate_trajectory(end_lambda=end_tau, OdeMethodKwargs={"stepsize":stepsize}) print(ans)(array([0.00000000e+00, 2.40000000e-07, 2.64000000e-06, ..., 9.99367909e-03, 9.99607909e-03, 9.99847909e-03]), array([[ 0.00000000e+00, 3.06000000e+02, 1.57079633e+00, ..., 0.00000000e+00, 0.00000000e+00, 9.50690000e+02], [ 2.39996635e-07, 3.05999885e+02, 1.57079633e+00, ..., -9.55164950e+02, 1.32822112e-17, 9.50690712e+02], [ 2.63996298e-06, 3.05986131e+02, 1.57079633e+00, ..., -1.05071184e+04, 1.46121838e-16, 9.50776184e+02], ..., [ 9.99381048e-03, 3.05156192e+02, 1.57079633e+00, ..., 8.30642520e+04, -1.99760372e-12, 9.55955926e+02], [ 9.99621044e-03, 3.05344028e+02, 1.57079633e+00, ..., 7.34673728e+04, -2.01494258e-12, 9.54780155e+02], [ 9.99861041e-03, 3.05508844e+02, 1.57079633e+00, ..., 6.38811856e+04, -2.03252073e-12, 9.53750261e+02]]))
Return value can be obtained in Cartesian Coordinates by :
ans = obj.calculate_trajectory(end_lambda=end_tau, OdeMethodKwargs={"stepsize":stepsize}, return_cartesian=True)
Bodies Module: bodies
¶
EinsteinPy has a module to define the attractor and revolving bodies, using which plotting and geodesic calculation becomes much easier.
Importing all the relevant modules and classes :
import numpy as np from astropy import units as u from einsteinpy.coordinates import BoyerLindquistDifferential from einsteinpy.metric import Kerr from einsteinpy.bodies import Body from einsteinpy.geodesic import Geodesic
Defining various astronomical bodies :
spin_factor = 0.3 * u.m Attractor = Body(name="BH", mass = 1.989e30 * u.kg, a = spin_factor) BL_obj = BoyerLindquistDifferential(50e5 * u.km, np.pi / 2 * u.rad, np.pi * u.rad, 0 * u.km / u.s, 0 * u.rad / u.s, 0 * u.rad / u.s, spin_factor) Particle = Body(differential = BL_obj, parent = Attractor) geodesic = Geodesic(body = Particle, end_lambda = ((1 * u.year).to(u.s)).value / 930, step_size = ((0.02 * u.min).to(u.s)).value, metric=Kerr) geodesic.trajectory # get the values of the trajectory
Plotting the trajectory :
from einsteinpy.plotting import GeodesicPlotter obj = GeodesicPlotter() obj.plot(geodesic) obj.show()
Utilities: utils
¶
EinsteinPy provides a great set of utility functions which are frequently used in general and numerical relativity.
Conversion of Coordinates (both position & velocity)
Cartesian/Spherical
Cartesian/Boyer-Lindquist
Calculation of Schwarzschild Geometry related quantities
Schwarzschild Radius
Rate of change of coordinate time w.r.t. proper time
Coordinate Conversion¶
In a short example, we would see coordinate conversion between Cartesian and Boyer-Lindquist Coordinates.
Using the functions:
to_cartesian
to_bl
import numpy as np from astropy import units as u from einsteinpy.coordinates import BoyerLindquistDifferential, CartesianDifferential, Cartesian, BoyerLindquist a = 0.5 * u.km pos_vec = Cartesian(.265003774 * u.km, -153.000000e-03 * u.km, 0 * u.km) bl_pos = pos_vec.to_bl(a) print(bl_pos) cartsn_pos = bl_pos.to_cartesian(a) print(cartsn_pos) pos_vel_coord = CartesianDifferential(.265003774 * u.km, -153.000000e-03 * u.km, 0 * u.km, 145.45557 * u.km/u.s, 251.93643748389 * u.km/u.s, 0 * u.km/u.s) bl_coord = pos_vel_coord.bl_differential(a) bl_coord = bl_coord.si_values() bl_vel = bl_coord[3:] print(bl_vel) cartsn_coord = bl_coord.cartesian_differential(a) cartsn_coord = cartsn_coord.si_values() cartsn_vel = cartsn_coord[3:] print(cartsn_vel)
[ 200. -100. 20.5] [224.54398697 1.47937288 -0.46364761]
Symbolic Calculations¶
EinsteinPy also supports symbolic calculations in
symbolic
import sympy from einsteinpy.symbolic import SchwarzschildMetric, ChristoffelSymbols m = SchwarzschildMetric() ch = ChristoffelSymbols.from_metric(m) print(ch[1,2,:])[0, 0, -r*(-a/r + 1), 0]import sympy from einsteinpy.symbolic import SchwarzschildMetric, EinsteinTensor m = SchwarzschildMetric() G1 = EinsteinTensor.from_metric(m) print(G1.arr)[[a*c**2*(-a + r)/r**4 + a*c**2*(a - r)/r**4, 0, 0, 0], [0, a/(r**2*(a - r)) + a/(r**2*(-a + r)), 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]
Future Plans¶
Support for null-geodesics in different geometries
Ultimate goal is providing numerical solutions for Einstein’s equations for arbitrarily complex matter distribution.
Relativistic hydrodynamics
Vacuum Solutions to Einstein’s Field Equations¶
Einstein’s Equation¶
Einstein’s Field Equation(EFE) is a ten component tensor equation which relates local space-time curvature with local energy and momentum. In short, they determine the metric tensor of a spacetime given arrangement of stress-energy in space-time. The EFE is given by
Here, \(R_{\mu\nu}\) is the Ricci Tensor, \(R\) is the curvature scalar(contraction of Ricci Tensor), \(g_{\mu\nu}\) is the metric tensor, \(\Lambda\) is the cosmological constant and lastly, \(T_{\mu\nu}\) is the stress-energy tensor. All the other variables hold their usual meaning.
Metric Tensor¶
The metric tensor gives us the differential length element for each durection of space. Small distance in a N-dimensional space is given by :
\(ds^2 = g_{ij}dx_{i}dx_{j}\)
The tensor is constructed when each \(g_{ij}\) is put in it’s position in a rank-2 tensor. For example, metric tensor in a spherical coordinate system is given by:
\(g_{00} = 1\)
\(g_{11} = r^2\)
\(g_{22} = r^2sin^2\theta\)
\(g_{ij} = 0\) when \(i{\neq}j\)
We can see the off-diagonal component of the metric to be equal to 0 as it is an orthogonal coordinate system, i.e. all the axis are perpendicular to each other. However it is not always the case. For example, a euclidean space defined by vectors i, j and j+k is a flat space but the metric tensor would surely contain off-diagonal components.
Notion of Curved Space¶
Imagine a bug travelling across a 2-D paper folded into a cone. The bug can’t see up and down, so he lives in a 2d world, but still he can experience the curvature, as after a long journey, he would come back at the position where he started. For him space is not infinite.
Mathematically, curvature of a space is given by Riemann Curvature Tensor, whose contraction is Ricii Tensor, and taking its trace yields a scalar called Ricci Scalar or Curvature Scalar.
Straight lines in Curved Space¶
Imagine driving a car on a hilly terrain keeping the steering absolutely straight. The trajectory followed by the car, gives us the notion of geodesics. Geodesics are like straight lines in higher dimensional(maybe curved) space.
Mathematically, geodesics are calculated by solving set of differential equation for each space(time) component using the equation:
\(\ddot{x}_i+0.5*g^{im}*(\partial_{l}g_{mk}+\partial_{k}g_{ml}-\partial_{m}g_{kl})\dot{x}_k\dot{x}_l = 0\)
which can be re-written as
\(\ddot{x}_i+\Gamma_{kl}^i \dot{x}_k\dot{x}_l = 0\)
where \(\Gamma\) is Christoffel symbol of the second kind.
Christoffel symbols can be encapsulated in a rank-3 tensor which is symmetric over it’s lower indices. Coming back to Riemann Curvature Tensor, which is derived from Christoffel symbols using the equation
\(R_{abc}^i=\partial_b\Gamma_{ca}^i-\partial_c\Gamma_{ba}^i+\Gamma_{bm}^i\Gamma_{ca}^m-\Gamma_{cm}^i\Gamma_{ba}^m\)
Of course, Einstein’s indicial notation applies everywhere.
Contraction of Riemann Tensor gives us Ricci Tensor, on which taking trace gives Ricci or Curvature scalar. A space with no curvature has Riemann Tensor as zero.
Exact Solutions of EFE¶
Schwarzschild Metric¶
It is the first exact solution of EFE given by Karl Schwarzschild, for a limited case of single spherical non-rotating mass. The metric is given as:
\(d\tau^2 = -(1-r_s/r)dt^2+(1-r_s/r)^{-1}dr^2+r^2d\theta^2/c^2+r^2sin^2\theta d\phi^2/c^2\)
where \(r_s=2*G*M/c^2\)
and is called the Schwarzschild Radius, a point beyond where space and time flips and any object inside the radius would require speed greater than speed of light to escape singularity, where the curvature of space becomes infinite and so is the case with the tidal forces. Putting \(r=\infty\), we see that the metric transforms to a metric for a flat space defined by spherical coordinates.
\(\tau\) is the proper time, the time experienced by the particle in motion in the space-time while \(t\) is the coordinate time observed by an observer at infinity.
Using the metric in the above discussed geodesic equation gives the four-position and four-velocity of a particle for a given range of \(\tau\). The differential equations can be solved by supplying the initial positions and velocities.
Kerr Metric and Kerr-Newman Metric¶
Kerr-Newman metric is also an exact solution of EFE. It deals with spinning, charged massive body as the solution has axial symettry. A quick search on google would give the exact metric as it is quite exhaustive.
Kerr-Newman metric is the most general vacuum solution consisting of a single body at the center.
Kerr metric is a specific case of Kerr-Newman where charge on the body \(Q=0\). Schwarzschild metric can be derived from Kerr-Newman solution by putting charge and spin as zero \(Q=0\), \(a=0\).
Jupyter notebooks¶
Visualizing advancement of perihelion in Schwarzschild space-time¶
[1]:
import numpy as np
import astropy.units as u
from plotly.offline import init_notebook_mode
from einsteinpy.plotting import GeodesicPlotter
from einsteinpy.coordinates import SphericalDifferential
from einsteinpy.bodies import Body
from einsteinpy.geodesic import Geodesic
[2]:
init_notebook_mode(connected=True)
# Essential when using Jupyter Notebook (May skip in Jupyter Lab)
Defining various parameters¶
Mass of the attractor(M)
Initial position and velocity vectors of test partcle
[3]:
Attractor = Body(name="BH", mass=6e24 * u.kg, parent=None)
sph_obj = SphericalDifferential(130*u.m, np.pi/2*u.rad, -np.pi/8*u.rad,
0*u.m/u.s, 0*u.rad/u.s, 1900*u.rad/u.s)
Object = Body(differential=sph_obj, parent=Attractor)
geodesic = Geodesic(body=Object, time=0 * u.s, end_lambda=0.002, step_size=5e-8)
Plotting the trajectory¶
[4]:
obj = GeodesicPlotter()
obj.plot(geodesic)
obj.show()
It can be seen that the orbit advances along the azimuth angle on each revolution of test partcle .
Animations in EinsteinPy¶
Import the required modules¶
[1]:
import numpy as np
import astropy.units as u
from einsteinpy.plotting import StaticGeodesicPlotter
from einsteinpy.coordinates import SphericalDifferential
from einsteinpy.bodies import Body
from einsteinpy.geodesic import Geodesic
Defining various parameters¶
Mass of the attractor (M)
Initial position and velocity vectors of test partcle
[2]:
Attractor = Body(name="BH", mass=6e24 * u.kg, parent=None)
sph_obj = SphericalDifferential(130*u.m, np.pi/2*u.rad, -np.pi/8*u.rad,
0*u.m/u.s, 0*u.rad/u.s, 1900*u.rad/u.s)
Object = Body(differential=sph_obj, parent=Attractor)
geodesic = Geodesic(body=Object, time=0 * u.s, end_lambda=0.002, step_size=5e-8)
Plotting the animation¶
[3]:
%matplotlib notebook
obj = StaticGeodesicPlotter()
obj.animate(geodesic, interval=25)
obj.show()
[ ]:
Symbolically Understanding Christoffel Symbol and Riemann Curvature Tensor using EinsteinPy¶
[1]:
import sympy
from einsteinpy.symbolic import MetricTensor, ChristoffelSymbols, RiemannCurvatureTensor
sympy.init_printing() # enables the best printing available in an environment
Defining the metric tensor for 3d spherical coordinates¶
[2]:
syms = sympy.symbols('r theta phi')
# define the metric for 3d spherical coordinates
metric = [[0 for i in range(3)] for i in range(3)]
metric[0][0] = 1
metric[1][1] = syms[0]**2
metric[2][2] = (syms[0]**2)*(sympy.sin(syms[1])**2)
# creating metric object
m_obj = MetricTensor(metric, syms)
m_obj.tensor()
[2]:
Calculating the christoffel symbols¶
[3]:
ch = ChristoffelSymbols.from_metric(m_obj)
ch.tensor()
[3]:
[4]:
ch.tensor()[1,1,0]
[4]:
Calculating the Riemann Curvature tensor¶
[5]:
# Calculating Riemann Tensor from Christoffel Symbols
rm1 = RiemannCurvatureTensor.from_christoffels(ch)
rm1.tensor()
[5]:
[6]:
# Calculating Riemann Tensor from Metric Tensor
rm2 = RiemannCurvatureTensor.from_metric(m_obj)
rm2.tensor()
[6]:
Calculating the christoffel symbols for Schwarzschild Spacetime Metric¶
The expressions are unsimplified
[7]:
syms = sympy.symbols("t r theta phi")
G, M, c, a = sympy.symbols("G M c a")
# using metric values of schwarschild space-time
# a is schwarzschild radius
list2d = [[0 for i in range(4)] for i in range(4)]
list2d[0][0] = 1 - (a / syms[1])
list2d[1][1] = -1 / ((1 - (a / syms[1])) * (c ** 2))
list2d[2][2] = -1 * (syms[1] ** 2) / (c ** 2)
list2d[3][3] = -1 * (syms[1] ** 2) * (sympy.sin(syms[2]) ** 2) / (c ** 2)
sch = MetricTensor(list2d, syms)
sch.tensor()
[7]:
[8]:
# single substitution
subs1 = sch.subs(a,0)
subs1.tensor()
[8]:
[9]:
# multiple substitution
subs2 = sch.subs([(a,0), (c,1)])
subs2.tensor()
[9]:
[10]:
sch_ch = ChristoffelSymbols.from_metric(sch)
sch_ch.tensor()
[10]:
Calculating the simplified expressions¶
[11]:
simplified = sch_ch.simplify()
simplified
[11]:
Contravariant & Covariant indices in Tensors (Symbolic)¶
[1]:
from einsteinpy.symbolic import SchwarzschildMetric, MetricTensor, ChristoffelSymbols, RiemannCurvatureTensor
import sympy
sympy.init_printing()
Analysing the schwarzschild metric along with performing various operations¶
[2]:
sch = SchwarzschildMetric()
sch.tensor()
[2]:
[3]:
sch_inv = sch.inv()
sch_inv.tensor()
[3]:
[4]:
sch.order
[4]:
[5]:
sch.config
[5]:
'll'
Obtaining Christoffel Symbols from Metric Tensor¶
[6]:
chr = ChristoffelSymbols.from_metric(sch_inv) # can be initialized from sch also
chr.tensor()
[6]:
[7]:
chr.config
[7]:
'ull'
Changing the first index to covariant¶
[8]:
new_chr = chr.change_config('lll') # changing the configuration to (covariant, covariant, covariant)
new_chr.tensor()
[8]:
[9]:
new_chr.config
[9]:
'lll'
Any arbitary index configuration would also work!¶
[10]:
new_chr2 = new_chr.change_config('lul')
new_chr2.tensor()
[10]:
Obtaining Riemann Tensor from Christoffel Symbols and manipulating it’s indices¶
[11]:
rm = RiemannCurvatureTensor.from_christoffels(new_chr2)
rm[0,0,:,:]
[11]:
[12]:
rm.config
[12]:
'ulll'
[13]:
rm2 = rm.change_config("uuuu")
rm2[0,0,:,:]
[13]:
[14]:
rm3 = rm2.change_config("lulu")
rm3[0,0,:,:]
[14]:
[15]:
rm4 = rm3.change_config("ulll")
rm4[0,0,:,:]
[15]:
It is seen that rm
and rm4
are same as they have the same configuration¶
Ricci Tensor and Scalar Curvature calculations using Symbolic module¶
[1]:
import sympy
from sympy import cos, sin, sinh
from einsteinpy.symbolic import MetricTensor, RicciTensor, RicciScalar
sympy.init_printing()
Defining the Anti-de Sitter spacetime Metric¶
[2]:
syms = sympy.symbols("t chi theta phi")
t, ch, th, ph = syms
m = sympy.diag(-1, cos(t) ** 2, cos(t) ** 2 * sinh(ch) ** 2, cos(t) ** 2 * sinh(ch) ** 2 * sin(th) ** 2).tolist()
metric = MetricTensor(m, syms)
Calculating the Ricci Tensor(with both indices covariant)¶
[3]:
Ric = RicciTensor.from_metric(metric)
Ric.tensor()
[3]:
Calculating the Ricci Scalar(Scalar Curvature) from the Ricci Tensor¶
[4]:
R = RicciScalar.from_riccitensor(Ric)
R.expr
[4]:
The curavture is -12 which is in-line with the theoretical results
Analysing Earth using EinsteinPy!¶
Calculating the eccentricity and speed at apehelion of Earth’s orbit¶
Various parameters of Earth’s orbit considering Sun as schwarzschild body and solving geodesic equations are calculated
1. Defining the initial parameters¶
[1]:
from astropy import units as u
import numpy as np
from einsteinpy.metric import Schwarzschild
from einsteinpy.coordinates import SphericalDifferential
[2]:
# Define position and velocity vectors in spherical coordinates
# Earth is at perihelion
M = 1.989e30 * u.kg # mass of sun
distance = 147.09e6 * u.km
speed_at_perihelion = 30.29 * u.km / u.s
omega = (u.rad * speed_at_perihelion) / distance
sph_obj = SphericalDifferential(distance, np.pi / 2 * u.rad, np.pi * u.rad,
0 * u.km / u.s, 0 * u.rad / u.s, omega)
Defining \(\lambda\) (or \(\tau\)) for which to calculate trajectory
\(\lambda\) is proper time and is approximately equal to coordinate time in non-relativistic limits
[3]:
# Set lambda to complete an year.
# Lambda is always specified in secs
end_lambda = ((1 * u.year).to(u.s)).value
# Choosing stepsize for ODE solver to be 5 minutes
stepsize = ((5 * u.min).to(u.s)).value
2. Making a class instance to get the trajectory in cartesian coordinates¶
[4]:
obj = Schwarzschild.from_coords(sph_obj, M)
ans = obj.calculate_trajectory(
end_lambda=end_lambda, OdeMethodKwargs={"stepsize": stepsize}, return_cartesian=True
)
Return value is a tuple consisting of 2 numpy array
First one contains list of \(\lambda\)
Seconds is array of shape (n,8) where each component is:
t - coordinate time
x - position in m
y - position in m
z - position in m
dt/d\(\lambda\)
dx/d\(\lambda\)
dy/d\(\lambda\)
dz/d\(\lambda\)
[5]:
ans[0].shape, ans[1].shape
[5]:
((13150,), (13150, 8))
Calculating distance at aphelion¶
Should be 152.10 million km
[6]:
r = np.sqrt(np.square(ans[1][:, 1]) + np.square(ans[1][:, 2]))
i = np.argmax(r)
(r[i] * u.m).to(u.km)
[6]:
Speed at aphelion should be 29.29 km/s and should be along y-axis¶
[7]:
((ans[1][i][6]) * u.m / u.s).to(u.km / u.s)
[7]:
Calculating the eccentricity¶
Should be 0.0167
[8]:
xlist, ylist = ans[1][:, 1], ans[1][:, 2]
i = np.argmax(ylist)
x, y = xlist[i], ylist[i]
eccentricity = x / (np.sqrt(x ** 2 + y ** 2))
eccentricity
[8]:
0.016709664332073014
Plotting the trajectory with time¶
[9]:
from einsteinpy.bodies import Body
from einsteinpy.geodesic import Geodesic
Sun = Body(name="Sun", mass=M, parent=None)
Object = Body(name="Earth", differential=sph_obj, parent=Sun)
geodesic = Geodesic(body=Object, time=0 * u.s, end_lambda=end_lambda, step_size=stepsize)
from einsteinpy.plotting import GeodesicPlotter
sgp = GeodesicPlotter()
sgp.plot(geodesic)
sgp.show()
All data regarding earth’s orbit is taken from https://nssdc.gsfc.nasa.gov/planetary/factsheet/earthfact.html
Visualizing frame dragging in Kerr space-time¶
Importing required modules¶
[1]:
from astropy import units as u
import numpy as np
from einsteinpy.metric import Kerr
from einsteinpy.coordinates import BoyerLindquistDifferential
from einsteinpy.bodies import Body
from einsteinpy.geodesic import Geodesic
Defining position/velocity of test particle¶
Initial velocity is kept 0
[2]:
M = 1.989e30 * u.kg
a = 0.3 * u.m
BL_obj = BoyerLindquistDifferential(49.95e5 * u.km, np.pi / 2 * u.rad, np.pi * u.rad,
0 * u.km / u.s, 0 * u.rad / u.s, 0 * u.rad / u.s,
a)
[3]:
end_lambda = ((1 * u.year).to(u.s)).value / 930
# Choosing stepsize for ODE solver to be 0.02 minutes
stepsize = ((0.02 * u.min).to(u.s)).value
[4]:
obj = Kerr.from_coords(BL_obj, M)
ans = obj.calculate_trajectory(
end_lambda=end_lambda, OdeMethodKwargs={"stepsize": stepsize}, return_cartesian=True
)[1]
x, y = ans[:,1], ans[:,2]
Plotting the trajectory¶
[5]:
%matplotlib inline
[6]:
import matplotlib.pyplot as plt
plt.scatter(x,y, s=0.2)
plt.scatter(0,0, c='black')
plt.show()

It can be seen that as the particle approaches the massive body, it acquires axial velocity due to spin and frame-dragging effect of the body.¶
[7]:
a = 0.3 * u.m
Attractor = Body(name="BH", mass=1.989e30 * u.kg, a=a)
init_conditions = BoyerLindquistDifferential(49.95e5 * u.km, np.pi / 2 * u.rad,
np.pi * u.rad, 0 * u.km / u.s,
0 * u.rad / u.s, 0 * u.rad / u.s,
a)
Particle = Body(differential=init_conditions, parent=Attractor)
[8]:
geodesic = Geodesic(body=Particle, time=0 * u.s, end_lambda=33932.90,
step_size=1.2, metric=Kerr)
ans = geodesic.trajectory
[9]:
x, y = ans[:,1], ans[:,2]
[10]:
%matplotlib inline
plt.scatter(x,y, s=0.2)
plt.scatter(0,0, c='red')
plt.show()

Visualizing event horizon and ergosphere of Kerr black hole¶
Importing required modules¶
[1]:
import numpy as np
import astropy.units as u
import matplotlib.pyplot as plt
from einsteinpy.utils import kerr_utils, schwarzschild_radius
Defining the black hole charecteristics¶
[2]:
M = 4e30
scr = schwarzschild_radius(M * u.kg).value
# for nearly maximally rotating black hole
a1 = 0.499999*scr
# for ordinary black hole
a2 = 0.3*scr
Calculating the ergosphere and event horizon for spherical coordinates¶
[3]:
ergo1, ergo2, hori1, hori2 = list(), list(), list(), list()
thetas = np.linspace(0, np.pi, 720)
for t in thetas:
ergo1.append(kerr_utils.radius_ergosphere(M, a1, t, "Spherical"))
ergo2.append(kerr_utils.radius_ergosphere(M, a2, t, "Spherical"))
hori1.append(kerr_utils.event_horizon(M, a1, t, "Spherical"))
hori2.append(kerr_utils.event_horizon(M, a2, t, "Spherical"))
ergo1, ergo2, hori1, hori2 = np.array(ergo1), np.array(ergo2), np.array(hori1), np.array(hori2)
Calculating the X, Y coordinates for plotting¶
[4]:
Xe1, Ye1 = ergo1[:,0] * np.sin(ergo1[:,1]), ergo1[:,0] * np.cos(ergo1[:,1])
Xh1, Yh1 = hori1[:,0] * np.sin(hori1[:,1]), hori1[:,0] * np.cos(hori1[:,1])
Xe2, Ye2 = ergo2[:,0] * np.sin(ergo2[:,1]), ergo2[:,0] * np.cos(ergo2[:,1])
Xh2, Yh2 = hori2[:,0] * np.sin(hori2[:,1]), hori2[:,0] * np.cos(hori2[:,1])
Plot for maximally rotating black hole¶
[5]:
%matplotlib inline
fig, ax = plt.subplots()
# for maximally rotating black hole
ax.fill(Xh1, Yh1, 'b', Xe1, Ye1, 'r', alpha=0.3)
ax.fill(-1*Xh1, Yh1, 'b', -1*Xe1, Ye1, 'r', alpha=0.3)
[5]:
[<matplotlib.patches.Polygon at 0x7fa4665277b8>,
<matplotlib.patches.Polygon at 0x7fa466527dd8>]

Plot for rotating(normally) black hole¶
[6]:
%matplotlib inline
fig, ax = plt.subplots()
ax.fill(Xh2, Yh2, 'b', Xe2, Ye2, 'r', alpha=0.3)
ax.fill(-1*Xh2, Yh2, 'b', -1*Xe2, Ye2, 'r', alpha=0.3)
[6]:
[<matplotlib.patches.Polygon at 0x7fa466598160>,
<matplotlib.patches.Polygon at 0x7fa438289ba8>]

The inner body represents event horizon and outer one represents ergosphere. It can be concluded that with decrease in angular momentum, radius of event horizon increases, and that of ergosphere decreases.
Plotting Spacial Hypersurface Embedding for Schwarzschild Space-Time¶
[1]:
from einsteinpy.hypersurface import SchwarzschildEmbedding
from einsteinpy.plotting import HypersurfacePlotter
from astropy import units as u
Declaring embedding object with specified mass of the body and plotting the embedding hypersurface for Schwarzschild spacetime
[2]:
surface_obj = SchwarzschildEmbedding(5.927e23 * u.kg)
[3]:
surface = HypersurfacePlotter(embedding=surface_obj, plot_type='surface')
surface.plot()
surface.show()

The plotted embedding has initial Schwarzschild radial coordinate to be greater than schwarzschild radius but the embedding can be defined for coordinates greater than 9m/4. The Schwarzschild spacetime is a static spacetime and thus the embeddings can be obtained by considering fermat’s surfaces of stationary time coordinate and thus this surface also represent the spacial geometry on which light rays would trace their paths along geodesics of this surface (spacially)!
Weyl Tensor calculations using Symbolic module¶
[1]:
import sympy
from sympy import cos, sin, sinh
from einsteinpy.symbolic import MetricTensor, WeylTensor
sympy.init_printing()
Defining the Anti-de Sitter spacetime Metric¶
[2]:
syms = sympy.symbols("t chi theta phi")
t, ch, th, ph = syms
m = sympy.diag(-1, cos(t) ** 2, cos(t) ** 2 * sinh(ch) ** 2, cos(t) ** 2 * sinh(ch) ** 2 * sin(th) ** 2).tolist()
metric = MetricTensor(m, syms)
Calculating the Weyl Tensor (with all indices covariant)¶
[3]:
weyl = WeylTensor.from_metric(metric)
weyl.tensor()
[3]:
[4]:
weyl.config
[4]:
'llll'
Einstein Tensor calculations using Symbolic module¶
[1]:
import numpy as np
import pytest
import sympy
from sympy import cos, simplify, sin, sinh, tensorcontraction
from einsteinpy.symbolic import EinsteinTensor, MetricTensor, RicciScalar
sympy.init_printing()
Defining the Anti-de Sitter spacetime Metric¶
[2]:
syms = sympy.symbols("t chi theta phi")
t, ch, th, ph = syms
m = sympy.diag(-1, cos(t) ** 2, cos(t) ** 2 * sinh(ch) ** 2, cos(t) ** 2 * sinh(ch) ** 2 * sin(th) ** 2).tolist()
metric = MetricTensor(m, syms)
Calculating the Einstein Tensor (with both indices covariant)¶
[3]:
einst = EinsteinTensor.from_metric(metric)
einst.tensor()
[3]:
Lambdify in symbolic module¶
Importing required modules¶
[1]:
import sympy
from sympy.abc import x, y
from sympy import symbols
from einsteinpy.symbolic import BaseRelativityTensor
sympy.init_printing()
Calculating a Base Relativity Tensor¶
[2]:
syms = symbols("x y")
x, y = syms
T = BaseRelativityTensor([[x, 1],[0, x+y]], syms, config="l")
Calling the lambdify function¶
[3]:
args, func = T.tensor_lambdify()
args
[3]:
args
indicates the order in which arguments should be passed to the returned function func
Executing the returned function for some value¶
[4]:
func(2, 1)
[4]:
Predefined Metrics in Symbolic Module¶
Importing some of the predefined tensors. All the metrics are comprehensively listed in EinsteinPy documentation.¶
[1]:
from einsteinpy.symbolic.predefined import Schwarzschild, DeSitter, AntiDeSitter, Minkowski, find
from einsteinpy.symbolic import RicciTensor, RicciScalar
import sympy
from sympy import simplify
sympy.init_printing() # for pretty printing
Printing the metrics for visualization¶
All the functions return instances of :py:class:~einsteinpy.symbolic.metric.MetricTensor
[2]:
sch = Schwarzschild()
sch.tensor()
[2]:
[3]:
Minkowski(c=1).tensor()
[3]:
[4]:
DeSitter().tensor()
[4]:
[5]:
AntiDeSitter().tensor()
[5]:
Calculating the scalar (Ricci) curavtures¶
They should be constant for De-Sitter and Anti-De-Sitter spacetimes.
[6]:
scalar_curvature_de_sitter = RicciScalar.from_metric(DeSitter())
scalar_curvature_anti_de_sitter = RicciScalar.from_metric(AntiDeSitter())
[7]:
scalar_curvature_de_sitter.expr
[7]:
[8]:
scalar_curvature_anti_de_sitter.expr
[8]:
On simplifying the expression we got above, we indeed obtain a constant
[9]:
simplify(scalar_curvature_anti_de_sitter.expr)
[9]:
Searching for a predefined metric¶
find function returns a list of available functions
[10]:
find("sitter")
[10]:
['AntiDeSitter', 'AntiDeSitterStatic', 'DeSitter']
Shadow cast by an thin emission disk around a Schwarzschild Black Hole¶
[1]:
import astropy.units as u
from einsteinpy.rays import Shadow
from einsteinpy.plotting import ShadowPlotter
Defining the conditions
[2]:
mass = 1 * u.kg
fov = 30 * u.km
# What field of view is the user expecting
[3]:
shadow = Shadow(mass=mass, fov=fov, n_rays=1000)
[5]:
obj = ShadowPlotter(shadow=shadow, is_line_plot=True)
obj.plot()
obj.show()

[6]:
obj = ShadowPlotter(shadow=shadow, is_line_plot=False)
obj.plot()
obj.show()

What’s new¶
einsteinpy 0.2.1 - 2019-11-02¶
This minor release would bring improvements and new feature additions to the already existing symbolic calculations module along with performance boosts of order of 15x.
This release concludes the SOCIS 2019 projects of Sofía Ortín Vela (ortinvela.sofia@gmail.com) and Varun Singh(varunsinghs2021@gmail.com).
Part of this release is sponsored by European Space Agency, through Summer of Code in Space (SOCIS) 2019 program.
Features¶
New tensors in symbolic module
Ricci Scalar
Weyl Tensor
Stress-Energy-Momentum Tensor
Einstein Tensor
Schouten Tensor
Improvement in performance of current tensors
Lambdify option for tensors
Support for vectors at arbitrary space-time symbolically as 1st order tensor.
Support for scalars at arbitrary space-time symbolically as 0th order tensor.
Addition of constants sub-module to symbolic module
Improvement in speed of Geodesic plotting
Move away from Jupyter and Plotly Widgets
New Plotting Framework
Contributors¶
This is the complete list of the people that contributed to this release, with a + sign indicating first contribution.
Shreyas Bapat
Ritwik Saha
Sofía Ortín Vela
Varun Singh
Arnav Das+
Calvin Jay Ross+
einsteinpy 0.2.0 - 2019-07-15¶
This release brings a lot of new features for the EinsteinPy Users.
A better API, intuitive structure and easy coordinates handling! This major release comes before Python in Astronomy 2019 workshop and brings a lots of cool stuff.
Part of this release is sponsored by ESA/ESTEC – Adv. Concepts & Studies Office (European Space Agency), through Summer of Code in Space (SOCIS) 2019 program.
This is a short-term supported version and will be supported only until December 2019. For any feature request, write a mail to developers@einsteinpy.org describing what you need.
Features¶
Kerr Metric
Kerr-Newman Metric
Coordinates Module with Boyer Lindquist Coordinates and transformation
Bodies Module
Defining Geodesics with ease!
Animated plots
Intuitive API for plotting
Schwarzschild Hypersurface Embedding
Interactive Plotting
Environment-aware plotting and exceptional support for iPython Notebooks!
Support for Tensor Algebra in General Relativity
Symbolic Manipulation of Metric Tensor, Riemann Tensor and Ricci Tensor
Support for Index Raising and Lowering in Tensors
Numerical Calculation and Symbolic Manipulation of Christoffel Symbols
Calculations of Event Horizon and Ergosphere of Kerr Black holes!
Contributors¶
This is the complete list of the people that contributed to this release, with a + sign indicating first contribution.
Shreyas Bapat
Ritwik Saha
Bhavya Bhatt
Sofía Ortín Vela+
Raphael Reyna+
Prithvi Manoj Krishna+
Manvi Gupta+
Divya Gupta+
Yash Sharma+
Shilpi Jain+
Rishi Sharma+
Varun Singh+
Alpesh Jamgade+
Saurabh Bansal+
Tanmay Rustagi+
Abhijeet Manhas+
Ankit Khandelwal+
Tushar Tyagi+
Hrishikesh Sarode
Naman Tayal+
Ratin Kumar+
Govind Dixit+
Jialin Ma+
Bugs Fixed¶
Issue #115: Coordinate Conversion had naming issues that made them confusing!
Issue #185: Isort had conflicts with Black
Issue #210: Same notebook had two different listings in Example Gallery
Issue #264: Removing all relative imports
Issue #265: New modules were lacking API Docs
Issue #266: The logo on documentation was not rendering
Issue #267: Docs were not present for Ricci Tensor and Vacuum Metrics
Issue #277: Coordinate Conversion in plotting module was handled incorrectly
Backwards incompatible changes¶
The old
StaticGeodesicPlotter
has been renamed toeinsteinpy.plotting.senile.StaticGeodesicPlotter
, please adjust your imports accordinglyThe old
ScatterGeodesicPlotter
has been renamed toeinsteinpy.plotting.senile.ScatterGeodesicPlotter
, please adjust your imports accordingly.einsteinpy.metric.Schwarzschild
,einsteinpy.metric.Kerr
, andeinsteinpy.metric.KerrNewman
now have different signatures for class methods, and they now explicitly supporteinsteinpy.coordinates
coordinate objects. Check out the notebooks and their respective documentation.The old coordinates conversion in
einsteinpy.utils
has been deprecated.The old symbolic module in
einsteinpy.utils
has been moved toeinsteinpy.symbolic
.
einsteinpy 0.1.0 - 2019-03-08¶
This is a major first release for world’s first actively maintained python library for General Relativity and Numerical methods. This major release just comes before the Annual AstroMeet of IIT Mandi, AstraX. This will be a short term support version and will be supported only until late 2019.
Features¶
Schwarzschild Geometry Analysis and trajectory calculation
Symbolic Calculation of various tensors in GR
Christoffel Symbols
Riemann Curvature Tensor
Static Geodesic Plotting
Velocity of Coordinate time w.r.t proper time
Easy Calculation of Schwarzschild Radius
Coordinate conversion with unit handling
Spherical/Cartesian Coordinates
Boyer-Lindquist/Cartesian Coordinates
Contributors¶
This is the complete list of the people that contributed to this release, with a + sign indicating first contribution.
Shreyas Bapat+
Ritwik Saha+
Bhavya Bhatt+
Priyanshu Khandelwal+
Gaurav Kumar+
Hrishikesh Sarode+
Sashank Mishra+
Developer Guide¶
Einsteinpy is a community project, hence all contributions are more than welcome!
Bug reporting¶
Not only things break all the time, but also different people have different use cases for the project. If you find anything that doesn’t work as expected or have suggestions, please refer to the issue tracker on GitHub.
Documentation¶
Documentation can always be improved and made easier to understand for newcomers. The docs are stored in text files under the docs/source directory, so if you think anything can be improved there please edit the files and proceed in the same way as with code writing.
The Python classes and methods also feature inline docs: if you detect any inconsistency or opportunity for improvement, you can edit those too.
Besides, the wiki is open for everybody to edit, so feel free to add new content.
To build the docs, you must first create a development environment (see
below) and then in the docs/
directory run:
$ cd docs $ make html
After this, the new docs will be inside build/html
. You can open
them by running an HTTP server:
$ cd build/html $ python -m http.server Serving HTTP on 0.0.0.0 port 8000 ...
And point your browser to http://0.0.0.0:8000.
Code writing¶
Code contributions are welcome! If you are looking for a place to start, help us fixing bugs in einsteinpy and check out the “easy” tag. Those should be easier to fix than the others and require less knowledge about the library.
If you are hesitant on what IDE or editor to use, just choose one that you find comfortable and stick to it while you are learning. People have strong opinions on which editor is better so I recommend you to ignore the crowd for the time being - again, choose one that you like :)
If you ask me for a recommendation, I would suggest PyCharm (complete IDE, free and gratis, RAM-hungry) or vim (powerful editor, very lightweight, steep learning curve). Other people use Spyder, emacs, gedit, Notepad++, Sublime, Atom…
You will also need to understand how git works. git is a decentralized version control system that preserves the history of the software, helps tracking changes and allows for multiple versions of the code to exist at the same time. If you are new to git and version control, I recommend following the Try Git tutorial.
If you already know how all this works and would like to contribute new features then that’s awesome! Before rushing out though please make sure it is within the scope of the library so you don’t waste your time - email us or chat with us on Riot!.
If the feature you suggest happens to be useful and within scope, you will probably be advised to create a new wiki page with some information about what problem you are trying to solve, how do you plan to do it and a sketch or idea of how the API is going to look like. You can go there to read other good examples on how to do it. The purpose is to describe without too much code what you are trying to accomplish to justify the effort and to make it understandable to a broader audience.
All new features should be thoroughly tested, and in the ideal case the coverage rate should increase or stay the same. Automatic services will ensure your code works on all the operative systems and package combinations einsteinpy support - specifically, note that einsteinpy is a Python 3 only library.
Development environment¶
These are some succint steps to set up a development environment:
Install git on your computer.
Install it in development mode using
pip install --editable /path/to/einsteinpy/[dev]
(this means that the installed code will change as soon as you change it in the download location).Create a new branch.
Make changes and commit.
EinsteinPy API¶
Welcome to the API documenatation of EinsteinPy. Please navigate through the given modules to get to know the API of the classes and methods. If you find anything missing, please open an issue in the repo .

Integrators module¶
This module contains the methods of solving Ordinary Differential Equations.
Runge Kutta module¶
-
class
einsteinpy.integrators.runge_kutta.
RK4naive
(fun, t0, y0, t_bound, stepsize)[source]¶ Class for Defining Runge-Kutta 4th Order ODE solving method
Initialization
- Parameters
fun (function) – Should accept t, y as parameters, and return same type as y
t0 (float) – Initial t
y0 (array or float) – Initial y
t_bound (float) – Boundary time - the integration won’t continue beyond it. It also determines the direction of the integration.
stepsize (float) – Size of each increment in t
-
class
einsteinpy.integrators.runge_kutta.
RK45
(fun, t0, y0, t_bound, stepsize, rtol=None, atol=None)[source]¶ This Class inherits ~scipy.integrate.RK45 Class
Initialization
- Parameters
fun (function) – Should accept t, y as parameters, and return same type as y
t0 (float) – Initial t
y0 (array or float) – Initial y
t_bound (float) – Boundary time - the integration won’t continue beyond it. It also determines the direction of the integration.
stepsize (float) – Size of each increment in t
rtol (float) – Relative tolerance, defaults to 0.2*stepsize
atol (float) – Absolute tolerance, defaults to rtol/0.8e3
Metric module¶
This module contains the basic classes of different metrics for various space-time geometries including schwarzschild, kerr etc.
schwarzschild module¶
This module contains the basic class for calculating time-like geodesics in Schwarzschild Space-Time:
-
class
einsteinpy.metric.schwarzschild.
Schwarzschild
(sph_coords, M, time)[source]¶ Class for defining a Schwarzschild Geometry methods
-
classmethod
from_coords
(coords, M, q=None, Q=None, time=<Quantity 0. s>, a=<Quantity 0. m>)[source]¶ Constructor
- Parameters
coords (CartesianDifferential) – Object having both initial positions and velocities of particle in Cartesian Coordinates
M (Quantity) – Mass of the body
time (Quantity) – Time of start, defaults to 0 seconds.
-
calculate_trajectory
(start_lambda=0.0, end_lambda=10.0, stop_on_singularity=True, OdeMethodKwargs={'stepsize': 0.001}, return_cartesian=False)[source]¶ Calculate trajectory in manifold according to geodesic equation
- Parameters
start_lambda (float) – Starting lambda(proper time), defaults to 0, (lambda ~= t)
end_lamdba (float) – Lambda(proper time) where iteartions will stop, defaults to 100000
stop_on_singularity (bool) – Whether to stop further computation on reaching singularity, defaults to True
OdeMethodKwargs (dict) – Kwargs to be supplied to the ODESolver, defaults to {‘stepsize’: 1e-3} Dictionary with key ‘stepsize’ along with an float value is expected.
return_cartesian (bool) – True if coordinates and velocities are required in cartesian coordinates(SI units), defaults to False
- Returns
~numpy.ndarray – N-element array containing proper time.
~numpy.ndarray – (n,8) shape array of [t, x1, x2, x3, velocity_of_time, v1, v2, v3] for each proper time(lambda).
-
calculate_trajectory_iterator
(start_lambda=0.0, stop_on_singularity=True, OdeMethodKwargs={'stepsize': 0.001}, return_cartesian=False)[source]¶ Calculate trajectory in manifold according to geodesic equation Yields an iterator
- Parameters
start_lambda (float) – Starting lambda, defaults to 0.0, (lambda ~= t)
stop_on_singularity (bool) – Whether to stop further computation on reaching singularity, defaults to True
OdeMethodKwargs (dict) – Kwargs to be supplied to the ODESolver, defaults to {‘stepsize’: 1e-3} Dictionary with key ‘stepsize’ along with an float value is expected.
return_cartesian (bool) – True if coordinates and velocities are required in cartesian coordinates(SI units), defaults to Falsed
- Yields
float – proper time
~numpy.ndarray – array of [t, x1, x2, x3, velocity_of_time, v1, v2, v3] for each proper time(lambda).
-
classmethod
kerr module¶
This module contains the basic class for calculating time-like geodesics in Kerr Space-Time:
-
class
einsteinpy.metric.kerr.
Kerr
(bl_coords, M, time)[source]¶ Class for defining Kerr Goemetry Methdos
-
classmethod
from_coords
(coords, M, q=None, Q=None, time=<Quantity 0. s>, a=<Quantity 0. m>)[source]¶ Constructor
- Parameters
coords (CartesianDifferential) – Object having both initial positions and velocities of particle in Cartesian Coordinates
M (Quantity) – Mass of the body
a (Quantity) – Spin factor of the massive body. Angular momentum divided by mass divided by speed of light.
time (Quantity) – Time of start, defaults to 0 seconds.
-
calculate_trajectory
(start_lambda=0.0, end_lambda=10.0, stop_on_singularity=True, OdeMethodKwargs={'stepsize': 0.001}, return_cartesian=False)[source]¶ Calculate trajectory in manifold according to geodesic equation
- Parameters
start_lambda (float) – Starting lambda(proper time), defaults to 0, (lambda ~= t)
end_lamdba (float) – Lambda(proper time) where iteartions will stop, defaults to 100000
stop_on_singularity (bool) – Whether to stop further computation on reaching singularity, defaults to True
OdeMethodKwargs (dict) – Kwargs to be supplied to the ODESolver, defaults to {‘stepsize’: 1e-3} Dictionary with key ‘stepsize’ along with an float value is expected.
return_cartesian (bool) – True if coordinates and velocities are required in cartesian coordinates(SI units), defaults to False
- Returns
~numpy.ndarray – N-element array containing proper time.
~numpy.ndarray – (n,8) shape array of [t, x1, x2, x3, velocity_of_time, v1, v2, v3] for each proper time(lambda).
-
calculate_trajectory_iterator
(start_lambda=0.0, stop_on_singularity=True, OdeMethodKwargs={'stepsize': 0.001}, return_cartesian=False)[source]¶ Calculate trajectory in manifold according to geodesic equation. Yields an iterator.
- Parameters
start_lambda (float) – Starting lambda, defaults to 0.0, (lambda ~= t)
stop_on_singularity (bool) – Whether to stop further computation on reaching singularity, defaults to True
OdeMethodKwargs (dict) – Kwargs to be supplied to the ODESolver, defaults to {‘stepsize’: 1e-3} Dictionary with key ‘stepsize’ along with an float value is expected.
return_cartesian (bool) – True if coordinates and velocities are required in cartesian coordinates(SI units), defaults to Falsed
- Yields
float – proper time
~numpy.ndarray – array of [t, x1, x2, x3, velocity_of_time, v1, v2, v3] for each proper time(lambda).
-
classmethod
kerr-newman module¶
This module contains the basic class for calculating time-like geodesics in Kerr-Newman Space-Time:
-
class
einsteinpy.metric.kerrnewman.
KerrNewman
(bl_coords, q, M, Q, time)[source]¶ Class for defining Kerr-Newman Goemetry Methods
-
classmethod
from_coords
(coords, M, q, Q, time=<Quantity 0. s>, a=<Quantity 0. m>)[source]¶ Constructor.
- Parameters
coords (BoyerLindquistDifferential) – Initial positions and velocities of particle in BL Coordinates, and spin factor of massive body.
q (Quantity) – Charge per unit mass of test particle
M (Quantity) – Mass of the massive body
Q (Quantity) – Charge on the massive body
a (Quantity) – Spin factor of the massive body(Angular Momentum per unit mass per speed of light)
time (Quantity) – Time of start, defaults to 0 seconds.
-
calculate_trajectory
(start_lambda=0.0, end_lambda=10.0, stop_on_singularity=True, OdeMethodKwargs={'stepsize': 0.001}, return_cartesian=False)[source]¶ Calculate trajectory in manifold according to geodesic equation
- Parameters
start_lambda (float) – Starting lambda(proper time), defaults to 0.0, (lambda ~= t)
end_lamdba (float) – Lambda(proper time) where iteartions will stop, defaults to 100000
stop_on_singularity (bool) – Whether to stop further computation on reaching singularity, defaults to True
OdeMethodKwargs (dict) – Kwargs to be supplied to the ODESolver, defaults to {‘stepsize’: 1e-3} Dictionary with key ‘stepsize’ along with an float value is expected.
return_cartesian (bool) – True if coordinates and velocities are required in cartesian coordinates(SI units), defaults to False
- Returns
~numpy.ndarray – N-element array containing proper time.
~numpy.ndarray – (n,8) shape array of [t, x1, x2, x3, velocity_of_time, v1, v2, v3] for each proper time(lambda).
-
calculate_trajectory_iterator
(start_lambda=0.0, stop_on_singularity=True, OdeMethodKwargs={'stepsize': 0.001}, return_cartesian=False)[source]¶ Calculate trajectory in manifold according to geodesic equation. Yields an iterator.
- Parameters
start_lambda (float) – Starting lambda, defaults to 0.0, (lambda ~= t)
stop_on_singularity (bool) – Whether to stop further computation on reaching singularity, defaults to True
OdeMethodKwargs (dict) – Kwargs to be supplied to the ODESolver, defaults to {‘stepsize’: 1e-3} Dictionary with key ‘stepsize’ along with an float value is expected.
return_cartesian (bool) – True if coordinates and velocities are required in cartesian coordinates(SI units), defaults to Falsed
- Yields
float – proper time
~numpy.ndarray – array of [t, x1, x2, x3, velocity_of_time, v1, v2, v3] for each proper time(lambda).
-
classmethod
Symbolic Relativity Module¶
This module contains the classes for performing symbolic calculations related to General Relativity.
Predefined Metrics¶
This module contains various pre-defined space-time metrics in General Relativity.
All Available Metrics¶
All the currently available pre-defined metrics are listed here.
-
einsteinpy.symbolic.predefined.vacuum_solutions.
Schwarzschild
(c=c, sch=r_s)[source]¶ Schwarzschild exterior metric in curvature coordinates Schwarzschild, Sitz. Preuss. Akad. Wiss., p189, (1916) Stephani (13.19) p157
-
einsteinpy.symbolic.predefined.vacuum_solutions.
Kerr
(c=c, sch=r_s, a=a)[source]¶ Kerr Metric in Boyer Lindquist coordinates.
- Parameters
c (Basic or int or float) – Any value to assign to speed of light. Defaults to
c
.sch (Basic or int or float) – Any value to assign to Schwarzschild Radius of the central object. Defaults to
r_s
.a (Basic or int or float) – Spin factor of the heavy body. Usually, given by
J/(Mc)
, whereJ
is the angular momentum. Defaults toa
.
This module contains pre-defined functions to obtain instances of various forms of Anti-De-Sitter and De-Sitter space-times.
-
einsteinpy.symbolic.predefined.de_sitter.
AntiDeSitter
()[source]¶ Anti-de Sitter space
Hawking and Ellis (5.9) p131
find¶
This module contains the function find to search for list of possible metrics.
Symbolic Constants Module¶
This module contains common constants used in physics/relativity and classes used to define them:
-
class
einsteinpy.symbolic.constants.
SymbolicConstant
[source]¶ This class inherits from ~sympy.core.symbol.Symbol
Constructor and Initializer
- Parameters
-
property
descriptive_name
¶ Returns the extended name of the constant
Tensor Module¶
This module contains Tensor class which serves as the base class for more specific Tensors in General Relativity:
-
class
einsteinpy.symbolic.tensor.
Tensor
(arr, config='ll')[source]¶ Base Class for Tensor manipulation
Constructor and Initializer
- Parameters
- Raises
-
property
order
¶ Returns the order of the Tensor
-
property
config
¶ Returns the configuration of covariant and contravariant indices
-
tensor
()[source]¶ Returns the sympy Array
- Returns
Sympy Array object
- Return type
ImmutableDenseNDimArray
-
subs
(*args)[source]¶ Substitute the variables/expressions in a Tensor with other sympy variables/expressions.
- Parameters
args (one argument or two argument) –
two arguments, e.g foo.subs(old, new)
one iterable argument, e.g foo.subs([(old1, new1), (old2, new2)]) for multiple substitutions at once.
- Returns
Tensor with substituted values
- Return type
-
class
einsteinpy.symbolic.tensor.
BaseRelativityTensor
(arr, syms, config='ll', parent_metric=None, variables=[], functions=[], name=None)[source]¶ Inherits from ~einsteinpy.symbolic.tensor.Tensor . Generic class for defining tensors in General Relativity. This would act as a base class for other Tensorial quantities in GR.
-
arr
¶ Raw Tensor in sympy array
- Type
ImmutableDenseNDimArray
-
variables
¶ free variables in the tensor expression other than the variables describing space-time axis.
- Type
Constructor and Initializer
- Parameters
arr (ImmutableDenseNDimArray or list) – Sympy Array or multi-dimensional list containing Sympy Expressions
syms (tuple or list) – List of crucial symbols dentoting time-axis and/or spacial axis. For example, in case of 4D space-time, the arrangement would look like [t, x1, x2, x3].
config (str) – Configuration of contravariant and covariant indices in tensor. ‘u’ for upper and ‘l’ for lower indices. Defaults to ‘ll’.
parent_metric (MetricTensor or None) – Metric Tensor for some particular space-time which is associated with this Tensor.
variables (tuple or list or set) – List of symbols used in expressing the tensor other than symbols associated with denoting the space-time axis. Calculates in real-time if left blank.
functions (tuple or list or set) – List of symbolic functions used in epressing the tensor. Calculates in real-time if left blank.
name (string) – Name of the Tensor. Defaults to None.
- Raises
TypeError – Raised when arr is not a list, sympy array or numpy array.
TypeError – Raised when config is not of type str or contains characters other than ‘l’ or ‘u’
TypeError – Raised when arguments syms, variables, functions have data type other than list, tuple or set.
TypeError – Raised when argument parent_metric does not belong to MetricTensor class and isn’t None.
-
property
parent_metric
¶ Returns the Metric from which Tensor was derived/associated, if available.
-
symbols
()[source]¶ Returns the symbols used for defining the time & spacial axis
- Returns
tuple containing (t,x1,x2,x3) in case of 4D space-time
- Return type
-
tensor_lambdify
(*args)[source]¶ Returns lambdified function of symbolic tensors. This means that the returned functions can accept numerical values and return numerical quantities.
- Parameters
*args – The variable number of arguments accept sympy symbols. The returned function accepts arguments in same order as initially defined in
*args
. Uses sympy symbols from class attributessyms
andvariables
(in the same order) if no*args
is passed Leaving*args
empty is recommended.- Returns
tuple – arguments to be passed in the returned function in exact order.
function – Lambdified function which accepts and returns numerical quantities.
-
Vector module¶
This module contains the class GenericVector to represent a vector in arbitrary space-time symbolically
-
class
einsteinpy.symbolic.vector.
GenericVector
(arr, syms, config='u', parent_metric=None)[source]¶ Inherits from ~einsteinpy.symbolic.tensor.BaseRelativityTensor. Class to represent a vector in arbitrary space-time symbolically
Constructor and Initializer
- Parameters
arr (ImmutableDenseNDimArray) – Sympy Array containing Sympy Expressions
syms (tuple or list) – Tuple of crucial symbols denoting time-axis, 1st, 2nd, and 3rd axis (t,x1,x2,x3)
config (str) – Configuration of contravariant and covariant indices in tensor. ‘u’ for upper and ‘l’ for lower indices. Defaults to ‘u’.
parent_metric (MetricTensor or None) – Corresponding Metric for the Generic Vector. Defaults to None.
- Raises
ValueError – config has more than 1 index
ValueError – Dimension should be equal to 1
-
change_config
(newconfig='u', metric=None)[source]¶ Changes the index configuration(contravariant/covariant)
- Parameters
newconfig (str) – Specify the new configuration. Defaults to ‘u’
metric (MetricTensor or None) – Parent metric tensor for changing indices. Already assumes the value of the metric tensor from which it was initialized if passed with None. Defaults to None.
- Returns
New tensor with new configuration.
- Return type
- Raises
Exception – Raised when a parent metric could not be found.
Metric Tensor Module¶
This module contains the class for defining a Metric belonging to any arbitrary space-time symbolically:
-
class
einsteinpy.symbolic.metric.
MetricTensor
(arr, syms, config='ll')[source]¶ Inherits from ~einsteinpy.symbolic.tensor.BaseRelativityTensor . Class to define a metric tensor for a space-time
Constructor and Initializer
- Parameters
arr (ImmutableDenseNDimArray or list) – Sympy Array or multi-dimensional list containing Sympy Expressions
syms (tuple or list) – Tuple of crucial symbols denoting time-axis, 1st, 2nd, and 3rd axis (t,x1,x2,x3)
config (str) – Configuration of contravariant and covariant indices in tensor. ‘u’ for upper and ‘l’ for lower indices. Defaults to ‘ll’.
- Raises
TypeError – Raised when arr is not a list or sympy Array
TypeError – syms is not a list or tuple
ValueError – config has more or less than 2 indices
-
change_config
(newconfig='uu')[source]¶ Changes the index configuration(contravariant/covariant)
- Parameters
newconfig (str) – Specify the new configuration. Defaults to ‘uu’
- Returns
New Metric with new configuration. Defaults to ‘uu’
- Return type
- Raises
ValueError – Raised when new configuration is not ‘ll’ or ‘uu’. This constraint is in place because we are dealing with Metric Tensor.
-
inv
()[source]¶ Returns the inverse of the Metric. Returns contravariant Metric if it is originally covariant or vice-versa.
- Returns
New Metric which is the inverse of original Metric.
- Return type
-
lower_config
()[source]¶ Returns a covariant instance of the given metric tensor.
- Returns
same instance if the configuration is already lower or inverse of given metric if configuration is upper
- Return type
Vacuum Solutions Module¶
This module contains various exact vacuum solutions to Einstein’s Field Equation in form of metric tensor:
-
einsteinpy.symbolic.vacuum_metrics.
SchwarzschildMetric
(symbolstr='t r theta phi')[source]¶ Returns Metric Tensor of symbols of Schwarzschild Metric.
- Parameters
symbolstr (string) – symbols to be used to define schwarzschild space, defaults to ‘t r theta phi’
- Returns
Metric Tensor for Schwarzschild space-time
- Return type
Christoffel Symbols Module¶
This module contains the class for obtaining Christoffel Symbols related to a Metric belonging to any arbitrary space-time symbolically:
-
class
einsteinpy.symbolic.christoffel.
ChristoffelSymbols
(arr, syms, config='ull', parent_metric=None)[source]¶ Inherits from ~einsteinpy.symbolic.tensor.BaseRelativityTensor . Class for defining christoffel symbols.
Constructor and Initializer
- Parameters
arr (ImmutableDenseNDimArray or list) – Sympy Array or multi-dimensional list containing Sympy Expressions
syms (tuple or list) – Tuple of crucial symbols denoting time-axis, 1st, 2nd, and 3rd axis (t,x1,x2,x3)
config (str) – Configuration of contravariant and covariant indices in tensor. ‘u’ for upper and ‘l’ for lower indices. Defaults to ‘ull’.
parent_metric (MetricTensor) – Metric Tensor from which Christoffel symbol is calculated. Defaults to None.
- Raises
TypeError – Raised when arr is not a list or sympy Array
TypeError – syms is not a list or tuple
ValueError – config has more or less than 3 indices
-
classmethod
from_metric
(metric)[source]¶ Get Christoffel symbols calculated from a metric tensor
- Parameters
metric (MetricTensor) – Space-time Metric from which Christoffel Symbols are to be calculated
-
change_config
(newconfig='lll', metric=None)[source]¶ Changes the index configuration(contravariant/covariant)
- Parameters
newconfig (str) – Specify the new configuration. Defaults to ‘lll’
metric (MetricTensor or None) – Parent metric tensor for changing indices. Already assumes the value of the metric tensor from which it was initialized if passed with None. Compulsory if not initialized with ‘from_metric’. Defaults to None.
- Returns
New tensor with new configuration. Defaults to ‘lll’
- Return type
- Raises
Exception – Raised when a parent metric could not be found.
Riemann Tensor Module¶
This module contains the class for obtaining Riemann Curvature Tensor related to a Metric belonging to any arbitrary space-time symbolically:
-
class
einsteinpy.symbolic.riemann.
RiemannCurvatureTensor
(arr, syms, config='ulll', parent_metric=None)[source]¶ Inherits from ~einsteinpy.symbolic.tensor.BaseRelativityTensor . Class for defining Riemann Curvature Tensor
Constructor and Initializer
- Parameters
arr (ImmutableDenseNDimArray or list) – Sympy Array or multi-dimensional list containing Sympy Expressions
syms (tuple or list) – Tuple of crucial symbols denoting time-axis, 1st, 2nd, and 3rd axis (t,x1,x2,x3)
config (str) – Configuration of contravariant and covariant indices in tensor. ‘u’ for upper and ‘l’ for lower indices. Defaults to ‘ulll’.
parent_metric (MetricTensor) – Metric Tensor related to this Riemann Curvature Tensor.
- Raises
TypeError – Raised when arr is not a list or sympy Array
TypeError – syms is not a list or tuple
ValueError – config has more or less than 4 indices
-
classmethod
from_christoffels
(chris, parent_metric=None)[source]¶ Get Riemann Tensor calculated from a Christoffel Symbols
- Parameters
chris (ChristoffelSymbols) – Christoffel Symbols from which Riemann Curvature Tensor to be calculated
parent_metric (MetricTensor or None) – Corresponding Metric for the Riemann Tensor. None if it should inherit the Parent Metric of Christoffel Symbols. Defaults to None.
-
classmethod
from_metric
(metric)[source]¶ Get Riemann Tensor calculated from a Metric Tensor
- Parameters
metric (MetricTensor) – Metric Tensor from which Riemann Curvature Tensor to be calculated
-
change_config
(newconfig='llll', metric=None)[source]¶ Changes the index configuration(contravariant/covariant)
- Parameters
newconfig (str) – Specify the new configuration. Defaults to ‘llll’
metric (MetricTensor or None) – Parent metric tensor for changing indices. Already assumes the value of the metric tensor from which it was initialized if passed with None. Compulsory if not initialized with ‘from_metric’. Defaults to None.
- Returns
New tensor with new configuration. Configuration defaults to ‘llll’
- Return type
- Raises
Exception – Raised when a parent metric could not be found.
Ricci Module¶
This module contains the basic classes for obtaining Ricci Tensor and Ricci Scalar related to a Metric belonging to any arbitrary space-time symbolically:
-
class
einsteinpy.symbolic.ricci.
RicciTensor
(arr, syms, config='ll', parent_metric=None)[source]¶ Inherits from ~einsteinpy.symbolic.tensor.BaseRelativityTensor . Class for defining Ricci Tensor
Constructor and Initializer
- Parameters
arr (ImmutableDenseNDimArray or list) – Sympy Array or multi-dimensional list containing Sympy Expressions
syms (tuple or list) – Tuple of crucial symbols denoting time-axis, 1st, 2nd, and 3rd axis (t,x1,x2,x3)
config (str) – Configuration of contravariant and covariant indices in tensor. ‘u’ for upper and ‘l’ for lower indices. Defaults to ‘ll’.
parent_metric (MetricTensor or None) – Corresponding Metric for the Ricci Tensor. Defaults to None.
- Raises
TypeError – Raised when arr is not a list or sympy Array
TypeError – syms is not a list or tuple
ValueError – config has more or less than 2 indices
-
classmethod
from_riemann
(riemann, parent_metric=None)[source]¶ Get Ricci Tensor calculated from Riemann Tensor
- Parameters
riemann (RiemannCurvatureTensor) – Riemann Tensor
parent_metric (MetricTensor or None) – Corresponding Metric for the Ricci Tensor. None if it should inherit the Parent Metric of Riemann Tensor. Defaults to None.
-
classmethod
from_christoffels
(chris, parent_metric=None)[source]¶ Get Ricci Tensor calculated from Christoffel Tensor
- Parameters
chris (ChristoffelSymbols) – Christoffel Tensor
parent_metric (MetricTensor or None) – Corresponding Metric for the Ricci Tensor. None if it should inherit the Parent Metric of Christoffel Symbols. Defaults to None.
-
classmethod
from_metric
(metric)[source]¶ Get Ricci Tensor calculated from Metric Tensor
- Parameters
metric (MetricTensor) – Metric Tensor
-
change_config
(newconfig='ul', metric=None)[source]¶ Changes the index configuration(contravariant/covariant)
- Parameters
newconfig (str) – Specify the new configuration. Defaults to ‘ul’
metric (MetricTensor or None) – Parent metric tensor for changing indices. Already assumes the value of the metric tensor from which it was initialized if passed with None. Compulsory if somehow does not have a parent metric. Defaults to None.
- Returns
New tensor with new configuration. Defaults to ‘ul’
- Return type
- Raises
Exception – Raised when a parent metric could not be found.
-
class
einsteinpy.symbolic.ricci.
RicciScalar
(arr, syms, parent_metric=None)[source]¶ Inherits from ~einsteinpy.symbolic.tensor.BaseRelativityTensor Class for defining Ricci Scalar
Constructor and Initializer
- Parameters
arr (ImmutableDenseNDimArray or list) – Sympy Array, multi-dimensional list containing Sympy Expressions, or Sympy Expressions or int or float scalar
syms (tuple or list) – Tuple of crucial symbols denoting time-axis, 1st, 2nd, and 3rd axis (t,x1,x2,x3)
parent_metric (MetricTensor or None) – Corresponding Metric for the Ricci Scalar. Defaults to None.
- Raises
TypeError – Raised when syms is not a list or tuple
-
property
expr
¶ Retuns the symbolic expression of the Ricci Scalar
-
classmethod
from_riccitensor
(riccitensor, parent_metric=None)[source]¶ Get Ricci Scalar calculated from Ricci Tensor
- Parameters
riccitensor (RicciTensor) – Ricci Tensor
parent_metric (MetricTensor or None) – Corresponding Metric for the Ricci Scalar. Defaults to None.
-
classmethod
from_riemann
(riemann, parent_metric=None)[source]¶ Get Ricci Scalar calculated from Riemann Tensor
- Parameters
riemann (RiemannCurvatureTensor) – Riemann Tensor
parent_metric (MetricTensor or None) – Corresponding Metric for the Ricci Scalar. Defaults to None.
-
classmethod
from_christoffels
(chris, parent_metric=None)[source]¶ Get Ricci Scalar calculated from Christoffel Tensor
- Parameters
chris (ChristoffelSymbols) – Christoffel Tensor
parent_metric (MetricTensor or None) – Corresponding Metric for the Ricci Scalar. Defaults to None.
-
classmethod
from_metric
(metric)[source]¶ Get Ricci Scalar calculated from Metric Tensor
- Parameters
metric (MetricTensor) – Metric Tensor
Einstein Tensor Module¶
This module contains the class for obtaining Einstein Tensor related to a Metric belonging to any arbitrary space-time symbolically:
-
class
einsteinpy.symbolic.einstein.
EinsteinTensor
(arr, syms, config='ll', parent_metric=None)[source]¶ Inherits from ~einsteinpy.symbolic.tensor.BaseRelativityTensor . Class for defining Einstein Tensor
Constructor and Initializer
- Parameters
arr (ImmutableDenseNDimArray or list) – Sympy Array or multi-dimensional list containing Sympy Expressions
syms (tuple or list) – Tuple of crucial symbols denoting time-axis, 1st, 2nd, and 3rd axis (t,x1,x2,x3)
config (str) – Configuration of contravariant and covariant indices in tensor. ‘u’ for upper and ‘l’ for lower indices. Defaults to ‘ll’.
parent_metric (MetricTensor or None) – Corresponding Metric for the Einstein Tensor. Defaults to None.
- Raises
TypeError – Raised when arr is not a list or sympy Array
TypeError – syms is not a list or tuple
ValueError – config has more or less than 2 indices
-
change_config
(newconfig='ul', metric=None)[source]¶ Changes the index configuration(contravariant/covariant)
- Parameters
newconfig (str) – Specify the new configuration. Defaults to ‘ul’
metric (MetricTensor or None) – Parent metric tensor for changing indices. Already assumes the value of the metric tensor from which it was initialized if passed with None. Compulsory if somehow does not have a parent metric. Defaults to None.
- Returns
New tensor with new configuration. Defaults to ‘ul’
- Return type
- Raises
Exception – Raised when a parent metric could not be found.
Stress Energy Momentum Tensor Module¶
This module contains the class for obtaining Stress Energy Momentum Tensor related to a Metric belonging to any arbitrary space-time symbolically:
-
class
einsteinpy.symbolic.stress_energy_momentum.
StressEnergyMomentumTensor
(arr, syms, config='ll', parent_metric=None)[source]¶ Inherits from ~einsteinpy.symbolic.tensor.BaseRelativityTensor Class for defining Stress-Energy Coefficient Tensor
Constructor and Initializer
- Parameters
arr (ImmutableDenseNDimArray or list) – Sympy Array or multi-dimensional list containing Sympy Expressions
syms (tuple or list) – Tuple of crucial symbols denoting time-axis, 1st, 2nd, and 3rd axis (t,x1,x2,x3)
config (str) – Configuration of contravariant and covariant indices in tensor. ‘u’ for upper and ‘l’ for lower indices. Defaults to ‘ll’.
parent_metric (MetricTensor or None) – Corresponding Metric for the Stress-Energy Coefficient Tensor. Defaults to None.
- Raises
TypeError – Raised when arr is not a list or sympy Array
TypeError – syms is not a list or tuple
ValueError – config has more or less than 2 indices
-
change_config
(newconfig='ul', metric=None)[source]¶ Changes the index configuration(contravariant/covariant)
- Parameters
newconfig (str) – Specify the new configuration. Defaults to ‘ul’
metric (MetricTensor or None) – Parent metric tensor for changing indices. Already assumes the value of the metric tensor from which it was initialized if passed with None. Compulsory if somehow does not have a parent metric. Defaults to None.
- Returns
New tensor with new configuration. Defaults to ‘ul’
- Return type
- Raises
Exception – Raised when a parent metric could not be found.
Weyl Tensor Module¶
This module contains the class for obtaining Weyl Tensor related to a Metric belonging to any arbitrary space-time symbolically:
-
class
einsteinpy.symbolic.weyl.
WeylTensor
(arr, syms, config='ulll', parent_metric=None)[source]¶ Inherits from ~einsteinpy.symbolic.tensor.BaseRelativityTensor . Class for defining Weyl Tensor
Constructor and Initializer
- Parameters
arr (ImmutableDenseNDimArray or list) – Sympy Array or multi-dimensional list containing Sympy Expressions
syms (tuple or list) – Tuple of crucial symbols denoting time-axis, 1st, 2nd, and 3rd axis (t,x1,x2,x3)
config (str) – Configuration of contravariant and covariant indices in tensor. ‘u’ for upper and ‘l’ for lower indices. Defaults to ‘ulll’.
parent_metric (WeylTensor) – Corresponding Metric for the Weyl Tensor. Defaults to None.
- Raises
TypeError – Raised when arr is not a list or sympy Array
TypeError – syms is not a list or tuple
ValueError – config has more or less than 4 indices
-
classmethod
from_metric
(metric)[source]¶ Get Weyl tensor calculated from a metric tensor
- Parameters
metric (MetricTensor) – Space-time Metric from which Christoffel Symbols are to be calculated
- Raises
ValueError – Raised when the dimension of the tensor is less than 3
-
change_config
(newconfig='llll', metric=None)[source]¶ Changes the index configuration(contravariant/covariant)
- Parameters
newconfig (str) – Specify the new configuration. Defaults to ‘llll’
metric (MetricTensor or None) – Parent metric tensor for changing indices. Already assumes the value of the metric tensor from which it was initialized if passed with None. Compulsory if not initialized with ‘from_metric’. Defaults to None.
- Returns
New tensor with new configuration. Configuration defaults to ‘llll’
- Return type
- Raises
Exception – Raised when a parent metric could not be found.
Schouten Module¶
This module contains the basic classes for obtaining Schouten Tensor related to a Metric belonging to any arbitrary space-time symbolically:
-
class
einsteinpy.symbolic.schouten.
SchoutenTensor
(arr, syms, config='ll', parent_metric=None)[source]¶ Inherits from ~einsteinpy.symbolic.tensor.BaseRelativityTensor . Class for defining Schouten Tensor
Constructor and Initializer
- Parameters
arr (ImmutableDenseNDimArray or list) – Sympy Array or multi-dimensional list containing Sympy Expressions
syms (tuple or list) – Tuple of crucial symbols denoting time-axis, 1st, 2nd, and 3rd axis (t,x1,x2,x3)
config (str) – Configuration of contravariant and covariant indices in tensor. ‘u’ for upper and ‘l’ for lower indices. Defaults to ‘ll’.
parent_metric (MetricTensor) – Corresponding Metric for the Schouten Tensor. Defaults to None.
- Raises
TypeError – Raised when arr is not a list or sympy Array
TypeError – syms is not a list or tuple
ValueError – config has more or less than 2 indices
-
classmethod
from_metric
(metric)[source]¶ Get Schouten tensor calculated from a metric tensor
- Parameters
metric (MetricTensor) – Space-time Metric from which Christoffel Symbols are to be calculated
- Raises
ValueError – Raised when the dimension of the tensor is less than 3
-
change_config
(newconfig='ul', metric=None)[source]¶ Changes the index configuration(contravariant/covariant)
- Parameters
newconfig (str) – Specify the new configuration. Defaults to ‘ul’
metric (MetricTensor or None) – Parent metric tensor for changing indices. Already assumes the value of the metric tensor from which it was initialized if passed with None. Compulsory if not initialized with ‘from_metric’. Defaults to None.
- Returns
New tensor with new configuration. Configuration defaults to ‘ul’
- Return type
- Raises
Exception – Raised when a parent metric could not be found.
Hypersurface module¶
This module contains Classes to calculate and plot hypersurfaces of various geometries.
Schwarzschild Embedding Module¶
Class for Utility functions for Schwarzschild Embedding surface to implement gravitational lensing:
-
class
einsteinpy.hypersurface.schwarzschildembedding.
SchwarzschildEmbedding
(M)[source]¶ Class for Utility functions for Schwarzschild Embedding surface to implement gravitational lensing
-
r_init
¶ - Type
m
Constructor Initialize mass and embedding initial radial coordinate in appropiate units in order to render the plots of the surface in finite grid. The initial r is taken to be just greater than schwarzschild radius but it is important to note that the embedding breaks at r < 9m/4.
- Parameters
M (kg) – Mass of the body
-
gradient
(r)[source]¶ Calculate gradient of Z coordinate w.r.t r to update the value of r and thereby get value of spherical radial coordinate R.
-
radial_coord
(r)[source]¶ Returns spherical radial coordinate (of the embedding) from given schwarzschild coordinate.
-
get_values
(alpha)[source]¶ Obtain the Z coordinate values and corrosponding R values for range of r as 9m/4 < r < 9m.
-
Rays module¶
This module contains Classes to calculate and plot trajectories and other interactions of light with heavy objects.
Utils module¶
The common utilities of the project are included in this module. This includes easy methods for calculation of the schwartzschild radius, calculation of the rate of expansion of the universe, velocity of time etc.
Scalar Factor¶
-
einsteinpy.utils.scalar_factor.
scalar_factor
(t, era='md', tuning_param=1.0)[source]¶ Acceleration of the universe in cosmological models of Robertson Walker Flat Universe.
- Parameters
era (string) – Can be chosen from ‘md’ (Matter Dominant), ‘rd’ (Radiation Dominant) and ‘ded’ (Dark Energy Dominant)
t (s) – Time for the event
tuning_param (float, optional) – Unit scaling factor, defaults to 1
- Returns
Value of scalar factor at time t.
- Return type
:raises ValueError : If era is not ‘md’ , ‘rd’, and ‘ded’.:
-
einsteinpy.utils.scalar_factor.
scalar_factor_derivative
(t, era='md', tuning_param=1.0)[source]¶ Derivative of acceleration of the universe in cosmological models of Robertson Walker Flat Universe.
- Parameters
era (string) – Can be chosen from ‘md’ (Matter Dominant), ‘rd’ (Radiation Dominant) and ‘ded’ (Dark Energy Dominant)
t (s) – Time for the event
tuning_param (float, optional) – Unit scaling factor, defaults to 1
- Returns
Value of derivative of scalar factor at time t.
- Return type
:raises ValueError : If era is not ‘md’ , ‘rd’, and ‘ded’.:
Schwarzschild Geometry Utilities¶
-
einsteinpy.utils.schwarzschild_utils.
schwarzschild_radius
(mass, c=<<class 'astropy.constants.codata2018.CODATA2018'> name='Speed of light in vacuum' value=299792458.0 uncertainty=0.0 unit='m / s' reference='CODATA 2018'>, G=<<class 'astropy.constants.codata2018.CODATA2018'> name='Gravitational constant' value=6.6743e-11 uncertainty=1.5e-15 unit='m3 / (kg s2)' reference='CODATA 2018'>)[source]¶ Schwarzschild radius is the radius defining the event horizon of a Schwarzschild black hole. It is characteristic radius associated with every quantity of mass.
- Parameters
mass (kg) –
- Returns
r – Schwarzschild radius for a given mass
- Return type
m
-
einsteinpy.utils.schwarzschild_utils.
schwarzschild_radius_dimensionless
(M, c=299792458.0, G=6.6743e-11)[source]¶
-
einsteinpy.utils.schwarzschild_utils.
time_velocity
(pos_vec, vel_vec, mass)[source]¶ Velocity of time calculated from einstein’s equation. See http://www.physics.usu.edu/Wheeler/GenRel/Lectures/GRNotesDecSchwarzschildGeodesicsPost.pdf
- Parameters
pos_vector (array) – Vector with r, theta, phi components in SI units
vel_vector (array) – Vector with velocities of r, theta, phi components in SI units
mass (kg) – Mass of the body
- Returns
Velocity of time
- Return type
one
-
einsteinpy.utils.schwarzschild_utils.
metric
(r, theta, M, c=299792458.0, G=6.6743e-11)[source]¶ Returns the Schwarzschild Metric
Kerr Geometry Utilities¶
-
einsteinpy.utils.kerr_utils.
nonzero_christoffels_list
= [(0, 0, 1), (0, 0, 2), (0, 1, 3), (0, 2, 3), (0, 1, 0), (0, 2, 0), (0, 3, 1), (0, 3, 2), (1, 0, 0), (1, 1, 1), (1, 2, 2), (1, 3, 3), (2, 0, 0), (2, 1, 1), (2, 2, 2), (2, 3, 3), (1, 0, 3), (1, 1, 2), (2, 0, 3), (2, 1, 2), (1, 2, 1), (1, 3, 0), (2, 2, 1), (2, 3, 0), (3, 0, 1), (3, 0, 2), (3, 1, 0), (3, 1, 3), (3, 2, 0), (3, 2, 3), (3, 3, 1), (3, 3, 2)]¶ Precomputed list of tuples consisting of indices of christoffel symbols which are non-zero in Kerr Metric
-
einsteinpy.utils.kerr_utils.
scaled_spin_factor
(a, M, c=299792458.0, G=6.6743e-11)[source]¶ Returns a scaled version of spin factor(a)
- Parameters
- Returns
Scaled spinf factor to consider changed units
- Return type
- Raises
ValueError – If a not between 0 & 1
-
einsteinpy.utils.kerr_utils.
sigma
(r, theta, a)[source]¶ Returns the value r^2 + a^2 * cos^2(theta) Specific to Boyer-Lindquist coordinates
-
einsteinpy.utils.kerr_utils.
delta
(r, M, a, c=299792458.0, G=6.6743e-11)[source]¶ Returns the value r^2 - Rs * r + a^2 Specific to Boyer-Lindquist coordinates
-
einsteinpy.utils.kerr_utils.
metric
(r, theta, M, a, c=299792458.0, G=6.6743e-11)[source]¶ Returns the Kerr Metric
-
einsteinpy.utils.kerr_utils.
metric_inv
(r, theta, M, a, c=299792458.0, G=6.6743e-11)[source]¶ Returns the inverse of Kerr Metric
-
einsteinpy.utils.kerr_utils.
dmetric_dx
(r, theta, M, a, c=299792458.0, G=6.6743e-11)[source]¶ Returns differentiation of each component of Kerr metric tensor w.r.t. t, r, theta, phi
- Parameters
- Returns
dmdx – Numpy array of shape (4,4,4) dmdx[0], dmdx[1], dmdx[2] & dmdx[3] is differentiation of metric w.r.t. t, r, theta & phi respectively
- Return type
array
-
einsteinpy.utils.kerr_utils.
christoffels
(r, theta, M, a, c=299792458.0, G=6.6743e-11)[source]¶ Returns the 3rd rank Tensor containing Christoffel Symbols for Kerr Metric
-
einsteinpy.utils.kerr_utils.
kerr_time_velocity
(pos_vec, vel_vec, mass, a)[source]¶ Velocity of coordinate time wrt proper metric
- Parameters
pos_vector (array) – Vector with r, theta, phi components in SI units
vel_vector (array) – Vector with velocities of r, theta, phi components in SI units
mass (kg) – Mass of the body
a (float) – Any constant
- Returns
Velocity of time
- Return type
one
-
einsteinpy.utils.kerr_utils.
nonzero_christoffels
()[source]¶ Returns a list of tuples consisting of indices of christoffel symbols which are non-zero in Kerr Metric computed in real-time.
- Returns
List of tuples each tuple (i,j,k) represent christoffel symbol with i as upper index and j,k as lower indices.
- Return type
-
einsteinpy.utils.kerr_utils.
event_horizon
(M, a, theta=1.5707963267948966, coord='BL', c=299792458.0, G=6.6743e-11)[source]¶ Calculate the radius of event horizon of Kerr black hole
- Parameters
M (float) – Mass of massive body
a (float) – Black hole spin factor
theta (float) – Angle from z-axis in Boyer-Lindquist coordinates in radians. Mandatory for coord==’Spherical’. Defaults to pi/2.
coord (str) – Output coordinate system. ‘BL’ for Boyer-Lindquist & ‘Spherical’ for spherical. Defaults to ‘BL’.
- Returns
[Radius of event horizon(R), angle from z axis(theta)] in BL/Spherical coordinates
- Return type
array
-
einsteinpy.utils.kerr_utils.
radius_ergosphere
(M, a, theta=1.5707963267948966, coord='BL', c=299792458.0, G=6.6743e-11)[source]¶ Calculate the radius of ergospere of Kerr black hole at a specific azimuthal angle
- Parameters
- Returns
[Radius of ergosphere(R), angle from z axis(theta)] in BL/Spherical coordinates
- Return type
array
Kerr-Newman Geometry Utilities¶
-
einsteinpy.utils.kerrnewman_utils.
nonzero_christoffels_list
= [(0, 0, 1), (0, 0, 2), (0, 1, 3), (0, 2, 3), (0, 1, 0), (0, 2, 0), (0, 3, 1), (0, 3, 2), (1, 0, 0), (1, 1, 1), (1, 2, 2), (1, 3, 3), (2, 0, 0), (2, 1, 1), (2, 2, 2), (2, 3, 3), (1, 0, 3), (1, 1, 2), (2, 0, 3), (2, 1, 2), (1, 2, 1), (1, 3, 0), (2, 2, 1), (2, 3, 0), (3, 0, 1), (3, 0, 2), (3, 1, 0), (3, 1, 3), (3, 2, 0), (3, 2, 3), (3, 3, 1), (3, 3, 2)]¶ Precomputed list of tuples consisting of indices of christoffel symbols which are non-zero in Kerr-Newman Metric
-
einsteinpy.utils.kerrnewman_utils.
charge_length_scale
(Q, c=299792458.0, G=6.6743e-11, Cc=8987551792.261171)[source]¶ Returns a length scale corrosponding to the Electric Charge Q of the mass
- Parameters
- Returns
returns (coulomb’s constant^0.5)*(Q/c^2)*G^0.5
- Return type
-
einsteinpy.utils.kerrnewman_utils.
rho
(r, theta, a)[source]¶ Returns the value sqrt(r^2 + a^2 * cos^2(theta)). Specific to Boyer-Lindquist coordinates
-
einsteinpy.utils.kerrnewman_utils.
delta
(r, M, a, Q, c=299792458.0, G=6.6743e-11, Cc=8987551792.261171)[source]¶ Returns the value r^2 - Rs * r + a^2 Specific to Boyer-Lindquist coordinates
- Parameters
- Returns
The value r^2 - Rs * r + a^2 + Rq^2
- Return type
-
einsteinpy.utils.kerrnewman_utils.
metric
(r, theta, M, a, Q, c=299792458.0, G=6.6743e-11, Cc=8987551792.261171)[source]¶ Returns the Kerr-Newman Metric
- Parameters
- Returns
Numpy array of shape (4,4)
- Return type
array
-
einsteinpy.utils.kerrnewman_utils.
metric_inv
(r, theta, M, a, Q, c=299792458.0, G=6.6743e-11, Cc=8987551792.261171)[source]¶ Returns the inverse of Kerr-Newman Metric
- Parameters
- Returns
Numpy array of shape (4,4)
- Return type
array
-
einsteinpy.utils.kerrnewman_utils.
dmetric_dx
(r, theta, M, a, Q, c=299792458.0, G=6.6743e-11, Cc=8987551792.261171)[source]¶ Returns differentiation of each component of Kerr-Newman metric tensor w.r.t. t, r, theta, phi
- Parameters
- Returns
dmdx – Numpy array of shape (4,4,4) dmdx[0], dmdx[1], dmdx[2] & dmdx[3] is differentiation of metric w.r.t. t, r, theta & phi respectively
- Return type
array
-
einsteinpy.utils.kerrnewman_utils.
christoffels
(r, theta, M, a, Q, c=299792458.0, G=6.6743e-11, Cc=8987551792.261171)[source]¶ Returns the 3rd rank Tensor containing Christoffel Symbols for Kerr-Newman Metric
- Parameters
- Returns
Numpy array of shape (4,4,4)
- Return type
array
-
einsteinpy.utils.kerrnewman_utils.
em_potential
(r, theta, a, Q, M, c=299792458.0, G=6.6743e-11, Cc=8987551792.261171)[source]¶ Returns a 4-d vector(for each component of 4-d space-time) containing the electromagnetic potential around a Kerr-Newman body
- Parameters
- Returns
Numpy array of shape (4,)
- Return type
array
-
einsteinpy.utils.kerrnewman_utils.
maxwell_tensor_covariant
(r, theta, a, Q, M, c=299792458.0, G=6.6743e-11, Cc=8987551792.261171)[source]¶ Returns a 2nd rank Tensor containing Maxwell Tensor with lower indices for Kerr-Newman Metric
- Parameters
- Returns
Numpy array of shape (4,4)
- Return type
array
-
einsteinpy.utils.kerrnewman_utils.
maxwell_tensor_contravariant
(r, theta, a, Q, M, c=299792458.0, G=6.6743e-11, Cc=8987551792.261171)[source]¶ Returns a 2nd rank Tensor containing Maxwell Tensor with upper indices for Kerr-Newman Metric
- Parameters
- Returns
Numpy array of shape (4,4)
- Return type
array
-
einsteinpy.utils.kerrnewman_utils.
kerrnewman_time_velocity
(pos_vec, vel_vec, mass, a, Q)[source]¶ Velocity of coordinate time wrt proper metric
- Parameters
pos_vector (array) – Vector with r, theta, phi components in SI units
vel_vector (array) – Vector with velocities of r, theta, phi components in SI units
mass (kg) – Mass of the body
a (float) – Any constant
Q (C) – Charge on the massive body
- Returns
Velocity of time
- Return type
one
Plotting module¶
This module contains the basic classes for static and interactive 3-D and 2-D geodesic, hypersurface and shadow plotting modules.
Geodesics Plotting module¶
This module contains Classes to plot geodesics.
Core plotting module¶
This module contains the advanced backend switching while plotting.
Interactive plotting module¶
This module contains interactive plotting backend.
Interactive plotting module¶
This module contains static plotting backend.
Hypersurface plotting module¶
This module contains the hypersurface plotting.
Rays Plotting module¶
This module contains classes and sub-modules for light interactions with heavy bodies.
Shadow plotting module¶
This module contains the black hole shadow plotting class.
-
class
einsteinpy.plotting.rays.shadow.
ShadowPlotter
(shadow, is_line_plot=True)[source]¶ Class for plotting and visualising shadows
Constructor for plotter.
- Parameters
embedding (Shadow) – The shadow object
is_line_plot (bool, optional) – If the plot is a line plot or a contour plot. Defaults to True.
Static Geodesic Plotting¶
This module contains the methods for static geodesic plotting.
-
class
einsteinpy.plotting.senile.geodesics_static.
StaticGeodesicPlotter
(time=<Quantity 0. s>, ax=None, attractor_radius_scale=-1.0, attractor_color='#ffcc00')[source]¶ Class for plotting static matplotlib plots and animations.
Constructor.
- Parameters
time (Quantity) – Time of start, defaults to 0 seconds.
attractor_radius_scale (float, optional) – Scales the attractor radius by the value given. Default is 1. It is used to make plots look more clear if needed.
attractor_color (string, optional) – Color which is used to denote the attractor. Defaults to #ffcc00.
-
plot_trajectory
(geodesic, color, only_points=False)[source]¶ - Parameters
geodesic (Geodesic) – Geodesic of the body.
color (string) – Color of the Geodesic
Auto and Manual scaling¶
EinsteinPy supports Automatic and Manual scaling of the attractor to make plots look better since radius of attractor can be really small and not visible.
- Manual_Scaling :
If the user provides the attractor_radius_scale, then the autoscaling will not work. This is checked by initialising the attractor_radius_scale by -1 and if the user enters the value then it will be >0 so the value won’t remain -1 which is easily checked.
The radius is multiplied to the value given in attractor_radius_scale
radius = radius * self.attractor_radius_scale
- Auto Scaling :
If the user does not provide the attractor_radius_scale, the value will be initialised to -1 and then we will call the auto scaling function. In autoscaling, the attractor radius is first initialised to the minimum distance between the attractor and the object moving around it. Now, if this radius is greater than the 1/12th of minimum of range of X and Y coordinates then, the radius is initialised to this minimum. This is done so that the plots are easy to look at.
minrad_nooverlap : Stores the minimum distance between the particle and attractor .. code-block:: python
- for i in range(0, len(self.xarr)):
minrad_nooverlap = min( minrad_nooverlap, self.mindist(self.xarr[i], self.yarr[i]))
minlen_plot : Stores the minimum of range of X and Y axis
xlen = max(self.xarr) - min(self.xarr) ylen = max(self.yarr) - min(self.yarr) minlen_plot = min(xlen, ylen)
multiplier : Stores the value which is multiplied to the radius to make it 1/12th of the minlenplot
mulitplier = minlen_plot / (12 * radius) min_radius = radius * mulitplier
Attractor Color¶
- Color Options :
User can give the color to attractor of his/her choice. It can be passed while calling the geodesics_static class. Default color of attractor is “black”.
self.attractor_color = attractor_color mpl.patches.Circle( (0, 0), radius.value, lw=0, color=self.attractor_color)
Static Geodesic Plotting (Scatter Plots)¶
This module contains the basic classes for static plottings in 2-dimensions for scatter and line:
Color¶
- Attractor :
User can give the color to attractor of his/her choice. It can be passed while making the object of geodesics_static class. Default color of attractor is “black”.
self.attractor_color = attractor_color plt.scatter(0, 0, color=self.attractor_color)
- Geodesic :
User can give the color to the orbit of the particle moving around the attractor of his/her choice. It can be passed while making the object of geodesics_scatter class. Default color is “Oranges”.
self.cmap_color = cmap_color plt.scatter(pos_x, pos_y, s=1, c=time, cmap=self.cmap_color)
This module contains the methods for static geodesic plotting using scatter plots.
-
class
einsteinpy.plotting.senile.geodesics_scatter.
ScatterGeodesicPlotter
(time=<Quantity 0. s>, attractor_color='black', cmap_color='Oranges')[source]¶ Class for plotting static matplotlib plots.
Constructor.
- Parameters
time (Quantity) – Time of start, defaults to 0 seconds.
attractor_color (string, optional) – Color which is used to denote the attractor. Defaults to black.
cmap_color (string, optional) – Color used in function plot.
Coordinates module¶
This module contains the classes for various coordinate systems and their position and velocity transformations.
core module¶
This module contains the basic classes for coordinate systems and their position transformation:
-
class
einsteinpy.coordinates.core.
Cartesian
(x, y, z)[source]¶ Class for Cartesian Coordinates and related transformations.
Constructor.
-
si_values
()[source]¶ Function for returning values in SI units.
- Returns
Array containing values in SI units (m, m, m)
- Return type
-
norm
()[source]¶ Function for finding euclidean norm of a vector.
- Returns
Euclidean norm with units.
- Return type
-
dot
(target)[source]¶ Dot product of two vectors.
- Parameters
target (Cartesian) –
- Returns
Dot product with units
- Return type
-
to_spherical
()[source]¶ Method for conversion to spherical coordinates.
- Returns
Spherical representation of the Cartesian Coordinates.
- Return type
-
-
class
einsteinpy.coordinates.core.
Spherical
(r, theta, phi)[source]¶ Class for Spherical Coordinates and related transformations.
Constructor.
-
si_values
()[source]¶ Function for returning values in SI units.
- Returns
Array containing values in SI units (m, rad, rad)
- Return type
-
to_cartesian
()[source]¶ Method for conversion to cartesian coordinates.
- Returns
Cartesian representation of the Spherical Coordinates.
- Return type
-
-
class
einsteinpy.coordinates.core.
BoyerLindquist
(r, theta, phi, a)[source]¶ Class for Spherical Coordinates and related transformations.
Constructor.
-
si_values
()[source]¶ Function for returning values in SI units.
- Returns
Array containing values in SI units (m, rad, rad)
- Return type
-
velocity module¶
This module contains the basic classes for time differentials of coordinate systems and the transformations:
-
class
einsteinpy.coordinates.velocity.
CartesianDifferential
(x, y, z, v_x, v_y, v_z)[source]¶ Class for calculating and transforming the velocity in Cartesian coordinates.
Constructor.
- Parameters
-
si_values
()[source]¶ Function for returning values in SI units.
- Returns
Array containing values in SI units (m, m, m, m/s, m/s, m/s)
- Return type
-
spherical_differential
()[source]¶ Function to convert velocity to spherical coordinates velocity
- Returns
Spherical representation of the velocity in Cartesian Coordinates.
- Return type
-
class
einsteinpy.coordinates.velocity.
SphericalDifferential
(r, theta, phi, v_r, v_t, v_p)[source]¶ Class for calculating and transforming the velocity in Spherical coordinates.
Constructor.
- Parameters
-
si_values
()[source]¶ Function for returning values in SI units.
- Returns
Array containing values in SI units (m, rad, rad, m/s, rad/s, rad/s)
- Return type
-
cartesian_differential
()[source]¶ Function to convert velocity to cartesian coordinates
- Returns
Cartesian representation of the velocity in Spherical Coordinates.
- Return type
-
class
einsteinpy.coordinates.velocity.
BoyerLindquistDifferential
(r, theta, phi, v_r, v_t, v_p, a)[source]¶ Class for calculating and transforming the velocity in Boyer-Lindquist coordinates
Constructor.
- Parameters
-
si_values
()[source]¶ Function for returning values in SI units.
- Returns
Array containing values in SI units (m, rad, rad, m/s, rad/s, rad/s)
- Return type
-
cartesian_differential
()[source]¶ Function to convert velocity to cartesian coordinates
- Returns
Cartesian representation of the velocity in Boyer-Lindquist Coordinates.
- Return type
Constant module¶
Units module¶
Bodies module¶
Important Bodies.
Contains some predefined bodies of the Solar System:
* Sun (☉)
* Earth (♁)
* Moon (☾)
* Mercury (☿)
* Venus (♀)
* Mars (♂)
* Jupiter (♃)
* Saturn (♄)
* Uranus (⛢)
* Neptune (♆)
* Pluto (♇)
and a way to define new bodies (Body
class).
Data references can be found in constant
-
class
einsteinpy.bodies.
Body
(name='Generic Body', mass=<Quantity 0. kg>, R=<Quantity 0. km>, differential=None, a=<Quantity 0. m>, q=<Quantity 0. C>, parent=None)[source]¶ Class to create a generic Body
- Parameters
name (str) – Name/ID of the body
mass (kg) – Mass of the body
R (units) – Radius of the body
differential (coordinates, optional) – Complete coordinates of the body
a (m, optional) – Spin factor of massive body. Should be less than half of schwarzschild radius.
q (C, optional) – Charge on the massive body
is_attractor (Bool, optional) – To denote is this body is acting as attractor or not
parent (Body, optional) – The parent object of the body.
Geodesic module¶
In differential geometry, a geodesic is a curve representing in some sense the shortest path between two points in a surface.
-
class
einsteinpy.geodesic.
Geodesic
(body, end_lambda, step_size=0.001, time=<Quantity 0. s>, metric=<class 'einsteinpy.metric.schwarzschild.Schwarzschild'>)[source]¶ Class for defining geodesics of different geometries.
- Parameters
body (Body) – Test particle for which geodesics is to be calculated.
end_lambda (float) – Lambda(proper time in seconds) where iterations will stop
step_size (float, optional) – Size of each increment in proper time. Defaults to
1e-3
.time (s, optional) – Time of start, Defaults to 0 seconds.
a (m, optional) – Spin factor of massive body. Should be less than half of schwarzschild radius.
q (C, optional) – Charge on the massive body
parent (Body, optional) – The parent object of the body.
metric (Schwarzschild or Kerr or KerrNewman, optional) – Class of the spacetime metric in which geodesics are to be calculated. Defaults to
Schwarzschild
.
Code of Conduct¶
The community of participants in einsteinpy is made up of members from around the globe with a diverse set of skills, personalities, and experiences. It is through these differences that our community experiences success and continued growth. We expect everyone in our community to follow these guidelines when interacting with others both inside and outside of our community. Our goal is to keep ours a positive, inclusive, successful, and growing community.
As members of the community,
We pledge to treat all people with respect and provide a harassment- and bullying-free environment, regardless of sex, sexual orientation and/or gender identity, disability, physical appearance, body size, race, nationality, ethnicity, and religion. In particular, sexual language and imagery, sexist, racist, or otherwise exclusionary jokes are not appropriate.
We pledge to respect the work of others by recognizing acknowledgment/citation requests of original authors. As authors, we pledge to be explicit about how we want our own work to be cited or acknowledged.
We pledge to welcome those interested in joining the community, and realize that including people with a variety of opinions and backgrounds will only serve to enrich our community. In particular, discussions relating to pros/cons of various technologies, programming languages, and so on are welcome, but these should be done with respect, taking proactive measure to ensure that all participants are heard and feel confident that they can freely express their opinions.
We pledge to welcome questions and answer them respectfully, paying particular attention to those new to the community. We pledge to provide respectful criticisms and feedback in forums, especially in discussion threads resulting from code contributions.
We pledge to be conscientious of the perceptions of the wider community and to respond to criticism respectfully. We will strive to model behaviors that encourage productive debate and disagreement, both within our community and where we are criticized. We will treat those outside our community with the same respect as people within our community.
We pledge to help the entire community follow the code of conduct, and to not remain silent when we see violations of the code of conduct. We will take action when members of our community violate this code such as contacting shreyas@einsteinpy.org (all emails sent to this address will be treated with the strictest confidence) or talking privately with the person.
This code of conduct applies to all community situations online and offline, including mailing lists, forums, social media, conferences, meetings, associated social events, and one-to-one interactions.
Parts of this code of conduct have been adapted from the Astropy code of conduct.
The Code of Conduct for the einsteinpy community is licensed under a Creative Commons Attribution 4.0 International License. We encourage other communities related to ours to use or adapt this code as they see fit.