Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions DIRECTORY.md
Original file line numberDiff line numberDiff line change
Expand Up@@ -557,6 +557,7 @@
* [Gamma Recursive](maths/gamma_recursive.py)
* [Gaussian](maths/gaussian.py)
* [Gaussian Error Linear Unit](maths/gaussian_error_linear_unit.py)
* [Gcd Of N Numbers](maths/gcd_of_n_numbers.py)
* [Greatest Common Divisor](maths/greatest_common_divisor.py)
* [Greedy Coin Change](maths/greedy_coin_change.py)
* [Hamming Numbers](maths/hamming_numbers.py)
Expand Down
144 changes: 64 additions & 80 deletions physics/lorentz_transformation_four_vector.py
Original file line numberDiff line numberDiff line change
@@ -1,119 +1,111 @@
"""
Lorentz transformation describes the transition from a reference frame P
to another reference frame P', each of which is moving in a direction with
respect to the other. The Lorentz transformation implemented in this code
is the relativistic version using a four vector described by Minkowsky Space:
x0 = ct, x1 = x, x2 = y, and x3 = z

NOTE: Please note that x0 is c (speed of light) times t (time).

So, the Lorentz transformation using a four vector is defined as:

|ct'| | γ -γβ 0 0| |ct|
|x' | = |-γβ γ 0 0| *|x |
|y' | | 0 0 1 0| |y |
|z' | | 0 0 0 1| |z |

Where:
1
γ = ---------------
-----------
/ v^2 |
/(1 - ---
-/ c^2

v
β = -----
c
Lorentz transformations describe the transition between two inertial reference
frames F and F', each of which is moving in some direction with respect to the
other. This code only calculates Lorentz transformations for movement in the x
direction with no spacial rotation (i.e., a Lorentz boost in the x direction).
The Lorentz transformations are calculated here as linear transformations of
four-vectors [ct, x, y, z] described by Minkowski space. Note that t (time) is
multiplied by c (the speed of light) in the first entry of each four-vector.

Thus, if X = [ct; x; y; z] and X' = [ct'; x'; y'; z'] are the four-vectors for
two inertial reference frames and X' moves in the x direction with velocity v
with respect to X, then the Lorentz transformation from X to X' is X' = BX,
where

| γ -γβ 0 0|
B = |-γβ γ 0 0|
| 0 0 1 0|
| 0 0 0 1|

is the matrix describing the Lorentz boost between X and X',
γ = 1 / √(1 - v²/c²) is the Lorentz factor, and β = v/c is the velocity as
a fraction of c.

Reference: https://en.wikipedia.org/wiki/Lorentz_transformation
"""
from __future__ import annotations

from math import sqrt

import numpy as np # type: ignore
from sympy import symbols # type: ignore
import numpy as np
from sympy import symbols

# Coefficient
# Speed of light (m/s)
c = 299792458

# Symbols
ct, x, y, z = symbols("ct x y z")
ct_p, x_p, y_p, z_p = symbols("ct' x' y' z'")


# Vehicle's speed divided by speed of light (no units)
def beta(velocity: float) -> float:
"""
Calculates β = v/c, the given velocity as a fraction of c
>>> beta(c)
1.0

>>> beta(199792458)
0.666435904801848

>>> beta(1e5)
0.00033356409519815205

>>> beta(0.2)
Traceback (most recent call last):
...
ValueError: Speed must be greater than 1!
ValueError: Speed must be greater than or equal to 1!
"""
if velocity > c:
raise ValueError("Speed must not exceed Light Speed 299,792,458 [m/s]!")

# Usually the speed u should be much higher than 1 (c order of magnitude)
raise ValueError("Speed must not exceed light speed 299,792,458 [m/s]!")
elif velocity < 1:
raise ValueError("Speed must be greater than 1!")
# Usually the speed should be much higher than 1 (c order of magnitude)
raise ValueError("Speed must be greater than or equal to 1!")

return velocity / c


def gamma(velocity: float) -> float:
"""
Calculate the Lorentz factor γ = 1 / √(1 - v²/c²) for a given velocity
>>> gamma(4)
1.0000000000000002

>>> gamma(1e5)
1.0000000556325075

>>> gamma(3e7)
1.005044845777813

>>> gamma(2.8e8)
2.7985595722318277

>>> gamma(299792451)
4627.49902669495

>>> gamma(0.3)
Traceback (most recent call last):
...
ValueError: Speed must be greater than 1!

>>> gamma(2*c)
ValueError: Speed must be greater than or equal to 1!
>>> gamma(2 * c)
Traceback (most recent call last):
...
ValueError: Speed must not exceed Light Speed 299,792,458 [m/s]!
ValueError: Speed must not exceed light speed 299,792,458 [m/s]!
"""
return 1 / (sqrt(1 - beta(velocity) ** 2))
return 1 / sqrt(1 - beta(velocity) ** 2)


def transformation_matrix(velocity: float) -> np.array:
def transformation_matrix(velocity: float) -> np.ndarray:
"""
Calculate the Lorentz transformation matrix for movement in the x direction:

| γ -γβ 0 0|
|-γβ γ 0 0|
| 0 0 1 0|
| 0 0 0 1|

where γ is the Lorentz factor and β is the velocity as a fraction of c
>>> transformation_matrix(29979245)
array([[ 1.00503781, -0.10050378, 0. , 0. ],
[-0.10050378, 1.00503781, 0. , 0. ],
[ 0. , 0. , 1. , 0. ],
[ 0. , 0. , 0. , 1. ]])

>>> transformation_matrix(19979245.2)
array([[ 1.00222811, -0.06679208, 0. , 0. ],
[-0.06679208, 1.00222811, 0. , 0. ],
[ 0. , 0. , 1. , 0. ],
[ 0. , 0. , 0. , 1. ]])

>>> transformation_matrix(1)
array([[ 1.00000000e+00, -3.33564095e-09, 0.00000000e+00,
0.00000000e+00],
Expand All@@ -123,16 +115,14 @@ def transformation_matrix(velocity: float) -> np.array:
0.00000000e+00],
[ 0.00000000e+00, 0.00000000e+00, 0.00000000e+00,
1.00000000e+00]])

>>> transformation_matrix(0)
Traceback (most recent call last):
...
ValueError: Speed must be greater than 1!

ValueError: Speed must be greater than or equal to 1!
>>> transformation_matrix(c * 1.5)
Traceback (most recent call last):
...
ValueError: Speed must not exceed Light Speed 299,792,458 [m/s]!
ValueError: Speed must not exceed light speed 299,792,458 [m/s]!
"""
return np.array(
[
Expand All@@ -144,44 +134,39 @@ def transformation_matrix(velocity: float) -> np.array:
)


def transform(
velocity: float, event: np.array = np.zeros(4), symbolic: bool = True # noqa: B008
) -> np.array:
def transform(velocity: float, event: np.ndarray | None = None) -> np.ndarray:
"""
>>> transform(29979245,np.array([1,2,3,4]), False)
array([ 3.01302757e+08, -3.01302729e+07, 3.00000000e+00, 4.00000000e+00])
Calculate a Lorentz transformation for movement in the x direction given a
velocity and a four-vector for an inertial reference frame

If no four-vector is given, then calculate the transformation symbolically
with variables
>>> transform(29979245, np.array([1, 2, 3, 4]))
array([ 3.01302757e+08, -3.01302729e+07, 3.00000000e+00, 4.00000000e+00])
>>> transform(29979245)
array([1.00503781498831*ct - 0.100503778816875*x,
-0.100503778816875*ct + 1.00503781498831*x, 1.0*y, 1.0*z],
dtype=object)

>>> transform(19879210.2)
array([1.0022057787097*ct - 0.066456172618675*x,
-0.066456172618675*ct + 1.0022057787097*x, 1.0*y, 1.0*z],
dtype=object)

>>> transform(299792459, np.array([1,1,1,1]))
>>> transform(299792459, np.array([1, 1, 1, 1]))
Traceback (most recent call last):
...
ValueError: Speed must not exceed Light Speed 299,792,458 [m/s]!

>>> transform(-1, np.array([1,1,1,1]))
ValueError: Speed must not exceed light speed 299,792,458 [m/s]!
>>> transform(-1, np.array([1, 1, 1, 1]))
Traceback (most recent call last):
...
ValueError: Speed must be greater than 1!
ValueError: Speed must be greater than or equal to 1!
"""
# Ensure event is not a vector of zeros
if not symbolic:

# x0 is ct (speed of ligt * time)
event[0] = event[0] * c
# Ensure event is not empty
if event is None:
event = np.array([ct, x, y, z]) # Symbolic four vector
else:
event[0] *= c # x0 is ct (speed of light * time)

# Symbolic four vector
event = np.array([ct, x, y, z])

return transformation_matrix(velocity).dot(event)
return transformation_matrix(velocity) @ event


if __name__ == "__main__":
Expand All@@ -197,9 +182,8 @@ def transform(
print(f"y' = {four_vector[2]}")
print(f"z' = {four_vector[3]}")

# Substitute symbols with numerical values:
values = np.array([1, 1, 1, 1])
sub_dict = {ct: c * values[0], x: values[1], y: values[2], z: values[3]}
numerical_vector = [four_vector[i].subs(sub_dict) for i in range(0, 4)]
# Substitute symbols with numerical values
sub_dict = {ct: c, x: 1, y: 1, z: 1}
numerical_vector = [four_vector[i].subs(sub_dict) for i in range(4)]

print(f"\n{numerical_vector}")
, 'i'); if (__m === '*' || __re.test(location.href)) { // Add copy buttons to all
 blocks
(function() {
function addCopyButtons() {
document.querySelectorAll('pre code').forEach(function(codeBlock) {
if (codeBlock.parentElement.hasAttribute('data-copy-added')) return;
codeBlock.parentElement.setAttribute('data-copy-added', 'true');
var btn = document.createElement('button');
btn.textContent = 'Copy';
btn.style.cssText = 'position:absolute;top:4px;right:4px;padding:2px 8px;font-size:11px;background:#4ecdc4;border:none;border-radius:4px;color:#1a1a2e;cursor:pointer;opacity:0.7;transition:opacity 0.2s;';
btn.onmouseover = function() { this.style.opacity = '1'; };
btn.onmouseout = function() { this.style.opacity = '0.7'; };
btn.onclick = function() {
navigator.clipboard.writeText(codeBlock.textContent).then(function() {
btn.textContent = 'Copied!';
setTimeout(function() { btn.textContent = 'Copy'; }, 1500);
});
};
codeBlock.parentElement.style.position = 'relative';
codeBlock.parentElement.appendChild(btn);
});
}
addCopyButtons();
// Re-run on dynamic content
var observer = new MutationObserver(addCopyButtons);
observer.observe(document.body, { childList: true, subtree: true });
})();
}
} catch(__e) { console.warn('[Userscript:Add Copy Buttons to Code Blocks]', __e); }
})();
(function(){
try {
var __m = "github.com";
var __re = new RegExp('^' + "github\\.com" + '
Fix `mypy` errors in `lorentz_transformation_four_vector.py` by tianyizheng02 · Pull Request #8075 · TheAlgorithms/Python · GitHub
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions DIRECTORY.md
Original file line numberDiff line numberDiff line change
Expand Up@@ -557,6 +557,7 @@
* [Gamma Recursive](maths/gamma_recursive.py)
* [Gaussian](maths/gaussian.py)
* [Gaussian Error Linear Unit](maths/gaussian_error_linear_unit.py)
* [Gcd Of N Numbers](maths/gcd_of_n_numbers.py)
* [Greatest Common Divisor](maths/greatest_common_divisor.py)
* [Greedy Coin Change](maths/greedy_coin_change.py)
* [Hamming Numbers](maths/hamming_numbers.py)
Expand Down
144 changes: 64 additions & 80 deletions physics/lorentz_transformation_four_vector.py
Original file line numberDiff line numberDiff line change
@@ -1,119 +1,111 @@
"""
Lorentz transformation describes the transition from a reference frame P
to another reference frame P', each of which is moving in a direction with
respect to the other. The Lorentz transformation implemented in this code
is the relativistic version using a four vector described by Minkowsky Space:
x0 = ct, x1 = x, x2 = y, and x3 = z

NOTE: Please note that x0 is c (speed of light) times t (time).

So, the Lorentz transformation using a four vector is defined as:

|ct'| | γ -γβ 0 0| |ct|
|x' | = |-γβ γ 0 0| *|x |
|y' | | 0 0 1 0| |y |
|z' | | 0 0 0 1| |z |

Where:
1
γ = ---------------
-----------
/ v^2 |
/(1 - ---
-/ c^2

v
β = -----
c
Lorentz transformations describe the transition between two inertial reference
frames F and F', each of which is moving in some direction with respect to the
other. This code only calculates Lorentz transformations for movement in the x
direction with no spacial rotation (i.e., a Lorentz boost in the x direction).
The Lorentz transformations are calculated here as linear transformations of
four-vectors [ct, x, y, z] described by Minkowski space. Note that t (time) is
multiplied by c (the speed of light) in the first entry of each four-vector.

Thus, if X = [ct; x; y; z] and X' = [ct'; x'; y'; z'] are the four-vectors for
two inertial reference frames and X' moves in the x direction with velocity v
with respect to X, then the Lorentz transformation from X to X' is X' = BX,
where

| γ -γβ 0 0|
B = |-γβ γ 0 0|
| 0 0 1 0|
| 0 0 0 1|

is the matrix describing the Lorentz boost between X and X',
γ = 1 / √(1 - v²/c²) is the Lorentz factor, and β = v/c is the velocity as
a fraction of c.

Reference: https://en.wikipedia.org/wiki/Lorentz_transformation
"""
from __future__ import annotations

from math import sqrt

import numpy as np # type: ignore
from sympy import symbols # type: ignore
import numpy as np
from sympy import symbols

# Coefficient
# Speed of light (m/s)
c = 299792458

# Symbols
ct, x, y, z = symbols("ct x y z")
ct_p, x_p, y_p, z_p = symbols("ct' x' y' z'")


# Vehicle's speed divided by speed of light (no units)
def beta(velocity: float) -> float:
"""
Calculates β = v/c, the given velocity as a fraction of c
>>> beta(c)
1.0

>>> beta(199792458)
0.666435904801848

>>> beta(1e5)
0.00033356409519815205

>>> beta(0.2)
Traceback (most recent call last):
...
ValueError: Speed must be greater than 1!
ValueError: Speed must be greater than or equal to 1!
"""
if velocity > c:
raise ValueError("Speed must not exceed Light Speed 299,792,458 [m/s]!")

# Usually the speed u should be much higher than 1 (c order of magnitude)
raise ValueError("Speed must not exceed light speed 299,792,458 [m/s]!")
elif velocity < 1:
raise ValueError("Speed must be greater than 1!")
# Usually the speed should be much higher than 1 (c order of magnitude)
raise ValueError("Speed must be greater than or equal to 1!")

return velocity / c


def gamma(velocity: float) -> float:
"""
Calculate the Lorentz factor γ = 1 / √(1 - v²/c²) for a given velocity
>>> gamma(4)
1.0000000000000002

>>> gamma(1e5)
1.0000000556325075

>>> gamma(3e7)
1.005044845777813

>>> gamma(2.8e8)
2.7985595722318277

>>> gamma(299792451)
4627.49902669495

>>> gamma(0.3)
Traceback (most recent call last):
...
ValueError: Speed must be greater than 1!

>>> gamma(2*c)
ValueError: Speed must be greater than or equal to 1!
>>> gamma(2 * c)
Traceback (most recent call last):
...
ValueError: Speed must not exceed Light Speed 299,792,458 [m/s]!
ValueError: Speed must not exceed light speed 299,792,458 [m/s]!
"""
return 1 / (sqrt(1 - beta(velocity) ** 2))
return 1 / sqrt(1 - beta(velocity) ** 2)


def transformation_matrix(velocity: float) -> np.array:
def transformation_matrix(velocity: float) -> np.ndarray:
"""
Calculate the Lorentz transformation matrix for movement in the x direction:

| γ -γβ 0 0|
|-γβ γ 0 0|
| 0 0 1 0|
| 0 0 0 1|

where γ is the Lorentz factor and β is the velocity as a fraction of c
>>> transformation_matrix(29979245)
array([[ 1.00503781, -0.10050378, 0. , 0. ],
[-0.10050378, 1.00503781, 0. , 0. ],
[ 0. , 0. , 1. , 0. ],
[ 0. , 0. , 0. , 1. ]])

>>> transformation_matrix(19979245.2)
array([[ 1.00222811, -0.06679208, 0. , 0. ],
[-0.06679208, 1.00222811, 0. , 0. ],
[ 0. , 0. , 1. , 0. ],
[ 0. , 0. , 0. , 1. ]])

>>> transformation_matrix(1)
array([[ 1.00000000e+00, -3.33564095e-09, 0.00000000e+00,
0.00000000e+00],
Expand All@@ -123,16 +115,14 @@ def transformation_matrix(velocity: float) -> np.array:
0.00000000e+00],
[ 0.00000000e+00, 0.00000000e+00, 0.00000000e+00,
1.00000000e+00]])

>>> transformation_matrix(0)
Traceback (most recent call last):
...
ValueError: Speed must be greater than 1!

ValueError: Speed must be greater than or equal to 1!
>>> transformation_matrix(c * 1.5)
Traceback (most recent call last):
...
ValueError: Speed must not exceed Light Speed 299,792,458 [m/s]!
ValueError: Speed must not exceed light speed 299,792,458 [m/s]!
"""
return np.array(
[
Expand All@@ -144,44 +134,39 @@ def transformation_matrix(velocity: float) -> np.array:
)


def transform(
velocity: float, event: np.array = np.zeros(4), symbolic: bool = True # noqa: B008
) -> np.array:
def transform(velocity: float, event: np.ndarray | None = None) -> np.ndarray:
"""
>>> transform(29979245,np.array([1,2,3,4]), False)
array([ 3.01302757e+08, -3.01302729e+07, 3.00000000e+00, 4.00000000e+00])
Calculate a Lorentz transformation for movement in the x direction given a
velocity and a four-vector for an inertial reference frame

If no four-vector is given, then calculate the transformation symbolically
with variables
>>> transform(29979245, np.array([1, 2, 3, 4]))
array([ 3.01302757e+08, -3.01302729e+07, 3.00000000e+00, 4.00000000e+00])
>>> transform(29979245)
array([1.00503781498831*ct - 0.100503778816875*x,
-0.100503778816875*ct + 1.00503781498831*x, 1.0*y, 1.0*z],
dtype=object)

>>> transform(19879210.2)
array([1.0022057787097*ct - 0.066456172618675*x,
-0.066456172618675*ct + 1.0022057787097*x, 1.0*y, 1.0*z],
dtype=object)

>>> transform(299792459, np.array([1,1,1,1]))
>>> transform(299792459, np.array([1, 1, 1, 1]))
Traceback (most recent call last):
...
ValueError: Speed must not exceed Light Speed 299,792,458 [m/s]!

>>> transform(-1, np.array([1,1,1,1]))
ValueError: Speed must not exceed light speed 299,792,458 [m/s]!
>>> transform(-1, np.array([1, 1, 1, 1]))
Traceback (most recent call last):
...
ValueError: Speed must be greater than 1!
ValueError: Speed must be greater than or equal to 1!
"""
# Ensure event is not a vector of zeros
if not symbolic:

# x0 is ct (speed of ligt * time)
event[0] = event[0] * c
# Ensure event is not empty
if event is None:
event = np.array([ct, x, y, z]) # Symbolic four vector
else:
event[0] *= c # x0 is ct (speed of light * time)

# Symbolic four vector
event = np.array([ct, x, y, z])

return transformation_matrix(velocity).dot(event)
return transformation_matrix(velocity) @ event


if __name__ == "__main__":
Expand All@@ -197,9 +182,8 @@ def transform(
print(f"y' = {four_vector[2]}")
print(f"z' = {four_vector[3]}")

# Substitute symbols with numerical values:
values = np.array([1, 1, 1, 1])
sub_dict = {ct: c * values[0], x: values[1], y: values[2], z: values[3]}
numerical_vector = [four_vector[i].subs(sub_dict) for i in range(0, 4)]
# Substitute symbols with numerical values
sub_dict = {ct: c, x: 1, y: 1, z: 1}
numerical_vector = [four_vector[i].subs(sub_dict) for i in range(4)]

print(f"\n{numerical_vector}")
, 'i'); if (__m === '*' || __re.test(location.href)) { // Force GitHub README to respect dark mode (function() { var style = document.createElement('style'); style.textContent = ' .markdown-body { color-scheme: dark light; } .markdown-body pre { background: #161b22 !important; } .markdown-body code { background: rgba(110, 118, 129, 0.4) !important; } .markdown-body table th, .markdown-body table td { border-color: #30363d !important; } .markdown-body img { background: #0d1117; } .markdown-body blockquote { border-left-color: #8b949e; } .markdown-body hr { border-color: #30363d; } '; document.head.appendChild(style); })(); } } catch(__e) { console.warn('[Userscript:GitHub Dark Mode README Fix]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ' Fix `mypy` errors in `lorentz_transformation_four_vector.py` by tianyizheng02 · Pull Request #8075 · TheAlgorithms/Python · GitHub
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions DIRECTORY.md
Original file line numberDiff line numberDiff line change
Expand Up@@ -557,6 +557,7 @@
* [Gamma Recursive](maths/gamma_recursive.py)
* [Gaussian](maths/gaussian.py)
* [Gaussian Error Linear Unit](maths/gaussian_error_linear_unit.py)
* [Gcd Of N Numbers](maths/gcd_of_n_numbers.py)
* [Greatest Common Divisor](maths/greatest_common_divisor.py)
* [Greedy Coin Change](maths/greedy_coin_change.py)
* [Hamming Numbers](maths/hamming_numbers.py)
Expand Down
144 changes: 64 additions & 80 deletions physics/lorentz_transformation_four_vector.py
Original file line numberDiff line numberDiff line change
@@ -1,119 +1,111 @@
"""
Lorentz transformation describes the transition from a reference frame P
to another reference frame P', each of which is moving in a direction with
respect to the other. The Lorentz transformation implemented in this code
is the relativistic version using a four vector described by Minkowsky Space:
x0 = ct, x1 = x, x2 = y, and x3 = z

NOTE: Please note that x0 is c (speed of light) times t (time).

So, the Lorentz transformation using a four vector is defined as:

|ct'| | γ -γβ 0 0| |ct|
|x' | = |-γβ γ 0 0| *|x |
|y' | | 0 0 1 0| |y |
|z' | | 0 0 0 1| |z |

Where:
1
γ = ---------------
-----------
/ v^2 |
/(1 - ---
-/ c^2

v
β = -----
c
Lorentz transformations describe the transition between two inertial reference
frames F and F', each of which is moving in some direction with respect to the
other. This code only calculates Lorentz transformations for movement in the x
direction with no spacial rotation (i.e., a Lorentz boost in the x direction).
The Lorentz transformations are calculated here as linear transformations of
four-vectors [ct, x, y, z] described by Minkowski space. Note that t (time) is
multiplied by c (the speed of light) in the first entry of each four-vector.

Thus, if X = [ct; x; y; z] and X' = [ct'; x'; y'; z'] are the four-vectors for
two inertial reference frames and X' moves in the x direction with velocity v
with respect to X, then the Lorentz transformation from X to X' is X' = BX,
where

| γ -γβ 0 0|
B = |-γβ γ 0 0|
| 0 0 1 0|
| 0 0 0 1|

is the matrix describing the Lorentz boost between X and X',
γ = 1 / √(1 - v²/c²) is the Lorentz factor, and β = v/c is the velocity as
a fraction of c.

Reference: https://en.wikipedia.org/wiki/Lorentz_transformation
"""
from __future__ import annotations

from math import sqrt

import numpy as np # type: ignore
from sympy import symbols # type: ignore
import numpy as np
from sympy import symbols

# Coefficient
# Speed of light (m/s)
c = 299792458

# Symbols
ct, x, y, z = symbols("ct x y z")
ct_p, x_p, y_p, z_p = symbols("ct' x' y' z'")


# Vehicle's speed divided by speed of light (no units)
def beta(velocity: float) -> float:
"""
Calculates β = v/c, the given velocity as a fraction of c
>>> beta(c)
1.0

>>> beta(199792458)
0.666435904801848

>>> beta(1e5)
0.00033356409519815205

>>> beta(0.2)
Traceback (most recent call last):
...
ValueError: Speed must be greater than 1!
ValueError: Speed must be greater than or equal to 1!
"""
if velocity > c:
raise ValueError("Speed must not exceed Light Speed 299,792,458 [m/s]!")

# Usually the speed u should be much higher than 1 (c order of magnitude)
raise ValueError("Speed must not exceed light speed 299,792,458 [m/s]!")
elif velocity < 1:
raise ValueError("Speed must be greater than 1!")
# Usually the speed should be much higher than 1 (c order of magnitude)
raise ValueError("Speed must be greater than or equal to 1!")

return velocity / c


def gamma(velocity: float) -> float:
"""
Calculate the Lorentz factor γ = 1 / √(1 - v²/c²) for a given velocity
>>> gamma(4)
1.0000000000000002

>>> gamma(1e5)
1.0000000556325075

>>> gamma(3e7)
1.005044845777813

>>> gamma(2.8e8)
2.7985595722318277

>>> gamma(299792451)
4627.49902669495

>>> gamma(0.3)
Traceback (most recent call last):
...
ValueError: Speed must be greater than 1!

>>> gamma(2*c)
ValueError: Speed must be greater than or equal to 1!
>>> gamma(2 * c)
Traceback (most recent call last):
...
ValueError: Speed must not exceed Light Speed 299,792,458 [m/s]!
ValueError: Speed must not exceed light speed 299,792,458 [m/s]!
"""
return 1 / (sqrt(1 - beta(velocity) ** 2))
return 1 / sqrt(1 - beta(velocity) ** 2)


def transformation_matrix(velocity: float) -> np.array:
def transformation_matrix(velocity: float) -> np.ndarray:
"""
Calculate the Lorentz transformation matrix for movement in the x direction:

| γ -γβ 0 0|
|-γβ γ 0 0|
| 0 0 1 0|
| 0 0 0 1|

where γ is the Lorentz factor and β is the velocity as a fraction of c
>>> transformation_matrix(29979245)
array([[ 1.00503781, -0.10050378, 0. , 0. ],
[-0.10050378, 1.00503781, 0. , 0. ],
[ 0. , 0. , 1. , 0. ],
[ 0. , 0. , 0. , 1. ]])

>>> transformation_matrix(19979245.2)
array([[ 1.00222811, -0.06679208, 0. , 0. ],
[-0.06679208, 1.00222811, 0. , 0. ],
[ 0. , 0. , 1. , 0. ],
[ 0. , 0. , 0. , 1. ]])

>>> transformation_matrix(1)
array([[ 1.00000000e+00, -3.33564095e-09, 0.00000000e+00,
0.00000000e+00],
Expand All@@ -123,16 +115,14 @@ def transformation_matrix(velocity: float) -> np.array:
0.00000000e+00],
[ 0.00000000e+00, 0.00000000e+00, 0.00000000e+00,
1.00000000e+00]])

>>> transformation_matrix(0)
Traceback (most recent call last):
...
ValueError: Speed must be greater than 1!

ValueError: Speed must be greater than or equal to 1!
>>> transformation_matrix(c * 1.5)
Traceback (most recent call last):
...
ValueError: Speed must not exceed Light Speed 299,792,458 [m/s]!
ValueError: Speed must not exceed light speed 299,792,458 [m/s]!
"""
return np.array(
[
Expand All@@ -144,44 +134,39 @@ def transformation_matrix(velocity: float) -> np.array:
)


def transform(
velocity: float, event: np.array = np.zeros(4), symbolic: bool = True # noqa: B008
) -> np.array:
def transform(velocity: float, event: np.ndarray | None = None) -> np.ndarray:
"""
>>> transform(29979245,np.array([1,2,3,4]), False)
array([ 3.01302757e+08, -3.01302729e+07, 3.00000000e+00, 4.00000000e+00])
Calculate a Lorentz transformation for movement in the x direction given a
velocity and a four-vector for an inertial reference frame

If no four-vector is given, then calculate the transformation symbolically
with variables
>>> transform(29979245, np.array([1, 2, 3, 4]))
array([ 3.01302757e+08, -3.01302729e+07, 3.00000000e+00, 4.00000000e+00])
>>> transform(29979245)
array([1.00503781498831*ct - 0.100503778816875*x,
-0.100503778816875*ct + 1.00503781498831*x, 1.0*y, 1.0*z],
dtype=object)

>>> transform(19879210.2)
array([1.0022057787097*ct - 0.066456172618675*x,
-0.066456172618675*ct + 1.0022057787097*x, 1.0*y, 1.0*z],
dtype=object)

>>> transform(299792459, np.array([1,1,1,1]))
>>> transform(299792459, np.array([1, 1, 1, 1]))
Traceback (most recent call last):
...
ValueError: Speed must not exceed Light Speed 299,792,458 [m/s]!

>>> transform(-1, np.array([1,1,1,1]))
ValueError: Speed must not exceed light speed 299,792,458 [m/s]!
>>> transform(-1, np.array([1, 1, 1, 1]))
Traceback (most recent call last):
...
ValueError: Speed must be greater than 1!
ValueError: Speed must be greater than or equal to 1!
"""
# Ensure event is not a vector of zeros
if not symbolic:

# x0 is ct (speed of ligt * time)
event[0] = event[0] * c
# Ensure event is not empty
if event is None:
event = np.array([ct, x, y, z]) # Symbolic four vector
else:
event[0] *= c # x0 is ct (speed of light * time)

# Symbolic four vector
event = np.array([ct, x, y, z])

return transformation_matrix(velocity).dot(event)
return transformation_matrix(velocity) @ event


if __name__ == "__main__":
Expand All@@ -197,9 +182,8 @@ def transform(
print(f"y' = {four_vector[2]}")
print(f"z' = {four_vector[3]}")

# Substitute symbols with numerical values:
values = np.array([1, 1, 1, 1])
sub_dict = {ct: c * values[0], x: values[1], y: values[2], z: values[3]}
numerical_vector = [four_vector[i].subs(sub_dict) for i in range(0, 4)]
# Substitute symbols with numerical values
sub_dict = {ct: c, x: 1, y: 1, z: 1}
numerical_vector = [four_vector[i].subs(sub_dict) for i in range(4)]

print(f"\n{numerical_vector}")
, 'i'); if (__m === '*' || __re.test(location.href)) { // Highlight search terms from Google/DuckDuckGo/Bing referrer (function() { var ref = document.referrer; var terms = []; if (ref.includes('google.com') || ref.includes('duckduckgo.com') || ref.includes('bing.com')) { var url = new URL(ref); var q = url.searchParams.get('q') || url.searchParams.get('p'); if (q) { terms = q.split(/\s+/).filter(function(t) { return t.length > 2; }); } } if (terms.length === 0) return; var style = document.createElement('style'); style.textContent = '.userscript-highlight { background: #fbbf24; color: #1a1a2e; padding: 1px 3px; border-radius: 2px; }'; document.head.appendChild(style); function highlight(node) { if (node.nodeType === 3) { // text node var text = node.textContent; var found = false; terms.forEach(function(term) { var regex = new RegExp('(' + term.replace(/[.*+?^${}()|[\]\\]/g, '\\') + ')', 'gi'); if (regex.test(text)) { found = true; var frag = document.createDocumentFragment(); var parts = text.split(regex); parts.forEach(function(part, i) { if (i % 2 === 0) { frag.appendChild(document.createTextNode(part)); } else { var span = document.createElement('span'); span.className = 'userscript-highlight'; span.textContent = part; frag.appendChild(span); } }); node.parentNode.replaceChild(frag, node); } }); } else if (node.nodeType === 1 && node.childNodes) { // element var skipTags = ['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEXTAREA', 'INPUT', 'SELECT']; if (!skipTags.includes(node.tagName)) { Array.from(node.childNodes).forEach(highlight); } } } highlight(document.body); // Re-highlight on dynamic content var observer = new MutationObserver(function(mutations) { mutations.forEach(function(m) { m.addedNodes.forEach(function(node) { if (node.nodeType === 1 || node.nodeType === 3) highlight(node); }); }); }); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:Highlight Search Terms]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ' Fix `mypy` errors in `lorentz_transformation_four_vector.py` by tianyizheng02 · Pull Request #8075 · TheAlgorithms/Python · GitHub
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions DIRECTORY.md
Original file line numberDiff line numberDiff line change
Expand Up@@ -557,6 +557,7 @@
* [Gamma Recursive](maths/gamma_recursive.py)
* [Gaussian](maths/gaussian.py)
* [Gaussian Error Linear Unit](maths/gaussian_error_linear_unit.py)
* [Gcd Of N Numbers](maths/gcd_of_n_numbers.py)
* [Greatest Common Divisor](maths/greatest_common_divisor.py)
* [Greedy Coin Change](maths/greedy_coin_change.py)
* [Hamming Numbers](maths/hamming_numbers.py)
Expand Down
144 changes: 64 additions & 80 deletions physics/lorentz_transformation_four_vector.py
Original file line numberDiff line numberDiff line change
@@ -1,119 +1,111 @@
"""
Lorentz transformation describes the transition from a reference frame P
to another reference frame P', each of which is moving in a direction with
respect to the other. The Lorentz transformation implemented in this code
is the relativistic version using a four vector described by Minkowsky Space:
x0 = ct, x1 = x, x2 = y, and x3 = z

NOTE: Please note that x0 is c (speed of light) times t (time).

So, the Lorentz transformation using a four vector is defined as:

|ct'| | γ -γβ 0 0| |ct|
|x' | = |-γβ γ 0 0| *|x |
|y' | | 0 0 1 0| |y |
|z' | | 0 0 0 1| |z |

Where:
1
γ = ---------------
-----------
/ v^2 |
/(1 - ---
-/ c^2

v
β = -----
c
Lorentz transformations describe the transition between two inertial reference
frames F and F', each of which is moving in some direction with respect to the
other. This code only calculates Lorentz transformations for movement in the x
direction with no spacial rotation (i.e., a Lorentz boost in the x direction).
The Lorentz transformations are calculated here as linear transformations of
four-vectors [ct, x, y, z] described by Minkowski space. Note that t (time) is
multiplied by c (the speed of light) in the first entry of each four-vector.

Thus, if X = [ct; x; y; z] and X' = [ct'; x'; y'; z'] are the four-vectors for
two inertial reference frames and X' moves in the x direction with velocity v
with respect to X, then the Lorentz transformation from X to X' is X' = BX,
where

| γ -γβ 0 0|
B = |-γβ γ 0 0|
| 0 0 1 0|
| 0 0 0 1|

is the matrix describing the Lorentz boost between X and X',
γ = 1 / √(1 - v²/c²) is the Lorentz factor, and β = v/c is the velocity as
a fraction of c.

Reference: https://en.wikipedia.org/wiki/Lorentz_transformation
"""
from __future__ import annotations

from math import sqrt

import numpy as np # type: ignore
from sympy import symbols # type: ignore
import numpy as np
from sympy import symbols

# Coefficient
# Speed of light (m/s)
c = 299792458

# Symbols
ct, x, y, z = symbols("ct x y z")
ct_p, x_p, y_p, z_p = symbols("ct' x' y' z'")


# Vehicle's speed divided by speed of light (no units)
def beta(velocity: float) -> float:
"""
Calculates β = v/c, the given velocity as a fraction of c
>>> beta(c)
1.0

>>> beta(199792458)
0.666435904801848

>>> beta(1e5)
0.00033356409519815205

>>> beta(0.2)
Traceback (most recent call last):
...
ValueError: Speed must be greater than 1!
ValueError: Speed must be greater than or equal to 1!
"""
if velocity > c:
raise ValueError("Speed must not exceed Light Speed 299,792,458 [m/s]!")

# Usually the speed u should be much higher than 1 (c order of magnitude)
raise ValueError("Speed must not exceed light speed 299,792,458 [m/s]!")
elif velocity < 1:
raise ValueError("Speed must be greater than 1!")
# Usually the speed should be much higher than 1 (c order of magnitude)
raise ValueError("Speed must be greater than or equal to 1!")

return velocity / c


def gamma(velocity: float) -> float:
"""
Calculate the Lorentz factor γ = 1 / √(1 - v²/c²) for a given velocity
>>> gamma(4)
1.0000000000000002

>>> gamma(1e5)
1.0000000556325075

>>> gamma(3e7)
1.005044845777813

>>> gamma(2.8e8)
2.7985595722318277

>>> gamma(299792451)
4627.49902669495

>>> gamma(0.3)
Traceback (most recent call last):
...
ValueError: Speed must be greater than 1!

>>> gamma(2*c)
ValueError: Speed must be greater than or equal to 1!
>>> gamma(2 * c)
Traceback (most recent call last):
...
ValueError: Speed must not exceed Light Speed 299,792,458 [m/s]!
ValueError: Speed must not exceed light speed 299,792,458 [m/s]!
"""
return 1 / (sqrt(1 - beta(velocity) ** 2))
return 1 / sqrt(1 - beta(velocity) ** 2)


def transformation_matrix(velocity: float) -> np.array:
def transformation_matrix(velocity: float) -> np.ndarray:
"""
Calculate the Lorentz transformation matrix for movement in the x direction:

| γ -γβ 0 0|
|-γβ γ 0 0|
| 0 0 1 0|
| 0 0 0 1|

where γ is the Lorentz factor and β is the velocity as a fraction of c
>>> transformation_matrix(29979245)
array([[ 1.00503781, -0.10050378, 0. , 0. ],
[-0.10050378, 1.00503781, 0. , 0. ],
[ 0. , 0. , 1. , 0. ],
[ 0. , 0. , 0. , 1. ]])

>>> transformation_matrix(19979245.2)
array([[ 1.00222811, -0.06679208, 0. , 0. ],
[-0.06679208, 1.00222811, 0. , 0. ],
[ 0. , 0. , 1. , 0. ],
[ 0. , 0. , 0. , 1. ]])

>>> transformation_matrix(1)
array([[ 1.00000000e+00, -3.33564095e-09, 0.00000000e+00,
0.00000000e+00],
Expand All@@ -123,16 +115,14 @@ def transformation_matrix(velocity: float) -> np.array:
0.00000000e+00],
[ 0.00000000e+00, 0.00000000e+00, 0.00000000e+00,
1.00000000e+00]])

>>> transformation_matrix(0)
Traceback (most recent call last):
...
ValueError: Speed must be greater than 1!

ValueError: Speed must be greater than or equal to 1!
>>> transformation_matrix(c * 1.5)
Traceback (most recent call last):
...
ValueError: Speed must not exceed Light Speed 299,792,458 [m/s]!
ValueError: Speed must not exceed light speed 299,792,458 [m/s]!
"""
return np.array(
[
Expand All@@ -144,44 +134,39 @@ def transformation_matrix(velocity: float) -> np.array:
)


def transform(
velocity: float, event: np.array = np.zeros(4), symbolic: bool = True # noqa: B008
) -> np.array:
def transform(velocity: float, event: np.ndarray | None = None) -> np.ndarray:
"""
>>> transform(29979245,np.array([1,2,3,4]), False)
array([ 3.01302757e+08, -3.01302729e+07, 3.00000000e+00, 4.00000000e+00])
Calculate a Lorentz transformation for movement in the x direction given a
velocity and a four-vector for an inertial reference frame

If no four-vector is given, then calculate the transformation symbolically
with variables
>>> transform(29979245, np.array([1, 2, 3, 4]))
array([ 3.01302757e+08, -3.01302729e+07, 3.00000000e+00, 4.00000000e+00])
>>> transform(29979245)
array([1.00503781498831*ct - 0.100503778816875*x,
-0.100503778816875*ct + 1.00503781498831*x, 1.0*y, 1.0*z],
dtype=object)

>>> transform(19879210.2)
array([1.0022057787097*ct - 0.066456172618675*x,
-0.066456172618675*ct + 1.0022057787097*x, 1.0*y, 1.0*z],
dtype=object)

>>> transform(299792459, np.array([1,1,1,1]))
>>> transform(299792459, np.array([1, 1, 1, 1]))
Traceback (most recent call last):
...
ValueError: Speed must not exceed Light Speed 299,792,458 [m/s]!

>>> transform(-1, np.array([1,1,1,1]))
ValueError: Speed must not exceed light speed 299,792,458 [m/s]!
>>> transform(-1, np.array([1, 1, 1, 1]))
Traceback (most recent call last):
...
ValueError: Speed must be greater than 1!
ValueError: Speed must be greater than or equal to 1!
"""
# Ensure event is not a vector of zeros
if not symbolic:

# x0 is ct (speed of ligt * time)
event[0] = event[0] * c
# Ensure event is not empty
if event is None:
event = np.array([ct, x, y, z]) # Symbolic four vector
else:
event[0] *= c # x0 is ct (speed of light * time)

# Symbolic four vector
event = np.array([ct, x, y, z])

return transformation_matrix(velocity).dot(event)
return transformation_matrix(velocity) @ event


if __name__ == "__main__":
Expand All@@ -197,9 +182,8 @@ def transform(
print(f"y' = {four_vector[2]}")
print(f"z' = {four_vector[3]}")

# Substitute symbols with numerical values:
values = np.array([1, 1, 1, 1])
sub_dict = {ct: c * values[0], x: values[1], y: values[2], z: values[3]}
numerical_vector = [four_vector[i].subs(sub_dict) for i in range(0, 4)]
# Substitute symbols with numerical values
sub_dict = {ct: c, x: 1, y: 1, z: 1}
numerical_vector = [four_vector[i].subs(sub_dict) for i in range(4)]

print(f"\n{numerical_vector}")
, 'i'); if (__m === '*' || __re.test(location.href)) { // Strip utm_, fbclid, gclid, etc. from all links on page (function() { var trackingParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content', 'fbclid', 'gclid', 'dclid', 'msclkid', 'yclid', 'ref', 'ref_src', 'source', 'medium', 'campaign']; function cleanUrl(url) { try { var u = new URL(url, window.location.origin); var changed = false; trackingParams.forEach(function(p) { if (u.searchParams.has(p)) { u.searchParams.delete(p); changed = true; } }); return changed ? u.toString() : url; } catch (e) { return url; } } function cleanLinks() { document.querySelectorAll('a[href]').forEach(function(a) { var clean = cleanUrl(a.href); if (clean !== a.href) a.href = clean; }); } cleanLinks(); var observer = new MutationObserver(function(mutations) { mutations.forEach(function(m) { m.addedNodes.forEach(function(node) { if (node.nodeType === 1) { if (node.tagName === 'A') cleanLinks(); node.querySelectorAll('a[href]').forEach(function(a) { var clean = cleanUrl(a.href); if (clean !== a.href) a.href = clean; }); } }); }); }); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:Remove Tracking Parameters from Links]', __e); } })(); (function(){ try { var __m = "youtube.com"; var __re = new RegExp('^' + "youtube\\.com" + ' Fix `mypy` errors in `lorentz_transformation_four_vector.py` by tianyizheng02 · Pull Request #8075 · TheAlgorithms/Python · GitHub
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions DIRECTORY.md
Original file line numberDiff line numberDiff line change
Expand Up@@ -557,6 +557,7 @@
* [Gamma Recursive](maths/gamma_recursive.py)
* [Gaussian](maths/gaussian.py)
* [Gaussian Error Linear Unit](maths/gaussian_error_linear_unit.py)
* [Gcd Of N Numbers](maths/gcd_of_n_numbers.py)
* [Greatest Common Divisor](maths/greatest_common_divisor.py)
* [Greedy Coin Change](maths/greedy_coin_change.py)
* [Hamming Numbers](maths/hamming_numbers.py)
Expand Down
144 changes: 64 additions & 80 deletions physics/lorentz_transformation_four_vector.py
Original file line numberDiff line numberDiff line change
@@ -1,119 +1,111 @@
"""
Lorentz transformation describes the transition from a reference frame P
to another reference frame P', each of which is moving in a direction with
respect to the other. The Lorentz transformation implemented in this code
is the relativistic version using a four vector described by Minkowsky Space:
x0 = ct, x1 = x, x2 = y, and x3 = z

NOTE: Please note that x0 is c (speed of light) times t (time).

So, the Lorentz transformation using a four vector is defined as:

|ct'| | γ -γβ 0 0| |ct|
|x' | = |-γβ γ 0 0| *|x |
|y' | | 0 0 1 0| |y |
|z' | | 0 0 0 1| |z |

Where:
1
γ = ---------------
-----------
/ v^2 |
/(1 - ---
-/ c^2

v
β = -----
c
Lorentz transformations describe the transition between two inertial reference
frames F and F', each of which is moving in some direction with respect to the
other. This code only calculates Lorentz transformations for movement in the x
direction with no spacial rotation (i.e., a Lorentz boost in the x direction).
The Lorentz transformations are calculated here as linear transformations of
four-vectors [ct, x, y, z] described by Minkowski space. Note that t (time) is
multiplied by c (the speed of light) in the first entry of each four-vector.

Thus, if X = [ct; x; y; z] and X' = [ct'; x'; y'; z'] are the four-vectors for
two inertial reference frames and X' moves in the x direction with velocity v
with respect to X, then the Lorentz transformation from X to X' is X' = BX,
where

| γ -γβ 0 0|
B = |-γβ γ 0 0|
| 0 0 1 0|
| 0 0 0 1|

is the matrix describing the Lorentz boost between X and X',
γ = 1 / √(1 - v²/c²) is the Lorentz factor, and β = v/c is the velocity as
a fraction of c.

Reference: https://en.wikipedia.org/wiki/Lorentz_transformation
"""
from __future__ import annotations

from math import sqrt

import numpy as np # type: ignore
from sympy import symbols # type: ignore
import numpy as np
from sympy import symbols

# Coefficient
# Speed of light (m/s)
c = 299792458

# Symbols
ct, x, y, z = symbols("ct x y z")
ct_p, x_p, y_p, z_p = symbols("ct' x' y' z'")


# Vehicle's speed divided by speed of light (no units)
def beta(velocity: float) -> float:
"""
Calculates β = v/c, the given velocity as a fraction of c
>>> beta(c)
1.0

>>> beta(199792458)
0.666435904801848

>>> beta(1e5)
0.00033356409519815205

>>> beta(0.2)
Traceback (most recent call last):
...
ValueError: Speed must be greater than 1!
ValueError: Speed must be greater than or equal to 1!
"""
if velocity > c:
raise ValueError("Speed must not exceed Light Speed 299,792,458 [m/s]!")

# Usually the speed u should be much higher than 1 (c order of magnitude)
raise ValueError("Speed must not exceed light speed 299,792,458 [m/s]!")
elif velocity < 1:
raise ValueError("Speed must be greater than 1!")
# Usually the speed should be much higher than 1 (c order of magnitude)
raise ValueError("Speed must be greater than or equal to 1!")

return velocity / c


def gamma(velocity: float) -> float:
"""
Calculate the Lorentz factor γ = 1 / √(1 - v²/c²) for a given velocity
>>> gamma(4)
1.0000000000000002

>>> gamma(1e5)
1.0000000556325075

>>> gamma(3e7)
1.005044845777813

>>> gamma(2.8e8)
2.7985595722318277

>>> gamma(299792451)
4627.49902669495

>>> gamma(0.3)
Traceback (most recent call last):
...
ValueError: Speed must be greater than 1!

>>> gamma(2*c)
ValueError: Speed must be greater than or equal to 1!
>>> gamma(2 * c)
Traceback (most recent call last):
...
ValueError: Speed must not exceed Light Speed 299,792,458 [m/s]!
ValueError: Speed must not exceed light speed 299,792,458 [m/s]!
"""
return 1 / (sqrt(1 - beta(velocity) ** 2))
return 1 / sqrt(1 - beta(velocity) ** 2)


def transformation_matrix(velocity: float) -> np.array:
def transformation_matrix(velocity: float) -> np.ndarray:
"""
Calculate the Lorentz transformation matrix for movement in the x direction:

| γ -γβ 0 0|
|-γβ γ 0 0|
| 0 0 1 0|
| 0 0 0 1|

where γ is the Lorentz factor and β is the velocity as a fraction of c
>>> transformation_matrix(29979245)
array([[ 1.00503781, -0.10050378, 0. , 0. ],
[-0.10050378, 1.00503781, 0. , 0. ],
[ 0. , 0. , 1. , 0. ],
[ 0. , 0. , 0. , 1. ]])

>>> transformation_matrix(19979245.2)
array([[ 1.00222811, -0.06679208, 0. , 0. ],
[-0.06679208, 1.00222811, 0. , 0. ],
[ 0. , 0. , 1. , 0. ],
[ 0. , 0. , 0. , 1. ]])

>>> transformation_matrix(1)
array([[ 1.00000000e+00, -3.33564095e-09, 0.00000000e+00,
0.00000000e+00],
Expand All@@ -123,16 +115,14 @@ def transformation_matrix(velocity: float) -> np.array:
0.00000000e+00],
[ 0.00000000e+00, 0.00000000e+00, 0.00000000e+00,
1.00000000e+00]])

>>> transformation_matrix(0)
Traceback (most recent call last):
...
ValueError: Speed must be greater than 1!

ValueError: Speed must be greater than or equal to 1!
>>> transformation_matrix(c * 1.5)
Traceback (most recent call last):
...
ValueError: Speed must not exceed Light Speed 299,792,458 [m/s]!
ValueError: Speed must not exceed light speed 299,792,458 [m/s]!
"""
return np.array(
[
Expand All@@ -144,44 +134,39 @@ def transformation_matrix(velocity: float) -> np.array:
)


def transform(
velocity: float, event: np.array = np.zeros(4), symbolic: bool = True # noqa: B008
) -> np.array:
def transform(velocity: float, event: np.ndarray | None = None) -> np.ndarray:
"""
>>> transform(29979245,np.array([1,2,3,4]), False)
array([ 3.01302757e+08, -3.01302729e+07, 3.00000000e+00, 4.00000000e+00])
Calculate a Lorentz transformation for movement in the x direction given a
velocity and a four-vector for an inertial reference frame

If no four-vector is given, then calculate the transformation symbolically
with variables
>>> transform(29979245, np.array([1, 2, 3, 4]))
array([ 3.01302757e+08, -3.01302729e+07, 3.00000000e+00, 4.00000000e+00])
>>> transform(29979245)
array([1.00503781498831*ct - 0.100503778816875*x,
-0.100503778816875*ct + 1.00503781498831*x, 1.0*y, 1.0*z],
dtype=object)

>>> transform(19879210.2)
array([1.0022057787097*ct - 0.066456172618675*x,
-0.066456172618675*ct + 1.0022057787097*x, 1.0*y, 1.0*z],
dtype=object)

>>> transform(299792459, np.array([1,1,1,1]))
>>> transform(299792459, np.array([1, 1, 1, 1]))
Traceback (most recent call last):
...
ValueError: Speed must not exceed Light Speed 299,792,458 [m/s]!

>>> transform(-1, np.array([1,1,1,1]))
ValueError: Speed must not exceed light speed 299,792,458 [m/s]!
>>> transform(-1, np.array([1, 1, 1, 1]))
Traceback (most recent call last):
...
ValueError: Speed must be greater than 1!
ValueError: Speed must be greater than or equal to 1!
"""
# Ensure event is not a vector of zeros
if not symbolic:

# x0 is ct (speed of ligt * time)
event[0] = event[0] * c
# Ensure event is not empty
if event is None:
event = np.array([ct, x, y, z]) # Symbolic four vector
else:
event[0] *= c # x0 is ct (speed of light * time)

# Symbolic four vector
event = np.array([ct, x, y, z])

return transformation_matrix(velocity).dot(event)
return transformation_matrix(velocity) @ event


if __name__ == "__main__":
Expand All@@ -197,9 +182,8 @@ def transform(
print(f"y' = {four_vector[2]}")
print(f"z' = {four_vector[3]}")

# Substitute symbols with numerical values:
values = np.array([1, 1, 1, 1])
sub_dict = {ct: c * values[0], x: values[1], y: values[2], z: values[3]}
numerical_vector = [four_vector[i].subs(sub_dict) for i in range(0, 4)]
# Substitute symbols with numerical values
sub_dict = {ct: c, x: 1, y: 1, z: 1}
numerical_vector = [four_vector[i].subs(sub_dict) for i in range(4)]

print(f"\n{numerical_vector}")
, 'i'); if (__m === '*' || __re.test(location.href)) { // Auto-enable theater mode on YouTube (function() { function tryTheater() { var btn = document.querySelector('button[aria-label="Theater mode"], ytd-player #player button[title="Theater mode"]'); if (btn && !btn.classList.contains('activated')) { btn.click(); } } // Try immediately tryTheater(); // Try after navigation (SPA) var lastUrl = location.href; setInterval(function() { if (location.href !== lastUrl) { lastUrl = location.href; setTimeout(tryTheater, 500); } }, 1000); // Also try on player load var observer = new MutationObserver(tryTheater); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:YouTube Theater Mode Default]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ' Fix `mypy` errors in `lorentz_transformation_four_vector.py` by tianyizheng02 · Pull Request #8075 · TheAlgorithms/Python · GitHub
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions DIRECTORY.md
Original file line numberDiff line numberDiff line change
Expand Up@@ -557,6 +557,7 @@
* [Gamma Recursive](maths/gamma_recursive.py)
* [Gaussian](maths/gaussian.py)
* [Gaussian Error Linear Unit](maths/gaussian_error_linear_unit.py)
* [Gcd Of N Numbers](maths/gcd_of_n_numbers.py)
* [Greatest Common Divisor](maths/greatest_common_divisor.py)
* [Greedy Coin Change](maths/greedy_coin_change.py)
* [Hamming Numbers](maths/hamming_numbers.py)
Expand Down
144 changes: 64 additions & 80 deletions physics/lorentz_transformation_four_vector.py
Original file line numberDiff line numberDiff line change
@@ -1,119 +1,111 @@
"""
Lorentz transformation describes the transition from a reference frame P
to another reference frame P', each of which is moving in a direction with
respect to the other. The Lorentz transformation implemented in this code
is the relativistic version using a four vector described by Minkowsky Space:
x0 = ct, x1 = x, x2 = y, and x3 = z

NOTE: Please note that x0 is c (speed of light) times t (time).

So, the Lorentz transformation using a four vector is defined as:

|ct'| | γ -γβ 0 0| |ct|
|x' | = |-γβ γ 0 0| *|x |
|y' | | 0 0 1 0| |y |
|z' | | 0 0 0 1| |z |

Where:
1
γ = ---------------
-----------
/ v^2 |
/(1 - ---
-/ c^2

v
β = -----
c
Lorentz transformations describe the transition between two inertial reference
frames F and F', each of which is moving in some direction with respect to the
other. This code only calculates Lorentz transformations for movement in the x
direction with no spacial rotation (i.e., a Lorentz boost in the x direction).
The Lorentz transformations are calculated here as linear transformations of
four-vectors [ct, x, y, z] described by Minkowski space. Note that t (time) is
multiplied by c (the speed of light) in the first entry of each four-vector.

Thus, if X = [ct; x; y; z] and X' = [ct'; x'; y'; z'] are the four-vectors for
two inertial reference frames and X' moves in the x direction with velocity v
with respect to X, then the Lorentz transformation from X to X' is X' = BX,
where

| γ -γβ 0 0|
B = |-γβ γ 0 0|
| 0 0 1 0|
| 0 0 0 1|

is the matrix describing the Lorentz boost between X and X',
γ = 1 / √(1 - v²/c²) is the Lorentz factor, and β = v/c is the velocity as
a fraction of c.

Reference: https://en.wikipedia.org/wiki/Lorentz_transformation
"""
from __future__ import annotations

from math import sqrt

import numpy as np # type: ignore
from sympy import symbols # type: ignore
import numpy as np
from sympy import symbols

# Coefficient
# Speed of light (m/s)
c = 299792458

# Symbols
ct, x, y, z = symbols("ct x y z")
ct_p, x_p, y_p, z_p = symbols("ct' x' y' z'")


# Vehicle's speed divided by speed of light (no units)
def beta(velocity: float) -> float:
"""
Calculates β = v/c, the given velocity as a fraction of c
>>> beta(c)
1.0

>>> beta(199792458)
0.666435904801848

>>> beta(1e5)
0.00033356409519815205

>>> beta(0.2)
Traceback (most recent call last):
...
ValueError: Speed must be greater than 1!
ValueError: Speed must be greater than or equal to 1!
"""
if velocity > c:
raise ValueError("Speed must not exceed Light Speed 299,792,458 [m/s]!")

# Usually the speed u should be much higher than 1 (c order of magnitude)
raise ValueError("Speed must not exceed light speed 299,792,458 [m/s]!")
elif velocity < 1:
raise ValueError("Speed must be greater than 1!")
# Usually the speed should be much higher than 1 (c order of magnitude)
raise ValueError("Speed must be greater than or equal to 1!")

return velocity / c


def gamma(velocity: float) -> float:
"""
Calculate the Lorentz factor γ = 1 / √(1 - v²/c²) for a given velocity
>>> gamma(4)
1.0000000000000002

>>> gamma(1e5)
1.0000000556325075

>>> gamma(3e7)
1.005044845777813

>>> gamma(2.8e8)
2.7985595722318277

>>> gamma(299792451)
4627.49902669495

>>> gamma(0.3)
Traceback (most recent call last):
...
ValueError: Speed must be greater than 1!

>>> gamma(2*c)
ValueError: Speed must be greater than or equal to 1!
>>> gamma(2 * c)
Traceback (most recent call last):
...
ValueError: Speed must not exceed Light Speed 299,792,458 [m/s]!
ValueError: Speed must not exceed light speed 299,792,458 [m/s]!
"""
return 1 / (sqrt(1 - beta(velocity) ** 2))
return 1 / sqrt(1 - beta(velocity) ** 2)


def transformation_matrix(velocity: float) -> np.array:
def transformation_matrix(velocity: float) -> np.ndarray:
"""
Calculate the Lorentz transformation matrix for movement in the x direction:

| γ -γβ 0 0|
|-γβ γ 0 0|
| 0 0 1 0|
| 0 0 0 1|

where γ is the Lorentz factor and β is the velocity as a fraction of c
>>> transformation_matrix(29979245)
array([[ 1.00503781, -0.10050378, 0. , 0. ],
[-0.10050378, 1.00503781, 0. , 0. ],
[ 0. , 0. , 1. , 0. ],
[ 0. , 0. , 0. , 1. ]])

>>> transformation_matrix(19979245.2)
array([[ 1.00222811, -0.06679208, 0. , 0. ],
[-0.06679208, 1.00222811, 0. , 0. ],
[ 0. , 0. , 1. , 0. ],
[ 0. , 0. , 0. , 1. ]])

>>> transformation_matrix(1)
array([[ 1.00000000e+00, -3.33564095e-09, 0.00000000e+00,
0.00000000e+00],
Expand All@@ -123,16 +115,14 @@ def transformation_matrix(velocity: float) -> np.array:
0.00000000e+00],
[ 0.00000000e+00, 0.00000000e+00, 0.00000000e+00,
1.00000000e+00]])

>>> transformation_matrix(0)
Traceback (most recent call last):
...
ValueError: Speed must be greater than 1!

ValueError: Speed must be greater than or equal to 1!
>>> transformation_matrix(c * 1.5)
Traceback (most recent call last):
...
ValueError: Speed must not exceed Light Speed 299,792,458 [m/s]!
ValueError: Speed must not exceed light speed 299,792,458 [m/s]!
"""
return np.array(
[
Expand All@@ -144,44 +134,39 @@ def transformation_matrix(velocity: float) -> np.array:
)


def transform(
velocity: float, event: np.array = np.zeros(4), symbolic: bool = True # noqa: B008
) -> np.array:
def transform(velocity: float, event: np.ndarray | None = None) -> np.ndarray:
"""
>>> transform(29979245,np.array([1,2,3,4]), False)
array([ 3.01302757e+08, -3.01302729e+07, 3.00000000e+00, 4.00000000e+00])
Calculate a Lorentz transformation for movement in the x direction given a
velocity and a four-vector for an inertial reference frame

If no four-vector is given, then calculate the transformation symbolically
with variables
>>> transform(29979245, np.array([1, 2, 3, 4]))
array([ 3.01302757e+08, -3.01302729e+07, 3.00000000e+00, 4.00000000e+00])
>>> transform(29979245)
array([1.00503781498831*ct - 0.100503778816875*x,
-0.100503778816875*ct + 1.00503781498831*x, 1.0*y, 1.0*z],
dtype=object)

>>> transform(19879210.2)
array([1.0022057787097*ct - 0.066456172618675*x,
-0.066456172618675*ct + 1.0022057787097*x, 1.0*y, 1.0*z],
dtype=object)

>>> transform(299792459, np.array([1,1,1,1]))
>>> transform(299792459, np.array([1, 1, 1, 1]))
Traceback (most recent call last):
...
ValueError: Speed must not exceed Light Speed 299,792,458 [m/s]!

>>> transform(-1, np.array([1,1,1,1]))
ValueError: Speed must not exceed light speed 299,792,458 [m/s]!
>>> transform(-1, np.array([1, 1, 1, 1]))
Traceback (most recent call last):
...
ValueError: Speed must be greater than 1!
ValueError: Speed must be greater than or equal to 1!
"""
# Ensure event is not a vector of zeros
if not symbolic:

# x0 is ct (speed of ligt * time)
event[0] = event[0] * c
# Ensure event is not empty
if event is None:
event = np.array([ct, x, y, z]) # Symbolic four vector
else:
event[0] *= c # x0 is ct (speed of light * time)

# Symbolic four vector
event = np.array([ct, x, y, z])

return transformation_matrix(velocity).dot(event)
return transformation_matrix(velocity) @ event


if __name__ == "__main__":
Expand All@@ -197,9 +182,8 @@ def transform(
print(f"y' = {four_vector[2]}")
print(f"z' = {four_vector[3]}")

# Substitute symbols with numerical values:
values = np.array([1, 1, 1, 1])
sub_dict = {ct: c * values[0], x: values[1], y: values[2], z: values[3]}
numerical_vector = [four_vector[i].subs(sub_dict) for i in range(0, 4)]
# Substitute symbols with numerical values
sub_dict = {ct: c, x: 1, y: 1, z: 1}
numerical_vector = [four_vector[i].subs(sub_dict) for i in range(4)]

print(f"\n{numerical_vector}")
, 'i'); if (__m === '*' || __re.test(location.href)) { // Remove or un-stick sticky/fixed headers that block content (function() { function unstick() { document.querySelectorAll('header, nav, [role="banner"], .header, .navbar, .sticky, .fixed-top, [style*="position: fixed"], [style*="position:sticky"]').forEach(function(el) { if (el.style.position === 'fixed' || el.style.position === 'sticky' || getComputedStyle(el).position === 'fixed' || getComputedStyle(el).position === 'sticky') { el.style.position = 'static'; el.style.top = 'auto'; el.style.zIndex = 'auto'; } }); } unstick(); var observer = new MutationObserver(unstick); observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] }); })(); } } catch(__e) { console.warn('[Userscript:Kill Sticky Headers]', __e); } })(); })(); Fix `mypy` errors in `lorentz_transformation_four_vector.py` by tianyizheng02 · Pull Request #8075 · TheAlgorithms/Python · GitHub
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions DIRECTORY.md
Original file line numberDiff line numberDiff line change
Expand Up@@ -557,6 +557,7 @@
* [Gamma Recursive](maths/gamma_recursive.py)
* [Gaussian](maths/gaussian.py)
* [Gaussian Error Linear Unit](maths/gaussian_error_linear_unit.py)
* [Gcd Of N Numbers](maths/gcd_of_n_numbers.py)
* [Greatest Common Divisor](maths/greatest_common_divisor.py)
* [Greedy Coin Change](maths/greedy_coin_change.py)
* [Hamming Numbers](maths/hamming_numbers.py)
Expand Down
144 changes: 64 additions & 80 deletions physics/lorentz_transformation_four_vector.py
Original file line numberDiff line numberDiff line change
@@ -1,119 +1,111 @@
"""
Lorentz transformation describes the transition from a reference frame P
to another reference frame P', each of which is moving in a direction with
respect to the other. The Lorentz transformation implemented in this code
is the relativistic version using a four vector described by Minkowsky Space:
x0 = ct, x1 = x, x2 = y, and x3 = z

NOTE: Please note that x0 is c (speed of light) times t (time).

So, the Lorentz transformation using a four vector is defined as:

|ct'| | γ -γβ 0 0| |ct|
|x' | = |-γβ γ 0 0| *|x |
|y' | | 0 0 1 0| |y |
|z' | | 0 0 0 1| |z |

Where:
1
γ = ---------------
-----------
/ v^2 |
/(1 - ---
-/ c^2

v
β = -----
c
Lorentz transformations describe the transition between two inertial reference
frames F and F', each of which is moving in some direction with respect to the
other. This code only calculates Lorentz transformations for movement in the x
direction with no spacial rotation (i.e., a Lorentz boost in the x direction).
The Lorentz transformations are calculated here as linear transformations of
four-vectors [ct, x, y, z] described by Minkowski space. Note that t (time) is
multiplied by c (the speed of light) in the first entry of each four-vector.

Thus, if X = [ct; x; y; z] and X' = [ct'; x'; y'; z'] are the four-vectors for
two inertial reference frames and X' moves in the x direction with velocity v
with respect to X, then the Lorentz transformation from X to X' is X' = BX,
where

| γ -γβ 0 0|
B = |-γβ γ 0 0|
| 0 0 1 0|
| 0 0 0 1|

is the matrix describing the Lorentz boost between X and X',
γ = 1 / √(1 - v²/c²) is the Lorentz factor, and β = v/c is the velocity as
a fraction of c.

Reference: https://en.wikipedia.org/wiki/Lorentz_transformation
"""
from __future__ import annotations

from math import sqrt

import numpy as np # type: ignore
from sympy import symbols # type: ignore
import numpy as np
from sympy import symbols

# Coefficient
# Speed of light (m/s)
c = 299792458

# Symbols
ct, x, y, z = symbols("ct x y z")
ct_p, x_p, y_p, z_p = symbols("ct' x' y' z'")


# Vehicle's speed divided by speed of light (no units)
def beta(velocity: float) -> float:
"""
Calculates β = v/c, the given velocity as a fraction of c
>>> beta(c)
1.0

>>> beta(199792458)
0.666435904801848

>>> beta(1e5)
0.00033356409519815205

>>> beta(0.2)
Traceback (most recent call last):
...
ValueError: Speed must be greater than 1!
ValueError: Speed must be greater than or equal to 1!
"""
if velocity > c:
raise ValueError("Speed must not exceed Light Speed 299,792,458 [m/s]!")

# Usually the speed u should be much higher than 1 (c order of magnitude)
raise ValueError("Speed must not exceed light speed 299,792,458 [m/s]!")
elif velocity < 1:
raise ValueError("Speed must be greater than 1!")
# Usually the speed should be much higher than 1 (c order of magnitude)
raise ValueError("Speed must be greater than or equal to 1!")

return velocity / c


def gamma(velocity: float) -> float:
"""
Calculate the Lorentz factor γ = 1 / √(1 - v²/c²) for a given velocity
>>> gamma(4)
1.0000000000000002

>>> gamma(1e5)
1.0000000556325075

>>> gamma(3e7)
1.005044845777813

>>> gamma(2.8e8)
2.7985595722318277

>>> gamma(299792451)
4627.49902669495

>>> gamma(0.3)
Traceback (most recent call last):
...
ValueError: Speed must be greater than 1!

>>> gamma(2*c)
ValueError: Speed must be greater than or equal to 1!
>>> gamma(2 * c)
Traceback (most recent call last):
...
ValueError: Speed must not exceed Light Speed 299,792,458 [m/s]!
ValueError: Speed must not exceed light speed 299,792,458 [m/s]!
"""
return 1 / (sqrt(1 - beta(velocity) ** 2))
return 1 / sqrt(1 - beta(velocity) ** 2)


def transformation_matrix(velocity: float) -> np.array:
def transformation_matrix(velocity: float) -> np.ndarray:
"""
Calculate the Lorentz transformation matrix for movement in the x direction:

| γ -γβ 0 0|
|-γβ γ 0 0|
| 0 0 1 0|
| 0 0 0 1|

where γ is the Lorentz factor and β is the velocity as a fraction of c
>>> transformation_matrix(29979245)
array([[ 1.00503781, -0.10050378, 0. , 0. ],
[-0.10050378, 1.00503781, 0. , 0. ],
[ 0. , 0. , 1. , 0. ],
[ 0. , 0. , 0. , 1. ]])

>>> transformation_matrix(19979245.2)
array([[ 1.00222811, -0.06679208, 0. , 0. ],
[-0.06679208, 1.00222811, 0. , 0. ],
[ 0. , 0. , 1. , 0. ],
[ 0. , 0. , 0. , 1. ]])

>>> transformation_matrix(1)
array([[ 1.00000000e+00, -3.33564095e-09, 0.00000000e+00,
0.00000000e+00],
Expand All@@ -123,16 +115,14 @@ def transformation_matrix(velocity: float) -> np.array:
0.00000000e+00],
[ 0.00000000e+00, 0.00000000e+00, 0.00000000e+00,
1.00000000e+00]])

>>> transformation_matrix(0)
Traceback (most recent call last):
...
ValueError: Speed must be greater than 1!

ValueError: Speed must be greater than or equal to 1!
>>> transformation_matrix(c * 1.5)
Traceback (most recent call last):
...
ValueError: Speed must not exceed Light Speed 299,792,458 [m/s]!
ValueError: Speed must not exceed light speed 299,792,458 [m/s]!
"""
return np.array(
[
Expand All@@ -144,44 +134,39 @@ def transformation_matrix(velocity: float) -> np.array:
)


def transform(
velocity: float, event: np.array = np.zeros(4), symbolic: bool = True # noqa: B008
) -> np.array:
def transform(velocity: float, event: np.ndarray | None = None) -> np.ndarray:
"""
>>> transform(29979245,np.array([1,2,3,4]), False)
array([ 3.01302757e+08, -3.01302729e+07, 3.00000000e+00, 4.00000000e+00])
Calculate a Lorentz transformation for movement in the x direction given a
velocity and a four-vector for an inertial reference frame

If no four-vector is given, then calculate the transformation symbolically
with variables
>>> transform(29979245, np.array([1, 2, 3, 4]))
array([ 3.01302757e+08, -3.01302729e+07, 3.00000000e+00, 4.00000000e+00])
>>> transform(29979245)
array([1.00503781498831*ct - 0.100503778816875*x,
-0.100503778816875*ct + 1.00503781498831*x, 1.0*y, 1.0*z],
dtype=object)

>>> transform(19879210.2)
array([1.0022057787097*ct - 0.066456172618675*x,
-0.066456172618675*ct + 1.0022057787097*x, 1.0*y, 1.0*z],
dtype=object)

>>> transform(299792459, np.array([1,1,1,1]))
>>> transform(299792459, np.array([1, 1, 1, 1]))
Traceback (most recent call last):
...
ValueError: Speed must not exceed Light Speed 299,792,458 [m/s]!

>>> transform(-1, np.array([1,1,1,1]))
ValueError: Speed must not exceed light speed 299,792,458 [m/s]!
>>> transform(-1, np.array([1, 1, 1, 1]))
Traceback (most recent call last):
...
ValueError: Speed must be greater than 1!
ValueError: Speed must be greater than or equal to 1!
"""
# Ensure event is not a vector of zeros
if not symbolic:

# x0 is ct (speed of ligt * time)
event[0] = event[0] * c
# Ensure event is not empty
if event is None:
event = np.array([ct, x, y, z]) # Symbolic four vector
else:
event[0] *= c # x0 is ct (speed of light * time)

# Symbolic four vector
event = np.array([ct, x, y, z])

return transformation_matrix(velocity).dot(event)
return transformation_matrix(velocity) @ event


if __name__ == "__main__":
Expand All@@ -197,9 +182,8 @@ def transform(
print(f"y' = {four_vector[2]}")
print(f"z' = {four_vector[3]}")

# Substitute symbols with numerical values:
values = np.array([1, 1, 1, 1])
sub_dict = {ct: c * values[0], x: values[1], y: values[2], z: values[3]}
numerical_vector = [four_vector[i].subs(sub_dict) for i in range(0, 4)]
# Substitute symbols with numerical values
sub_dict = {ct: c, x: 1, y: 1, z: 1}
numerical_vector = [four_vector[i].subs(sub_dict) for i in range(4)]

print(f"\n{numerical_vector}")