File size: 11,575 Bytes
05354e5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
# app/core/simulations/simulation_pib.py
from __future__ import annotations
import os
import sys
import math
import numpy as np
import plotly.graph_objects as go
from typing import Tuple, Optional, List

# Ensure repo root is importable when Streamlit runs the UI directly
CURRENT_DIR = os.path.dirname(os.path.abspath(__file__))           # .../app/core/simulations
PROJECT_ROOT = os.path.abspath(os.path.join(CURRENT_DIR, "..", "..", ".."))
if PROJECT_ROOT not in sys.path:
    sys.path.append(PROJECT_ROOT)

# Optional TDSE solver (best-effort import) - user may add solvers.py later
try:
    from app.core.physics_engine.solvers import TDSESolver  # type: ignore
    TDSE_AVAILABLE = True
except Exception:
    TDSE_AVAILABLE = False

# ------------------------
# Physics: analytic functions
# ------------------------
def calc_1d_wavefunction(n: int, L: float = 1.0, resolution: int = 400) -> Tuple[np.ndarray, np.ndarray, np.ndarray, float]:
    """

    Return x, psi(x), probability density, energy (dimensionless units).

    Keep L in arbitrary units (convert externally if needed).

    """
    x = np.linspace(0.0, L, resolution)
    psi = np.sqrt(2.0 / L) * np.sin(n * np.pi * x / L)
    prob = psi ** 2
    energy = (n ** 2 * np.pi ** 2) / (2.0 * L ** 2)
    return x, psi, prob, energy

def normalized_wavefunction(n: int, L: float = 1.0, x: Optional[np.ndarray] = None) -> np.ndarray:
    if x is None:
        x = np.linspace(0, L, 400)
    return np.sqrt(2.0 / L) * np.sin(n * np.pi * x / L)

# ------------------------
# Graphs (static)
# ------------------------
def plot_2d_wavefunction(n: int, L: float = 1.0, resolution: int = 400) -> go.Figure:
    x, psi, prob, energy = calc_1d_wavefunction(n, L, resolution)
    fig = go.Figure()
    fig.add_trace(go.Scatter(x=x, y=psi, mode="lines", name="ψ(x)"))
    fig.add_trace(go.Scatter(x=x, y=prob, mode="lines", name="|ψ(x)|²"))
    fig.update_layout(
        title=f"Particle in a 1D Box — n={n}, L={L:.3g} — Energy ∝ {energy:.4g}",
        xaxis_title="x",
        yaxis_title="Amplitude / Probability",
        template="plotly_dark",
    )
    return fig

def plot_nodes(n: int, L: float = 1.0, resolution: int = 400) -> go.Figure:
    x, psi, prob, energy = calc_1d_wavefunction(n, L, resolution)
    fig = go.Figure()
    fig.add_trace(go.Scatter(x=x, y=psi, mode="lines", name=f"ψ n={n}"))
    nodes = [L * k / n for k in range(1, n)]
    if nodes:
        fig.add_trace(go.Scatter(x=nodes, y=[0.0] * len(nodes), mode="markers", marker=dict(size=8, color="red"), name="Nodes"))
    fig.update_layout(title=f"Nodes of ψ (n={n})", xaxis_title="x", yaxis_title="ψ(x)", template="plotly_dark")
    return fig

def plot_energy_levels(max_n: int = 6, L: float = 1.0) -> go.Figure:
    ns = np.arange(1, max_n + 1)
    energies = (ns ** 2 * np.pi ** 2) / (2.0 * L ** 2)
    fig = go.Figure()
    for n, E in zip(ns, energies):
        fig.add_trace(go.Scatter(x=[0, 1], y=[E, E], mode="lines", name=f"n={n}", line=dict(width=2)))
        fig.add_trace(go.Scatter(x=[0.5], y=[E], mode="markers+text", text=[f"n={n}, E={E:.3g}"], textposition="top center", showlegend=False))
    fig.update_layout(title=f"Energy Levels (scale arbitrary) — L={L}", xaxis=dict(visible=False), yaxis_title="Energy (arb.units)", template="plotly_dark")
    return fig

def plot_multi_n_comparison(ns: List[int], L: float = 1.0, resolution: int = 400) -> go.Figure:
    x = np.linspace(0, L, resolution)
    fig = go.Figure()
    for n in ns:
        psi = normalized_wavefunction(n, L, x)
        fig.add_trace(go.Scatter(x=x, y=psi, mode="lines", name=f"ψ n={n}"))
    fig.update_layout(title=f"Wavefunction comparison (n={ns})", xaxis_title="x", yaxis_title="ψ(x)", template="plotly_dark")
    return fig

def plot_fourier_spectrum(n: int = 1, L: float = 1.0, resolution: int = 1024) -> go.Figure:
    x = np.linspace(0, L, resolution)
    psi = normalized_wavefunction(n, L, x)
    psi_k = np.fft.fftshift(np.fft.fft(psi))
    k = np.fft.fftshift(np.fft.fftfreq(resolution, d=(x[1] - x[0])))
    power = np.abs(psi_k) ** 2
    fig = go.Figure()
    fig.add_trace(go.Scatter(x=k, y=power, mode="lines", name="|Ψ(k)|²"))
    fig.update_layout(title=f"Fourier Spectrum of ψ (n={n})", xaxis_title="k (1/units)", yaxis_title="Power", template="plotly_dark")
    return fig

def plot_expectation_values(n: int = 1, L: float = 1.0) -> go.Figure:
    x, psi, prob, energy = calc_1d_wavefunction(n, L, resolution=1000)
    dx = x[1] - x[0]
    exp_x = np.sum(x * prob) * dx
    exp_x2 = np.sum((x ** 2) * prob) * dx
    var = exp_x2 - exp_x ** 2
    fig = go.Figure()
    fig.add_trace(go.Bar(x=["<x>", "<x^2>", "Var(x)"], y=[exp_x, exp_x2, var], text=[f"{exp_x:.4g}", f"{exp_x2:.4g}", f"{var:.4g}"], textposition="auto"))
    fig.update_layout(title=f"Expectation Values (n={n}, L={L})", template="plotly_dark")
    return fig

def plot_probability_3d(n: int = 1, m: int = 1, L: float = 1.0, resolution: int = 80) -> go.Figure:
    """

    Build and return a 3D surface Plotly figure of |ψ(x,y)|² for a 2D box (n,m).

    Important: this returns a Surface trace (x,y grid) so Plotly will render a real 3D surface.

    """
    x = np.linspace(0, L, resolution)
    y = np.linspace(0, L, resolution)
    X, Y = np.meshgrid(x, y)
    psi2 = (2.0 / L) * np.sin(n * np.pi * X / L) * np.sin(m * np.pi * Y / L)
    prob = psi2 ** 2

    # Use a Surface trace with explicit X, Y grid — this guarantees a true 3D surface
    surface = go.Surface(z=prob, x=X, y=Y, colorscale="Viridis", showscale=True)
    fig = go.Figure(data=[surface])
    fig.update_layout(
        title=f"Probability Surface — n={n}, m={m}, L={L}",
        scene=dict(xaxis_title="x", yaxis_title="y", zaxis_title="|ψ|²"),
        template="plotly_dark",
    )
    return fig

# ------------------------
# Animation helpers (small wrappers)
# ------------------------
def build_time_evolution_2d(n: int, L: float = 1.0, frames_count: int = 60, speed: float = 1.0) -> go.Figure:
    x = np.linspace(0, L, 400)
    t_vals = np.linspace(0.0, 2.0 * np.pi, frames_count)
    frames = []
    for t in t_vals:
        psi_t = np.sqrt(2.0 / L) * np.sin(n * np.pi * x / L) * np.cos((n ** 2) * t)
        prob_t = psi_t ** 2
        frames.append(go.Frame(data=[
            go.Scatter(x=x, y=psi_t, mode="lines", name="ψ(x,t)"),
            go.Scatter(x=x, y=prob_t, mode="lines", name="|ψ|²")
        ]))
    fig = go.Figure(
        data=[go.Scatter(x=x, y=np.zeros_like(x)), go.Scatter(x=x, y=np.zeros_like(x))],
        frames=frames,
        layout=go.Layout(
            title=f"Time evolution (2D) — n={n}, L={L}",
            xaxis=dict(title="x"),
            yaxis=dict(title="ψ / |ψ|²"),
            template="plotly_dark",
            updatemenus=[dict(type="buttons",
                              buttons=[
                                  dict(label="▶ Play", method="animate",
                                       args=[None, {"frame": {"duration": max(20, int(600 / speed))}, "fromcurrent": True}]),
                                  dict(label="⏸ Pause", method="animate",
                                       args=[[None], {"mode": "immediate", "frame": {"duration": 0}}])
                              ],
                              pad={"r": 10, "t": 10})]
        )
    )
    return fig

def build_pov_animation(n: int, L: float = 1.0, frames_count: int = 80, speed: float = 1.0, display_mode: str = "2D") -> go.Figure:
    if display_mode == "2D":
        x = np.linspace(0, L, 400)
        psi = np.sqrt(2.0 / L) * np.sin(n * np.pi * x / L)
        prob = psi ** 2
        t_vals = np.linspace(0.0, 2.0 * np.pi, frames_count)
        frames = []
        for t in t_vals:
            px = L * (0.5 + 0.45 * math.sin(t))
            py = np.sqrt(2.0 / L) * np.sin(n * np.pi * px / L)
            frames.append(go.Frame(data=[
                go.Scatter(x=x, y=psi, mode="lines", name="ψ(x)"),
                go.Scatter(x=x, y=prob, mode="lines", name="|ψ|²", opacity=0.4),
                go.Scatter(x=[px], y=[py], mode="markers", marker=dict(size=10, color="red"), name="particle")
            ]))
        fig = go.Figure(data=[go.Scatter(x=x, y=psi)], frames=frames)
        fig.update_layout(
            title=f"POV (2D) — n={n}, L={L}",
            xaxis=dict(title="x"),
            yaxis=dict(title="ψ"),
            template="plotly_dark",
            updatemenus=[dict(type="buttons",
                              buttons=[
                                  dict(label="▶ Play", method="animate",
                                       args=[None, {"frame": {"duration": max(20, int(600 / speed))}, "fromcurrent": True}]),
                                  dict(label="⏸ Pause", method="animate",
                                       args=[[None], {"mode": "immediate", "frame": {"duration": 0}}])
                              ])]
        )
        return fig
    else:
        # For 3D POV we simply return the full 3D surface (marker overlay could be added if needed)
        return plot_probability_3d(n=n, m=1, L=L)

# ------------------------
# Public API
# ------------------------
def run_pib_simulation(mode: str = "2D", L: float = 1.0, n: int = 1, pov: bool = False, speed: float = 1.0, extra: Optional[str] = None) -> go.Figure:
    """

    Primary entry used by the Streamlit UI.

    Returns a Plotly Figure (static or with frames).

    """
    # Try TDSE if available and pov requested for 'real' evolution
    if TDSE_AVAILABLE and pov:
        try:
            x = np.linspace(0.0, L, 400)
            def V_fn(arr): return np.zeros_like(arr)
            solver = TDSESolver(x=x, potential_fn=V_fn, method="crank-nicolson")
            psi0 = np.sqrt(2.0 / L) * np.sin(n * np.pi * x / L)
            snapshots = []
            psi = psi0.copy()
            for _ in range(30):
                psi = solver.evolve(psi, dt=0.01, steps=5)
                snapshots.append(psi.copy())
            fig = go.Figure()
            fig.add_trace(go.Scatter(x=x, y=np.real(snapshots[-1]), mode="lines", name="Re(ψ)"))
            fig.add_trace(go.Scatter(x=x, y=np.abs(snapshots[-1]) ** 2, mode="lines", name="|ψ|²"))
            fig.update_layout(title=f"TDSE snapshot (n={n}) — last evolved frame", template="plotly_dark")
            return fig
        except Exception:
            # fallback to analytic cinematic
            pass

    # POV cinematic
    if pov:
        return build_pov_animation(n=n, L=L, frames_count=80, speed=speed, display_mode=mode)

    # if speed != 1 produce time evolution frames
    if speed != 1.0:
        return build_time_evolution_2d(n=n, L=L, frames_count=60, speed=speed)

    # static outputs
    if mode == "2D":
        return plot_2d_wavefunction(n=n, L=L)
    elif mode == "3D":
        return plot_probability_3d(n=n, m=1, L=L)
    else:
        raise ValueError("mode must be '2D' or '3D'")

def run_simulation(mode: str = "2D", L: float = 1.0, n: int = 1, pov: bool = False, speed: float = 1.0):
    return run_pib_simulation(mode=mode, L=L, n=n, pov=pov, speed=speed)

def available_graphs() -> List[str]:
    return [
        "wavefunction",
        "probability",
        "nodes",
        "energy_levels",
        "multi_n",
        "fourier",
        "expectation"
    ]