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
 
 
 
 
 
 
 
 
 
 
 
d2ec756
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c9793cd
d2ec756
 
 
 
 
 
 
 
 
 
c9793cd
 
 
 
 
 
 
 
 
 
e1d92e1
c9793cd
 
 
 
 
d2ec756
 
 
 
 
 
 
 
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
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
import os
import time
import shutil

import numpy as np
import gradio as gr
import plotly.graph_objs as go

glob_a = -2
glob_b = -2
glob_c = -4
glob_d = 7


def clear_npz():
    current_directory = os.getcwd()  # Get the current working directory
    for filename in os.listdir(current_directory):
        if filename.endswith(".npz"):  # Check if the file ends with .npz
            file_path = os.path.join(current_directory, filename)
            try:
                if os.path.isfile(file_path) or os.path.islink(file_path):
                    os.unlink(file_path)  # Remove the file or symbolic link
                else:
                    print(f"Skipping {file_path}, not a file or symbolic link.")
            except Exception as e:
                print(f"Failed to delete {file_path}. Reason: {e}")


def complex_heat_eq_solution(x, t, a=glob_a, b=glob_b, c=glob_c, d=glob_d, k=0.5):
    global glob_a, glob_b, glob_c, glob_d
    return (
        np.exp(-k * t) * np.sin(np.pi * x)
        + 0.5 * np.exp(glob_a * k * t) * np.sin(glob_b * np.pi * x)
        + 0.25 * np.exp(glob_c * k * t) * np.sin(glob_d * np.pi * x)
    )


def plot_heat_equation(m, approx_type):
    # Define grid dimensions
    n_x = 32  # Fixed spatial grid resolution
    n_t = 50

    try:
        loaded_values = np.load(f"{approx_type}_m{m}.npz")
    except:
        raise gr.Error(f"First train the coefficients for {approx_type} and m = {m}")
    alpha = loaded_values["alpha"]
    Phi = loaded_values["Phi"]

    # Create grids for x and t
    x = np.linspace(0, 1, n_x)  # Spatial grid
    t = np.linspace(0, 5, n_t)  # Temporal grid
    X, T = np.meshgrid(x, t)

    # Compute the real solution over the grid
    U_real = complex_heat_eq_solution(X, T)

    # Compute the selected approximation
    U_approx = np.zeros_like(U_real)
    for i, t_val in enumerate(t):
        Phi_gff_at_t = Phi[i * n_x : (i + 1) * n_x]
        U_approx[i, :] = np.dot(Phi_gff_at_t, alpha)

    # Create the 3D plot with Plotly
    traces = []

    # Real solution surface with a distinct color (e.g., 'Viridis')
    traces.append(
        go.Surface(
            z=U_real,
            x=X,
            y=T,
            colorscale="Blues",
            showscale=False,
            name="Real Solution",
            showlegend=True,
        )
    )

    # Approximation surface with a distinct color (e.g., 'Plasma')
    traces.append(
        go.Surface(
            z=U_approx,
            x=X,
            y=T,
            colorscale="Reds",
            reversescale=True,
            showscale=False,
            name=f"{approx_type} Approximation",
            showlegend=True,
        )
    )

    # Layout for the Plotly plot without controls
    layout = go.Layout(
        title=f"Heat Equation Approximation | Kernel = {approx_type} | m = {m}",
        scene=dict(
            camera=dict(
                eye=dict(x=0, y=-2, z=0),  # Front view
            ),
            xaxis_title="x",
            yaxis_title="t",
            zaxis_title="u",
        ),
    )

    # Config to remove modebar buttons except the save image button
    config = {
        "modeBarButtonsToRemove": [
            "pan",
            "resetCameraLastSave",
            "hoverClosest3d",
            "hoverCompareCartesian",
            "zoomIn",
            "zoomOut",
            "select2d",
            "lasso2d",
            "zoomIn2d",
            "zoomOut2d",
            "sendDataToCloud",
            "zoom3d",
            "orbitRotation",
            "tableRotation",
        ],
        "displayModeBar": True,  # Keep the modebar visible
        "displaylogo": False,  # Hide the Plotly logo
    }

    # Create the figure
    fig = go.Figure(data=traces, layout=layout)

    fig.update_layout(
        modebar_remove=[
            "pan",
            "resetCameraLastSave",
            "hoverClosest3d",
            "hoverCompareCartesian",
            "zoomIn",
            "zoomOut",
            "select2d",
            "lasso2d",
            "zoomIn2d",
            "zoomOut2d",
            "sendDataToCloud",
            "zoom3d",
            "orbitRotation",
            "tableRotation",
            "toImage",
            "resetCameraDefault3d",
        ]
    )

    return fig


def plot_errors(m, approx_type):
    # Define grid dimensions
    n_x = 32  # Fixed spatial grid resolution
    n_t = 50

    try:
        loaded_values = np.load(f"{approx_type}_m{m}.npz")
    except:
        raise gr.Error(f"First train the coefficients for {approx_type} and m = {m}")
    alpha = loaded_values["alpha"]
    Phi = loaded_values["Phi"]

    # Create grids for x and t
    x = np.linspace(0, 1, n_x)  # Spatial grid
    t = np.linspace(0, 5, n_t)  # Temporal grid
    X, T = np.meshgrid(x, t)

    # Compute the real solution over the grid
    U_real = complex_heat_eq_solution(X, T)

    # Compute the selected approximation
    U_approx = np.zeros_like(U_real)
    for i, t_val in enumerate(t):
        Phi_gff_at_t = Phi[i * n_x : (i + 1) * n_x]
        U_approx[i, :] = np.dot(Phi_gff_at_t, alpha)

    U_err = abs(U_approx - U_real)

    # Create the 3D plot with Plotly
    traces = []

    # Real solution surface with a distinct color (e.g., 'Viridis')
    traces.append(
        go.Surface(
            z=U_err,
            x=X,
            y=T,
            colorscale="Viridis",
            showscale=False,
            name=f"Absolute Error",
            showlegend=True,
        )
    )

    # Layout for the Plotly plot without controls
    layout = go.Layout(
        title=f"Heat Equation Approximation Error | Kernel = {approx_type} | m = {m}",
        scene=dict(
            camera=dict(
                eye=dict(x=0, y=-2, z=0),  # Front view
            ),
            xaxis_title="x",
            yaxis_title="t",
            zaxis_title="u",
        ),
    )

    # Config to remove modebar buttons except the save image button
    config = {
        "modeBarButtonsToRemove": [
            "pan",
            "resetCameraLastSave",
            "hoverClosest3d",
            "hoverCompareCartesian",
            "zoomIn",
            "zoomOut",
            "select2d",
            "lasso2d",
            "zoomIn2d",
            "zoomOut2d",
            "sendDataToCloud",
            "zoom3d",
            "orbitRotation",
            "tableRotation",
        ],
        "displayModeBar": True,  # Keep the modebar visible
        "displaylogo": False,  # Hide the Plotly logo
    }

    # Create the figure
    fig = go.Figure(data=traces, layout=layout)

    fig.update_layout(
        modebar_remove=[
            "pan",
            "resetCameraLastSave",
            "hoverClosest3d",
            "hoverCompareCartesian",
            "zoomIn",
            "zoomOut",
            "select2d",
            "lasso2d",
            "zoomIn2d",
            "zoomOut2d",
            "sendDataToCloud",
            "zoom3d",
            "orbitRotation",
            "tableRotation",
            "toImage",
            "resetCameraDefault3d",
        ]
    )

    return fig


def generate_data(n_x=32, n_t=50):
    """Generate training data."""
    x = np.linspace(0, 1, n_x)  # spatial points
    t = np.linspace(0, 5, n_t)  # temporal points
    X, T = np.meshgrid(x, t)
    a_train = np.c_[X.ravel(), T.ravel()]  # shape (n_x * n_t, 2)
    u_train = complex_heat_eq_solution(
        a_train[:, 0], a_train[:, 1]
    )  # shape (n_x * n_t,)
    return a_train, u_train, x, t


def random_features(a, theta_j, kernel="SINE", k=0.5, t=1.0):
    """Compute random features with adjustable kernel width."""
    if kernel == "SINE":
        return np.sin(t * np.linalg.norm(a - theta_j, axis=-1))
    elif kernel == "GFF":
        return np.log(np.linalg.norm(a - theta_j, axis=-1)) / (2 * np.pi)
    else:
        raise ValueError("Unsupported kernel type!")


def design_matrix(a, theta, kernel):
    """Construct design matrix."""
    return np.array([random_features(a, theta_j, kernel=kernel) for theta_j in theta]).T


def learn_coefficients(Phi, u):
    """Learn coefficients alpha via least squares."""
    return np.linalg.lstsq(Phi, u, rcond=None)[0]


def approximate_solution(a, alpha, theta, kernel):
    """Compute the approximation."""
    Phi = design_matrix(a, theta, kernel)
    return Phi @ alpha


def polyfit2d(x, y, z, kx=3, ky=3, order=None):
    # grid coords
    x, y = np.meshgrid(x, y)
    # coefficient array, up to x^kx, y^ky
    coeffs = np.ones((kx + 1, ky + 1))

    # solve array
    a = np.zeros((coeffs.size, x.size))

    # for each coefficient produce array x^i, y^j
    for index, (j, i) in enumerate(np.ndindex(coeffs.shape)):
        # do not include powers greater than order
        if order is not None and i + j > order:
            arr = np.zeros_like(x)
        else:
            arr = coeffs[i, j] * x**i * y**j
        a[index] = arr.ravel()

    # do leastsq fitting and return leastsq result
    return np.linalg.lstsq(a.T, np.ravel(z), rcond=None)


def train_coefficients(m, kernel):
    # Start time for training
    start_time = time.time()

    # Generate data
    n_x, n_t = 32, 50
    a_train, u_train, x, t = generate_data(n_x, n_t)

    # Define random features
    theta = np.column_stack(
        (
            np.random.uniform(-1, 1, size=m),  # First dimension: [-1, 1]
            np.random.uniform(-5, 5, size=m),  # Second dimension: [-5, 5]
        )
    )

    # Construct design matrix and learn coefficients
    Phi = design_matrix(a_train, theta, kernel)
    alpha = learn_coefficients(Phi, u_train)
    # Validate and animate results
    u_real = np.array([complex_heat_eq_solution(x, t_i) for t_i in t])
    a_test = np.c_[np.meshgrid(x, t)[0].ravel(), np.meshgrid(x, t)[1].ravel()]
    u_approx = approximate_solution(a_test, alpha, theta, kernel).reshape(n_t, n_x)

    # Save values to the npz folder
    np.savez(
        f"{kernel}_m{m}.npz",
        alpha=alpha,
        kernel=kernel,
        Phi=Phi,
        theta=theta,
    )

    # Compute average error
    avg_err = np.mean(np.abs(u_real - u_approx))

    return f"Training completed in {time.time() - start_time:.2f} seconds. The average error is {avg_err}."


def plot_function(a, b, c, d, k=0.5):
    global glob_a, glob_b, glob_c, glob_d

    glob_a, glob_b, glob_c, glob_d = a, b, c, d

    x = np.linspace(0, 1, 100)
    t = np.linspace(0, 5, 500)
    X, T = np.meshgrid(x, t)  # Create the mesh grid
    Z = complex_heat_eq_solution(X, T, a, b, c, d)

    traces = []
    traces.append(
        go.Surface(
            z=Z,
            x=X,
            y=T,
            colorscale="Viridis",
            showscale=False,
            showlegend=False,
        )
    )

    # Layout for the Plotly plot without controls
    layout = go.Layout(
        scene=dict(
            camera=dict(
                eye=dict(x=1.25, y=-1.75, z=0.3),  # Front view
            ),
            xaxis_title="x",
            yaxis_title="t",
            zaxis_title="u",
        ),
        margin=dict(l=0, r=0, t=0, b=0),  # Reduce margins
    )

    # Create the figure
    fig = go.Figure(data=traces, layout=layout)

    fig.update_layout(
        modebar_remove=[
            "pan",
            "resetCameraLastSave",
            "hoverClosest3d",
            "hoverCompareCartesian",
            "zoomIn",
            "zoomOut",
            "select2d",
            "lasso2d",
            "zoomIn2d",
            "zoomOut2d",
            "sendDataToCloud",
            "zoom3d",
            "orbitRotation",
            "tableRotation",
            "toImage",
            "resetCameraDefault3d",
        ]
    )

    return fig

def plot_all(m, kernel):
    # Generate the plot content (replace this with your actual plot logic)
    approx_fig = plot_heat_equation(m, kernel)  # Replace with your function for approx_plot
    error_fig = plot_errors(m, kernel)    # Replace with your function for error_plot
    
    # Return the figures and make the plots visible
    return (
        gr.update(visible=True, value=approx_fig),
        gr.update(visible=True, value=error_fig),
    )

# Gradio interface
def create_gradio_ui():
    # Get the initial available files
    with gr.Blocks() as demo:
        gr.Markdown("# Learn the Coefficients for the Heat Equation using the RFM")

        # Function parameter inputs
        gr.Markdown(
            """
        ## Function: $$u_k(x, t)\\coloneqq\\exp(-kt)\\cdot\\sin(\\pi x)+0.5\\cdot\\exp(\\textcolor{red}{a}kt)\\cdot\\sin(\\textcolor{red}{b}\\pi x)+0.25\\cdot\\exp(\\textcolor{red}{c}kt)\\cdot\\sin(\\textcolor{red}{d}\\pi x)$$
        
        Adjust the values for <span style='color: red;'>a</span>, <span style='color: red;'>b</span>, <span style='color: red;'>c</span> and <span style='color: red;'>d</span> with the sliders below.
        """
        )

        with gr.Row():
            with gr.Column():
                a_slider = gr.Slider(
                    minimum=-10, maximum=-1, step=1, value=-2, label="a"
                )
                b_slider = gr.Slider(
                    minimum=-10, maximum=10, step=1, value=-2, label="b"
                )
                c_slider = gr.Slider(
                    minimum=-10, maximum=-1, step=1, value=-4, label="c"
                )
                d_slider = gr.Slider(
                    minimum=-10, maximum=10, step=1, value=7, label="d"
                )

            plot_output = gr.Plot()

        a_slider.change(
            fn=plot_function,
            inputs=[a_slider, b_slider, c_slider, d_slider],
            outputs=[plot_output],
        )
        b_slider.change(
            fn=plot_function,
            inputs=[a_slider, b_slider, c_slider, d_slider],
            outputs=[plot_output],
        )
        c_slider.change(
            fn=plot_function,
            inputs=[a_slider, b_slider, c_slider, d_slider],
            outputs=[plot_output],
        )
        d_slider.change(
            fn=plot_function,
            inputs=[a_slider, b_slider, c_slider, d_slider],
            outputs=[plot_output],
        )

        with gr.Column():
            with gr.Row():
                # Kernel selection and slider for m
                kernel_dropdown = gr.Dropdown(
                    label="Choose Kernel", choices=["SINE", "GFF"], value="SINE"
                )
                m_slider = gr.Dropdown(
                    label="Number of Random Features (m)",
                    choices=[50, 250, 1000, 5000, 10000, 25000],
                    value=1000,
                )

                # Output to show status
                output = gr.Textbox(label="Status", interactive=False)

            with gr.Column():
                # Button to train coefficients
                train_button = gr.Button("Train Coefficients")
                # Function to trigger training and update dropdown
                train_button.click(
                    fn=train_coefficients,
                    inputs=[m_slider, kernel_dropdown],
                    outputs=output,
                )
                approx_button = gr.Button("Plot Approximation")

        with gr.Row():
            approx_plot = gr.Plot(visible=False)
            error_plot = gr.Plot(visible=False)

        approx_button.click(
            fn=plot_all,
            inputs=[m_slider, kernel_dropdown],
            outputs=[approx_plot, error_plot],
        )

        demo.load(fn=clear_npz, inputs=None, outputs=None)
        demo.load(
            fn=plot_function,
            inputs=[a_slider, b_slider, c_slider, d_slider],
            outputs=[plot_output],
        )

    return demo


# Launch Gradio app
if __name__ == "__main__":
    interface = create_gradio_ui()
    interface.launch(share=False)