From da5b1ffeba232fbf453145f9a0484321c2d75912 Mon Sep 17 00:00:00 2001 From: Paul Tuemmler <136888490+ptuemmler@users.noreply.github.com> Date: Wed, 9 Jul 2025 21:58:05 +0200 Subject: [PATCH 01/14] Updated contributing.md --- docs/contributing.md | 39 +++++++++++++++++++++------------------ 1 file changed, 21 insertions(+), 18 deletions(-) diff --git a/docs/contributing.md b/docs/contributing.md index 4bed552..02dc499 100644 --- a/docs/contributing.md +++ b/docs/contributing.md @@ -7,7 +7,7 @@ We welcome contributions to this project! If you have an idea for a new tool, a ## Setting up a development environment You should first fork [this](https://github.com/physicsapps/teaching) repository and then clone it to your local machine. ```bash -git clone https://github.com/physicsapps/teaching.git +git clone https://github.com//teaching.git cd TeachingTools ``` @@ -27,23 +27,25 @@ git switch -c my-new-feature To create a new tool, you should copy one of the template tools from the `apps` directory and modify it to your needs. Each tool should have its own directory with the following structure: ``` -apps/ -└── MyNewTool - ├── app.py - ├── app.md - └── requirements.txt +docs/ +└── apps/ + └── MyNewTool + ├── app.py + ├── app.md + └── requirements.txt ``` If you want to use multiple apps in one tool, you can create a separate directory for every app: ``` -apps/ -└── MyNewTool - ├── app1 - | ├── app.py - | └── requirements.txt - ├── app2 - | ├── app.py - | └── requirements.txt - └── app.md +docs/ +└── apps/ + └── MyNewTool + ├── app1 + | ├── app.py + | └── requirements.txt + ├── app2 + | ├── app.py + | └── requirements.txt + └── app.md ``` The tools themselves are created using [Shiny for python](https://shiny.posit.co/py/), which allows you to create interactive web applications using Python. In the case of static sites, such as this one, the tools are rendered as static HTML files using the [shinylive](https://github.com/posit-dev/py-shinylive) library. @@ -89,14 +91,15 @@ authors: slug: url # Author profile slug url: url # Author website URL ``` -Set the category to one of the existing categories, or create a new one to `mkdocs.yml` if necessary. +Set the category to one of the existing categories, or create a new one to `mkdocs.yml` if necessary. ```yml title="mkdocs.yml" plugins: - blog: categories_allowed: - ``` -The tags are used to further categorize the tool and can be anything you like. +Note that the amount of categories should be kept to a minimum, so try to use existing categories if possible. +Instead, use the `tags` section to add more specific tags to your tool. The name of the tool is generated from the title of the `app.md` file, so make sure to use a descriptive title. The `` tag is used to separate the introduction, which is shown as an excerpt, from the rest of the documentation. To embed the app in the documentation, you can use the `{{embed_app("width", "height")}}` macro. @@ -109,7 +112,7 @@ mkdocs build --clean python -m http.server --directory ./site --bind localhost 8008 ``` This will create a `site` directory containing the static HTML files for the documentation, including your new tool. -You can then open your browser and navigate to [localhost](http://[::1]:8008/) to see the documentation and test if everything works. +You can then open your browser and navigate to [localhost http://[::1]:8008/](http://[::1]:8008/) to see the documentation and test if everything works. If that is the case, congratulations! You have successfully created a new tool for TeachingTools and can now submit your changes. ## Submitting your changes From 7dd99cb5246fe2e51c9ef2c3d7a1235519405986 Mon Sep 17 00:00:00 2001 From: tuemmler Date: Thu, 30 Oct 2025 19:25:32 +0100 Subject: [PATCH 02/14] - updated contributing.md --- docs/contributing.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/contributing.md b/docs/contributing.md index 02dc499..40254d4 100644 --- a/docs/contributing.md +++ b/docs/contributing.md @@ -91,7 +91,7 @@ authors: slug: url # Author profile slug url: url # Author website URL ``` -Set the category to one of the existing categories, or create a new one to `mkdocs.yml` if necessary. +Set the category to one of the existing categories, or create a new one to `mkdocs.yml` if necessary. ```yml title="mkdocs.yml" plugins: - blog: @@ -122,4 +122,4 @@ git add . git commit -m "Add MyNewTool" git push origin my-new-feature ``` -Then, create a pull request on the original repository. Make sure to provide a clear description of your changes and what they do. +Then, create a pull request on the original repository. Make sure to provide a clear description of your changes and what they do. \ No newline at end of file From dad42cf18c7ea43a6ac7cfb36bde15b815954cca Mon Sep 17 00:00:00 2001 From: tuemmler Date: Thu, 30 Oct 2025 19:26:36 +0100 Subject: [PATCH 03/14] - updated mkdocs.yml to automatically use dark mode according to user device settings --- mkdocs.yml | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/mkdocs.yml b/mkdocs.yml index 05ad8e4..f428c29 100644 --- a/mkdocs.yml +++ b/mkdocs.yml @@ -6,6 +6,26 @@ theme: - toc.integrate - content.tabs.link - content.code.copy + palette: + # Palette toggle for automatic mode + - media: "(prefers-color-scheme)" + toggle: + icon: material/brightness-auto + name: Switch to light mode + + # Palette toggle for light mode + - media: "(prefers-color-scheme: light)" + scheme: default + toggle: + icon: material/brightness-7 + name: Switch to dark mode + + # Palette toggle for dark mode + - media: "(prefers-color-scheme: dark)" + scheme: slate + toggle: + icon: material/brightness-4 + name: Switch to system preference extra_css: - stylesheets/extra.css From 4933b0df0878b070c3d75eb54933d37b6797ac20 Mon Sep 17 00:00:00 2001 From: tuemmler Date: Thu, 30 Oct 2025 19:27:22 +0100 Subject: [PATCH 04/14] - updated (wip!) TaylorExpansion to use dark mode as a first test --- docs/apps/TaylorExpansion/app.py | 79 +++++++++++++++++--------------- 1 file changed, 42 insertions(+), 37 deletions(-) diff --git a/docs/apps/TaylorExpansion/app.py b/docs/apps/TaylorExpansion/app.py index e96bab2..c53039d 100644 --- a/docs/apps/TaylorExpansion/app.py +++ b/docs/apps/TaylorExpansion/app.py @@ -45,6 +45,7 @@ 'Show Contributions', value=False, ), + ui.input_dark_mode(id='dark_mode'), open='always' ), ui.output_plot("taylor_plot", width="100%", height="440px") @@ -119,48 +120,52 @@ def calculate_derivatives(): @render.plot() def taylor_plot(): - x, y_true, func_str = evaluate_function() - a = input.center() - order = input.order() - derivative_values = calculate_derivatives() - - fig, ax = plt.subplots() + if input.dark_mode() == "dark": + style_label = 'dark_background' + else: + style_label = 'seaborn-v0_8' - # Plot original function - ax.plot(x, y_true, linewidth=2, label=f'f(x)') + with plt.style.context(style_label): + x, y_true, func_str = evaluate_function() + a = input.center() + order = input.order() + derivative_values = calculate_derivatives() - # Calculate Taylor expansion - y_taylor_terms = [] - for n in range(order + 1): - # Add nth term of Taylor series - y_taylor_terms.append(derivative_values[n] * ((x - a) ** n) / math.factorial(n)) - y_taylor = np.sum(y_taylor_terms, axis=0) + fig, ax = plt.subplots() - # Plot Taylor approximation - ax.plot(x, y_taylor, '--', linewidth=2, - label=fr'f_{order}(x)') + # Plot original function + ax.plot(x, y_true, linewidth=2, label=r'$f(x)$') - # Mark the point on the original function at expansion center - center_idx = np.argmin(np.abs(x - a)) - temp = ax.plot(a, y_true[center_idx], 'o', markersize=8) - ax.axvline(x=a, linestyle=':', color=temp[0].get_color(), - label=f'a={a:.2f})') - - if input.show_contrib(): + # Calculate Taylor expansion + y_taylor_terms = [] for n in range(order + 1): - ax.plot(x, y_taylor_terms[n], 'k--', linewidth=1, alpha=0.4) - # Formatting - ax.set_xlabel('x') - ax.set_ylabel('y') - # ax.set_title(f'Taylor Expansion of {func_str} around x = {a:.2f}') - ax.legend() - - # Set reasonable y-limits based on the data - y_min = np.min(y_true) - y_max = np.max(y_true) - y_range = y_max - y_min - ax.set_ylim(y_min - 0.1 * y_range, y_max + 0.1 * y_range) - + # Add nth term of Taylor series + y_taylor_terms.append(derivative_values[n] * ((x - a) ** n) / math.factorial(n)) + y_taylor = np.sum(y_taylor_terms, axis=0) + + # Plot Taylor approximation + ax.plot(x, y_taylor, '--', linewidth=2, label=rf'$f_{order}(x)$') + + # Mark the point on the original function at expansion center + center_idx = np.argmin(np.abs(x - a)) + temp = ax.plot(a, y_true[center_idx], 'o', markersize=8) + ax.axvline(x=a, linestyle=':', color=temp[0].get_color(), + label=rf'$a={a:.2f}$') + + if input.show_contrib(): + for n in range(order + 1): + ax.plot(x, y_taylor_terms[n], color='grey', ls='--', linewidth=1, alpha=0.4) + # Formatting + ax.set_xlabel('x') + ax.set_ylabel('y') + # ax.set_title(f'Taylor Expansion of {func_str} around x = {a:.2f}') + ax.legend() + + # Set reasonable y-limits based on the data + y_min = np.min(y_true) + y_max = np.max(y_true) + y_range = y_max - y_min + ax.set_ylim(y_min - 0.1 * y_range, y_max + 0.1 * y_range) return fig From da522b1916e14daa3f23611d73776905b315bcbf Mon Sep 17 00:00:00 2001 From: tuemmler Date: Thu, 30 Oct 2025 19:27:39 +0100 Subject: [PATCH 05/14] - started working on FourierTransforms app --- docs/apps/FastFourierTransforms/1d/app.py | 213 ++++++++++++++++++++-- docs/apps/FastFourierTransforms/2d/app.py | 179 ++++++++++++++++-- docs/apps/FastFourierTransforms/app.md | 4 +- 3 files changed, 368 insertions(+), 28 deletions(-) diff --git a/docs/apps/FastFourierTransforms/1d/app.py b/docs/apps/FastFourierTransforms/1d/app.py index fbf5227..b5e5ba4 100644 --- a/docs/apps/FastFourierTransforms/1d/app.py +++ b/docs/apps/FastFourierTransforms/1d/app.py @@ -1,18 +1,205 @@ import matplotlib.pyplot as plt -from palmerpenguins import load_penguins -from shiny.express import input, render, ui +import matplotlib +import numpy as np +from shiny import App, render, ui, reactive -ui.input_slider("n", "Number of bins", 1, 100, 20) +app_ui = ui.page_sidebar( + ui.sidebar( + ui.input_slider( + "sigma", + "Width of Gaussian (σ)", + min=0, + max=0.5, + value=0, + step=0.025, + animate=True + ), + ui.input_slider( + "event_x", + "Frequency", + min=-2, + max=2, + value=0.5, + step=0.025, + animate=True + ), + ui.input_slider( + "event_y", + "Amplitude", + min=-0.9, + max=0.9, + value=0.5, + step=0.025, + animate=True + ), -@render.plot(alt="A histogram") -def plot(): - df = load_penguins() - mass = df["body_mass_g"] + ui.input_checkbox( + 'show_imaginary', + 'Show imaginary parts', + value=True, + ), - fig, ax = plt.subplots() - ax.hist(mass, input.n(), density=True) - ax.set_title("Palmer Penguin Masses") - ax.set_xlabel("Mass (g)") - ax.set_ylabel("Density") + ui.input_checkbox( + 'include_negative_frequencies', + 'Add imaginary Fourier component', + value=True, + ), + ui.input_checkbox( + 'flip_imaginary', + 'Flip imaginary Fourier component', + value=True, + ), + ui.input_checkbox( + 'show_contributions', + 'Show individual contributions', + value=True, + ), + ui.input_dark_mode(id='dark_mode'), + open='always', + ), + ui.layout_columns( + ui.output_plot( + "fourier_plot", + click=True, + width="100%", height="700px" + ), + ui.output_plot( + "real_plot", + width="100%", height="700px" + ), + ), +) - return fig \ No newline at end of file +def server(input, output, session): + click_data = reactive.value(None) + blue = 'navy' + red = 'firebrick' + + x_axis = np.linspace(-20, 20, 1024) + freq_axis = np.fft.fftfreq(len(x_axis), d=(x_axis[1] - x_axis[0])) + freq_axis = np.fft.fftshift(freq_axis) + + x_axis_lims = (-5, 5) + freq_axis_lims = (-2, 2) + + # Update click data when plot is clicked + @reactive.effect + def _(): + if input.fourier_plot_click() is not None: + click_data.set(input.fourier_plot_click()) + ui.update_slider('event_x', value=input.fourier_plot_click()['x']) + ui.update_slider('event_y', value=input.fourier_plot_click()['y']) + # One could actually calculate everything here and then only use the resulting data in the plots + + + + @render.plot() + def fourier_plot(): + if input.dark_mode() == "dark": + style_label = 'dark_background' + blue = 'lightsteelblue' + red = 'lightcoral' + else: + style_label = 'seaborn-v0_8' + blue = 'navy' + red = 'firebrick' + + with plt.style.context(style_label): + sigma = input.sigma() + + fig, axs = plt.subplots() + axs.set_xlim(freq_axis_lims) + axs.set_ylim(-1, 1) + + eventx, eventy = input.event_x(), input.event_y() + fourier_signal = get_gaussian(freq_axis, eventx, sigma, eventy) + + sign = -1 if input.flip_imaginary() else 1 + if input.include_negative_frequencies(): + # add negative frequencies for real signal + fourier_signal = fourier_signal + sign * 1j * get_gaussian(freq_axis, -eventx, sigma, eventy) + + if sigma == 0: + axs.plot(freq_axis, np.zeros_like(freq_axis), color=red, label=f'Real Part') + axs.plot([eventx, eventx], [0, eventy], color=red) + if input.show_imaginary(): + axs.plot(freq_axis, np.zeros_like(freq_axis), color=blue, ls='--', label=f'Imaginary Part') + + if input.include_negative_frequencies(): + axs.plot([-eventx, -eventx], [0, sign * eventy], color=blue, ls='--') + else: + axs.plot(freq_axis, np.real(fourier_signal), color=red, label=f'Real Part') + if input.show_imaginary(): + axs.plot(freq_axis, np.imag(fourier_signal), color=blue, ls='--', label=f'Imaginary Part') + + # axs.scatter([eventx], [eventy], color='black') + axs.legend() + + axs.set_title("Fourier Transform") + + axs.set_xlabel("Frequency (Hz)") + axs.set_ylabel("Amplitude") + return fig + + @render.plot() + def real_plot(): + if input.dark_mode() == "dark": + style_label = 'dark_background' + blue = 'lightsteelblue' + red = 'lightcoral' + else: + style_label = 'seaborn-v0_8' + blue = 'navy' + red = 'firebrick' + + with plt.style.context(style_label): + sigma = input.sigma() + + + fig, axs = plt.subplots() + axs.set_xlim(x_axis_lims) + if sigma == 0: + axs.set_ylim(-1, 1) + + eventx, eventy = input.event_x(), input.event_y() + fourier_signal = get_gaussian(freq_axis, eventx, sigma, eventy) + if input.include_negative_frequencies(): + # add negative frequencies for real signal + sign = -1 if input.flip_imaginary() else 1 + fourier_signal = fourier_signal + sign * 1j * get_gaussian(freq_axis, -eventx, sigma, eventy) + + real_signal = np.fft.ifftshift(np.fft.ifft(np.fft.ifftshift(fourier_signal))) * len(x_axis) + + if input.show_contributions(): + # plot individual contributions + for freq, amplitude in zip(freq_axis, fourier_signal): + if np.abs(amplitude) < 1e-3: + continue + contribution = amplitude * np.exp(2j * np.pi * freq * x_axis) + axs.plot(x_axis, np.real(contribution), color=red, alpha=0.1) + if input.show_imaginary(): + axs.plot(x_axis, np.imag(contribution), color=blue, alpha=0.1) + + # real signal + axs.plot(x_axis, np.real(real_signal), color=red, label=f'Real Part') + if input.show_imaginary(): + axs.plot(x_axis, np.imag(real_signal), color=blue, ls='--', label=f'Imaginary Part') + + axs.legend() + + axs.set_title("Real Space Signal") + axs.set_xlabel("Time [s]") + axs.set_ylabel("Amplitude") + return fig + +def get_gaussian(x, x0, sigma, amp): + if sigma == 0: + signal = np.zeros_like(x) + closest_idx = (np.abs(x - x0)).argmin() + signal[closest_idx] = amp + else: + signal = amp * np.exp(-(x - x0) ** 2 / (2 * sigma ** 2)) + + return signal + +app = App(app_ui, server, debug=True) diff --git a/docs/apps/FastFourierTransforms/2d/app.py b/docs/apps/FastFourierTransforms/2d/app.py index fbf5227..062c98c 100644 --- a/docs/apps/FastFourierTransforms/2d/app.py +++ b/docs/apps/FastFourierTransforms/2d/app.py @@ -1,18 +1,171 @@ import matplotlib.pyplot as plt -from palmerpenguins import load_penguins -from shiny.express import input, render, ui +import matplotlib.ticker as ticker +import numpy as np +from shiny import App, render, ui, reactive -ui.input_slider("n", "Number of bins", 1, 100, 20) +app_ui = ui.page_sidebar( + ui.sidebar( + ui.input_slider( + "sigma", + "Width of Gaussian (σ)", + min=0, + max=0.5, + value=0, + step=0.025, + animate=True + ), + ui.input_slider( + "event_x", + "Frequency in x", + min=-2, + max=2, + value=0.5, + step=0.025, + animate=True + ), + ui.input_slider( + "event_y", + "Frequency in y", + min=-2, + max=2, + value=0.5, + step=0.025, + animate=True + ), + ui.input_checkbox( + 'include_negative_frequencies', + 'Add imaginary Fourier component', + value=True, + ), + ui.input_checkbox( + 'flip_imaginary', + 'Flip imaginary Fourier component', + value=True, + ), + ui.input_dark_mode(id='dark_mode'), + open='always', + ), + ui.layout_columns( + ui.output_plot( + "fourier_plot", + click=True, + width="100%", height="700px" + ), + ui.output_plot( + "real_plot", + width="100%", height="700px" + ), + ), +) -@render.plot(alt="A histogram") -def plot(): - df = load_penguins() - mass = df["body_mass_g"] +def server(input, output, session): + click_data = reactive.value(None) + blue = 'navy' + red = 'firebrick' - fig, ax = plt.subplots() - ax.hist(mass, input.n(), density=True) - ax.set_title("Palmer Penguin Masses") - ax.set_xlabel("Mass (g)") - ax.set_ylabel("Density") + x_axis = np.linspace(-20, 20, 1024) + y_axis = np.linspace(-20, 20, 1024) + freq_axis = np.fft.fftfreq(len(x_axis), d=(x_axis[1] - x_axis[0])) + freq_axis = np.fft.fftshift(freq_axis) - return fig \ No newline at end of file + x_axis_lims = (-5, 5) + freq_axis_lims = (-2, 2) + + # Update click data when plot is clicked + @reactive.effect + def _(): + if input.fourier_plot_click() is not None: + click_data.set(input.fourier_plot_click()) + ui.update_slider('event_x', value=input.fourier_plot_click()['x']) + ui.update_slider('event_y', value=input.fourier_plot_click()['y']) + # One could actually calculate everything here and then only use the resulting data in the plots + + + + @render.plot() + def fourier_plot(): + if input.dark_mode() == "dark": + style_label = 'dark_background' + else: + style_label = 'seaborn-v0_8' + + with plt.style.context(style_label): + sigma = input.sigma() + fig, axs = plt.subplots() + axs.set_xlim(freq_axis_lims) + axs.set_ylim(freq_axis_lims) + + eventx, eventy = input.event_x(), input.event_y() + fourier_signal = get_gaussian2d(freq_axis, freq_axis, eventx, eventy, sigma, 1) + + sign = -1 if input.flip_imaginary() else 1 + if input.include_negative_frequencies(): + # add negative frequencies for real signal + fourier_signal = fourier_signal + sign * 1j * get_gaussian2d(freq_axis, freq_axis, -eventx, -eventy, sigma, 1) + + if sigma == 0: + img = axs.imshow(np.zeros((len(freq_axis), len(freq_axis))), interpolation='none', + cmap='RdBu_r', extent=(freq_axis[0], freq_axis[-1], freq_axis[0], freq_axis[-1]), origin='lower', vmin=-1, vmax=1) + axs.plot([eventx], [eventy], marker='o', color='red', label='Real Part') + if input.include_negative_frequencies(): + axs.plot([sign * eventx], [sign * eventy], marker='x', color='blue', label='Imaginary Part') + axs.legend() + else: + img = axs.imshow(np.sqrt(np.abs(fourier_signal)) * np.sign(np.real(fourier_signal ** 2)), interpolation='none', cmap='RdBu_r', vmin=-1, vmax=1, + extent=(freq_axis[0], freq_axis[-1], freq_axis[0], freq_axis[-1]), origin='lower') + cbar = fig.colorbar(img, ax=axs) + cbar.ax.yaxis.set_major_formatter(ticker.FuncFormatter(lambda x, pos: f"{-float(x):.1f}i" if x < 0 else f"{float(x):.1f}")) + + + axs.set_title("Fourier Transform") + + axs.set_xlabel("Frequency in x (Hz)") + axs.set_ylabel("Frequency in y (Hz)") + return fig + + @render.plot() + def real_plot(): + if input.dark_mode() == "dark": + style_label = 'dark_background' + else: + style_label = 'seaborn-v0_8' + with plt.style.context(style_label): + sigma = input.sigma() + + fig, axs = plt.subplots() + axs.set_xlim(x_axis_lims) + axs.set_ylim(x_axis_lims) + + eventx, eventy = input.event_x(), input.event_y() + fourier_signal = get_gaussian2d(freq_axis, freq_axis, eventx, eventy, sigma, 1) + + sign = -1 if input.flip_imaginary() else 1 + if input.include_negative_frequencies(): + # add negative frequencies for real signal + fourier_signal = fourier_signal + sign * 1j * get_gaussian2d(freq_axis, freq_axis, -eventx, -eventy, sigma, 1) + + real_signal = np.fft.ifftshift(np.fft.ifft2(np.fft.fftshift(fourier_signal))) * len(x_axis) * len(y_axis) + + # real signal + img = axs.imshow(np.abs(real_signal), interpolation='none', cmap='turbo', + extent=(x_axis[0], x_axis[-1], x_axis[0], x_axis[-1]), origin='lower') + cbar = fig.colorbar(img, ax=axs) + + axs.set_title("Real Space Signal") + axs.set_xlabel("Time in x [s]") + axs.set_ylabel("Time in y [s]") + return fig + +def get_gaussian2d(x, y, x0, y0, sigma, amp): + if sigma == 0: + signal = np.zeros((len(x), len(y))) + closest_idx_x = (np.abs(y - y0)).argmin() + closest_idx_y = (np.abs(x - x0)).argmin() + signal[closest_idx_x, closest_idx_y] = amp + else: + X, Y = np.meshgrid(x, y, indexing='xy') + signal = amp * np.exp(-((X - x0) ** 2 + (Y - y0) ** 2) / (2 * sigma ** 2)) + + return signal + +app = App(app_ui, server, debug=True) diff --git a/docs/apps/FastFourierTransforms/app.md b/docs/apps/FastFourierTransforms/app.md index ad72fde..c608e6d 100644 --- a/docs/apps/FastFourierTransforms/app.md +++ b/docs/apps/FastFourierTransforms/app.md @@ -84,5 +84,5 @@ For the 1D case, we can use the following python and matlab code snippets to com ``` -{{embed_app("100%", "500px", "1d")}} -{{embed_app("100%", "500px", "2d")}} +{{embed_app("100%", "800px", "1d")}} +{{embed_app("100%", "800px", "2d")}} From 2be1831fb4e96844856768b40c66eda6d8abc36f Mon Sep 17 00:00:00 2001 From: tuemmler Date: Thu, 30 Oct 2025 19:27:59 +0100 Subject: [PATCH 06/14] - started working on MinkowskiSpaceTime app --- docs/apps/MinkowskiSpaceTime/app.md | 19 +++ docs/apps/MinkowskiSpaceTime/app.py | 139 ++++++++++++++++++ docs/apps/MinkowskiSpaceTime/requirements.txt | 2 + 3 files changed, 160 insertions(+) create mode 100644 docs/apps/MinkowskiSpaceTime/app.md create mode 100644 docs/apps/MinkowskiSpaceTime/app.py create mode 100644 docs/apps/MinkowskiSpaceTime/requirements.txt diff --git a/docs/apps/MinkowskiSpaceTime/app.md b/docs/apps/MinkowskiSpaceTime/app.md new file mode 100644 index 0000000..f68764e --- /dev/null +++ b/docs/apps/MinkowskiSpaceTime/app.md @@ -0,0 +1,19 @@ +--- +authors: + - ptuemmler +categories: + - Mathematics + - Numerics +tags: + - Code + - Fourier Transform +date: 2025-10-27 +hide: + - toc +draft: true +--- +# Minkowski Space-Time +Bli + +BlaBlu +{{embed_app("100%", "800px")}} diff --git a/docs/apps/MinkowskiSpaceTime/app.py b/docs/apps/MinkowskiSpaceTime/app.py new file mode 100644 index 0000000..9cd99b8 --- /dev/null +++ b/docs/apps/MinkowskiSpaceTime/app.py @@ -0,0 +1,139 @@ +import matplotlib.pyplot as plt +import matplotlib.ticker as ticker +import numpy as np +from shiny import App, render, ui, reactive + +# plt.style.use('seaborn-v0_8') + +app_ui = ui.page_sidebar( + ui.sidebar( + ui.input_slider( + "velocity", + "Velocity (units of c)", + min=-0.99, + max=0.99, + value=0, + step=0.01, + animate=True + ), + ui.input_checkbox( + 'show_minkowski', + 'Minkowski Metric', + value=True, + ), + ui.input_checkbox( + 'show_isolines', + 'Isolines', + value=True, + ), + open='always' + ), + ui.output_plot( + "plot", + click=True, + width="100%", height="700px" + ), + ui.output_text("event_params"), +) + +def server(input, output, session): + click_data = reactive.value(None) + x_ct_axis = np.linspace(-5, 5, 251) + metric_x, metric_ct = np.meshgrid(x_ct_axis, x_ct_axis) + minkowski_metric = metric_ct**2 - metric_x**2 + + blue = 'navy' + red = 'firebrick' + # Update click data when plot is clicked + @reactive.effect + def _(): + if input.plot_click() is not None: + click_data.set(input.plot_click()) + + @render.plot() + def plot(): + v = input.velocity() + + fig, ax = plt.subplots() + ax.set_xlim(-5, 5) + ax.set_ylim(-5, 5) + ax.xaxis.set_major_locator(ticker.MultipleLocator(base=1)) + ax.yaxis.set_major_locator(ticker.MultipleLocator(base=1)) + tick_positions = ax.get_xticks() + + if input.show_minkowski(): + img = ax.imshow(np.sqrt(np.abs(minkowski_metric)) * np.sign(minkowski_metric), extent=(-5, 5, -5, 5), + origin='lower', cmap='RdBu', alpha=0.3) + cbar=fig.colorbar(img, ax=ax, label=r'Eigenzeit $\sqrt{(c^2t^2 - x^2)}$', ticks=tick_positions) + cbar.ax.yaxis.set_major_formatter(ticker.FuncFormatter(lambda x, pos: f"{-int(x)}i" if x < 0 else f"{int(x)}")) + + + if input.show_isolines(): + for tick_pos in tick_positions: + if tick_pos <= 0: + continue + x0 = np.sqrt(x_ct_axis ** 2 + tick_pos ** 2) + ax.plot(x0, x_ct_axis, color='grey', linestyle='--', alpha=0.5) + ax.plot(-x0, x_ct_axis, color='grey', linestyle='--', alpha=0.5) + ax.plot(x_ct_axis, x0, color='grey', linestyle='--', alpha=0.5) + ax.plot(x_ct_axis, -x0, color='grey', linestyle='--', alpha=0.5) + + # Draw axes + ax.axhline(0, color=blue) + ax.axvline(0, color=blue) + # Apply Lorentz transformation to axes + if v != 0: + x_axis_transformed, ct_axis_transformed = lorentz_transform(x_ct_axis, np.zeros_like(x_ct_axis), v) + ax.plot(x_axis_transformed, ct_axis_transformed, color=red) + ax.plot(ct_axis_transformed, x_axis_transformed, color=red) + + # Draw intersections of isolines and axes + for tick_pos in tick_positions: + if tick_pos == 0: + continue + x_axis_transformed, ct_axis_transformed = lorentz_transform(tick_pos, 0, v) + ax.plot(x_axis_transformed, ct_axis_transformed, 'o', color=red) + ax.plot(ct_axis_transformed, x_axis_transformed, 'o', color=red) + + ax.plot(tick_pos, 0, 'o', color=blue) + ax.plot(0, tick_pos, 'o', color=blue) + + stored_click = click_data() + if stored_click is not None: + eventx, eventy = stored_click["x"], stored_click["y"] + ax.scatter(eventx, eventy, color='green') + # Draw lines from click to axes + ax.plot([eventx, eventx], [0, eventy], color=blue, linestyle=':') + ax.plot([0, eventx], [eventy, eventy], color=blue, linestyle=':') + + x_transformed, y_transformed = lorentz_transform(eventx, eventy, -v) + + # Draw lines to transformed axes + ref_x_transformed, ref_ct_transformed = lorentz_transform(x_transformed, 0, v) + ax.plot([ref_x_transformed, eventx], [ref_ct_transformed, eventy], color=red, linestyle=':') + ref_x_transformed, ref_ct_transformed = lorentz_transform(0, y_transformed, v) + ax.plot([ref_x_transformed, eventx], [ref_ct_transformed, eventy], color=red, linestyle=':') + + ax.set_xlabel("x") + ax.set_ylabel("ct") + ax.set_aspect('equal') + return fig + + @render.text() + def event_params(): + stored_click = click_data() + if stored_click is None: + return "Click on the plot to select an event." + + eventx, eventy = stored_click["x"], stored_click["y"] + return (f"Event coordinates:\n" + f" In rest frame: x = {eventx:.2f}, ct = {eventy:.2f}\n") + +def lorentz_transform(x, t, v): + c = 1 # velocity of light v will be in units of c + gamma = 1 / (1 - (v**2 / c**2))**0.5 + x_prime = gamma * (x + v * t) + t_prime = gamma * (t + (v * x) / c**2) + return x_prime, t_prime + +app = App(app_ui, server, debug=True) diff --git a/docs/apps/MinkowskiSpaceTime/requirements.txt b/docs/apps/MinkowskiSpaceTime/requirements.txt new file mode 100644 index 0000000..806f221 --- /dev/null +++ b/docs/apps/MinkowskiSpaceTime/requirements.txt @@ -0,0 +1,2 @@ +numpy +matplotlib \ No newline at end of file From 6d4dbd413a3cb3c4fe7741339999d2ffac3263ae Mon Sep 17 00:00:00 2001 From: tuemmler Date: Thu, 30 Oct 2025 20:28:48 +0100 Subject: [PATCH 07/14] - started adding berlin colormap to MinkowskiSpaceTime app --- docs/apps/MinkowskiSpaceTime/app.py | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/docs/apps/MinkowskiSpaceTime/app.py b/docs/apps/MinkowskiSpaceTime/app.py index 9cd99b8..41c98b2 100644 --- a/docs/apps/MinkowskiSpaceTime/app.py +++ b/docs/apps/MinkowskiSpaceTime/app.py @@ -3,7 +3,9 @@ import numpy as np from shiny import App, render, ui, reactive -# plt.style.use('seaborn-v0_8') +berlin_cmap = [[0.621082, 0.690182, 0.999507],[0.612157, 0.689228, 0.995374],[0.603202, 0.688250, 0.991239],[0.594200, 0.687257, 0.987092],[0.585165, 0.686248, 0.982922],[0.576088, 0.685222, 0.978733],[0.566961, 0.684166, 0.974524],[0.557791, 0.683098, 0.970288],[0.548590, 0.681992, 0.966016],[0.539327, 0.680859, 0.961704],[0.530034, 0.679691, 0.957350],[0.520687, 0.678484, 0.952942],[0.511295, 0.677230, 0.948466],[0.501863, 0.675908, 0.943923],[0.492368, 0.674526, 0.939297],[0.482832, 0.673075, 0.934574],[0.473239, 0.671530, 0.929751],[0.463610, 0.669898, 0.924806],[0.453931, 0.668152, 0.919735],[0.444213, 0.666275, 0.914518],[0.434440, 0.664271, 0.909136],[0.424645, 0.662120, 0.903586],[0.414818, 0.659791, 0.897845],[0.404975, 0.657289, 0.891905],[0.395137, 0.654579, 0.885750],[0.385296, 0.651674, 0.879368],[0.375493, 0.648536, 0.872757],[0.365742, 0.645164, 0.865903],[0.356059, 0.641552, 0.858801],[0.346453, 0.637692, 0.851451],[0.336982, 0.633574, 0.843855],[0.327642, 0.629189, 0.836017],[0.318487, 0.624551, 0.827937],[0.309539, 0.619657, 0.819628],[0.300784, 0.614497, 0.811108],[0.292309, 0.609115, 0.802379],[0.284098, 0.603485, 0.793470],[0.276205, 0.597634, 0.784386],[0.268595, 0.591580, 0.775143],[0.261308, 0.585335, 0.765780],[0.254368, 0.578908, 0.756296],[0.247753, 0.572328, 0.746719],[0.241464, 0.565596, 0.737066],[0.235515, 0.558748, 0.727351],[0.229842, 0.551802, 0.717600],[0.224503, 0.544750, 0.707805],[0.219485, 0.537628, 0.697998],[0.214694, 0.530433, 0.688190],[0.210172, 0.523193, 0.678377],[0.205889, 0.515897, 0.668578],[0.201771, 0.508598, 0.658787],[0.197878, 0.501258, 0.649030],[0.194172, 0.493903, 0.639287],[0.190556, 0.486541, 0.629572],[0.187112, 0.479181, 0.619898],[0.183752, 0.471826, 0.610241],[0.180500, 0.464474, 0.600622],[0.177365, 0.457117, 0.591037],[0.174264, 0.449788, 0.581483],[0.171224, 0.442474, 0.571966],[0.168242, 0.435172, 0.562486],[0.165292, 0.427884, 0.553021],[0.162439, 0.420608, 0.543603],[0.159545, 0.413370, 0.534210],[0.156739, 0.406147, 0.524856],[0.153905, 0.398932, 0.515524],[0.151122, 0.391757, 0.506230],[0.148346, 0.384591, 0.496972],[0.145641, 0.377462, 0.487751],[0.142879, 0.370343, 0.478544],[0.140138, 0.363257, 0.469389],[0.137466, 0.356204, 0.460239],[0.134777, 0.349162, 0.451147],[0.132079, 0.342150, 0.442085],[0.129401, 0.335173, 0.433042],[0.126735, 0.328195, 0.424036],[0.124090, 0.321259, 0.415071],[0.121456, 0.314347, 0.406144],[0.118899, 0.307460, 0.397234],[0.116316, 0.300608, 0.388376],[0.113731, 0.293781, 0.379546],[0.111187, 0.286980, 0.370748],[0.108613, 0.280217, 0.362004],[0.106159, 0.273497, 0.353280],[0.103670, 0.266776, 0.344594],[0.101183, 0.260108, 0.335952],[0.098776, 0.253467, 0.327342],[0.096347, 0.246850, 0.318783],[0.094059, 0.240264, 0.310267],[0.091788, 0.233727, 0.301758],[0.089506, 0.227245, 0.293318],[0.087341, 0.220800, 0.284914],[0.085142, 0.214360, 0.276576],[0.083069, 0.207981, 0.268249],[0.081098, 0.201631, 0.259992],[0.079130, 0.195361, 0.251781],[0.077286, 0.189136, 0.243589],[0.075571, 0.182943, 0.235502],[0.073993, 0.176835, 0.227434],[0.072410, 0.170785, 0.219433],[0.071045, 0.164795, 0.211500],[0.069767, 0.158901, 0.203628],[0.068618, 0.153040, 0.195818],[0.067560, 0.147319, 0.188124],[0.066665, 0.141671, 0.180452],[0.065923, 0.136076, 0.172917],[0.065339, 0.130695, 0.165458],[0.064911, 0.125349, 0.158169],[0.064636, 0.120132, 0.150946],[0.064517, 0.115070, 0.143889],[0.064554, 0.110222, 0.136957],[0.064749, 0.105427, 0.130230],[0.065100, 0.100849, 0.123569],[0.065383, 0.096469, 0.117170],[0.065574, 0.092338, 0.111008],[0.065892, 0.088201, 0.104982],[0.066388, 0.084134, 0.099288],[0.067108, 0.080051, 0.093829],[0.068193, 0.076099, 0.088470],[0.069720, 0.072283, 0.083025],[0.071639, 0.068654, 0.077544],[0.073978, 0.065058, 0.072110],[0.076596, 0.061657, 0.066651],[0.079637, 0.058550, 0.061133],[0.082963, 0.055666, 0.055745],[0.086537, 0.052997, 0.050336],[0.090315, 0.050699, 0.045040],[0.094260, 0.048753, 0.039773],[0.098319, 0.047041, 0.034683],[0.102458, 0.045624, 0.030074],[0.106732, 0.044705, 0.026012],[0.110986, 0.043972, 0.022379],[0.115245, 0.043596, 0.019150],[0.119547, 0.043567, 0.016299],[0.123812, 0.043861, 0.013797],[0.128105, 0.044459, 0.011588],[0.132315, 0.045229, 0.009531],[0.136451, 0.046164, 0.007895],[0.140635, 0.047374, 0.006502],[0.144884, 0.048634, 0.005327],[0.149230, 0.049836, 0.004346],[0.153685, 0.050997, 0.003537],[0.158309, 0.052130, 0.002882],[0.163014, 0.053218, 0.002363],[0.167811, 0.054240, 0.001963],[0.172736, 0.055172, 0.001669],[0.177801, 0.056018, 0.001469],[0.182863, 0.056820, 0.001340],[0.188058, 0.057574, 0.001262],[0.193233, 0.058514, 0.001226],[0.198463, 0.059550, 0.001227],[0.203778, 0.060501, 0.001260],[0.209092, 0.061486, 0.001322],[0.214470, 0.062710, 0.001412],[0.219897, 0.063823, 0.001529],[0.225345, 0.065027, 0.001675],[0.230856, 0.066297, 0.001853],[0.236422, 0.067645, 0.002068],[0.242016, 0.069092, 0.002325],[0.247681, 0.070458, 0.002632],[0.253390, 0.071986, 0.002998],[0.259176, 0.073640, 0.003435],[0.264997, 0.075237, 0.003955],[0.270934, 0.076965, 0.004571],[0.276928, 0.078822, 0.005301],[0.283017, 0.080819, 0.006161],[0.289196, 0.082879, 0.007171],[0.295466, 0.085075, 0.008349],[0.301858, 0.087460, 0.009726],[0.308387, 0.089912, 0.011455],[0.315024, 0.092530, 0.013324],[0.321806, 0.095392, 0.015413],[0.328738, 0.098396, 0.017780],[0.335805, 0.101580, 0.020449],[0.343036, 0.104977, 0.023440],[0.350413, 0.108640, 0.026771],[0.357947, 0.112564, 0.030456],[0.365629, 0.116658, 0.034571],[0.373470, 0.120971, 0.039115],[0.381463, 0.125606, 0.043693],[0.389583, 0.130457, 0.048471],[0.397845, 0.135474, 0.053136],[0.406220, 0.140795, 0.057848],[0.414690, 0.146274, 0.062715],[0.423229, 0.151979, 0.067685],[0.431837, 0.157906, 0.073044],[0.440444, 0.164028, 0.078620],[0.449085, 0.170269, 0.084644],[0.457704, 0.176666, 0.090869],[0.466314, 0.183213, 0.097335],[0.474900, 0.189888, 0.104064],[0.483420, 0.196677, 0.111039],[0.491910, 0.203516, 0.118190],[0.500322, 0.210433, 0.125501],[0.508690, 0.217425, 0.132983],[0.516977, 0.224432, 0.140623],[0.525197, 0.231543, 0.148349],[0.533349, 0.238624, 0.156261],[0.541440, 0.245755, 0.164233],[0.549481, 0.252923, 0.172265],[0.557462, 0.260091, 0.180403],[0.565378, 0.267255, 0.188640],[0.573272, 0.274461, 0.196924],[0.581112, 0.281673, 0.205237],[0.588920, 0.288894, 0.213625],[0.596716, 0.296114, 0.222054],[0.604484, 0.303345, 0.230529],[0.612228, 0.310617, 0.239052],[0.619976, 0.317867, 0.247618],[0.627708, 0.325132, 0.256189],[0.635438, 0.332443, 0.264815],[0.643173, 0.339745, 0.273490],[0.650917, 0.347064, 0.282179],[0.658661, 0.354395, 0.290887],[0.666419, 0.361751, 0.299640],[0.674194, 0.369121, 0.308415],[0.681975, 0.376518, 0.317219],[0.689783, 0.383920, 0.326043],[0.697596, 0.391354, 0.334929],[0.705434, 0.398794, 0.343796],[0.713288, 0.406271, 0.352720],[0.721158, 0.413757, 0.361662],[0.729054, 0.421259, 0.370618],[0.736968, 0.428796, 0.379616],[0.744900, 0.436349, 0.388639],[0.752851, 0.443923, 0.397680],[0.760831, 0.451512, 0.406747],[0.768821, 0.459124, 0.415838],[0.776844, 0.466756, 0.424962],[0.784879, 0.474407, 0.434092],[0.792935, 0.482080, 0.443269],[0.801009, 0.489763, 0.452465],[0.809110, 0.497486, 0.461672],[0.817222, 0.505207, 0.470910],[0.825358, 0.512962, 0.480170],[0.833517, 0.520732, 0.489445],[0.841692, 0.528527, 0.498763],[0.849885, 0.536335, 0.508096],[0.858092, 0.544161, 0.517448],[0.866324, 0.552013, 0.526825],[0.874568, 0.559879, 0.536218],[0.882829, 0.567761, 0.545643],[0.891110, 0.575670, 0.555082],[0.899407, 0.583585, 0.564550],[0.907716, 0.591530, 0.574038],[0.916031, 0.599492, 0.583552],[0.924368, 0.607473, 0.593095],[0.932714, 0.615460, 0.602649],[0.941076, 0.623483, 0.612229],[0.949447, 0.631512, 0.621832],[0.957832, 0.639563, 0.631467],[0.966219, 0.647628, 0.641113],[0.974619, 0.655718, 0.650792],[0.983030, 0.663823, 0.660487],[0.991448, 0.671939, 0.670216],[0.999873, 0.680072, 0.679950]] +#Taken from F. Crameri's scientific-colour-maps version 8.0.1. https://doi.org/10.5281/zenodo.1243862 (included by default in newer matplotlib versions) + app_ui = ui.page_sidebar( ui.sidebar( From 04fc39c4ff3c15c76f642bdd3618af553956e8a0 Mon Sep 17 00:00:00 2001 From: ptuemmler Date: Sun, 2 Nov 2025 20:01:47 +0100 Subject: [PATCH 08/14] - fixed windows specific local building --- gen_shinylive.py | 11 ++++++++--- main.py | 11 +++++++++-- 2 files changed, 17 insertions(+), 5 deletions(-) diff --git a/gen_shinylive.py b/gen_shinylive.py index 96dbc86..393972c 100644 --- a/gen_shinylive.py +++ b/gen_shinylive.py @@ -3,8 +3,7 @@ from shinylive import _export import os from pymdownx.slugs import slugify - - +import platform target_url = 'https://physicsapps.github.io/teaching/' #use this for QR-code generation via e.g. https://pypi.org/project/qrcode/ @@ -25,7 +24,13 @@ raise ValueError(f"No title found in {file_path}. Please ensure the app.md file contains a title starting with '# '.") base_apppath = Path("docs", *parts[:-1]) # e.g. "docs/blog/PlotlyPenguins" - base_shinypath = Path('apps', slugify(case='lower')(title, sep='-')) + + if platform.system() == "Windows": + base_shinypath = Path('apps_' + slugify(case='lower')(title, sep='-')) + elif platform.system() == "Linux": + base_shinypath = Path('apps', slugify(case='lower')(title, sep='-')) + else: + raise ValueError("Unsupported operating system. This script only supports Windows and Linux.") # Look for all app.py files here and in subdirectories e.g. "docs/apps/FastFourierTransforms/1d/app.py" for app_path in Path("docs", *parts[:-1]).glob("**/app.py"): subdirpath = app_path.relative_to(Path("docs", *parts[:-1])) # 1d/app.py diff --git a/main.py b/main.py index 8d90e80..5b85ae6 100644 --- a/main.py +++ b/main.py @@ -1,12 +1,19 @@ from pathlib import Path - +import platform def get_app_link(current_path, subdir: str): parts = current_path.parts html_filename = str(parts[-1]).split('.')[0] if subdir is not None: html_filename += '_' + subdir - return str(Path('apps', html_filename, 'index.html')) + + if platform.system() == "Windows": + app_link = str(Path('apps_' + html_filename, 'index.html')) + elif platform.system() == "Linux": + app_link = str(Path('apps', html_filename, 'index.html')) + else: + raise ValueError("Unsupported operating system. This script only supports Windows and Linux.") + return app_link def define_env(env): """ From 63c38eaa519dfed827c9db5298f2df6d9705a8ad Mon Sep 17 00:00:00 2001 From: ptuemmler Date: Sun, 2 Nov 2025 20:49:56 +0100 Subject: [PATCH 09/14] - finished 1d fft app --- docs/apps/FastFourierTransforms/1d/app.py | 57 +++++++++++------------ 1 file changed, 27 insertions(+), 30 deletions(-) diff --git a/docs/apps/FastFourierTransforms/1d/app.py b/docs/apps/FastFourierTransforms/1d/app.py index b5e5ba4..2e24842 100644 --- a/docs/apps/FastFourierTransforms/1d/app.py +++ b/docs/apps/FastFourierTransforms/1d/app.py @@ -34,19 +34,18 @@ ), ui.input_checkbox( - 'show_imaginary', - 'Show imaginary parts', + 'include_negative_frequencies', + 'Add negative Fourier component', value=True, ), - ui.input_checkbox( - 'include_negative_frequencies', - 'Add imaginary Fourier component', + 'flip_negative_frequencies', + 'Flip negative Fourier component', value=True, ), ui.input_checkbox( - 'flip_imaginary', - 'Flip imaginary Fourier component', + 'set_imaginary', + 'Make Fourier component imaginary', value=True, ), ui.input_checkbox( @@ -112,25 +111,25 @@ def fourier_plot(): axs.set_ylim(-1, 1) eventx, eventy = input.event_x(), input.event_y() - fourier_signal = get_gaussian(freq_axis, eventx, sigma, eventy) - - sign = -1 if input.flip_imaginary() else 1 + imag = 1j if input.set_imaginary() else 1 + sign = -1 if input.flip_negative_frequencies() else 1 + fourier_signal = imag * get_gaussian(freq_axis, eventx, sigma, eventy) if input.include_negative_frequencies(): - # add negative frequencies for real signal - fourier_signal = fourier_signal + sign * 1j * get_gaussian(freq_axis, -eventx, sigma, eventy) + fourier_signal = fourier_signal + sign * imag * get_gaussian(freq_axis, -eventx, sigma, eventy) if sigma == 0: axs.plot(freq_axis, np.zeros_like(freq_axis), color=red, label=f'Real Part') - axs.plot([eventx, eventx], [0, eventy], color=red) - if input.show_imaginary(): - axs.plot(freq_axis, np.zeros_like(freq_axis), color=blue, ls='--', label=f'Imaginary Part') - + axs.plot(freq_axis, np.zeros_like(freq_axis), color=blue, ls='--', label=f'Imaginary Part') + color, ls = (red, '-') if imag == 1 else (blue, '--') + if eventx == 0 and input.include_negative_frequencies() and sign == 1: + axs.plot([eventx, eventx], [0, 2 * eventy], color=color, ls=ls) + else: + axs.plot([eventx, eventx], [0, eventy], color=color, ls=ls) if input.include_negative_frequencies(): - axs.plot([-eventx, -eventx], [0, sign * eventy], color=blue, ls='--') + axs.plot([-eventx, -eventx], [0, sign * eventy], color=color, ls=ls) else: axs.plot(freq_axis, np.real(fourier_signal), color=red, label=f'Real Part') - if input.show_imaginary(): - axs.plot(freq_axis, np.imag(fourier_signal), color=blue, ls='--', label=f'Imaginary Part') + axs.plot(freq_axis, np.imag(fourier_signal), color=blue, ls='--', label=f'Imaginary Part') # axs.scatter([eventx], [eventy], color='black') axs.legend() @@ -158,35 +157,33 @@ def real_plot(): fig, axs = plt.subplots() axs.set_xlim(x_axis_lims) - if sigma == 0: - axs.set_ylim(-1, 1) eventx, eventy = input.event_x(), input.event_y() - fourier_signal = get_gaussian(freq_axis, eventx, sigma, eventy) + imag = 1j if input.set_imaginary() else 1 + sign = -1 if input.flip_negative_frequencies() else 1 + fourier_signal = imag * get_gaussian(freq_axis, eventx, sigma, eventy) if input.include_negative_frequencies(): - # add negative frequencies for real signal - sign = -1 if input.flip_imaginary() else 1 - fourier_signal = fourier_signal + sign * 1j * get_gaussian(freq_axis, -eventx, sigma, eventy) + fourier_signal = fourier_signal + sign * imag * get_gaussian(freq_axis, -eventx, sigma, eventy) real_signal = np.fft.ifftshift(np.fft.ifft(np.fft.ifftshift(fourier_signal))) * len(x_axis) if input.show_contributions(): - # plot individual contributions for freq, amplitude in zip(freq_axis, fourier_signal): if np.abs(amplitude) < 1e-3: continue contribution = amplitude * np.exp(2j * np.pi * freq * x_axis) axs.plot(x_axis, np.real(contribution), color=red, alpha=0.1) - if input.show_imaginary(): - axs.plot(x_axis, np.imag(contribution), color=blue, alpha=0.1) + axs.plot(x_axis, np.imag(contribution), color=blue, alpha=0.1) # real signal axs.plot(x_axis, np.real(real_signal), color=red, label=f'Real Part') - if input.show_imaginary(): - axs.plot(x_axis, np.imag(real_signal), color=blue, ls='--', label=f'Imaginary Part') + axs.plot(x_axis, np.imag(real_signal), color=blue, ls='--', label=f'Imaginary Part') axs.legend() + limit = np.max([np.max(np.abs(np.real(real_signal))) * 1.1, np.abs(np.max(np.imag(real_signal))) * 1.1, 1]) + + axs.set_ylim(-limit, limit) axs.set_title("Real Space Signal") axs.set_xlabel("Time [s]") axs.set_ylabel("Amplitude") From 3f9ad45ee6c76a2d90f60e0ac38ec5c763351b53 Mon Sep 17 00:00:00 2001 From: ptuemmler Date: Sun, 2 Nov 2025 20:52:42 +0100 Subject: [PATCH 10/14] - cleaned up unfinished fft apps --- docs/apps/FastFourierTransforms/2d/app.py | 171 ------------------ .../FastFourierTransforms/2d/requirements.txt | 3 - docs/apps/FastFourierTransforms/app.md | 88 --------- docs/apps/FourierTransforms/app.md | 15 ++ .../1d => FourierTransforms}/app.py | 0 .../1d => FourierTransforms}/requirements.txt | 0 6 files changed, 15 insertions(+), 262 deletions(-) delete mode 100644 docs/apps/FastFourierTransforms/2d/app.py delete mode 100644 docs/apps/FastFourierTransforms/2d/requirements.txt delete mode 100644 docs/apps/FastFourierTransforms/app.md create mode 100644 docs/apps/FourierTransforms/app.md rename docs/apps/{FastFourierTransforms/1d => FourierTransforms}/app.py (100%) rename docs/apps/{FastFourierTransforms/1d => FourierTransforms}/requirements.txt (100%) diff --git a/docs/apps/FastFourierTransforms/2d/app.py b/docs/apps/FastFourierTransforms/2d/app.py deleted file mode 100644 index 062c98c..0000000 --- a/docs/apps/FastFourierTransforms/2d/app.py +++ /dev/null @@ -1,171 +0,0 @@ -import matplotlib.pyplot as plt -import matplotlib.ticker as ticker -import numpy as np -from shiny import App, render, ui, reactive - -app_ui = ui.page_sidebar( - ui.sidebar( - ui.input_slider( - "sigma", - "Width of Gaussian (σ)", - min=0, - max=0.5, - value=0, - step=0.025, - animate=True - ), - ui.input_slider( - "event_x", - "Frequency in x", - min=-2, - max=2, - value=0.5, - step=0.025, - animate=True - ), - ui.input_slider( - "event_y", - "Frequency in y", - min=-2, - max=2, - value=0.5, - step=0.025, - animate=True - ), - ui.input_checkbox( - 'include_negative_frequencies', - 'Add imaginary Fourier component', - value=True, - ), - ui.input_checkbox( - 'flip_imaginary', - 'Flip imaginary Fourier component', - value=True, - ), - ui.input_dark_mode(id='dark_mode'), - open='always', - ), - ui.layout_columns( - ui.output_plot( - "fourier_plot", - click=True, - width="100%", height="700px" - ), - ui.output_plot( - "real_plot", - width="100%", height="700px" - ), - ), -) - -def server(input, output, session): - click_data = reactive.value(None) - blue = 'navy' - red = 'firebrick' - - x_axis = np.linspace(-20, 20, 1024) - y_axis = np.linspace(-20, 20, 1024) - freq_axis = np.fft.fftfreq(len(x_axis), d=(x_axis[1] - x_axis[0])) - freq_axis = np.fft.fftshift(freq_axis) - - x_axis_lims = (-5, 5) - freq_axis_lims = (-2, 2) - - # Update click data when plot is clicked - @reactive.effect - def _(): - if input.fourier_plot_click() is not None: - click_data.set(input.fourier_plot_click()) - ui.update_slider('event_x', value=input.fourier_plot_click()['x']) - ui.update_slider('event_y', value=input.fourier_plot_click()['y']) - # One could actually calculate everything here and then only use the resulting data in the plots - - - - @render.plot() - def fourier_plot(): - if input.dark_mode() == "dark": - style_label = 'dark_background' - else: - style_label = 'seaborn-v0_8' - - with plt.style.context(style_label): - sigma = input.sigma() - fig, axs = plt.subplots() - axs.set_xlim(freq_axis_lims) - axs.set_ylim(freq_axis_lims) - - eventx, eventy = input.event_x(), input.event_y() - fourier_signal = get_gaussian2d(freq_axis, freq_axis, eventx, eventy, sigma, 1) - - sign = -1 if input.flip_imaginary() else 1 - if input.include_negative_frequencies(): - # add negative frequencies for real signal - fourier_signal = fourier_signal + sign * 1j * get_gaussian2d(freq_axis, freq_axis, -eventx, -eventy, sigma, 1) - - if sigma == 0: - img = axs.imshow(np.zeros((len(freq_axis), len(freq_axis))), interpolation='none', - cmap='RdBu_r', extent=(freq_axis[0], freq_axis[-1], freq_axis[0], freq_axis[-1]), origin='lower', vmin=-1, vmax=1) - axs.plot([eventx], [eventy], marker='o', color='red', label='Real Part') - if input.include_negative_frequencies(): - axs.plot([sign * eventx], [sign * eventy], marker='x', color='blue', label='Imaginary Part') - axs.legend() - else: - img = axs.imshow(np.sqrt(np.abs(fourier_signal)) * np.sign(np.real(fourier_signal ** 2)), interpolation='none', cmap='RdBu_r', vmin=-1, vmax=1, - extent=(freq_axis[0], freq_axis[-1], freq_axis[0], freq_axis[-1]), origin='lower') - cbar = fig.colorbar(img, ax=axs) - cbar.ax.yaxis.set_major_formatter(ticker.FuncFormatter(lambda x, pos: f"{-float(x):.1f}i" if x < 0 else f"{float(x):.1f}")) - - - axs.set_title("Fourier Transform") - - axs.set_xlabel("Frequency in x (Hz)") - axs.set_ylabel("Frequency in y (Hz)") - return fig - - @render.plot() - def real_plot(): - if input.dark_mode() == "dark": - style_label = 'dark_background' - else: - style_label = 'seaborn-v0_8' - with plt.style.context(style_label): - sigma = input.sigma() - - fig, axs = plt.subplots() - axs.set_xlim(x_axis_lims) - axs.set_ylim(x_axis_lims) - - eventx, eventy = input.event_x(), input.event_y() - fourier_signal = get_gaussian2d(freq_axis, freq_axis, eventx, eventy, sigma, 1) - - sign = -1 if input.flip_imaginary() else 1 - if input.include_negative_frequencies(): - # add negative frequencies for real signal - fourier_signal = fourier_signal + sign * 1j * get_gaussian2d(freq_axis, freq_axis, -eventx, -eventy, sigma, 1) - - real_signal = np.fft.ifftshift(np.fft.ifft2(np.fft.fftshift(fourier_signal))) * len(x_axis) * len(y_axis) - - # real signal - img = axs.imshow(np.abs(real_signal), interpolation='none', cmap='turbo', - extent=(x_axis[0], x_axis[-1], x_axis[0], x_axis[-1]), origin='lower') - cbar = fig.colorbar(img, ax=axs) - - axs.set_title("Real Space Signal") - axs.set_xlabel("Time in x [s]") - axs.set_ylabel("Time in y [s]") - return fig - -def get_gaussian2d(x, y, x0, y0, sigma, amp): - if sigma == 0: - signal = np.zeros((len(x), len(y))) - closest_idx_x = (np.abs(y - y0)).argmin() - closest_idx_y = (np.abs(x - x0)).argmin() - signal[closest_idx_x, closest_idx_y] = amp - else: - X, Y = np.meshgrid(x, y, indexing='xy') - signal = amp * np.exp(-((X - x0) ** 2 + (Y - y0) ** 2) / (2 * sigma ** 2)) - - return signal - -app = App(app_ui, server, debug=True) diff --git a/docs/apps/FastFourierTransforms/2d/requirements.txt b/docs/apps/FastFourierTransforms/2d/requirements.txt deleted file mode 100644 index a46db3e..0000000 --- a/docs/apps/FastFourierTransforms/2d/requirements.txt +++ /dev/null @@ -1,3 +0,0 @@ -numpy -palmerpenguins -matplotlib \ No newline at end of file diff --git a/docs/apps/FastFourierTransforms/app.md b/docs/apps/FastFourierTransforms/app.md deleted file mode 100644 index c608e6d..0000000 --- a/docs/apps/FastFourierTransforms/app.md +++ /dev/null @@ -1,88 +0,0 @@ ---- -authors: - - ptuemmler -categories: - - Mathematics - - Numerics -tags: - - Code - - Fourier Transform -date: 2025-07-04 -hide: - - toc -draft: true ---- -# Fast Fourier Transforms - -The [Fast Fourier Transform (FFT)](https://en.wikipedia.org/wiki/Fast_Fourier_transform) is an efficient algorithm to compute the Discrete Fourier Transform (DFT) and its inverse. It is widely used in signal processing, image analysis, and solving partial differential equations. A typical issue is the physically correct scaling and calculation of respective axes. -A common problem is the scaling of the axes, which can lead to confusion when interpreting the results. This app provides a simple interface to visualize the FFT and its inverse, allowing you to explore the effects of different parameters on the resulting spectra. - -The simplest case of the FFT is the transformation of a 1D signal, which can be extended to 2D signals (e.g. images) and higher dimensions. The app allows you to visualize the FFT of a 1D signal and its inverse, as well as the scaling of the axes. -For the 1D case, we can use the following python and matlab code snippets to compute the FFT and its inverse with the correct scaling and also return the respective axes if desired: - -=== "python" - - ``` python title="fft.py" linenums="1" - from numpy import fft - - def fft_1d(axis, signal, return_axes=False): - """ - Compute the 1D FFT of a signal and return the transformed signal and axes. - - Parameters - ---------- - axis : 1D array-like - The axis of the signal. - signal : 1D array-like - The signal to be transformed. - return_axes : bool, optional - If True, return the transformed axes and signal. Default is False. - - Returns - ------- - tuple - If return_axes is True, return a tuple of the transformed axes and signal. - Otherwise, return only the transformed signal. - """ - transformed_signal = fft.fft(signal) - if return_axes: - transformed_axis = fft.fftfreq(len(axis), axis[1] - axis[0]) - return transformed_axis, transformed_signal - else: - return transformed_signal - - def ifft_1d(axis, transformed_signal, return_axes=False): - """ - Compute the inverse 1D FFT of a transformed signal and return the original signal and axes. - - Parameters - ---------- - axis : 1D array-like - The axis of the transformed signal. - transformed_signal : 1D array-like - The transformed signal to be inverted. - return_axes : bool, optional - If True, return the original axes and signal. Default is False. - - Returns - ------- - tuple - If return_axes is True, return a tuple of the original axes and signal. - Otherwise, return only the original signal. - """ - original_signal = fft.ifft(transformed_signal) - if return_axes: - original_axis = fft.fftfreq(len(axis), axis[1] - axis[0]) - return original_axis, original_signal - else: - return original_signal - ``` - -=== "matlab" - - ``` matlab - - ``` - -{{embed_app("100%", "800px", "1d")}} -{{embed_app("100%", "800px", "2d")}} diff --git a/docs/apps/FourierTransforms/app.md b/docs/apps/FourierTransforms/app.md new file mode 100644 index 0000000..fe87851 --- /dev/null +++ b/docs/apps/FourierTransforms/app.md @@ -0,0 +1,15 @@ +--- +authors: + - ptuemmler +categories: + - Mathematics +tags: + - Fourier Transform +date: 2025-11-02 +hide: + - toc +draft: true +--- +# Fourier Transforms + +{{embed_app("100%", "800px")}} diff --git a/docs/apps/FastFourierTransforms/1d/app.py b/docs/apps/FourierTransforms/app.py similarity index 100% rename from docs/apps/FastFourierTransforms/1d/app.py rename to docs/apps/FourierTransforms/app.py diff --git a/docs/apps/FastFourierTransforms/1d/requirements.txt b/docs/apps/FourierTransforms/requirements.txt similarity index 100% rename from docs/apps/FastFourierTransforms/1d/requirements.txt rename to docs/apps/FourierTransforms/requirements.txt From 2e58be198e8756026e2de75fb89a1909a7f08f61 Mon Sep 17 00:00:00 2001 From: tuemmler Date: Mon, 3 Nov 2025 10:14:21 +0100 Subject: [PATCH 11/14] - updated license information --- LICENSE | 395 ++++++++++++++++++++++++++++++++++++++++++++++++ LICENSE-code | 20 +++ docs/license.md | 23 +-- 3 files changed, 417 insertions(+), 21 deletions(-) create mode 100644 LICENSE create mode 100644 LICENSE-code diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..10fabd9 --- /dev/null +++ b/LICENSE @@ -0,0 +1,395 @@ +Attribution 4.0 International + +======================================================================= + +Creative Commons Corporation ("Creative Commons") is not a law firm and +does not provide legal services or legal advice. Distribution of +Creative Commons public licenses does not create a lawyer-client or +other relationship. Creative Commons makes its licenses and related +information available on an "as-is" basis. Creative Commons gives no +warranties regarding its licenses, any material licensed under their +terms and conditions, or any related information. Creative Commons +disclaims all liability for damages resulting from their use to the +fullest extent possible. + +Using Creative Commons Public Licenses + +Creative Commons public licenses provide a standard set of terms and +conditions that creators and other rights holders may use to share +original works of authorship and other material subject to copyright +and certain other rights specified in the public license below. The +following considerations are for informational purposes only, are not +exhaustive, and do not form part of our licenses. + + Considerations for licensors: Our public licenses are + intended for use by those authorized to give the public + permission to use material in ways otherwise restricted by + copyright and certain other rights. Our licenses are + irrevocable. Licensors should read and understand the terms + and conditions of the license they choose before applying it. + Licensors should also secure all rights necessary before + applying our licenses so that the public can reuse the + material as expected. Licensors should clearly mark any + material not subject to the license. This includes other CC- + licensed material, or material used under an exception or + limitation to copyright. More considerations for licensors: + wiki.creativecommons.org/Considerations_for_licensors + + Considerations for the public: By using one of our public + licenses, a licensor grants the public permission to use the + licensed material under specified terms and conditions. If + the licensor's permission is not necessary for any reason--for + example, because of any applicable exception or limitation to + copyright--then that use is not regulated by the license. Our + licenses grant only permissions under copyright and certain + other rights that a licensor has authority to grant. Use of + the licensed material may still be restricted for other + reasons, including because others have copyright or other + rights in the material. A licensor may make special requests, + such as asking that all changes be marked or described. + Although not required by our licenses, you are encouraged to + respect those requests where reasonable. More considerations + for the public: + wiki.creativecommons.org/Considerations_for_licensees + +======================================================================= + +Creative Commons Attribution 4.0 International Public License + +By exercising the Licensed Rights (defined below), You accept and agree +to be bound by the terms and conditions of this Creative Commons +Attribution 4.0 International Public License ("Public License"). To the +extent this Public License may be interpreted as a contract, You are +granted the Licensed Rights in consideration of Your acceptance of +these terms and conditions, and the Licensor grants You such rights in +consideration of benefits the Licensor receives from making the +Licensed Material available under these terms and conditions. + + +Section 1 -- Definitions. + + a. Adapted Material means material subject to Copyright and Similar + Rights that is derived from or based upon the Licensed Material + and in which the Licensed Material is translated, altered, + arranged, transformed, or otherwise modified in a manner requiring + permission under the Copyright and Similar Rights held by the + Licensor. For purposes of this Public License, where the Licensed + Material is a musical work, performance, or sound recording, + Adapted Material is always produced where the Licensed Material is + synched in timed relation with a moving image. + + b. Adapter's License means the license You apply to Your Copyright + and Similar Rights in Your contributions to Adapted Material in + accordance with the terms and conditions of this Public License. + + c. Copyright and Similar Rights means copyright and/or similar rights + closely related to copyright including, without limitation, + performance, broadcast, sound recording, and Sui Generis Database + Rights, without regard to how the rights are labeled or + categorized. For purposes of this Public License, the rights + specified in Section 2(b)(1)-(2) are not Copyright and Similar + Rights. + + d. Effective Technological Measures means those measures that, in the + absence of proper authority, may not be circumvented under laws + fulfilling obligations under Article 11 of the WIPO Copyright + Treaty adopted on December 20, 1996, and/or similar international + agreements. + + e. Exceptions and Limitations means fair use, fair dealing, and/or + any other exception or limitation to Copyright and Similar Rights + that applies to Your use of the Licensed Material. + + f. Licensed Material means the artistic or literary work, database, + or other material to which the Licensor applied this Public + License. + + g. Licensed Rights means the rights granted to You subject to the + terms and conditions of this Public License, which are limited to + all Copyright and Similar Rights that apply to Your use of the + Licensed Material and that the Licensor has authority to license. + + h. Licensor means the individual(s) or entity(ies) granting rights + under this Public License. + + i. Share means to provide material to the public by any means or + process that requires permission under the Licensed Rights, such + as reproduction, public display, public performance, distribution, + dissemination, communication, or importation, and to make material + available to the public including in ways that members of the + public may access the material from a place and at a time + individually chosen by them. + + j. Sui Generis Database Rights means rights other than copyright + resulting from Directive 96/9/EC of the European Parliament and of + the Council of 11 March 1996 on the legal protection of databases, + as amended and/or succeeded, as well as other essentially + equivalent rights anywhere in the world. + + k. You means the individual or entity exercising the Licensed Rights + under this Public License. Your has a corresponding meaning. + + +Section 2 -- Scope. + + a. License grant. + + 1. Subject to the terms and conditions of this Public License, + the Licensor hereby grants You a worldwide, royalty-free, + non-sublicensable, non-exclusive, irrevocable license to + exercise the Licensed Rights in the Licensed Material to: + + a. reproduce and Share the Licensed Material, in whole or + in part; and + + b. produce, reproduce, and Share Adapted Material. + + 2. Exceptions and Limitations. For the avoidance of doubt, where + Exceptions and Limitations apply to Your use, this Public + License does not apply, and You do not need to comply with + its terms and conditions. + + 3. Term. The term of this Public License is specified in Section + 6(a). + + 4. Media and formats; technical modifications allowed. The + Licensor authorizes You to exercise the Licensed Rights in + all media and formats whether now known or hereafter created, + and to make technical modifications necessary to do so. The + Licensor waives and/or agrees not to assert any right or + authority to forbid You from making technical modifications + necessary to exercise the Licensed Rights, including + technical modifications necessary to circumvent Effective + Technological Measures. For purposes of this Public License, + simply making modifications authorized by this Section 2(a) + (4) never produces Adapted Material. + + 5. Downstream recipients. + + a. Offer from the Licensor -- Licensed Material. Every + recipient of the Licensed Material automatically + receives an offer from the Licensor to exercise the + Licensed Rights under the terms and conditions of this + Public License. + + b. No downstream restrictions. You may not offer or impose + any additional or different terms or conditions on, or + apply any Effective Technological Measures to, the + Licensed Material if doing so restricts exercise of the + Licensed Rights by any recipient of the Licensed + Material. + + 6. No endorsement. Nothing in this Public License constitutes or + may be construed as permission to assert or imply that You + are, or that Your use of the Licensed Material is, connected + with, or sponsored, endorsed, or granted official status by, + the Licensor or others designated to receive attribution as + provided in Section 3(a)(1)(A)(i). + + b. Other rights. + + 1. Moral rights, such as the right of integrity, are not + licensed under this Public License, nor are publicity, + privacy, and/or other similar personality rights; however, to + the extent possible, the Licensor waives and/or agrees not to + assert any such rights held by the Licensor to the limited + extent necessary to allow You to exercise the Licensed + Rights, but not otherwise. + + 2. Patent and trademark rights are not licensed under this + Public License. + + 3. To the extent possible, the Licensor waives any right to + collect royalties from You for the exercise of the Licensed + Rights, whether directly or through a collecting society + under any voluntary or waivable statutory or compulsory + licensing scheme. In all other cases the Licensor expressly + reserves any right to collect such royalties. + + +Section 3 -- License Conditions. + +Your exercise of the Licensed Rights is expressly made subject to the +following conditions. + + a. Attribution. + + 1. If You Share the Licensed Material (including in modified + form), You must: + + a. retain the following if it is supplied by the Licensor + with the Licensed Material: + + i. identification of the creator(s) of the Licensed + Material and any others designated to receive + attribution, in any reasonable manner requested by + the Licensor (including by pseudonym if + designated); + + ii. a copyright notice; + + iii. a notice that refers to this Public License; + + iv. a notice that refers to the disclaimer of + warranties; + + v. a URI or hyperlink to the Licensed Material to the + extent reasonably practicable; + + b. indicate if You modified the Licensed Material and + retain an indication of any previous modifications; and + + c. indicate the Licensed Material is licensed under this + Public License, and include the text of, or the URI or + hyperlink to, this Public License. + + 2. You may satisfy the conditions in Section 3(a)(1) in any + reasonable manner based on the medium, means, and context in + which You Share the Licensed Material. For example, it may be + reasonable to satisfy the conditions by providing a URI or + hyperlink to a resource that includes the required + information. + + 3. If requested by the Licensor, You must remove any of the + information required by Section 3(a)(1)(A) to the extent + reasonably practicable. + + 4. If You Share Adapted Material You produce, the Adapter's + License You apply must not prevent recipients of the Adapted + Material from complying with this Public License. + + +Section 4 -- Sui Generis Database Rights. + +Where the Licensed Rights include Sui Generis Database Rights that +apply to Your use of the Licensed Material: + + a. for the avoidance of doubt, Section 2(a)(1) grants You the right + to extract, reuse, reproduce, and Share all or a substantial + portion of the contents of the database; + + b. if You include all or a substantial portion of the database + contents in a database in which You have Sui Generis Database + Rights, then the database in which You have Sui Generis Database + Rights (but not its individual contents) is Adapted Material; and + + c. You must comply with the conditions in Section 3(a) if You Share + all or a substantial portion of the contents of the database. + +For the avoidance of doubt, this Section 4 supplements and does not +replace Your obligations under this Public License where the Licensed +Rights include other Copyright and Similar Rights. + + +Section 5 -- Disclaimer of Warranties and Limitation of Liability. + + a. UNLESS OTHERWISE SEPARATELY UNDERTAKEN BY THE LICENSOR, TO THE + EXTENT POSSIBLE, THE LICENSOR OFFERS THE LICENSED MATERIAL AS-IS + AND AS-AVAILABLE, AND MAKES NO REPRESENTATIONS OR WARRANTIES OF + ANY KIND CONCERNING THE LICENSED MATERIAL, WHETHER EXPRESS, + IMPLIED, STATUTORY, OR OTHER. THIS INCLUDES, WITHOUT LIMITATION, + WARRANTIES OF TITLE, MERCHANTABILITY, FITNESS FOR A PARTICULAR + PURPOSE, NON-INFRINGEMENT, ABSENCE OF LATENT OR OTHER DEFECTS, + ACCURACY, OR THE PRESENCE OR ABSENCE OF ERRORS, WHETHER OR NOT + KNOWN OR DISCOVERABLE. WHERE DISCLAIMERS OF WARRANTIES ARE NOT + ALLOWED IN FULL OR IN PART, THIS DISCLAIMER MAY NOT APPLY TO YOU. + + b. TO THE EXTENT POSSIBLE, IN NO EVENT WILL THE LICENSOR BE LIABLE + TO YOU ON ANY LEGAL THEORY (INCLUDING, WITHOUT LIMITATION, + NEGLIGENCE) OR OTHERWISE FOR ANY DIRECT, SPECIAL, INDIRECT, + INCIDENTAL, CONSEQUENTIAL, PUNITIVE, EXEMPLARY, OR OTHER LOSSES, + COSTS, EXPENSES, OR DAMAGES ARISING OUT OF THIS PUBLIC LICENSE OR + USE OF THE LICENSED MATERIAL, EVEN IF THE LICENSOR HAS BEEN + ADVISED OF THE POSSIBILITY OF SUCH LOSSES, COSTS, EXPENSES, OR + DAMAGES. WHERE A LIMITATION OF LIABILITY IS NOT ALLOWED IN FULL OR + IN PART, THIS LIMITATION MAY NOT APPLY TO YOU. + + c. The disclaimer of warranties and limitation of liability provided + above shall be interpreted in a manner that, to the extent + possible, most closely approximates an absolute disclaimer and + waiver of all liability. + + +Section 6 -- Term and Termination. + + a. This Public License applies for the term of the Copyright and + Similar Rights licensed here. However, if You fail to comply with + this Public License, then Your rights under this Public License + terminate automatically. + + b. Where Your right to use the Licensed Material has terminated under + Section 6(a), it reinstates: + + 1. automatically as of the date the violation is cured, provided + it is cured within 30 days of Your discovery of the + violation; or + + 2. upon express reinstatement by the Licensor. + + For the avoidance of doubt, this Section 6(b) does not affect any + right the Licensor may have to seek remedies for Your violations + of this Public License. + + c. For the avoidance of doubt, the Licensor may also offer the + Licensed Material under separate terms or conditions or stop + distributing the Licensed Material at any time; however, doing so + will not terminate this Public License. + + d. Sections 1, 5, 6, 7, and 8 survive termination of this Public + License. + + +Section 7 -- Other Terms and Conditions. + + a. The Licensor shall not be bound by any additional or different + terms or conditions communicated by You unless expressly agreed. + + b. Any arrangements, understandings, or agreements regarding the + Licensed Material not stated herein are separate from and + independent of the terms and conditions of this Public License. + + +Section 8 -- Interpretation. + + a. For the avoidance of doubt, this Public License does not, and + shall not be interpreted to, reduce, limit, restrict, or impose + conditions on any use of the Licensed Material that could lawfully + be made without permission under this Public License. + + b. To the extent possible, if any provision of this Public License is + deemed unenforceable, it shall be automatically reformed to the + minimum extent necessary to make it enforceable. If the provision + cannot be reformed, it shall be severed from this Public License + without affecting the enforceability of the remaining terms and + conditions. + + c. No term or condition of this Public License will be waived and no + failure to comply consented to unless expressly agreed to by the + Licensor. + + d. Nothing in this Public License constitutes or may be interpreted + as a limitation upon, or waiver of, any privileges and immunities + that apply to the Licensor or You, including from the legal + processes of any jurisdiction or authority. + + +======================================================================= + +Creative Commons is not a party to its public licenses. +Notwithstanding, Creative Commons may elect to apply one of its public +licenses to material it publishes and in those instances will be +considered the “Licensor.” The text of the Creative Commons public +licenses is dedicated to the public domain under the CC0 Public Domain +Dedication. Except for the limited purpose of indicating that material +is shared under a Creative Commons public license or as otherwise +permitted by the Creative Commons policies published at +creativecommons.org/policies, Creative Commons does not authorize the +use of the trademark "Creative Commons" or any other trademark or logo +of Creative Commons without its prior written consent including, +without limitation, in connection with any unauthorized modifications +to any of its public licenses or any other arrangements, +understandings, or agreements concerning use of licensed material. For +the avoidance of doubt, this paragraph does not form part of the public +licenses. + +Creative Commons may be contacted at creativecommons.org. diff --git a/LICENSE-code b/LICENSE-code new file mode 100644 index 0000000..f5634ac --- /dev/null +++ b/LICENSE-code @@ -0,0 +1,20 @@ +MIT License +Copyright (c) 2025 Paul Tuemmler + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/docs/license.md b/docs/license.md index c5d7818..5f2586b 100644 --- a/docs/license.md +++ b/docs/license.md @@ -1,22 +1,3 @@ # License -**MIT License** - -Copyright (c) 2025 Paul Tuemmler - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. +## CC BY 4.0 (for teaching materials) +## MIT License (for code examples) From c3e7281eae0472ab7ec6e8df446c30fca6d1ecb3 Mon Sep 17 00:00:00 2001 From: tuemmler Date: Mon, 3 Nov 2025 10:18:05 +0100 Subject: [PATCH 12/14] - updated minkowski category and tags --- docs/apps/MinkowskiSpaceTime/app.md | 8 +++----- 1 file changed, 3 insertions(+), 5 deletions(-) diff --git a/docs/apps/MinkowskiSpaceTime/app.md b/docs/apps/MinkowskiSpaceTime/app.md index f68764e..86157ed 100644 --- a/docs/apps/MinkowskiSpaceTime/app.md +++ b/docs/apps/MinkowskiSpaceTime/app.md @@ -2,12 +2,10 @@ authors: - ptuemmler categories: - - Mathematics - - Numerics + - Physics tags: - - Code - - Fourier Transform -date: 2025-10-27 + - Relativity +date: 2025-11-03 hide: - toc draft: true From b3fba9e711a94bdc03a2c7ced9f1add4762f922d Mon Sep 17 00:00:00 2001 From: tuemmler Date: Mon, 3 Nov 2025 13:29:36 +0100 Subject: [PATCH 13/14] - updated minkowski app, added read out of event data --- docs/apps/MinkowskiSpaceTime/app.md | 2 - docs/apps/MinkowskiSpaceTime/app.py | 224 ++++++++++++------ docs/apps/MinkowskiSpaceTime/requirements.txt | 1 + mkdocs.yml | 2 + 4 files changed, 149 insertions(+), 80 deletions(-) diff --git a/docs/apps/MinkowskiSpaceTime/app.md b/docs/apps/MinkowskiSpaceTime/app.md index 86157ed..ed3785a 100644 --- a/docs/apps/MinkowskiSpaceTime/app.md +++ b/docs/apps/MinkowskiSpaceTime/app.md @@ -11,7 +11,5 @@ hide: draft: true --- # Minkowski Space-Time -Bli -BlaBlu {{embed_app("100%", "800px")}} diff --git a/docs/apps/MinkowskiSpaceTime/app.py b/docs/apps/MinkowskiSpaceTime/app.py index 41c98b2..13c21e8 100644 --- a/docs/apps/MinkowskiSpaceTime/app.py +++ b/docs/apps/MinkowskiSpaceTime/app.py @@ -1,11 +1,13 @@ import matplotlib.pyplot as plt import matplotlib.ticker as ticker +from matplotlib.colors import LinearSegmentedColormap import numpy as np +import pandas as pd from shiny import App, render, ui, reactive berlin_cmap = [[0.621082, 0.690182, 0.999507],[0.612157, 0.689228, 0.995374],[0.603202, 0.688250, 0.991239],[0.594200, 0.687257, 0.987092],[0.585165, 0.686248, 0.982922],[0.576088, 0.685222, 0.978733],[0.566961, 0.684166, 0.974524],[0.557791, 0.683098, 0.970288],[0.548590, 0.681992, 0.966016],[0.539327, 0.680859, 0.961704],[0.530034, 0.679691, 0.957350],[0.520687, 0.678484, 0.952942],[0.511295, 0.677230, 0.948466],[0.501863, 0.675908, 0.943923],[0.492368, 0.674526, 0.939297],[0.482832, 0.673075, 0.934574],[0.473239, 0.671530, 0.929751],[0.463610, 0.669898, 0.924806],[0.453931, 0.668152, 0.919735],[0.444213, 0.666275, 0.914518],[0.434440, 0.664271, 0.909136],[0.424645, 0.662120, 0.903586],[0.414818, 0.659791, 0.897845],[0.404975, 0.657289, 0.891905],[0.395137, 0.654579, 0.885750],[0.385296, 0.651674, 0.879368],[0.375493, 0.648536, 0.872757],[0.365742, 0.645164, 0.865903],[0.356059, 0.641552, 0.858801],[0.346453, 0.637692, 0.851451],[0.336982, 0.633574, 0.843855],[0.327642, 0.629189, 0.836017],[0.318487, 0.624551, 0.827937],[0.309539, 0.619657, 0.819628],[0.300784, 0.614497, 0.811108],[0.292309, 0.609115, 0.802379],[0.284098, 0.603485, 0.793470],[0.276205, 0.597634, 0.784386],[0.268595, 0.591580, 0.775143],[0.261308, 0.585335, 0.765780],[0.254368, 0.578908, 0.756296],[0.247753, 0.572328, 0.746719],[0.241464, 0.565596, 0.737066],[0.235515, 0.558748, 0.727351],[0.229842, 0.551802, 0.717600],[0.224503, 0.544750, 0.707805],[0.219485, 0.537628, 0.697998],[0.214694, 0.530433, 0.688190],[0.210172, 0.523193, 0.678377],[0.205889, 0.515897, 0.668578],[0.201771, 0.508598, 0.658787],[0.197878, 0.501258, 0.649030],[0.194172, 0.493903, 0.639287],[0.190556, 0.486541, 0.629572],[0.187112, 0.479181, 0.619898],[0.183752, 0.471826, 0.610241],[0.180500, 0.464474, 0.600622],[0.177365, 0.457117, 0.591037],[0.174264, 0.449788, 0.581483],[0.171224, 0.442474, 0.571966],[0.168242, 0.435172, 0.562486],[0.165292, 0.427884, 0.553021],[0.162439, 0.420608, 0.543603],[0.159545, 0.413370, 0.534210],[0.156739, 0.406147, 0.524856],[0.153905, 0.398932, 0.515524],[0.151122, 0.391757, 0.506230],[0.148346, 0.384591, 0.496972],[0.145641, 0.377462, 0.487751],[0.142879, 0.370343, 0.478544],[0.140138, 0.363257, 0.469389],[0.137466, 0.356204, 0.460239],[0.134777, 0.349162, 0.451147],[0.132079, 0.342150, 0.442085],[0.129401, 0.335173, 0.433042],[0.126735, 0.328195, 0.424036],[0.124090, 0.321259, 0.415071],[0.121456, 0.314347, 0.406144],[0.118899, 0.307460, 0.397234],[0.116316, 0.300608, 0.388376],[0.113731, 0.293781, 0.379546],[0.111187, 0.286980, 0.370748],[0.108613, 0.280217, 0.362004],[0.106159, 0.273497, 0.353280],[0.103670, 0.266776, 0.344594],[0.101183, 0.260108, 0.335952],[0.098776, 0.253467, 0.327342],[0.096347, 0.246850, 0.318783],[0.094059, 0.240264, 0.310267],[0.091788, 0.233727, 0.301758],[0.089506, 0.227245, 0.293318],[0.087341, 0.220800, 0.284914],[0.085142, 0.214360, 0.276576],[0.083069, 0.207981, 0.268249],[0.081098, 0.201631, 0.259992],[0.079130, 0.195361, 0.251781],[0.077286, 0.189136, 0.243589],[0.075571, 0.182943, 0.235502],[0.073993, 0.176835, 0.227434],[0.072410, 0.170785, 0.219433],[0.071045, 0.164795, 0.211500],[0.069767, 0.158901, 0.203628],[0.068618, 0.153040, 0.195818],[0.067560, 0.147319, 0.188124],[0.066665, 0.141671, 0.180452],[0.065923, 0.136076, 0.172917],[0.065339, 0.130695, 0.165458],[0.064911, 0.125349, 0.158169],[0.064636, 0.120132, 0.150946],[0.064517, 0.115070, 0.143889],[0.064554, 0.110222, 0.136957],[0.064749, 0.105427, 0.130230],[0.065100, 0.100849, 0.123569],[0.065383, 0.096469, 0.117170],[0.065574, 0.092338, 0.111008],[0.065892, 0.088201, 0.104982],[0.066388, 0.084134, 0.099288],[0.067108, 0.080051, 0.093829],[0.068193, 0.076099, 0.088470],[0.069720, 0.072283, 0.083025],[0.071639, 0.068654, 0.077544],[0.073978, 0.065058, 0.072110],[0.076596, 0.061657, 0.066651],[0.079637, 0.058550, 0.061133],[0.082963, 0.055666, 0.055745],[0.086537, 0.052997, 0.050336],[0.090315, 0.050699, 0.045040],[0.094260, 0.048753, 0.039773],[0.098319, 0.047041, 0.034683],[0.102458, 0.045624, 0.030074],[0.106732, 0.044705, 0.026012],[0.110986, 0.043972, 0.022379],[0.115245, 0.043596, 0.019150],[0.119547, 0.043567, 0.016299],[0.123812, 0.043861, 0.013797],[0.128105, 0.044459, 0.011588],[0.132315, 0.045229, 0.009531],[0.136451, 0.046164, 0.007895],[0.140635, 0.047374, 0.006502],[0.144884, 0.048634, 0.005327],[0.149230, 0.049836, 0.004346],[0.153685, 0.050997, 0.003537],[0.158309, 0.052130, 0.002882],[0.163014, 0.053218, 0.002363],[0.167811, 0.054240, 0.001963],[0.172736, 0.055172, 0.001669],[0.177801, 0.056018, 0.001469],[0.182863, 0.056820, 0.001340],[0.188058, 0.057574, 0.001262],[0.193233, 0.058514, 0.001226],[0.198463, 0.059550, 0.001227],[0.203778, 0.060501, 0.001260],[0.209092, 0.061486, 0.001322],[0.214470, 0.062710, 0.001412],[0.219897, 0.063823, 0.001529],[0.225345, 0.065027, 0.001675],[0.230856, 0.066297, 0.001853],[0.236422, 0.067645, 0.002068],[0.242016, 0.069092, 0.002325],[0.247681, 0.070458, 0.002632],[0.253390, 0.071986, 0.002998],[0.259176, 0.073640, 0.003435],[0.264997, 0.075237, 0.003955],[0.270934, 0.076965, 0.004571],[0.276928, 0.078822, 0.005301],[0.283017, 0.080819, 0.006161],[0.289196, 0.082879, 0.007171],[0.295466, 0.085075, 0.008349],[0.301858, 0.087460, 0.009726],[0.308387, 0.089912, 0.011455],[0.315024, 0.092530, 0.013324],[0.321806, 0.095392, 0.015413],[0.328738, 0.098396, 0.017780],[0.335805, 0.101580, 0.020449],[0.343036, 0.104977, 0.023440],[0.350413, 0.108640, 0.026771],[0.357947, 0.112564, 0.030456],[0.365629, 0.116658, 0.034571],[0.373470, 0.120971, 0.039115],[0.381463, 0.125606, 0.043693],[0.389583, 0.130457, 0.048471],[0.397845, 0.135474, 0.053136],[0.406220, 0.140795, 0.057848],[0.414690, 0.146274, 0.062715],[0.423229, 0.151979, 0.067685],[0.431837, 0.157906, 0.073044],[0.440444, 0.164028, 0.078620],[0.449085, 0.170269, 0.084644],[0.457704, 0.176666, 0.090869],[0.466314, 0.183213, 0.097335],[0.474900, 0.189888, 0.104064],[0.483420, 0.196677, 0.111039],[0.491910, 0.203516, 0.118190],[0.500322, 0.210433, 0.125501],[0.508690, 0.217425, 0.132983],[0.516977, 0.224432, 0.140623],[0.525197, 0.231543, 0.148349],[0.533349, 0.238624, 0.156261],[0.541440, 0.245755, 0.164233],[0.549481, 0.252923, 0.172265],[0.557462, 0.260091, 0.180403],[0.565378, 0.267255, 0.188640],[0.573272, 0.274461, 0.196924],[0.581112, 0.281673, 0.205237],[0.588920, 0.288894, 0.213625],[0.596716, 0.296114, 0.222054],[0.604484, 0.303345, 0.230529],[0.612228, 0.310617, 0.239052],[0.619976, 0.317867, 0.247618],[0.627708, 0.325132, 0.256189],[0.635438, 0.332443, 0.264815],[0.643173, 0.339745, 0.273490],[0.650917, 0.347064, 0.282179],[0.658661, 0.354395, 0.290887],[0.666419, 0.361751, 0.299640],[0.674194, 0.369121, 0.308415],[0.681975, 0.376518, 0.317219],[0.689783, 0.383920, 0.326043],[0.697596, 0.391354, 0.334929],[0.705434, 0.398794, 0.343796],[0.713288, 0.406271, 0.352720],[0.721158, 0.413757, 0.361662],[0.729054, 0.421259, 0.370618],[0.736968, 0.428796, 0.379616],[0.744900, 0.436349, 0.388639],[0.752851, 0.443923, 0.397680],[0.760831, 0.451512, 0.406747],[0.768821, 0.459124, 0.415838],[0.776844, 0.466756, 0.424962],[0.784879, 0.474407, 0.434092],[0.792935, 0.482080, 0.443269],[0.801009, 0.489763, 0.452465],[0.809110, 0.497486, 0.461672],[0.817222, 0.505207, 0.470910],[0.825358, 0.512962, 0.480170],[0.833517, 0.520732, 0.489445],[0.841692, 0.528527, 0.498763],[0.849885, 0.536335, 0.508096],[0.858092, 0.544161, 0.517448],[0.866324, 0.552013, 0.526825],[0.874568, 0.559879, 0.536218],[0.882829, 0.567761, 0.545643],[0.891110, 0.575670, 0.555082],[0.899407, 0.583585, 0.564550],[0.907716, 0.591530, 0.574038],[0.916031, 0.599492, 0.583552],[0.924368, 0.607473, 0.593095],[0.932714, 0.615460, 0.602649],[0.941076, 0.623483, 0.612229],[0.949447, 0.631512, 0.621832],[0.957832, 0.639563, 0.631467],[0.966219, 0.647628, 0.641113],[0.974619, 0.655718, 0.650792],[0.983030, 0.663823, 0.660487],[0.991448, 0.671939, 0.670216],[0.999873, 0.680072, 0.679950]] #Taken from F. Crameri's scientific-colour-maps version 8.0.1. https://doi.org/10.5281/zenodo.1243862 (included by default in newer matplotlib versions) - +berlin = LinearSegmentedColormap.from_list('berlin', berlin_cmap, N=256) app_ui = ui.page_sidebar( ui.sidebar( @@ -28,6 +30,11 @@ 'Isolines', value=True, ), + ui.navset_tab( + *[ui.nav_panel(id, ui.output_data_frame(f"{id}_event_data_frame")) for id in ["A", "B", "C"]], + id="tab", + ), + ui.input_dark_mode(id='dark_mode'), open='always' ), ui.output_plot( @@ -35,101 +42,162 @@ click=True, width="100%", height="700px" ), - ui.output_text("event_params"), ) def server(input, output, session): - click_data = reactive.value(None) + click_data_A = reactive.value(None) + click_data_B = reactive.value(None) + click_data_C = reactive.value(None) + + double_click_precision = 1e-1 + x_ct_axis = np.linspace(-5, 5, 251) metric_x, metric_ct = np.meshgrid(x_ct_axis, x_ct_axis) minkowski_metric = metric_ct**2 - metric_x**2 - blue = 'navy' - red = 'firebrick' - # Update click data when plot is clicked + # Update click data when plot is clicked, if same point is clicked - remove it @reactive.effect def _(): if input.plot_click() is not None: - click_data.set(input.plot_click()) + if input.tab() == "A": + click_data = click_data_A + elif input.tab() == "B": + click_data = click_data_B + else: + click_data = click_data_C + + do_nothing = False + # if click_data() is not None: + # distance = np.sqrt((click_data()["x"] - input.plot_click()["x"])**2 + + # (click_data()["y"] - input.plot_click()["y"])**2) + # if distance < double_click_precision: + # click_data.set(None) + # do_nothing = True + if not do_nothing: + click_data.set(input.plot_click()) @render.plot() def plot(): - v = input.velocity() - - fig, ax = plt.subplots() - ax.set_xlim(-5, 5) - ax.set_ylim(-5, 5) - ax.xaxis.set_major_locator(ticker.MultipleLocator(base=1)) - ax.yaxis.set_major_locator(ticker.MultipleLocator(base=1)) - tick_positions = ax.get_xticks() - - if input.show_minkowski(): - img = ax.imshow(np.sqrt(np.abs(minkowski_metric)) * np.sign(minkowski_metric), extent=(-5, 5, -5, 5), - origin='lower', cmap='RdBu', alpha=0.3) - cbar=fig.colorbar(img, ax=ax, label=r'Eigenzeit $\sqrt{(c^2t^2 - x^2)}$', ticks=tick_positions) - cbar.ax.yaxis.set_major_formatter(ticker.FuncFormatter(lambda x, pos: f"{-int(x)}i" if x < 0 else f"{int(x)}")) - - - if input.show_isolines(): + if input.dark_mode() == "dark": + style_label = 'dark_background' + blue = 'lightsteelblue' + red = 'lightcoral' + color_A = 'lime' + color_B = 'darkred' + color_C = 'darkblue' + cmap = berlin + else: + style_label = 'seaborn-v0_8' + blue = 'navy' + red = 'firebrick' + color_A = 'green' + color_B = 'red' + color_C = 'blue' + cmap = 'RdBu_r' + + with plt.style.context(style_label): + v = input.velocity() + + fig, ax = plt.subplots() + ax.set_xlim(-5, 5) + ax.set_ylim(-5, 5) + ax.xaxis.set_major_locator(ticker.MultipleLocator(base=1)) + ax.yaxis.set_major_locator(ticker.MultipleLocator(base=1)) + tick_positions = ax.get_xticks() + + if input.show_minkowski(): + img = ax.imshow(np.sqrt(np.abs(minkowski_metric)) * np.sign(minkowski_metric), extent=(-5, 5, -5, 5), + origin='lower', cmap=cmap, alpha=0.75) + cbar=fig.colorbar(img, ax=ax, label=r'Eigenzeit $\sqrt{(c^2t^2 - x^2)}$', ticks=tick_positions) + cbar.ax.yaxis.set_major_formatter(ticker.FuncFormatter(lambda x, pos: f"{-int(x)}i" if x < 0 else f"{int(x)}")) + + + if input.show_isolines(): + for tick_pos in tick_positions: + if tick_pos <= 0: + continue + x0 = np.sqrt(x_ct_axis ** 2 + tick_pos ** 2) + ax.plot(x0, x_ct_axis, color='grey', linestyle='--', alpha=0.5) + ax.plot(-x0, x_ct_axis, color='grey', linestyle='--', alpha=0.5) + ax.plot(x_ct_axis, x0, color='grey', linestyle='--', alpha=0.5) + ax.plot(x_ct_axis, -x0, color='grey', linestyle='--', alpha=0.5) + + # Draw axes + ax.axhline(0, color=blue) + ax.axvline(0, color=blue) + # Apply Lorentz transformation to axes + if v != 0: + x_axis_transformed, ct_axis_transformed = lorentz_transform(x_ct_axis, np.zeros_like(x_ct_axis), v) + ax.plot(x_axis_transformed, ct_axis_transformed, color=red) + ax.plot(ct_axis_transformed, x_axis_transformed, color=red) + + # Draw intersections of isolines and axes for tick_pos in tick_positions: - if tick_pos <= 0: + if tick_pos == 0: continue - x0 = np.sqrt(x_ct_axis ** 2 + tick_pos ** 2) - ax.plot(x0, x_ct_axis, color='grey', linestyle='--', alpha=0.5) - ax.plot(-x0, x_ct_axis, color='grey', linestyle='--', alpha=0.5) - ax.plot(x_ct_axis, x0, color='grey', linestyle='--', alpha=0.5) - ax.plot(x_ct_axis, -x0, color='grey', linestyle='--', alpha=0.5) - - # Draw axes - ax.axhline(0, color=blue) - ax.axvline(0, color=blue) - # Apply Lorentz transformation to axes - if v != 0: - x_axis_transformed, ct_axis_transformed = lorentz_transform(x_ct_axis, np.zeros_like(x_ct_axis), v) - ax.plot(x_axis_transformed, ct_axis_transformed, color=red) - ax.plot(ct_axis_transformed, x_axis_transformed, color=red) - - # Draw intersections of isolines and axes - for tick_pos in tick_positions: - if tick_pos == 0: - continue - x_axis_transformed, ct_axis_transformed = lorentz_transform(tick_pos, 0, v) - ax.plot(x_axis_transformed, ct_axis_transformed, 'o', color=red) - ax.plot(ct_axis_transformed, x_axis_transformed, 'o', color=red) - - ax.plot(tick_pos, 0, 'o', color=blue) - ax.plot(0, tick_pos, 'o', color=blue) - - stored_click = click_data() - if stored_click is not None: - eventx, eventy = stored_click["x"], stored_click["y"] - ax.scatter(eventx, eventy, color='green') - # Draw lines from click to axes - ax.plot([eventx, eventx], [0, eventy], color=blue, linestyle=':') - ax.plot([0, eventx], [eventy, eventy], color=blue, linestyle=':') - - x_transformed, y_transformed = lorentz_transform(eventx, eventy, -v) - - # Draw lines to transformed axes - ref_x_transformed, ref_ct_transformed = lorentz_transform(x_transformed, 0, v) - ax.plot([ref_x_transformed, eventx], [ref_ct_transformed, eventy], color=red, linestyle=':') - ref_x_transformed, ref_ct_transformed = lorentz_transform(0, y_transformed, v) - ax.plot([ref_x_transformed, eventx], [ref_ct_transformed, eventy], color=red, linestyle=':') - - ax.set_xlabel("x") - ax.set_ylabel("ct") - ax.set_aspect('equal') + x_axis_transformed, ct_axis_transformed = lorentz_transform(tick_pos, 0, v) + ax.plot(x_axis_transformed, ct_axis_transformed, 'o', color=red) + ax.plot(ct_axis_transformed, x_axis_transformed, 'o', color=red) + + ax.plot(tick_pos, 0, 'o', color=blue) + ax.plot(0, tick_pos, 'o', color=blue) + + for stored_click, color in zip([click_data_A(), click_data_B(), click_data_C()], + [color_A, color_B, color_C]): + if stored_click is not None: + eventx, eventy = stored_click["x"], stored_click["y"] + ax.scatter(eventx, eventy, color=color) + # Draw lines from click to axes + ax.plot([eventx, eventx], [0, eventy], color=blue, linestyle=':') + ax.plot([0, eventx], [eventy, eventy], color=blue, linestyle=':') + + x_transformed, y_transformed = lorentz_transform(eventx, eventy, -v) + + # Draw lines to transformed axes + ref_x_transformed, ref_ct_transformed = lorentz_transform(x_transformed, 0, v) + ax.plot([ref_x_transformed, eventx], [ref_ct_transformed, eventy], color=red, linestyle=':') + ref_x_transformed, ref_ct_transformed = lorentz_transform(0, y_transformed, v) + ax.plot([ref_x_transformed, eventx], [ref_ct_transformed, eventy], color=red, linestyle=':') + + ax.set_xlabel("x") + ax.set_ylabel("ct") + ax.set_aspect('equal') return fig - @render.text() - def event_params(): - stored_click = click_data() - if stored_click is None: - return "Click on the plot to select an event." + @render.data_frame + def A_event_data_frame(): + df = get_pdDataFrame(click_data_A(), input.velocity()) + return render.DataTable(df) + + @render.data_frame + def B_event_data_frame(): + df = get_pdDataFrame(click_data_B(), input.velocity()) + return render.DataTable(df) + + @render.data_frame + def C_event_data_frame(): + df = get_pdDataFrame(click_data_C(), input.velocity()) + return render.DataTable(df) + #Use modules to clean this up :) + + def get_pdDataFrame(click_data, velocity): + if click_data is not None: + x, t = lorentz_transform(click_data["x"], click_data["y"], -velocity) + self_time = (t**2 - x**2)**0.5 + df = pd.DataFrame({ + " ": [r"x", r"ct", r"tau"], + "rest": [f"{click_data["x"]:.1f}", f"{click_data["y"]:.1f}", f"{np.imag(self_time):.1f}i" if np.imag(self_time) != 0 else f"{self_time:.1f}"], + "moving": [f"{x:.1f}", f"{t:.1f}", f"{np.imag(self_time):.1f}i" if np.imag(self_time) != 0 else f"{self_time:.1f}"], + }) + #}, index=["x", "ct", "tau"]) + else: + df = pd.DataFrame({ + " ": [r"x", r"ct", r"tau"], + "rest": ['-', '-', '-'], + "moving": ['-', '-', '-'], + }) + return df - eventx, eventy = stored_click["x"], stored_click["y"] - return (f"Event coordinates:\n" - f" In rest frame: x = {eventx:.2f}, ct = {eventy:.2f}\n") def lorentz_transform(x, t, v): c = 1 # velocity of light v will be in units of c diff --git a/docs/apps/MinkowskiSpaceTime/requirements.txt b/docs/apps/MinkowskiSpaceTime/requirements.txt index 806f221..fb0f9d3 100644 --- a/docs/apps/MinkowskiSpaceTime/requirements.txt +++ b/docs/apps/MinkowskiSpaceTime/requirements.txt @@ -1,2 +1,3 @@ numpy +pandas matplotlib \ No newline at end of file diff --git a/mkdocs.yml b/mkdocs.yml index f428c29..6b16d26 100644 --- a/mkdocs.yml +++ b/mkdocs.yml @@ -83,3 +83,5 @@ markdown_extensions: - pymdownx.superfences - pymdownx.tabbed: alternate_style: true +copyright: CC BY 4.0 for teaching materials, MIT License for code examples + From 5280a1592937fbf4a8305938dc01aa4bb689dfd2 Mon Sep 17 00:00:00 2001 From: tuemmler Date: Mon, 3 Nov 2025 13:33:54 +0100 Subject: [PATCH 14/14] - updated colors of minkowski app --- docs/apps/MinkowskiSpaceTime/app.py | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/docs/apps/MinkowskiSpaceTime/app.py b/docs/apps/MinkowskiSpaceTime/app.py index 13c21e8..5a33152 100644 --- a/docs/apps/MinkowskiSpaceTime/app.py +++ b/docs/apps/MinkowskiSpaceTime/app.py @@ -84,8 +84,9 @@ def plot(): red = 'lightcoral' color_A = 'lime' color_B = 'darkred' - color_C = 'darkblue' + color_C = 'deepskyblue' cmap = berlin + alpha = 0.85 else: style_label = 'seaborn-v0_8' blue = 'navy' @@ -94,6 +95,7 @@ def plot(): color_B = 'red' color_C = 'blue' cmap = 'RdBu_r' + alpha = 0.3 with plt.style.context(style_label): v = input.velocity() @@ -107,7 +109,7 @@ def plot(): if input.show_minkowski(): img = ax.imshow(np.sqrt(np.abs(minkowski_metric)) * np.sign(minkowski_metric), extent=(-5, 5, -5, 5), - origin='lower', cmap=cmap, alpha=0.75) + origin='lower', cmap=cmap, alpha=alpha) cbar=fig.colorbar(img, ax=ax, label=r'Eigenzeit $\sqrt{(c^2t^2 - x^2)}$', ticks=tick_positions) cbar.ax.yaxis.set_major_formatter(ticker.FuncFormatter(lambda x, pos: f"{-int(x)}i" if x < 0 else f"{int(x)}"))