broadfield-dev's picture
Update app.py
c463819 verified
from flask import Flask, request, jsonify
import math
import os
app = Flask(__name__)
# Constants
C = 299792458 # Speed of light in m/s
G = 6.67430e-11 # Gravitational constant in m^3 kg^-1 s^-2
def gravitational_time_dilation(mass, radius, t0):
"""
Calculate gravitational time dilation factor based on mass and radius.
t0: Proper time for observer (seconds)
Returns: Dilated time (seconds)
"""
try:
rs = (2 * G * mass) / (C ** 2)
factor = math.sqrt(1 - rs / radius)
if factor <= 0 or math.isnan(factor):
return None
return t0 / factor
except Exception:
return None
def relativistic_time_dilation(velocity, t0):
"""
Calculate relativistic time dilation due to velocity.
velocity: Speed of observer (m/s)
t0: Proper time for observer (seconds)
Returns: Dilated time (seconds)
"""
try:
beta = velocity / C
if beta >= 1:
return None
factor = math.sqrt(1 - beta ** 2)
return t0 / factor
except Exception:
return None
@app.route('/')
def home():
return """
<html>
<head>
<title>Time Dilation Calculator</title>
<style>
body { font-family: Arial, sans-serif; margin: 20px; }
.container { max-width: 800px; margin: auto; }
.input-group { margin: 20px 0; }
label {
display: inline-block;
width: 200px;
cursor: pointer;
color: #007bff;
text-decoration: underline;
}
label:hover { color: #0056b3; }
input { padding: 5px; width: 200px; margin-left: 10px; }
button {
padding: 10px 20px;
margin: 20px 0;
background-color: #007bff;
color: white;
border: none;
cursor: pointer;
}
button:hover { background-color: #0056b3; }
#result { margin-top: 20px; padding: 10px; border: 1px solid #ddd; }
.popdown {
display: none;
margin-top: 5px;
padding: 10px;
background-color: #f8f9fa;
border: 1px solid #ddd;
border-radius: 4px;
max-width: 400px;
font-size: 14px;
}
.popdown.show { display: block; }
</style>
</head>
<body>
<div class='container'>
<h1>Time Dilation Calculator</h1>
<p>Calculate gravitational and relativistic time dilation for two observers.</p>
<div class='input-group'>
<h3>Observer 1</h3>
<div>
<label onclick="togglePopdown('mass1-info')">Mass (kg):</label>
<input type='number' id='mass1' value='5.972e24'>
<div id='mass1-info' class='popdown'>
The mass of the object (e.g., planet or star) affecting Observer 1, in kilograms.
This determines the strength of the gravitational field. For example, Earth's mass is approximately 5.972 × 10²⁴ kg.
Larger masses cause greater gravitational time dilation, slowing time for the observer.
</div>
</div>
<div>
<label onclick="togglePopdown('radius1-info')">Radius (m):</label>
<input type='number' id='radius1' value='6.371e6'>
<div id='radius1-info' class='popdown'>
The distance from the center of the massive object to Observer 1, in meters.
This is typically the radius of the planet or star. For example, Earth's radius is about 6.371 × 10⁶ m.
Smaller radii (closer to the mass) increase gravitational time dilation.
</div>
</div>
<div>
<label onclick="togglePopdown('velocity1-info')">Velocity (m/s):</label>
<input type='number' id='velocity1' value='0'>
<div id='velocity1-info' class='popdown'>
The speed of Observer 1 relative to a stationary reference frame, in meters per second.
This affects relativistic time dilation. For example, a velocity of 0 m/s means no relativistic effects,
while high speeds (e.g., 0.5 × speed of light) significantly slow time. Must be less than 299,792,458 m/s.
</div>
</div>
</div>
<div class='input-group'>
<h3>Observer 2</h3>
<div>
<label onclick="togglePopdown('mass2-info')">Mass (kg):</label>
<input type='number' id='mass2' value='5.972e26'>
<div id='mass2-info' class='popdown'>
The mass of the object affecting Observer 2, in kilograms.
For example, a planet 100 times Earth's mass would be 5.972 × 10²⁶ kg.
This influences gravitational time dilation, with larger masses causing greater time dilation.
</div>
</div>
<div>
<label onclick="togglePopdown('radius2-info')">Radius (m):</label>
<input type='number' id='radius2' value='6.371e6'>
<div id='radius2-info' class='popdown'>
The distance from the center of the massive object to Observer 2, in meters.
For example, using Earth's radius (6.371 × 10⁶ m) assumes Observer 2 is on the surface.
Smaller distances amplify gravitational time dilation effects.
</div>
</div>
<div>
<label onclick="togglePopdown('velocity2-info')">Velocity (m/s):</label>
<input type='number' id='velocity2' value='0'>
<div id='velocity2-info' class='popdown'>
The speed of Observer 2 relative to a stationary reference frame, in meters per second.
High velocities cause relativistic time dilation, slowing time for the observer.
Set to 0 for no relativistic effects. Must be less than the speed of light (299,792,458 m/s).
</div>
</div>
</div>
<div class='input-group'>
<div>
<label onclick="togglePopdown('proper_time-info')">Proper Time (s):</label>
<input type='number' id='proper_time' value='86400'>
<div id='proper_time-info' class='popdown'>
The time experienced by a reference observer in a weak gravitational field and at rest, in seconds.
For example, 86,400 seconds equals 1 day. This is the baseline time used to calculate how much
time each observer experiences after dilation effects are applied.
</div>
</div>
</div>
<button onclick='calculate()'>Calculate</button>
<div id='result'></div>
</div>
<script>
function togglePopdown(id) {
const popdown = document.getElementById(id);
popdown.classList.toggle('show');
}
async function calculate() {
const data = {
mass1: parseFloat(document.getElementById('mass1').value),
radius1: parseFloat(document.getElementById('radius1').value),
velocity1: parseFloat(document.getElementById('velocity1').value),
mass2: parseFloat(document.getElementById('mass2').value),
radius2: parseFloat(document.getElementById('radius2').value),
velocity2: parseFloat(document.getElementById('velocity2').value),
proper_time: parseFloat(document.getElementById('proper_time').value)
};
const response = await fetch('/calculate', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(data)
});
const result = await response.json();
document.getElementById('result').innerHTML = result.message.replace(/\\n/g, '<br>');
}
</script>
</body>
</html>
"""
@app.route('/calculate', methods=['POST'])
def calculate():
try:
data = request.get_json()
mass1 = data.get('mass1')
radius1 = data.get('radius1')
velocity1 = data.get('velocity1', 0)
mass2 = data.get('mass2')
radius2 = data.get('radius2')
velocity2 = data.get('velocity2', 0)
t0 = data.get('proper_time')
if not all([mass1, radius1, mass2, radius2, t0]) or any(x <= 0 for x in [mass1, radius1, mass2, radius2, t0]):
return jsonify({"message": "Invalid input: All values must be positive numbers."}), 400
t1_grav = gravitational_time_dilation(mass1, radius1, t0)
t2_grav = gravitational_time_dilation(mass2, radius2, t0)
if t1_grav is None or t2_grav is None:
return jsonify({"message": "Error: Invalid gravitational parameters (e.g., within event horizon)."}), 400
t1_rel = relativistic_time_dilation(velocity1, t0) if velocity1 > 0 else t0
t2_rel = relativistic_time_dilation(velocity2, t0) if velocity2 > 0 else t0
if (velocity1 > 0 and t1_rel is None) or (velocity2 > 0 and t2_rel is None):
return jsonify({"message": "Error: Velocity exceeds speed of light."}), 400
t1_total = t1_grav if velocity1 == 0 else t1_grav * (t1_rel / t0)
t2_total = t2_grav if velocity2 == 0 else t2_grav * (t2_rel / t0)
time_diff = abs(t1_total - t2_total)
message = (
f"Results for proper time {t0:.2f} seconds:\n"
f"Observer 1:\n"
f" Gravitational dilated time: {t1_grav:.2f} seconds\n"
f" Relativistic dilated time: {t1_rel:.2f} seconds\n"
f" Total dilated time: {t1_total:.2f} seconds\n"
f"Observer 2:\n"
f" Gravitational dilated time: {t2_grav:.2f} seconds\n"
f" Relativistic dilated time: {t2_rel:.2f} seconds\n"
f" Total dilated time: {t2_total:.2f} seconds\n"
f"Relative time difference: {time_diff:.2f} seconds"
)
return jsonify({"message": message})
except Exception as e:
return jsonify({"message": f"Error: {str(e)}"}), 500
if __name__ == '__main__':
port = int(os.environ.get("PORT", 7860))
app.run(host='0.0.0.0', port=port)