dual-general-relativity 1.0.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Dual General Relativity
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,151 @@
1
+ Metadata-Version: 2.5
2
+ Name: dual-general-relativity
3
+ Version: 1.0.0
4
+ Summary: Dual General Relativity (DGR): companion metric f = 2 eta - g, separate GR and DGR systems, Flask app to compute curvature, C / Rcal, eps = G - 8 pi T, and implied stress tensor.
5
+ Project-URL: Homepage, https://github.com/YOUR-USERNAME/dual-general-relativity
6
+ Project-URL: Repository, https://github.com/YOUR-USERNAME/dual-general-relativity
7
+ Project-URL: Issues, https://github.com/YOUR-USERNAME/dual-general-relativity/issues
8
+ Author: Dual General Relativity
9
+ License-Expression: MIT
10
+ License-File: LICENSE
11
+ Keywords: differential-geometry,flask,general-relativity,sympy
12
+ Classifier: Intended Audience :: Science/Research
13
+ Classifier: License :: OSI Approved :: MIT License
14
+ Classifier: Operating System :: OS Independent
15
+ Classifier: Programming Language :: Python :: 3
16
+ Classifier: Topic :: Scientific/Engineering :: Physics
17
+ Requires-Python: >=3.9
18
+ Requires-Dist: flask
19
+ Requires-Dist: numpy
20
+ Requires-Dist: sympy
21
+ Description-Content-Type: text/markdown
22
+
23
+ # Dual General Relativity
24
+
25
+ **Dual General Relativity (DGR)** — one repo, two distributions, same name:
26
+
27
+ - **GitHub:** `dual-general-relativity`
28
+ - **PyPI:** `dual-general-relativity`
29
+
30
+ ## The theory in one paragraph
31
+
32
+ Constraint: $2\eta = g + f$. $g$ is the input metric, $f = 2\eta - g$ is the companion.
33
+ GR: $R[g] + S_g \to G[g] = 8\pi T(g)$.
34
+ DGR: $R[f] + S_f \to G[f] = 8\pi T(f)$.
35
+ The two systems are **separate**; the constraint links solutions only. There is no combined action.
36
+
37
+ ## T rule (read this before using the app)
38
+
39
+ - **Blank = symbolic UNKNOWN, never 0.**
40
+ - **T = 0 ONLY** when explicitly written as a zero matrix, or when `Vacuum` mode is chosen.
41
+ - A **defined** T in a preset is **NOT zero** (except the vacuum presets):
42
+ FLRW / interior: defined T is the non-zero perfect fluid.
43
+ Schwarzschild / Schwarzschild-companion Tf: defined T = 0 (vacuum).
44
+ Companion blanks (FLRW / interior / Schwarzschild Tg): unknown dual matter, NOT 0.
45
+ - If T is symbolic, the `eps = G - 8 pi T = 0` check is **N/A**, not FAIL.
46
+ FAIL means T was explicitly given and `G - 8 pi T != 0`.
47
+
48
+ ## Install
49
+
50
+ ### From PyPI (once published)
51
+
52
+ ```bash
53
+ pip install dual-general-relativity
54
+ dual-general-relativity
55
+ # open http://127.0.0.1:5000
56
+ ```
57
+
58
+ ### From GitHub / source
59
+
60
+ ```bash
61
+ git clone https://github.com/YOUR-USERNAME/dual-general-relativity
62
+ cd dual-general-relativity
63
+ pip install -e .
64
+ dual-general-relativity
65
+ ```
66
+
67
+ Or without installing:
68
+
69
+ ```bash
70
+ pip install -r requirements.txt
71
+ python -m dual_general_relativity
72
+ ```
73
+
74
+ ### As a library
75
+
76
+ ```python
77
+ import sympy as sp
78
+ from dual_general_relativity import compute_all
79
+
80
+ t, r, th, ph = sp.symbols("t r theta phi")
81
+ coords = [t, r, th, ph]
82
+ # g = your metric (SymPy Matrix), eta = flat background in same coordinates
83
+ res = compute_all(g, coords, eta, Tf="zero") # Tf="zero" = explicit vacuum
84
+ print(res["f"]) # companion metric
85
+ print(res["G_f"]) # Einstein tensor of f
86
+ print(res["eps_f"]) # G(f) - 8 pi T(f)
87
+ print(res["C"]) # C = R(f) + Rcal
88
+ ```
89
+
90
+ ## The web app
91
+
92
+ - Single page, same-page results, progress bar, MathJax.
93
+ - Enter $g$ (and $T$, if known) as SymPy expressions. Rows by `;` or newline, entries by `,`.
94
+ - 8 presets: minkowski, minkowski-companion, schwarzschild, schwarzschild-companion,
95
+ flrw, flrw-companion, interior, interior-companion. Companion = $g \to 2\eta - g$.
96
+ - **Compute mode:** `Full` = all quantities incl. Rcal / C. `Fast` = substitute M, R, ... from the
97
+ Evaluation point before curvature, skip Rcal / C, keep G, eps, T_imp, rho/p.
98
+ Use **Fast** for interior on an old laptop: ~6 s here vs ~80 s Full (old code: ~7 min).
99
+ In Fast mode Rcal / C are reported as skipped — ignore the Rcal=0, C=R(f) placeholders.
100
+ - **Implied stress tensor:** for each sector, $T_{imp} = G / 8\pi$ — the T that *would* make eps = 0 —
101
+ plus for diagonal metrics $\rho_{imp} = -T^t{}_t$ and $p_{imp,i} = T^i{}_i$.
102
+ This is the direct test of the paper's claim: take a normal-matter solution (interior, FLRW),
103
+ form its companion, and read off the companion's implied matter. For interior,
104
+ $\rho^{(f)}_{imp} < 0$ and $\rho^{(f)}_{imp} + p^{(f)}_{imp} < 0$: the companion violates
105
+ the usual energy conditions.
106
+
107
+ ## Behaviour / limitations (unchanged from the app)
108
+
109
+ - C explicit formula uses **(M + delta)**, not (M - delta). (M - delta) fails at O(h^2).
110
+ - C check is independent and only runs when d(eta) = 0 (Cartesian); otherwise N/A.
111
+ There is no independent C check in spherical coordinates: eta itself depends on r, theta,
112
+ so the (M + delta) formula as written does not apply. The identity R[f] = -Rcal + C still
113
+ holds by definition of C.
114
+ - G(f) decomposition is an identity by definition of C, not a test; labelled as such.
115
+ - Signature check (needs numpy) + det g / det f shown; checks are PASS / FAIL / N/A.
116
+ - No combined-action residual: GR and DGR are kept as separate systems by design.
117
+ - Security: the app runs `sympify` on user text and `debug=True`. Run locally only,
118
+ never expose it to the internet.
119
+
120
+ ## Publishing (maintainer)
121
+
122
+ Replace `YOUR-USERNAME` in `pyproject.toml` and this README with your GitHub username,
123
+ then:
124
+
125
+ ```bash
126
+ # GitHub
127
+ git init
128
+ git add .
129
+ git commit -m "Dual General Relativity v0.1.0"
130
+ git branch -M main
131
+ git remote add origin https://github.com/YOUR-USERNAME/dual-general-relativity.git
132
+ git push -u origin main
133
+
134
+ # PyPI — check the name first at https://pypi.org/project/dual-general-relativity/
135
+ pip install build twine
136
+ python -m build
137
+ twine upload dist/*
138
+ ```
139
+
140
+ ## Files
141
+
142
+ - `src/dual_general_relativity/compute.py` — DGR computation
143
+ - `src/dual_general_relativity/server.py` — Flask app (`dual-general-relativity` command)
144
+ - `tests/test_dgr.py` — smoke tests (`pytest`)
145
+ - `pyproject.toml` — PyPI packaging (Hatchling, `src` layout)
146
+ - `requirements.txt` — Flask, SymPy, NumPy
147
+ - `LICENSE` — MIT
148
+
149
+ ## License
150
+
151
+ MIT — see `LICENSE`.
@@ -0,0 +1,129 @@
1
+ # Dual General Relativity
2
+
3
+ **Dual General Relativity (DGR)** — one repo, two distributions, same name:
4
+
5
+ - **GitHub:** `dual-general-relativity`
6
+ - **PyPI:** `dual-general-relativity`
7
+
8
+ ## The theory in one paragraph
9
+
10
+ Constraint: $2\eta = g + f$. $g$ is the input metric, $f = 2\eta - g$ is the companion.
11
+ GR: $R[g] + S_g \to G[g] = 8\pi T(g)$.
12
+ DGR: $R[f] + S_f \to G[f] = 8\pi T(f)$.
13
+ The two systems are **separate**; the constraint links solutions only. There is no combined action.
14
+
15
+ ## T rule (read this before using the app)
16
+
17
+ - **Blank = symbolic UNKNOWN, never 0.**
18
+ - **T = 0 ONLY** when explicitly written as a zero matrix, or when `Vacuum` mode is chosen.
19
+ - A **defined** T in a preset is **NOT zero** (except the vacuum presets):
20
+ FLRW / interior: defined T is the non-zero perfect fluid.
21
+ Schwarzschild / Schwarzschild-companion Tf: defined T = 0 (vacuum).
22
+ Companion blanks (FLRW / interior / Schwarzschild Tg): unknown dual matter, NOT 0.
23
+ - If T is symbolic, the `eps = G - 8 pi T = 0` check is **N/A**, not FAIL.
24
+ FAIL means T was explicitly given and `G - 8 pi T != 0`.
25
+
26
+ ## Install
27
+
28
+ ### From PyPI (once published)
29
+
30
+ ```bash
31
+ pip install dual-general-relativity
32
+ dual-general-relativity
33
+ # open http://127.0.0.1:5000
34
+ ```
35
+
36
+ ### From GitHub / source
37
+
38
+ ```bash
39
+ git clone https://github.com/YOUR-USERNAME/dual-general-relativity
40
+ cd dual-general-relativity
41
+ pip install -e .
42
+ dual-general-relativity
43
+ ```
44
+
45
+ Or without installing:
46
+
47
+ ```bash
48
+ pip install -r requirements.txt
49
+ python -m dual_general_relativity
50
+ ```
51
+
52
+ ### As a library
53
+
54
+ ```python
55
+ import sympy as sp
56
+ from dual_general_relativity import compute_all
57
+
58
+ t, r, th, ph = sp.symbols("t r theta phi")
59
+ coords = [t, r, th, ph]
60
+ # g = your metric (SymPy Matrix), eta = flat background in same coordinates
61
+ res = compute_all(g, coords, eta, Tf="zero") # Tf="zero" = explicit vacuum
62
+ print(res["f"]) # companion metric
63
+ print(res["G_f"]) # Einstein tensor of f
64
+ print(res["eps_f"]) # G(f) - 8 pi T(f)
65
+ print(res["C"]) # C = R(f) + Rcal
66
+ ```
67
+
68
+ ## The web app
69
+
70
+ - Single page, same-page results, progress bar, MathJax.
71
+ - Enter $g$ (and $T$, if known) as SymPy expressions. Rows by `;` or newline, entries by `,`.
72
+ - 8 presets: minkowski, minkowski-companion, schwarzschild, schwarzschild-companion,
73
+ flrw, flrw-companion, interior, interior-companion. Companion = $g \to 2\eta - g$.
74
+ - **Compute mode:** `Full` = all quantities incl. Rcal / C. `Fast` = substitute M, R, ... from the
75
+ Evaluation point before curvature, skip Rcal / C, keep G, eps, T_imp, rho/p.
76
+ Use **Fast** for interior on an old laptop: ~6 s here vs ~80 s Full (old code: ~7 min).
77
+ In Fast mode Rcal / C are reported as skipped — ignore the Rcal=0, C=R(f) placeholders.
78
+ - **Implied stress tensor:** for each sector, $T_{imp} = G / 8\pi$ — the T that *would* make eps = 0 —
79
+ plus for diagonal metrics $\rho_{imp} = -T^t{}_t$ and $p_{imp,i} = T^i{}_i$.
80
+ This is the direct test of the paper's claim: take a normal-matter solution (interior, FLRW),
81
+ form its companion, and read off the companion's implied matter. For interior,
82
+ $\rho^{(f)}_{imp} < 0$ and $\rho^{(f)}_{imp} + p^{(f)}_{imp} < 0$: the companion violates
83
+ the usual energy conditions.
84
+
85
+ ## Behaviour / limitations (unchanged from the app)
86
+
87
+ - C explicit formula uses **(M + delta)**, not (M - delta). (M - delta) fails at O(h^2).
88
+ - C check is independent and only runs when d(eta) = 0 (Cartesian); otherwise N/A.
89
+ There is no independent C check in spherical coordinates: eta itself depends on r, theta,
90
+ so the (M + delta) formula as written does not apply. The identity R[f] = -Rcal + C still
91
+ holds by definition of C.
92
+ - G(f) decomposition is an identity by definition of C, not a test; labelled as such.
93
+ - Signature check (needs numpy) + det g / det f shown; checks are PASS / FAIL / N/A.
94
+ - No combined-action residual: GR and DGR are kept as separate systems by design.
95
+ - Security: the app runs `sympify` on user text and `debug=True`. Run locally only,
96
+ never expose it to the internet.
97
+
98
+ ## Publishing (maintainer)
99
+
100
+ Replace `YOUR-USERNAME` in `pyproject.toml` and this README with your GitHub username,
101
+ then:
102
+
103
+ ```bash
104
+ # GitHub
105
+ git init
106
+ git add .
107
+ git commit -m "Dual General Relativity v0.1.0"
108
+ git branch -M main
109
+ git remote add origin https://github.com/YOUR-USERNAME/dual-general-relativity.git
110
+ git push -u origin main
111
+
112
+ # PyPI — check the name first at https://pypi.org/project/dual-general-relativity/
113
+ pip install build twine
114
+ python -m build
115
+ twine upload dist/*
116
+ ```
117
+
118
+ ## Files
119
+
120
+ - `src/dual_general_relativity/compute.py` — DGR computation
121
+ - `src/dual_general_relativity/server.py` — Flask app (`dual-general-relativity` command)
122
+ - `tests/test_dgr.py` — smoke tests (`pytest`)
123
+ - `pyproject.toml` — PyPI packaging (Hatchling, `src` layout)
124
+ - `requirements.txt` — Flask, SymPy, NumPy
125
+ - `LICENSE` — MIT
126
+
127
+ ## License
128
+
129
+ MIT — see `LICENSE`.
@@ -0,0 +1,21 @@
1
+ """Dual General Relativity (DGR).
2
+
3
+ Constraint: 2 eta = g + f. g is the input metric, f = 2 eta - g is the
4
+ companion. GR: R[g] + S_g -> G[g] = 8 pi T(g). DGR: R[f] + S_f -> G[f] = 8 pi T(f).
5
+ The two systems are separate; the constraint links solutions only.
6
+
7
+ T rule: blank = symbolic UNKNOWN, never 0. T = 0 only when explicitly
8
+ written as a zero matrix, or when Vacuum mode is chosen.
9
+ """
10
+ from .compute import compute_all, curvature_all, implied_T, mixed_T
11
+
12
+ __version__ = "0.1.0"
13
+ __all__ = ["compute_all", "curvature_all", "implied_T", "mixed_T", "create_app", "main"]
14
+
15
+ def __getattr__(name):
16
+ # create_app / main need Flask, so they are imported lazily:
17
+ # `import dual_general_relativity` works for library use without Flask.
18
+ if name in ("create_app", "main"):
19
+ from .server import create_app, main
20
+ return {"create_app": create_app, "main": main}[name]
21
+ raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
@@ -0,0 +1,5 @@
1
+ """`python -m dual_general_relativity` launches the web app."""
2
+ from .server import main
3
+
4
+ if __name__ == "__main__":
5
+ main()
@@ -0,0 +1,299 @@
1
+ """DGR computation: curvature, companion metric, C / Rcal, eps, implied T."""
2
+
3
+
4
+ """
5
+ Dual General Relativity (DGR) — compute everything from g only.
6
+ ================================================================
7
+ Convention used here (paper convention):
8
+ eta = fixed flat background, in the coordinates you give
9
+ (Cartesian: diag(-1,1,1,1); spherical: diag(-1,1,r^2,r^2 sin^2 th))
10
+ g = ONLY INPUT (the metric you feed in)
11
+ f = 2*eta - g (derived companion / dual metric)
12
+ M^l_r = f^{l a} g_{a r}
13
+
14
+ Computed:
15
+ f_{mu nu}
16
+ R^{(f)}_{mu nu}, R^{(g)}_{mu nu}, R^{(f)}, R^{(g)}
17
+ Rcal_{mu nu} = M^l_a R^a_{mu l nu}[g] (NOT Ricci of g)
18
+ C_{mu nu} = R_{mu nu}[f] + Rcal_{mu nu}
19
+ C = f^{mu nu} C_{mu nu}, Rcal = f^{mu nu} Rcal_{mu nu}
20
+ G^{(f)}_{mu nu} = direct Einstein of f
21
+ = -(Rcal_{mu nu} - 1/2 Rcal f_{mu nu})
22
+ + (C_{mu nu} - 1/2 C f_{mu nu}) <-- checked
23
+ G^{(g)}_{mu nu} = direct Einstein of g
24
+ T^{(f)}_{mu nu}, T^{(g)}_{mu nu} = supplied tensors. RULE: blank / None = symbolic UNKNOWN.
25
+ T = 0 ONLY when explicitly given as a zero matrix or t_mode='zero' / 'zero' string.
26
+ eps^{(f)}_{mu nu} = G^{(f)}_{mu nu} - 8*pi*T^{(f)}_{mu nu}
27
+ eps^{(g)}_{mu nu} = G^{(g)}_{mu nu} - 8*pi*T^{(g)}_{mu nu}
28
+
29
+ T is NOT computed from matter. RULE: blank / None = symbolic UNKNOWN, never 0.
30
+ T = 0 only when explicitly supplied as zero. A defined T in a preset (FLRW/interior fluid) is NOT zero.
31
+ eps == 0 <=> Einstein equation holds for that sector.
32
+
33
+ Usage:
34
+ python dgr_compute.py # runs Schwarzschild + Minkowski checks
35
+ from dgr_compute import compute_all # in your own script
36
+ """
37
+ import sympy as sp
38
+
39
+ def _fsimp(e):
40
+ # Fast simplification: cancel + factor only. Full sp.simplify() on sqrt
41
+ # expressions (interior solution) is what made the interior presets time out.
42
+ # Results are mathematically identical; only the final form may be less reduced.
43
+ if e == 0:
44
+ return sp.S(0)
45
+ try:
46
+ return sp.factor(sp.cancel(sp.together(e)))
47
+ except Exception:
48
+ return e
49
+
50
+ # ---------------------------------------------------------------- helpers
51
+ def inv(m):
52
+ return _fsimp(m.inv())
53
+
54
+ def christoffel(g, ginv, coords):
55
+ n = len(coords)
56
+ Gamma = [[[sp.S(0)]*n for _ in range(n)] for _ in range(n)] # Gamma[l][m][n]
57
+ for l in range(n):
58
+ for m in range(n):
59
+ for nu in range(n):
60
+ s = 0
61
+ for sidx in range(n):
62
+ s += ginv[l, sidx] * (sp.diff(g[sidx, nu], coords[m])
63
+ + sp.diff(g[sidx, m], coords[nu])
64
+ - sp.diff(g[m, nu], coords[sidx]))
65
+ Gamma[l][m][nu] = _fsimp(s/2)
66
+ return Gamma
67
+
68
+ def riemann(Gamma, coords):
69
+ """R^rho_{sigma mu nu} = d_mu Gamma^rho_{nu sigma} - d_nu Gamma^rho_{mu sigma}
70
+ + Gamma^rho_{mu lam} Gamma^lam_{nu sigma} - Gamma^rho_{nu lam} Gamma^lam_{mu sigma}"""
71
+ n = len(coords)
72
+ R = [[[[sp.S(0)]*n for _ in range(n)] for _ in range(n)] for _ in range(n)]
73
+ for rho in range(n):
74
+ for sig in range(n):
75
+ for mu in range(n):
76
+ for nu in range(n):
77
+ s = (sp.diff(Gamma[rho][nu][sig], coords[mu])
78
+ - sp.diff(Gamma[rho][mu][sig], coords[nu]))
79
+ for lam in range(n):
80
+ s += Gamma[rho][mu][lam]*Gamma[lam][nu][sig]
81
+ s -= Gamma[rho][nu][lam]*Gamma[lam][mu][sig]
82
+ R[rho][sig][mu][nu] = _fsimp(s)
83
+ return R
84
+
85
+ def ricci_from_riemann(R):
86
+ """R_{sigma nu} = R^lam_{sigma lam nu} == d_lam Gamma^lam_{nu sigma}
87
+ - d_nu Gamma^lam_{lam sigma} + ... (paper convention)."""
88
+ n = len(R)
89
+ Ric = sp.zeros(n)
90
+ for sig in range(n):
91
+ for nu in range(n):
92
+ Ric[sig, nu] = _fsimp(sum(R[lam][sig][lam][nu] for lam in range(n)))
93
+ return Ric
94
+
95
+ def scalar_from_ricci(ginv, Ric):
96
+ return _fsimp(sum(ginv[i, j]*Ric[i, j] for i in range(ginv.rows) for j in range(ginv.cols)))
97
+
98
+ def einstein_from(Ric, Rscalar, g):
99
+ n = g.rows
100
+ return _fsimp(Ric - sp.Rational(1, 2)*Rscalar*g)
101
+
102
+ def curvature_all(g, coords):
103
+ ginv = inv(g)
104
+ G = christoffel(g, ginv, coords)
105
+ Riem = riemann(G, coords)
106
+ Ric = ricci_from_riemann(Riem)
107
+ Rs = scalar_from_ricci(ginv, Ric)
108
+ Ein = einstein_from(Ric, Rs, g)
109
+ return dict(ginv=ginv, Gamma=G, Riem=Riem, Ric=Ric, Rscalar=Rs, G=Ein)
110
+
111
+ # ---------------------------------------------------------------- DGR
112
+
113
+ def eta_is_const(eta, coords):
114
+ """True iff eta has zero derivatives wrt coords (Cartesian inertial coords)."""
115
+ try:
116
+ return all(sp.simplify(sp.diff(eta[i, j], c)) == 0 for i in range(eta.rows) for j in range(eta.cols) for c in coords)
117
+ except Exception:
118
+ return False
119
+
120
+ def c_formula(M, Gg, coords):
121
+ """Explicit C_{mu nu} (valid only when d(eta)=0):
122
+ C = -(d_l M^l_a) G^a_{nu mu} + (d_nu M^l_a) G^a_{l mu}
123
+ + M^l_a (M^k_b + delta^k_b) G^a_{l k} G^b_{nu mu}
124
+ - M^l_a (M^k_b + delta^k_b) G^a_{nu k} G^b_{l mu}
125
+ NOTE factor is (M + delta), NOT (M - delta). (M - delta) fails at O(h^2)."""
126
+ n = len(coords)
127
+ dM = [[[sp.diff(M[l, r], coords[mu]) for mu in range(n)] for r in range(n)] for l in range(n)]
128
+ C = sp.zeros(n)
129
+ for mu in range(n):
130
+ for nu in range(n):
131
+ s = 0
132
+ for lam in range(n):
133
+ for a in range(n):
134
+ s += -dM[lam][a][lam]*Gg[a][nu][mu]
135
+ s += dM[lam][a][nu]*Gg[a][lam][mu]
136
+ for lam in range(n):
137
+ for a in range(n):
138
+ for kap in range(n):
139
+ for b in range(n):
140
+ d = M[kap, b] + (1 if kap == b else 0)
141
+ s += M[lam, a]*d*Gg[a][lam][kap]*Gg[b][nu][mu]
142
+ s -= M[lam, a]*d*Gg[a][nu][kap]*Gg[b][lam][mu]
143
+ C[mu, nu] = sp.simplify(s)
144
+ return C
145
+
146
+ def signature_at(mat, subs):
147
+ """Numerical signature (n_negative, n_positive, n_zero) at a point, or None."""
148
+ try:
149
+ import numpy as np
150
+ A = np.array(mat.subs(subs).evalf().tolist(), dtype=float)
151
+ ev = np.linalg.eigvalsh((A + A.T)/2)
152
+ tol = 1e-9*max(1.0, float(np.abs(ev).max()))
153
+ return int((ev < -tol).sum()), int((ev > tol).sum()), int((np.abs(ev) <= tol).sum())
154
+ except Exception:
155
+ return None
156
+
157
+ def is_lorentzian(sig):
158
+ return sig is not None and sig[0] == 1 and sig[2] == 0
159
+
160
+ def compute_all(g, coords, eta, Tf=None, Tg=None, simplify=True):
161
+ """
162
+ g : sympy Matrix (n x n), the ONLY metric input
163
+ coords: list of sympy symbols
164
+ eta : sympy Matrix (n x n), flat background in SAME coordinates
165
+ Tf,Tg : optional sympy Matrices (n x n) of unknown functions.
166
+ RULE: If None / blank -> symbolic unknowns Tf_mu_nu(coords), Tg_mu_nu(coords) are created (NEVER 0).
167
+ Pass 'zero' or an explicit zero matrix for vacuum T = 0. Pass 'symbolic' for explicit unknown.
168
+ Returns dict with every quantity.
169
+ """
170
+ n = len(coords)
171
+ pi = sp.pi
172
+ # RULE: None / blank = symbolic UNKNOWN, never 0. 'zero' = explicit vacuum.
173
+ if isinstance(Tf, str) and Tf == 'zero':
174
+ Tf = sp.zeros(n)
175
+ elif Tf is None or (isinstance(Tf, str) and Tf == 'symbolic'):
176
+ Tf = sp.Matrix(n, n, lambda i, j: sp.Function(f'Tf_{i}{j}')(*coords) if i <= j else sp.Function(f'Tf_{j}{i}')(*coords))
177
+ if isinstance(Tg, str) and Tg == 'zero':
178
+ Tg = sp.zeros(n)
179
+ elif Tg is None or (isinstance(Tg, str) and Tg == 'symbolic'):
180
+ Tg = sp.Matrix(n, n, lambda i, j: sp.Function(f'Tg_{i}{j}')(*coords) if i <= j else sp.Function(f'Tg_{j}{i}')(*coords))
181
+ # symmetrise T (T_mu_nu = T_nu_mu)
182
+ Tf = sp.Matrix(n, n, lambda i, j: Tf[min(i, j), max(i, j)])
183
+ Tg = sp.Matrix(n, n, lambda i, j: Tg[min(i, j), max(i, j)])
184
+
185
+ f = _fsimp(2*eta - g)
186
+
187
+ cur_g = curvature_all(g, coords) # R^{(g)}, G^{(g)}
188
+ cur_f = curvature_all(f, coords) # R^{(f)}, G^{(f)}
189
+
190
+ finv = cur_f['ginv']
191
+ # M^l_r = f^{l a} g_{a r}
192
+ M = _fsimp(finv * g)
193
+ Minv = _fsimp(cur_g['ginv'] * f) # = g^{-1} f
194
+
195
+ # Rcal_{mu nu} = M^lam_a * R^a_{mu lam nu}[g]
196
+ Rg = cur_g['Riem']
197
+ Rcal = sp.zeros(n)
198
+ for mu in range(n):
199
+ for nu in range(n):
200
+ Rcal[mu, nu] = _fsimp(sum(M[lam, a]*Rg[a][mu][lam][nu] for lam in range(n) for a in range(n)))
201
+ Rcal_scalar = _fsimp(sum(finv[mu, nu]*Rcal[mu, nu] for mu in range(n) for nu in range(n)))
202
+
203
+ # C_{mu nu} = R_{mu nu}[f] + Rcal_{mu nu} (since R[f] = -Rcal + C)
204
+ Cmat = _fsimp(cur_f['Ric'] + Rcal)
205
+ C_scalar = _fsimp(sum(finv[mu, nu]*Cmat[mu, nu] for mu in range(n) for nu in range(n)))
206
+
207
+ # C via explicit formula (dM + (M+delta) Gamma Gamma): INDEPENDENT check
208
+ # of C = R[f] + Rcal. Valid only if d(eta)=0 (Cartesian inertial coords).
209
+ if eta_is_const(eta, coords):
210
+ C_formula = c_formula(M, cur_g['Gamma'], coords)
211
+ C_check = _fsimp(Cmat - C_formula) # independent check; zero if formula is correct
212
+ else:
213
+ C_formula = None
214
+ C_check = None # not applicable: d(eta) != 0 in these coordinates
215
+
216
+ # G^{(f)} via decomposition
217
+ Gf_decomp = cur_f['G'] # identity by definition of C
218
+ # G_f_check is zero BY CONSTRUCTION: C is defined as R[f] + Rcal, so the
219
+ # decomposition is an identity, not a test. It is kept only as a consistency check.
220
+ Gf_check = sp.zeros(n) # zero by construction
221
+
222
+ eps_f = cur_f['G'] - 8*pi*Tf
223
+ eps_g = cur_g['G'] - 8*pi*Tg
224
+
225
+ out = dict(
226
+ coords=coords, eta=eta, g=g, f=f, M=M, Minv=Minv,
227
+ R_g=cur_g['Ric'], R_f=cur_f['Ric'],
228
+ Rscalar_g=cur_g['Rscalar'], Rscalar_f=cur_f['Rscalar'],
229
+ G_g=cur_g['G'], G_f=cur_f['G'],
230
+ G_f_decomp=Gf_decomp, G_f_check=Gf_check,
231
+ Rcal=Rcal, Rcal_scalar=Rcal_scalar,
232
+ C=Cmat, C_scalar=C_scalar, C_formula=C_formula, C_check=C_check,
233
+ Tf=Tf, Tg=Tg, eps_f=eps_f, eps_g=eps_g,
234
+ Gamma_g=Gg, Gamma_f=cur_f['Gamma'],
235
+ Riem_g=Rg, Riem_f=cur_f['Riem'],
236
+ )
237
+ return out
238
+
239
+ def show(name, res, verbose=False):
240
+ print(f"\n===== {name} =====")
241
+ print("f ="); sp.pprint(res['f'])
242
+ print("R^{(g)} scalar =", sp.simplify(res['Rscalar_g']))
243
+ print("R^{(f)} scalar =", sp.simplify(res['Rscalar_f']))
244
+ print("Rcal scalar =", sp.simplify(res['Rcal_scalar']))
245
+ print("C scalar =", sp.simplify(res['C_scalar']))
246
+ print("Identity R[f] = -Rcal + C (holds by definition of C):", _fsimp(res['Rscalar_f'] + res['Rcal_scalar'] - res['C_scalar']))
247
+ print("Check G^{(f)} == decomp (should be 0 matrix):")
248
+ sp.pprint(res['G_f_check'])
249
+ print("Independent check C == C_formula with (M+delta) (Cartesian only; None = d(eta)!=0, skipped):")
250
+ sp.pprint(res['C_check'])
251
+ if verbose:
252
+ print("G^{(f)} ="); sp.pprint(res['G_f'])
253
+ print("eps^{(f)} = G^{(f)} - 8 pi Tf ="); sp.pprint(res['eps_f'])
254
+ print("eps^{(g)} = G^{(g)} - 8 pi Tg ="); sp.pprint(res['eps_g'])
255
+
256
+ # ---------------------------------------------------------------- examples
257
+ if __name__ == "__main__":
258
+ # --- Example 1: Minkowski (Cartesian) ---
259
+ t, x, y, z = sp.symbols('t x y z')
260
+ coords = [t, x, y, z]
261
+ eta = sp.diag(-1, 1, 1, 1)
262
+ g_mink = sp.diag(-1, 1, 1, 1)
263
+ res = compute_all(g_mink, coords, eta)
264
+ show("Minkowski: g = eta", res)
265
+
266
+ # --- Example 2: Schwarzschild as INPUT g ---
267
+ # Here g is the input metric; f = 2 eta - g is derived.
268
+ # eta in Schwarzschild spherical coords: diag(-1, 1, r^2, r^2 sin^2 th)
269
+ r, th, ph, M = sp.symbols('r theta phi M', positive=True)
270
+ coords2 = [t, r, th, ph]
271
+ eta_sph = sp.diag(-1, 1, r**2, r**2*sp.sin(th)**2)
272
+ f_sch = 1 - 2*M/r
273
+ g_sch = sp.diag(-f_sch, 1/f_sch, r**2, r**2*sp.sin(th)**2)
274
+ res2 = compute_all(g_sch, coords2, eta_sph)
275
+ show("Schwarzschild as input g (f = 2 eta - g derived)", res2, verbose=False)
276
+ print("\nG^{(g)} (should be 0, Schwarzschild is vacuum GR):")
277
+ sp.pprint(res2['G_g'])
278
+ print("\nG^{(f)} for the companion (not zero in general):")
279
+ sp.pprint(res2['G_f'])
280
+ print("\neps^{(f)} with T^{(f)} left symbolic (eps = G^{(f)} - 8 pi Tf):")
281
+ sp.pprint(res2['eps_f'])
282
+
283
+ # --- Example 3: FLRW as INPUT g ---
284
+ a = sp.Function('a')(t)
285
+ coords3 = [t, x, y, z]
286
+ g_flrw = sp.diag(-1, a**2, a**2, a**2)
287
+ res3 = compute_all(g_flrw, coords3, eta)
288
+ show("FLRW as input g", res3, verbose=False)
289
+ print("\nC_{mu nu} for FLRW:"); sp.pprint(res3['C'])
290
+
291
+ def implied_T(G):
292
+ """Implied stress tensor T_imp = G / (8 pi): the T that would be needed for
293
+ eps = G - 8 pi T = 0 in that sector. Shown when the supplied T is unknown."""
294
+ return _fsimp(G / (8*sp.pi))
295
+
296
+ def mixed_T(Tcov, ginv):
297
+ """T^mu_nu = g^{mu alpha} T_{alpha nu}. For a diagonal metric the diagonal
298
+ entries are rho = -T^t_t and p_i = T^i_i (no sum)."""
299
+ return _fsimp(ginv * Tcov)
@@ -0,0 +1,285 @@
1
+ import re, traceback, threading, uuid
2
+ import sympy as sp
3
+ from flask import Flask, render_template_string, request, jsonify
4
+ try:
5
+ from . import compute as dc # package import: dual_general_relativity.server
6
+ except ImportError:
7
+ import dgr_compute as dc # standalone: server.py next to dgr_compute.py
8
+ app = Flask(__name__)
9
+ PRESETS = {
10
+ 'minkowski': {'coords':'t,x,y,z','eta_preset':'cartesian','g':'-1,0,0,0; 0,1,0,0; 0,0,1,0; 0,0,0,1','t_mode':'zero','Tg':'','Tf':'','point':''},
11
+ 'minkowski-companion': {'coords':'t,x,y,z','eta_preset':'cartesian','g':'-1,0,0,0; 0,1,0,0; 0,0,1,0; 0,0,0,1','t_mode':'zero','Tg':'','Tf':'','point':''},
12
+ 'schwarzschild': {'coords':'t,r,theta,phi','eta_preset':'spherical','g':'-(1-2*M/r),0,0,0; 0,1/(1-2*M/r),0,0; 0,0,r**2,0; 0,0,0,r**2*sin(theta)**2','t_mode':'zero','Tg':'','Tf':'','point':'r=5, M=1, theta=1'},
13
+ 'schwarzschild-companion': {'coords':'t,r,theta,phi','eta_preset':'spherical','g':'-1-2*M/r,0,0,0; 0,(1-4*M/r)/(1-2*M/r),0,0; 0,0,r**2,0; 0,0,0,r**2*sin(theta)**2','t_mode':'separate','Tg':'','Tf':'0,0,0,0; 0,0,0,0; 0,0,0,0; 0,0,0,0','point':'r=5, M=1, theta=1'},
14
+ 'flrw': {'coords':'t,x,y,z','eta_preset':'cartesian','g':'-1,0,0,0; 0,a(t)**2,0,0; 0,0,a(t)**2,0; 0,0,0,a(t)**2','t_mode':'separate','Tg':'3*Derivative(a(t),t)**2/(8*pi*a(t)**2),0,0,0; 0,-(2*Derivative(a(t),t,t)/a(t) + Derivative(a(t),t)**2/a(t)**2)*a(t)**2/(8*pi),0,0; 0,0,-(2*Derivative(a(t),t,t)/a(t) + Derivative(a(t),t)**2/a(t)**2)*a(t)**2/(8*pi),0; 0,0,0,-(2*Derivative(a(t),t,t)/a(t) + Derivative(a(t),t)**2/a(t)**2)*a(t)**2/(8*pi)','Tf':'','point':''},
15
+ 'flrw-companion': {'coords':'t,x,y,z','eta_preset':'cartesian','g':'-1,0,0,0; 0,2-a(t)**2,0,0; 0,0,2-a(t)**2,0; 0,0,0,2-a(t)**2','t_mode':'separate','Tg':'','Tf':'3*Derivative(a(t),t)**2/(8*pi*a(t)**2),0,0,0; 0,-(2*Derivative(a(t),t,t)/a(t) + Derivative(a(t),t)**2/a(t)**2)*a(t)**2/(8*pi),0,0; 0,0,-(2*Derivative(a(t),t,t)/a(t) + Derivative(a(t),t)**2/a(t)**2)*a(t)**2/(8*pi),0; 0,0,0,-(2*Derivative(a(t),t,t)/a(t) + Derivative(a(t),t)**2/a(t)**2)*a(t)**2/(8*pi)','point':''},
16
+ 'interior': {'coords':'t,r,theta,phi','eta_preset':'spherical','g':'-(3*sqrt(1-2*M/R)-sqrt(1-2*M*r**2/R**3))**2/4,0,0,0; 0,1/(1-2*M*r**2/R**3),0,0; 0,0,r**2,0; 0,0,0,r**2*sin(theta)**2','t_mode':'separate','Tg':'(3*M/(4*pi*R**3))*(3*sqrt(1-2*M/R)-sqrt(1-2*M*r**2/R**3))**2/4,0,0,0; 0,((3*M/(4*pi*R**3))*(sqrt(1-2*M*r**2/R**3)-sqrt(1-2*M/R))/(3*sqrt(1-2*M/R)-sqrt(1-2*M*r**2/R**3)))/(1-2*M*r**2/R**3),0,0; 0,0,((3*M/(4*pi*R**3))*(sqrt(1-2*M*r**2/R**3)-sqrt(1-2*M/R))/(3*sqrt(1-2*M/R)-sqrt(1-2*M*r**2/R**3)))*r**2,0; 0,0,0,((3*M/(4*pi*R**3))*(sqrt(1-2*M*r**2/R**3)-sqrt(1-2*M/R))/(3*sqrt(1-2*M/R)-sqrt(1-2*M*r**2/R**3)))*r**2*sin(theta)**2','Tf':'','point':'r=1, M=1, R=3, theta=1'},
17
+ 'interior-companion': {'coords':'t,r,theta,phi','eta_preset':'spherical','g':'(3*sqrt(1-2*M/R)-sqrt(1-2*M*r**2/R**3))**2/4-2,0,0,0; 0,(1-4*M*r**2/R**3)/(1-2*M*r**2/R**3),0,0; 0,0,r**2,0; 0,0,0,r**2*sin(theta)**2','t_mode':'separate','Tg':'','Tf':'(3*M/(4*pi*R**3))*(3*sqrt(1-2*M/R)-sqrt(1-2*M*r**2/R**3))**2/4,0,0,0; 0,((3*M/(4*pi*R**3))*(sqrt(1-2*M*r**2/R**3)-sqrt(1-2*M/R))/(3*sqrt(1-2*M/R)-sqrt(1-2*M*r**2/R**3)))/(1-2*M*r**2/R**3),0,0; 0,0,((3*M/(4*pi*R**3))*(sqrt(1-2*M*r**2/R**3)-sqrt(1-2*M/R))/(3*sqrt(1-2*M/R)-sqrt(1-2*M*r**2/R**3)))*r**2,0; 0,0,0,((3*M/(4*pi*R**3))*(sqrt(1-2*M*r**2/R**3)-sqrt(1-2*M/R))/(3*sqrt(1-2*M/R)-sqrt(1-2*M*r**2/R**3)))*r**2*sin(theta)**2','point':'r=1, M=1, R=3, theta=1'},
18
+ }
19
+ JOBS = {}
20
+ def split_top_level(text, delims):
21
+ parts=[]; depth=0; cur=[]
22
+ for ch in text:
23
+ if ch in '([{': depth+=1
24
+ elif ch in ')]}': depth-=1
25
+ if depth==0 and ch in delims:
26
+ parts.append(''.join(cur)); cur=[]
27
+ else:
28
+ cur.append(ch)
29
+ parts.append(''.join(cur))
30
+ return [p.strip() for p in parts if p.strip()!='']
31
+ def parse_matrix(text, local):
32
+ text=(text or '').strip()
33
+ if not text: raise ValueError('empty matrix')
34
+ rows=split_top_level(text, ';\n')
35
+ mat=[]
36
+ for row in rows:
37
+ entries=split_top_level(row, ',')
38
+ mat.append([sp.sympify(e, locals=local) for e in entries])
39
+ n=len(mat)
40
+ if any(len(r)!=n for r in mat): raise ValueError('matrix must be square')
41
+ return sp.Matrix(mat)
42
+ def is_zero_mat(M):
43
+ try: return all(dc._fsimp(x)==0 for x in M)
44
+ except Exception: return False
45
+ def parse_point(text, local):
46
+ subs={}
47
+ for part in (text or '').split(','):
48
+ if '=' in part:
49
+ k,v=part.split('=',1); subs[sp.sympify(k.strip(), locals=local)]=sp.sympify(v.strip(), locals=local)
50
+ return subs
51
+ def staged_compute(form, set_progress):
52
+ coord_names=[c.strip() for c in form['coords'].split(',') if c.strip()]
53
+ if len(coord_names) not in (2,3,4): raise ValueError('need 2-4 coordinates')
54
+ coords=list(sp.symbols(' '.join(coord_names)))
55
+ local={str(c): c for c in coords}
56
+ for name in ['M','R','rho','p']:
57
+ if name not in local: local[name]=sp.Symbol(name)
58
+ if 'a' not in local: local['a']=sp.Function('a')
59
+ set_progress(5, 'Parsing g and T ...')
60
+ g=parse_matrix(form['g'], local)
61
+ if form['eta_preset']=='cartesian': eta=sp.diag(*([-1]+[1]*(len(coords)-1)))
62
+ elif form['eta_preset']=='spherical':
63
+ r=local.get('r'); th=local.get('theta')
64
+ if r is None or th is None: raise ValueError('spherical eta needs coords r and theta')
65
+ eta=sp.diag(-1,1,r**2,r**2*sp.sin(th)**2)
66
+ else: eta=parse_matrix(form['eta'], local)
67
+ n=len(coords)
68
+ fast_mode = (form.get('compute_mode') == 'fast')
69
+ if fast_mode:
70
+ _subs_early = parse_point(form.get('point',''), local)
71
+ _param_subs = {k: v for k, v in _subs_early.items() if k not in coords}
72
+ if _param_subs:
73
+ g = g.subs(_param_subs)
74
+ eta = eta.subs(_param_subs)
75
+ # T RULE (T rule): blank = symbolic UNKNOWN, never 0.
76
+ # T = 0 ONLY when explicitly written as a zero matrix, or t_mode == 'zero' (Vacuum).
77
+ # A defined T in a preset (FLRW / interior fluid) is NOT zero.
78
+ Tf=Tg=None
79
+ def T_or_unknown(text):
80
+ return parse_matrix(text, local) if (text or '').strip() else None # None -> symbolic below
81
+ if form['t_mode']=='unknown': Tf=Tg=None # both symbolic
82
+ elif form['t_mode']=='zero': Tg=Tf=sp.zeros(n) # explicit vacuum only
83
+ elif form['t_mode']=='same':
84
+ Tg=T_or_unknown(form['Tg']); Tf=Tg
85
+ else: # 'separate'
86
+ Tg=T_or_unknown(form['Tg']); Tf=T_or_unknown(form['Tf'])
87
+ Tg_symbolic = Tg is None
88
+ Tf_symbolic = Tf is None
89
+ if fast_mode and '_param_subs' in dir() and _param_subs:
90
+ if Tg is not None: Tg = Tg.subs(_param_subs)
91
+ if Tf is not None: Tf = Tf.subs(_param_subs)
92
+ set_progress(12, 'Computing f = 2 eta - g and M ...')
93
+ f=dc._fsimp(2*eta-g)
94
+ set_progress(28, 'Curvature of g: Gamma, Riemann, Ricci, G(g) ...')
95
+ cur_g=dc.curvature_all(g, coords)
96
+ set_progress(48, 'Curvature of f: Gamma, Riemann, Ricci, G(f) ...')
97
+ cur_f=dc.curvature_all(f, coords)
98
+ finv=cur_f['ginv']; M=dc._fsimp(finv*g)
99
+ set_progress(66, 'Mixed Ricci Rcal and C = R(f) + Rcal ...')
100
+ Rg=cur_g['Riem']
101
+ if fast_mode:
102
+ Rcal=sp.zeros(n); Rcal_scalar=sp.S(0); Cmat=cur_f['Ric']; C_scalar=cur_f['Rscalar']
103
+ else:
104
+ Rcal=sp.zeros(n)
105
+ for mu in range(n):
106
+ for nu in range(n):
107
+ Rcal[mu,nu]=dc._fsimp(sum(M[lam,a]*Rg[a][mu][lam][nu] for lam in range(n) for a in range(n)))
108
+ Rcal_scalar=dc._fsimp(sum(finv[mu,nu]*Rcal[mu,nu] for mu in range(n) for nu in range(n)))
109
+ Cmat=dc._fsimp(cur_f['Ric']+Rcal)
110
+ C_scalar=dc._fsimp(sum(finv[mu,nu]*Cmat[mu,nu] for mu in range(n) for nu in range(n)))
111
+ set_progress(78, 'Einstein tensors and eps = G - 8 pi T ...')
112
+ if Tf is None:
113
+ Tf=sp.Matrix(n,n,lambda i,j: sp.Function(f'Tf_{i}{j}')(*coords) if i<=j else sp.Function(f'Tf_{j}{i}')(*coords))
114
+ if Tg is None:
115
+ Tg=sp.Matrix(n,n,lambda i,j: sp.Function(f'Tg_{i}{j}')(*coords) if i<=j else sp.Function(f'Tg_{j}{i}')(*coords))
116
+ Tf=sp.Matrix(n,n,lambda i,j: Tf[min(i,j),max(i,j)]); Tg=sp.Matrix(n,n,lambda i,j: Tg[min(i,j),max(i,j)])
117
+ eps_f=cur_f['G']-8*sp.pi*Tf; eps_g=cur_g['G']-8*sp.pi*Tg # raw difference, no simplify
118
+ set_progress(88, 'Checking G(f) decomposition ...')
119
+ Gf_decomp=cur_f['G'] # identity by definition of C, no recomputation
120
+ Gf_check=sp.zeros(n) # zero by construction
121
+ set_progress(94, 'Rendering results ...')
122
+ # Implied stress tensors: T_imp = G / (8 pi) is the T that WOULD make eps = 0.
123
+ # Shown always (it is informative even when T is supplied: compare it with the
124
+ # supplied T). When T is unknown it is the only matter content the app can test.
125
+ Timp_g=dc.implied_T(cur_g['G']); Timp_f=dc.implied_T(cur_f['G'])
126
+ # Mixed components for rho / pressures, only meaningful for a diagonal metric.
127
+ def _diag_mixed(Tcov, ginv):
128
+ try:
129
+ if all(ginv[i,j]==0 for i in range(n) for j in range(n) if i!=j):
130
+ Mmix=dc._fsimp(ginv*Tcov)
131
+ return [dc._fsimp(Mmix[i,i]) for i in range(n)]
132
+ except Exception:
133
+ return None
134
+ return None
135
+ mix_g=_diag_mixed(Timp_g, cur_g['ginv']); mix_f=_diag_mixed(Timp_f, finv)
136
+ # rho = -T^t_t, p_i = T^i_i. Scalars appended below when diagonal.
137
+ extra_scalars=[]
138
+ if mix_g is not None:
139
+ extra_scalars.append((r"\rho^{(g)}_{imp}=-T^{(g)t}{}_{t}", sp.latex(-mix_g[0])))
140
+ for i in range(1,n):
141
+ extra_scalars.append((r"p^{(g)}_{imp,%d}=T^{(g)%d}{}_{%d}" % (i,i,i), sp.latex(mix_g[i])))
142
+ if mix_f is not None:
143
+ extra_scalars.append((r"\rho^{(f)}_{imp}=-T^{(f)t}{}_{t}", sp.latex(-mix_f[0])))
144
+ for i in range(1,n):
145
+ extra_scalars.append((r"p^{(f)}_{imp,%d}=T^{(f)%d}{}_{%d}" % (i,i,i), sp.latex(mix_f[i])))
146
+ titles=[r"Input\ g_{\mu\nu}",r"Background\ \eta_{\mu\nu}",r"Companion\ f_{\mu\nu}=2\eta-g",r"M^\lambda{}_{\rho}=f^{\lambda\alpha}g_{\alpha\rho}",r"Ricci\ R^{(g)}_{\mu\nu}",r"Ricci\ R^{(f)}_{\mu\nu}",r"\mathcal{R}_{\mu\nu}",r"C_{\mu\nu}=R^{(f)}_{\mu\nu}+\mathcal{R}_{\mu\nu}",r"Einstein\ G^{(g)}_{\mu\nu}",r"Einstein\ G^{(f)}_{\mu\nu}",r"T^{(g)}_{\mu\nu}",r"T^{(f)}_{\mu\nu}",r"\varepsilon^{(g)}_{\mu\nu}=G^{(g)}_{\mu\nu}-8\pi T^{(g)}_{\mu\nu}",r"\varepsilon^{(f)}_{\mu\nu}=G^{(f)}_{\mu\nu}-8\pi T^{(f)}_{\mu\nu}",r"T^{(g)}_{imp,\mu\nu}=G^{(g)}_{\mu\nu}/8\pi",r"T^{(f)}_{imp,\mu\nu}=G^{(f)}_{\mu\nu}/8\pi"]
147
+ mats=[g,eta,f,M,cur_g['Ric'],cur_f['Ric'],Rcal,Cmat,cur_g['G'],cur_f['G'],Tg,Tf,eps_g,eps_f,Timp_g,Timp_f]
148
+ sections=[(t, sp.latex(m, mat_str='bmatrix')) for t,m in zip(titles,mats)]
149
+ scalars=[(r"Mode", 'Fast - Rcal/C skipped' if fast_mode else 'Full'),(r"R^{(g)}", sp.latex(cur_g['Rscalar'])),(r"R^{(f)}", sp.latex(cur_f['Rscalar'])),(r"\mathcal{R}", sp.latex(Rcal_scalar)),(r"C", sp.latex(C_scalar)),(r"\det g", sp.latex(sp.factor(dc._fsimp(g.det())))),(r"\det f", sp.latex(sp.factor(dc._fsimp(f.det())))),(r"R^{(f)}+\mathcal{R}-C\ (identity,\ holds\ by\ definition\ of\ C)", sp.latex(dc._fsimp(cur_f['Rscalar']+Rcal_scalar-C_scalar)))] + extra_scalars
150
+ # Independent test of C (explicit formula with (M+delta)); only valid if d(eta)=0.
151
+ if fast_mode:
152
+ c_check_ok=None
153
+ elif dc.eta_is_const(eta, coords):
154
+ C_formula=dc.c_formula(M, cur_g['Gamma'], coords)
155
+ c_check_ok=is_zero_mat(dc._fsimp(Cmat-C_formula))
156
+ else:
157
+ c_check_ok=None # not applicable: d(eta) != 0 in these coordinates
158
+ subs=parse_point(form['point'], local)
159
+ sig_g=dc.signature_at(g, subs) if subs else None
160
+ sig_f=dc.signature_at(f, subs) if subs else None
161
+ checks=[(r"C = explicit\ formula\ with\ (M+\delta)\ [independent;\ Cartesian\ eta\ only]", c_check_ok),
162
+ (r"G^{(f)}\ decomposition\ [identity\ by\ definition\ of\ C,\ not\ a\ test]", is_zero_mat(Gf_check)),
163
+ (r"\varepsilon^{(g)}=0 (N/A if T^{(g)} unknown)", None if Tg_symbolic else is_zero_mat(eps_g)),(r"\varepsilon^{(f)}=0 (N/A if T^{(f)} unknown)", None if Tf_symbolic else is_zero_mat(eps_f))]
164
+ if subs:
165
+ checks.append((r"g\ Lorentzian\ at\ point\ (sig=%s)" % (sig_g,), dc.is_lorentzian(sig_g) if sig_g else None))
166
+ checks.append((r"f\ Lorentzian\ at\ point\ (sig=%s)" % (sig_f,), dc.is_lorentzian(sig_f) if sig_f else None))
167
+ numeric=None
168
+ if subs:
169
+ def num(e):
170
+ try: return '%.6g' % float(sp.N(e.subs(subs)))
171
+ except Exception: return sp.latex(e.subs(subs))
172
+ numeric=r"R^{(g)}=%s,\ R^{(f)}=%s,\ \mathcal{R}=%s,\ C=%s" % (num(cur_g['Rscalar']), num(cur_f['Rscalar']), num(Rcal_scalar), num(C_scalar))
173
+ if mix_g is not None and mix_f is not None:
174
+ numeric += r",\ \rho^{(g)}_{imp}=%s,\ p^{(g)}_{imp,1}=%s,\ \rho^{(f)}_{imp}=%s,\ p^{(f)}_{imp,1}=%s,\ \rho^{(f)}_{imp}+p^{(f)}_{imp,1}=%s" % (num(-mix_g[0]), num(mix_g[1]), num(-mix_f[0]), num(mix_f[1]), num(-mix_f[0]+mix_f[1]))
175
+ set_progress(100, 'Done')
176
+ return dict(sections=sections, scalars=scalars, checks=checks, numeric=numeric)
177
+ def run_job(job_id, form):
178
+ job=JOBS[job_id]
179
+ def set_progress(p, label):
180
+ job['progress']=p; job['label']=label
181
+ try:
182
+ job['result']=staged_compute(form, set_progress); job['status']='done'
183
+ except Exception:
184
+ job['status']='error'; job['error']=traceback.format_exc()
185
+ def start_job(form):
186
+ job_id=str(uuid.uuid4())
187
+ JOBS[job_id]={'status':'running','progress':0,'label':'Starting ...','result':None,'error':None}
188
+ threading.Thread(target=run_job, args=(job_id, form), daemon=True).start()
189
+ return job_id
190
+ RESULT_HTML = '''{% if error %}<div class="error">{{error}}</div>{% endif %}{% if result %}<div class="card"><h2>Scalars</h2>{% for name,val in scalars %}<div class="scalar">$$ {{name}} = {{val}} $$</div>{% endfor %}<h2>Checks</h2>{% for name,ok in checks %}<div>{{name}} - {% if ok is none %}<span>N/A</span>{% else %}<span class="{{'pass' if ok else 'fail'}}">{{'PASS' if ok else 'FAIL / non-zero'}}</span>{% endif %}</div>{% endfor %}{% if numeric %}<h2>Numeric evaluation at point</h2><div class="scalar">$$ {{numeric}} $$</div>{% endif %}</div>{% for title,mat in sections %}<div class="card scroll"><h3>$$ {{title}} $$</h3><div>$$ {{mat}} $$</div></div>{% endfor %}{% endif %}'''
191
+ HTML = '''<!doctype html><html><head><meta charset="utf-8"><title>DGR Calculator</title>
192
+ <script src="https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-mml-chtml.js"></script>
193
+ <style>body{font-family:system-ui,sans-serif;max-width:1100px;margin:24px auto;padding:0 16px;background:#f7f7f5}h1{margin-bottom:4px}.card{background:#fff;border:1px solid #ddd;border-radius:12px;padding:16px;margin:14px 0}label{font-weight:600;display:block;margin:12px 0 4px}textarea,input[type=text],select{width:100%;box-sizing:border-box;padding:8px;font-family:ui-monospace,monospace;font-size:14px}textarea{height:110px}.row{display:grid;grid-template-columns:1fr 1fr;gap:16px}button{background:#111;color:#fff;border:0;border-radius:8px;padding:10px 18px;font-size:16px;cursor:pointer}button:disabled{opacity:.5;cursor:wait}.error{background:#ffe9e9;border:1px solid #f99;padding:12px;border-radius:8px;white-space:pre-wrap}.pass{color:#0a7a2f;font-weight:700}.fail{color:#b00;font-weight:700}.scroll{overflow-x:auto}.scalar{font-size:17px;margin:6px 0}.note{color:#555;font-size:14px}.bar-wrap{background:#eee;border-radius:999px;height:22px;overflow:hidden}.bar{background:#111;height:100%;width:0%;transition:width .3s}.bar-label{margin:6px 0 0;font-size:14px}</style></head><body>
194
+ <h1>Dual General Relativity - g + T calculator</h1>
195
+ <p class="note">Enter g (and T, if known) as SymPy expressions. A blank T means <b>symbolic unknown</b>, never 0. T = 0 only if you write a zero matrix or choose <b>Vacuum</b>. Rows separated by <code>;</code> or newline, entries by <code>,</code>. Use <code>a(t)</code> for a function, <code>M</code>, <code>R</code> as free parameters. Each preset has its companion $f = 2\\eta - g$ as a separate preset; applying $D$ twice returns the original. A blank $T$ box means $T$ is <b>symbolic unknown</b>, never $0$. $T=0$ only if you write a zero matrix or choose Vacuum. A defined $T$ in a preset (FLRW / interior fluid) is NOT zero.</p>
196
+ <form id="calc-form" method="post"><div class="card">
197
+ <label>Preset (loads example into the form)</label><select name="preset" onchange="this.form.submit()">{% for k in presets %}<option value="{{k}}" {% if form.preset==k %}selected{% endif %}>{{k}}</option>{% endfor %}</select>
198
+ <label>Coordinates</label><input type="text" name="coords" value="{{form.coords}}">
199
+ <div class="row"><div><label>Background eta preset</label><select name="eta_preset"><option value="cartesian" {% if form.eta_preset=='cartesian' %}selected{% endif %}>Cartesian diag(-1,1,1,1)</option><option value="spherical" {% if form.eta_preset=='spherical' %}selected{% endif %}>Spherical diag(-1,1,r^2,r^2 sin^2 theta)</option><option value="custom" {% if form.eta_preset=='custom' %}selected{% endif %}>Custom (below)</option></select></div>
200
+ <div><label>Evaluation point (optional, e.g. r=5, M=1)</label><input type="text" name="point" value="{{form.point}}"></div></div>
201
+ <label>Custom eta (only if Custom)</label><textarea name="eta" style="height:70px">{{form.eta}}</textarea>
202
+ <label>g</label><textarea name="g">{{form.g}}</textarea>
203
+ <label>Compute mode</label><select name="compute_mode"><option value="full" {% if form.compute_mode!='fast' %}selected{% endif %}>Full - all quantities incl. Rcal / C (slow on interior)</option><option value="fast" {% if form.compute_mode=='fast' %}selected{% endif %}>Fast - substitute M, R, ... from the point, skip Rcal / C, keep G, eps, T_imp, rho/p</option></select>
204
+ <label>T mode</label><select name="t_mode"><option value="unknown" {% if form.t_mode=='unknown' %}selected{% endif %}>Unknown - keep T(g), T(f) symbolic (same as leaving both blank)</option><option value="zero" {% if form.t_mode=='zero' %}selected{% endif %}>Vacuum - T = 0 in both sectors</option><option value="same" {% if form.t_mode=='same' %}selected{% endif %}>Known - one T, used for both sectors</option><option value="separate" {% if form.t_mode=='separate' %}selected{% endif %}>Known - separate T(g) and T(f)</option></select>
205
+ <label>T / T(g) (ignored in Unknown / Vacuum modes; blank = symbolic unknown)</label><textarea name="Tg">{{form.Tg}}</textarea>
206
+ <label>T(f) (only in Separate mode; blank = symbolic unknown)</label><textarea name="Tf">{{form.Tf}}</textarea>
207
+ <p><button id="compute-btn" type="submit" name="action" value="compute">Compute all</button></p>
208
+ <div id="progress" style="display:none"><div class="bar-wrap"><div id="bar" class="bar"></div></div><div class="bar-label"><span id="bar-pct">0%</span> - <span id="bar-label">Starting ...</span></div></div>
209
+ </div></form>
210
+ <div id="results"></div>
211
+ <script>
212
+ var form=document.getElementById('calc-form');
213
+ var btn=document.getElementById('compute-btn');
214
+ function poll(jobId){
215
+ fetch('/api/progress/'+jobId).then(r=>r.json()).then(function(j){
216
+ document.getElementById('bar').style.width=j.progress+'%';
217
+ document.getElementById('bar-pct').textContent=j.progress+'%';
218
+ document.getElementById('bar-label').textContent=j.label;
219
+ if(j.status==='done'){
220
+ fetch('/api/result/'+jobId).then(r=>r.text()).then(function(html){
221
+ document.getElementById('results').innerHTML=html;
222
+ if(window.MathJax) MathJax.typesetPromise();
223
+ document.getElementById('progress').style.display='none'; btn.disabled=false; btn.textContent='Compute all';
224
+ });
225
+ } else if(j.status==='error'){
226
+ fetch('/api/result/'+jobId).then(r=>r.text()).then(function(html){
227
+ document.getElementById('results').innerHTML=html;
228
+ document.getElementById('progress').style.display='none'; btn.disabled=false; btn.textContent='Compute all';
229
+ });
230
+ } else { setTimeout(function(){poll(jobId);}, 500); }
231
+ });
232
+ }
233
+ form.addEventListener('submit', function(e){
234
+ if(e.submitter && e.submitter.value==='compute'){
235
+ e.preventDefault();
236
+ document.getElementById('results').innerHTML='';
237
+ document.getElementById('progress').style.display='block';
238
+ btn.disabled=true; btn.textContent='Computing ...';
239
+ fetch('/api/start', {method:'POST', body:new FormData(form)}).then(r=>r.json()).then(function(j){ poll(j.job_id); });
240
+ }
241
+ });
242
+ </script>
243
+ </body></html>'''
244
+ @app.route('/', methods=['GET','POST'])
245
+ def index():
246
+ form=dict(PRESETS['minkowski']); form['preset']='minkowski'; form['eta']=''; form['compute_mode']='full'
247
+ if request.method=='POST':
248
+ form={k: request.form.get(k,'') for k in ['preset','coords','eta_preset','eta','g','t_mode','Tg','Tf','point','compute_mode']}
249
+ if request.form.get('action')!='compute':
250
+ p=PRESETS.get(form['preset'], PRESETS['minkowski']); form.update(p); form['preset']=request.form.get('preset'); form['eta']=''
251
+ return render_template_string(HTML, presets=list(PRESETS), form=form)
252
+ @app.route('/api/start', methods=['POST'])
253
+ def api_start():
254
+ form={k: request.form.get(k,'') for k in ['preset','coords','eta_preset','eta','g','t_mode','Tg','Tf','point']}
255
+ return jsonify({'job_id': start_job(form)})
256
+ @app.route('/api/progress/<job_id>')
257
+ def api_progress(job_id):
258
+ job=JOBS.get(job_id)
259
+ if not job: return jsonify({'status':'error','progress':0,'label':'unknown job'}), 404
260
+ return jsonify({'status':job['status'],'progress':job['progress'],'label':job['label']})
261
+ @app.route('/api/result/<job_id>')
262
+ def api_result(job_id):
263
+ job=JOBS.get(job_id)
264
+ if not job: return 'Unknown job', 404
265
+ if job['status']=='error':
266
+ return render_template_string(RESULT_HTML, error=job['error'], result=False)
267
+ if job['status']!='done': return 'Not ready yet', 409
268
+ r=job['result']
269
+ return render_template_string(RESULT_HTML, error=None, result=True, sections=r['sections'], scalars=r['scalars'], checks=r['checks'], numeric=r['numeric'])
270
+
271
+
272
+ def create_app():
273
+ """Return the Flask app (same app as `python -m dual_general_relativity`)."""
274
+ return app
275
+
276
+
277
+ def main(host="127.0.0.1", port=5000):
278
+ """Entry point for the `dual-general-relativity` console script. Local only."""
279
+ print("Dual General Relativity — open http://127.0.0.1:5000")
280
+ print("T rule: blank T = symbolic unknown, never 0. T = 0 only if written as zero or Vacuum mode.")
281
+ app.run(host=host, port=port, debug=True)
282
+
283
+
284
+ if __name__ == "__main__":
285
+ main()
@@ -0,0 +1,35 @@
1
+ [build-system]
2
+ requires = ["hatchling"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "dual-general-relativity"
7
+ version = "1.0.0"
8
+ description = "Dual General Relativity (DGR): companion metric f = 2 eta - g, separate GR and DGR systems, Flask app to compute curvature, C / Rcal, eps = G - 8 pi T, and implied stress tensor."
9
+ readme = "README.md"
10
+ license = "MIT"
11
+ authors = [{name = "Dual General Relativity"}]
12
+ keywords = ["general-relativity", "differential-geometry", "sympy", "flask"]
13
+ classifiers = [
14
+ "Programming Language :: Python :: 3",
15
+ "License :: OSI Approved :: MIT License",
16
+ "Operating System :: OS Independent",
17
+ "Intended Audience :: Science/Research",
18
+ "Topic :: Scientific/Engineering :: Physics",
19
+ ]
20
+ requires-python = ">=3.9"
21
+ dependencies = ["flask", "sympy", "numpy"]
22
+
23
+ [project.urls]
24
+ Homepage = "https://github.com/YOUR-USERNAME/dual-general-relativity"
25
+ Repository = "https://github.com/YOUR-USERNAME/dual-general-relativity"
26
+ Issues = "https://github.com/YOUR-USERNAME/dual-general-relativity/issues"
27
+
28
+ [project.scripts]
29
+ dual-general-relativity = "dual_general_relativity.server:main"
30
+
31
+ [tool.hatch.build.targets.wheel]
32
+ packages = ["src/dual_general_relativity"]
33
+
34
+ [tool.hatch.build.targets.sdist]
35
+ packages = ["src/dual_general_relativity"]