From f682c577ecb3421cf5ae5ce85f5435b917b97de0 Mon Sep 17 00:00:00 2001 From: Paul Tuemmler <136888490+ptuemmler@users.noreply.github.com> Date: Mon, 3 Nov 2025 16:34:58 +0100 Subject: [PATCH 01/22] - updated license on page --- docs/license.md | 423 ++++++++++++++++++++++++++++++++++++++++++++++++ mkdocs.yml | 1 + 2 files changed, 424 insertions(+) diff --git a/docs/license.md b/docs/license.md index 5f2586b..17afcec 100644 --- a/docs/license.md +++ b/docs/license.md @@ -1,3 +1,426 @@ # License ## CC BY 4.0 (for teaching materials) +??? info + ```text + + 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. + ``` + ## MIT License (for code examples) +??? info + ```text + 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/mkdocs.yml b/mkdocs.yml index 6b16d26..37248aa 100644 --- a/mkdocs.yml +++ b/mkdocs.yml @@ -81,6 +81,7 @@ markdown_extensions: - pymdownx.inlinehilite - pymdownx.snippets - pymdownx.superfences + - pymdownx.details - pymdownx.tabbed: alternate_style: true copyright: CC BY 4.0 for teaching materials, MIT License for code examples From 9579e5aaf96da2fcbb16e0df9fe7164ad874c66f Mon Sep 17 00:00:00 2001 From: tuemmler Date: Wed, 5 Nov 2025 18:36:00 +0100 Subject: [PATCH 02/22] - added draft tags --- docs/apps/FourierTransforms/app.md | 1 + docs/apps/MinkowskiSpaceTime/app.md | 1 + 2 files changed, 2 insertions(+) diff --git a/docs/apps/FourierTransforms/app.md b/docs/apps/FourierTransforms/app.md index fe87851..732006c 100644 --- a/docs/apps/FourierTransforms/app.md +++ b/docs/apps/FourierTransforms/app.md @@ -5,6 +5,7 @@ categories: - Mathematics tags: - Fourier Transform + - Draft date: 2025-11-02 hide: - toc diff --git a/docs/apps/MinkowskiSpaceTime/app.md b/docs/apps/MinkowskiSpaceTime/app.md index 2ecffbe..f4c9324 100644 --- a/docs/apps/MinkowskiSpaceTime/app.md +++ b/docs/apps/MinkowskiSpaceTime/app.md @@ -6,6 +6,7 @@ categories: - Physics tags: - Relativity + - Draft date: 2025-11-03 hide: - toc From 9fa3854ff1a2f52d38536c376e4cea103aa430d1 Mon Sep 17 00:00:00 2001 From: tuemmler Date: Wed, 5 Nov 2025 18:37:21 +0100 Subject: [PATCH 03/22] - added fractional derivatives app --- docs/apps/FractionalDerivatives/app.md | 16 +++ docs/apps/FractionalDerivatives/app.py | 124 ++++++++++++++++++ .../FractionalDerivatives/requirements.txt | 3 + 3 files changed, 143 insertions(+) create mode 100644 docs/apps/FractionalDerivatives/app.md create mode 100644 docs/apps/FractionalDerivatives/app.py create mode 100644 docs/apps/FractionalDerivatives/requirements.txt diff --git a/docs/apps/FractionalDerivatives/app.md b/docs/apps/FractionalDerivatives/app.md new file mode 100644 index 0000000..5d9cc30 --- /dev/null +++ b/docs/apps/FractionalDerivatives/app.md @@ -0,0 +1,16 @@ +--- +authors: + - ptuemmler +categories: + - Mathematics +tags: + - Fourier Transform + - Draft +date: 2025-11-05 +hide: + - toc +draft: true +--- +# Fractional Derivatives + +{{embed_app("100%", "860px")}} diff --git a/docs/apps/FractionalDerivatives/app.py b/docs/apps/FractionalDerivatives/app.py new file mode 100644 index 0000000..f9f8dc3 --- /dev/null +++ b/docs/apps/FractionalDerivatives/app.py @@ -0,0 +1,124 @@ +import numpy as np +import matplotlib.pyplot as plt +import re +from shiny import App, Inputs, Outputs, Session, render, ui, reactive + +app_ui = ui.page_sidebar( + ui.sidebar( + ui.input_text( + "function", + "Function f(x)", + value="e**(-x**2)", + placeholder="Enter function like: sin(x), cos(x), exp(x), x**2, etc." + ), + ui.input_slider( + "order", + "Derivative order", + min=0, + max=4, + value=1, + step=0.1, + animate=True + ), + ui.input_dark_mode(id='dark_mode'), + open='always' + ), + ui.output_plot("plot", width="100%", height="800px"), +) + + +def server(input: Inputs, output: Outputs, session: Session): + xrange = 10 # Fixed x-range for plotting + factor = 10 # Oversampling factor for better accuracy + npix_real = int(2**14) + 1 + + @reactive.calc + def clean_function(): + """Clean and validate the input function""" + func_str = input.function().strip() + + # Replace common mathematical functions with numpy equivalents + replacements = { + 'sin': 'np.sin', + 'cos': 'np.cos', + 'tan': 'np.tan', + 'exp': 'np.exp', + 'log': 'np.log', + 'sqrt': 'np.sqrt', + 'abs': 'np.abs', + } + + # Apply replacements only to function names (not as part of other words) + for old, new in replacements.items(): + func_str = re.sub(r'\b' + old + r'\b', new, func_str) + + # Replace 'x' with the actual variable name for evaluation + return func_str + + @reactive.calc + def evaluate_function(): + """Evaluate the function at given x values""" + func_str = clean_function() + + x = np.linspace(-xrange*factor, xrange*factor, npix_real) + try: + # Create a safe namespace for evaluation + namespace = {'x': x, 'np': np, 'pi': np.pi, 'e': np.e} + y = eval(func_str, {"__builtins__": {}}, namespace) + return x, y, func_str + except Exception as e: + # Return a default function if evaluation fails + ui.notification_show(f"Error evaluating function: {func_str}. Using default e**(-x**2).", duration=10, type="error") + return x, np.exp(-x**2), "e**(-x**2)" + + + @render.plot() + def plot(): + if input.dark_mode() == "dark": + style_label = 'dark_background' + else: + style_label = 'seaborn-v0_8' + + with plt.style.context(style_label): + x, y_true, func_str = evaluate_function() + order = input.order() + + fig, ax = plt.subplots(2,1, sharex=True) + + # Plot original function + ax[0].plot(x, y_true, linewidth=2, label=r'$f(x)$') + + # Compute non-integer derivative using Fourier transform method + Y = np.fft.fft(y_true) + k = np.fft.fftfreq(len(x), d=(x[1]-x[0])) * 2 * np.pi # Angular frequency + + Y_deriv = Y * ((1j * k) ** order) + y_deriv = np.real(np.fft.ifft(Y_deriv)) + + # Plot derivative + ax[1].plot([0], [0]) # Dummy plot to ensure proper scaling + ax[1].plot(x, y_deriv, linewidth=2, label=r'$f^{(' + f'{order}' + ')}(x)$') + + ax[0].set_ylabel(r'$f(x)$') + ax[1].set_ylabel(r'$\frac{d}{dx}^{' + f'{order}' + '}f(x)$') + + ax[1].set_xlabel('x') + # Set reasonable y-limits based on the data + + y_min = np.min(y_true[np.abs(x)<=xrange]) + y_max = np.max(y_true[np.abs(x)<=xrange]) + y_range = y_max - y_min + ax[0].set_ylim(y_min - 0.1 * y_range, y_max + 0.1 * y_range) + + y_min = np.min(y_deriv[np.abs(x)<=xrange]) + y_max = np.max(y_deriv[np.abs(x)<=xrange]) + y_range = y_max - y_min + ax[1].set_ylim(y_min - 0.1 * y_range, y_max + 0.1 * y_range) + + ax[0].set_xlim(-xrange, xrange) + ax[1].set_xlim(-xrange, xrange) + return fig + + +app = App(app_ui, server) + diff --git a/docs/apps/FractionalDerivatives/requirements.txt b/docs/apps/FractionalDerivatives/requirements.txt new file mode 100644 index 0000000..a46db3e --- /dev/null +++ b/docs/apps/FractionalDerivatives/requirements.txt @@ -0,0 +1,3 @@ +numpy +palmerpenguins +matplotlib \ No newline at end of file From fd5b165a960ab6e59820eafc1468f3b7827db875 Mon Sep 17 00:00:00 2001 From: tuemmler Date: Fri, 7 Nov 2025 10:55:57 +0100 Subject: [PATCH 04/22] - added first vector calculus app, namely for gradients! --- docs/apps/NablaShowcase/app.md | 17 ++++ docs/apps/NablaShowcase/app.py | 123 +++++++++++++++++++++++ docs/apps/NablaShowcase/requirements.txt | 2 + 3 files changed, 142 insertions(+) create mode 100644 docs/apps/NablaShowcase/app.md create mode 100644 docs/apps/NablaShowcase/app.py create mode 100644 docs/apps/NablaShowcase/requirements.txt diff --git a/docs/apps/NablaShowcase/app.md b/docs/apps/NablaShowcase/app.md new file mode 100644 index 0000000..007cb6d --- /dev/null +++ b/docs/apps/NablaShowcase/app.md @@ -0,0 +1,17 @@ +--- +authors: + - ptuemmler +categories: + - Mathematics +tags: + - Templates + - Draft +date: 2025-07-01 +hide: + - toc +--- + +# Nabla Showcase + + +{{embed_app("100%", "830px")}} \ No newline at end of file diff --git a/docs/apps/NablaShowcase/app.py b/docs/apps/NablaShowcase/app.py new file mode 100644 index 0000000..e4b1c08 --- /dev/null +++ b/docs/apps/NablaShowcase/app.py @@ -0,0 +1,123 @@ +import numpy as np +import plotly.graph_objects as go +import re +from shiny import App, Inputs, Outputs, Session, render, ui, reactive + +app_ui = ui.page_sidebar( + ui.sidebar( + ui.input_text( + "function", + "Function f(x)", + value="e**(-x**2 - y**2) * sin(x)", + placeholder="Enter function like: sin(x) * cos(y)." + ), + ui.input_checkbox('show_gradient', 'Show Gradient', value=True), + ui.input_checkbox('align_gradient', 'Align Gradient', value=True), + ui.input_dark_mode(id='dark_mode'), + open='always' + ), + ui.card(ui.output_ui("plot"), full_screen=True), +) + + +def server(input: Inputs, output: Outputs, session: Session): + num_pix = 100 + limit = 5 + x_axis = np.linspace(-limit, limit, num_pix) + y_axis = np.linspace(-limit, limit, num_pix) + x, y = np.meshgrid(x_axis, y_axis) + + @reactive.calc + def clean_function(): + """Clean and validate the input function""" + func_str = input.function().strip() + + # Replace common mathematical functions with numpy equivalents + replacements = { + 'sin': 'np.sin', + 'cos': 'np.cos', + 'tan': 'np.tan', + 'exp': 'np.exp', + 'log': 'np.log', + 'sqrt': 'np.sqrt', + 'abs': 'np.abs', + } + + # Apply replacements only to function names (not as part of other words) + for old, new in replacements.items(): + func_str = re.sub(r'\b' + old + r'\b', new, func_str) + + # Replace 'x' with the actual variable name for evaluation + return func_str + + @reactive.calc + def evaluate_function(): + """Evaluate the function at given x values""" + func_str = clean_function() + try: + # Create a safe namespace for evaluation + namespace = {'x': x, 'y': y, 'np': np, 'pi': np.pi, 'e': np.e} + f = eval(func_str, {"__builtins__": {}}, namespace) + return f, func_str + except Exception as e: + # Return a default function if evaluation fails + ui.notification_show(f"Error evaluating function: {func_str}. Using default e**(-x**2).", duration=10, + type="error") + return np.e**(-x**2 - y**2) * np.sin(x), "e**(-x**2 - y**2) * sin(x)" + + @render.ui + def plot(): + f, func_str = evaluate_function() + + gradient = np.gradient(f) + + + # Set template based on dark mode + if input.dark_mode() == "dark": + template = "plotly_dark" + else: + template = "plotly_white" + + + skip = (slice(None, None, 1), slice(None, None, 1)) # Skip some points for clarity + # Create 3D surface plot + fig = go.Figure(data=[ + go.Cone( + x=x[skip].flatten(), + y=y[skip].flatten(), + z=f[skip].flatten() if input.align_gradient() else np.zeros_like(f[skip].flatten()), + u=gradient[1][skip].flatten(), + v=gradient[0][skip].flatten(), + w=np.sqrt(gradient[0][skip].flatten() ** 2 + gradient[1][skip].flatten() ** 2) if input.align_gradient() else np.zeros_like(gradient[0][skip].flatten()), + sizemode="absolute", + sizeref=0.2, + anchor="tip", + # colorscale='portland', + # showscale=True, + ) + if input.show_gradient() else + go.Surface( + x=x, + y=y, + z=f, + colorscale='turbo', + colorbar_title_text='f(x,y)', + showscale=True, + ), + ]) + + fig.update_layout( + template=template, + scene=dict( + xaxis_title='X-axis', + yaxis_title='Y-axis', + zaxis_title='f(x,y)', + ), + height=700, + margin=dict(l=0, r=0, t=0, b=0), + ) + + return ui.HTML(fig.to_html()) + + +app = App(app_ui, server) diff --git a/docs/apps/NablaShowcase/requirements.txt b/docs/apps/NablaShowcase/requirements.txt new file mode 100644 index 0000000..51e83f6 --- /dev/null +++ b/docs/apps/NablaShowcase/requirements.txt @@ -0,0 +1,2 @@ +numpy +plotly \ No newline at end of file From 1fa605f85221945c5a94b5f086a21c0aee340049 Mon Sep 17 00:00:00 2001 From: ptuemmler Date: Sat, 8 Nov 2025 14:46:02 +0100 Subject: [PATCH 05/22] improved function inputs - update only on leaving focus or pressing enter - allowing '^' instead of requiring '**' --- docs/apps/FractionalDerivatives/app.py | 25 +++++++++++++------------ docs/apps/TaylorExpansion/app.py | 26 ++++++++++++++------------ 2 files changed, 27 insertions(+), 24 deletions(-) diff --git a/docs/apps/FractionalDerivatives/app.py b/docs/apps/FractionalDerivatives/app.py index f9f8dc3..2cb072d 100644 --- a/docs/apps/FractionalDerivatives/app.py +++ b/docs/apps/FractionalDerivatives/app.py @@ -9,7 +9,8 @@ "function", "Function f(x)", value="e**(-x**2)", - placeholder="Enter function like: sin(x), cos(x), exp(x), x**2, etc." + placeholder="Enter function like: sin(x), cos(x), exp(x), x**2, etc.", + update_on='blur', ), ui.input_slider( "order", @@ -39,20 +40,20 @@ def clean_function(): # Replace common mathematical functions with numpy equivalents replacements = { - 'sin': 'np.sin', - 'cos': 'np.cos', - 'tan': 'np.tan', - 'exp': 'np.exp', - 'log': 'np.log', - 'sqrt': 'np.sqrt', - 'abs': 'np.abs', + r'\b(sin)\b': 'np.sin', + r'\b(cos)\b': 'np.cos', + r'\b(tan)\b': 'np.tan', + r'\b(exp)\b': 'np.exp', + r'\b(log)\b': 'np.log', + r'\b(sqrt)\b': 'np.sqrt', + r'\b(abs)\b': 'np.abs', + r'\^': '**', # escaped caret for literal match } - # Apply replacements only to function names (not as part of other words) - for old, new in replacements.items(): - func_str = re.sub(r'\b' + old + r'\b', new, func_str) + # Apply all replacements + for pattern, replacement in replacements.items(): + func_str = re.sub(pattern, replacement, func_str) - # Replace 'x' with the actual variable name for evaluation return func_str @reactive.calc diff --git a/docs/apps/TaylorExpansion/app.py b/docs/apps/TaylorExpansion/app.py index c53039d..fabd317 100644 --- a/docs/apps/TaylorExpansion/app.py +++ b/docs/apps/TaylorExpansion/app.py @@ -13,7 +13,8 @@ "function", "Function f(x)", value="cos(x)", - placeholder="Enter function like: sin(x), cos(x), exp(x), x**2, etc." + placeholder="Enter function like: sin(x), cos(x), exp(x), x**2, etc.", + update_on='blur', ), ui.input_slider( "order", @@ -53,6 +54,7 @@ def server(input: Inputs, output: Outputs, session: Session): + @reactive.calc @reactive.calc def clean_function(): """Clean and validate the input function""" @@ -60,20 +62,20 @@ def clean_function(): # Replace common mathematical functions with numpy equivalents replacements = { - 'sin': 'np.sin', - 'cos': 'np.cos', - 'tan': 'np.tan', - 'exp': 'np.exp', - 'log': 'np.log', - 'sqrt': 'np.sqrt', - 'abs': 'np.abs' + r'\b(sin)\b': 'np.sin', + r'\b(cos)\b': 'np.cos', + r'\b(tan)\b': 'np.tan', + r'\b(exp)\b': 'np.exp', + r'\b(log)\b': 'np.log', + r'\b(sqrt)\b': 'np.sqrt', + r'\b(abs)\b': 'np.abs', + r'\^': '**', # escaped caret for literal match } - # Apply replacements only to function names (not as part of other words) - for old, new in replacements.items(): - func_str = re.sub(r'\b' + old + r'\b', new, func_str) + # Apply all replacements + for pattern, replacement in replacements.items(): + func_str = re.sub(pattern, replacement, func_str) - # Replace 'x' with the actual variable name for evaluation return func_str @reactive.calc From fcced319c16285af540cfd1bf03c74174d33b4fc Mon Sep 17 00:00:00 2001 From: ptuemmler Date: Sat, 8 Nov 2025 16:47:14 +0100 Subject: [PATCH 06/22] added curl and gradient apps to nabla demonstration --- docs/apps/NablaShowcase/app.md | 8 +- docs/apps/NablaShowcase/curl/app.py | 166 ++++++++++++++++++ .../NablaShowcase/{ => curl}/requirements.txt | 0 docs/apps/NablaShowcase/{ => gradient}/app.py | 43 ++--- .../NablaShowcase/gradient/requirements.txt | 2 + 5 files changed, 197 insertions(+), 22 deletions(-) create mode 100644 docs/apps/NablaShowcase/curl/app.py rename docs/apps/NablaShowcase/{ => curl}/requirements.txt (100%) rename docs/apps/NablaShowcase/{ => gradient}/app.py (79%) create mode 100644 docs/apps/NablaShowcase/gradient/requirements.txt diff --git a/docs/apps/NablaShowcase/app.md b/docs/apps/NablaShowcase/app.md index 007cb6d..1170076 100644 --- a/docs/apps/NablaShowcase/app.md +++ b/docs/apps/NablaShowcase/app.md @@ -4,7 +4,7 @@ authors: categories: - Mathematics tags: - - Templates + - Calculus - Draft date: 2025-07-01 hide: @@ -14,4 +14,8 @@ hide: # Nabla Showcase -{{embed_app("100%", "830px")}} \ No newline at end of file +## Gradient +{{embed_app("100%", "830px", "gradient")}} + +## Curl +{{embed_app("100%", "830px", "Curl")}} \ No newline at end of file diff --git a/docs/apps/NablaShowcase/curl/app.py b/docs/apps/NablaShowcase/curl/app.py new file mode 100644 index 0000000..878f314 --- /dev/null +++ b/docs/apps/NablaShowcase/curl/app.py @@ -0,0 +1,166 @@ +import numpy as np +import plotly.graph_objects as go +import re +from shiny import App, Inputs, Outputs, Session, render, ui, reactive + +app_ui = ui.page_sidebar( + ui.sidebar( + ui.input_text( + "function_x", + "F_x", + value="e^(-y^2) * e^(-z^2)", + placeholder="Enter function like: sin(x) * cos(y).", + update_on='blur', + ), + ui.input_text( + "function_y", + "F_y", + value="0", + placeholder="Enter function like: sin(x) * cos(y).", + update_on='blur', + ), + ui.input_text( + "function_z", + "F_z", + value="0", + placeholder="Enter function like: sin(x) * cos(y).", + update_on='blur', + ), + ui.input_checkbox('show_curl', 'Show Curl', value=True), + ui.input_dark_mode(id='dark_mode'), + ), + ui.output_ui("plot") +) + + +def server(input: Inputs, output: Outputs, session: Session): + num_pix = 16 + limit = np.pi + x_axis = np.linspace(-limit, limit, num_pix) + y_axis = np.linspace(-limit, limit, num_pix) + z_axis = np.linspace(-limit, limit, num_pix) + x, y, z = np.meshgrid(x_axis, y_axis, z_axis) + # z = np.zeros_like(x) + + @reactive.calc + def clean_function(): + """Clean and validate the input function""" + func_strings = [] + # Replace common mathematical functions with numpy equivalents + replacements = { + r'\b(sin)\b': 'np.sin', + r'\b(cos)\b': 'np.cos', + r'\b(tan)\b': 'np.tan', + r'\b(exp)\b': 'np.exp', + r'\b(log)\b': 'np.log', + r'\b(sqrt)\b': 'np.sqrt', + r'\b(abs)\b': 'np.abs', + r'\^': '**', # escaped caret for literal match + } + + for func_str in [input.function_x().strip(), + input.function_y().strip(), + input.function_z().strip()]: + + # Apply all replacements + for pattern, replacement in replacements.items(): + func_str = re.sub(pattern, replacement, func_str) + + func_strings.append(func_str) + return func_strings + + @reactive.calc + def evaluate_function(): + """Evaluate the function at given x values""" + func_strings = clean_function() + + results = [] + ones = np.ones_like(x) # force correct output dimension + for func_str in func_strings: + try: + # Create a safe namespace for evaluation + namespace = {'x': x, 'y': y, 'z': z, 'np': np, 'pi': np.pi, 'e': np.e} + f = eval(func_str, {"__builtins__": {}}, namespace) + results.append(ones * f) + except Exception as e: + # Return a default function if evaluation fails + ui.notification_show(f"Error evaluating function: {func_str}.", duration=10, + type="error") + results.append(ones * 0) + return results + + @render.ui + def plot(): + # Set template based on dark mode + if input.dark_mode() == "dark": + template = "plotly_dark" + else: + template = "plotly_white" + + fx, fy, fz = evaluate_function() + + # Create 3D surface plot + fig = go.Figure() + + if input.show_curl(): + curl_x, curl_y, curl_z = get_curl(x, y, z, fx, fy, fz) + fig.add_trace( + go.Cone( + x=x.flatten(), + y=y.flatten(), + z=z.flatten(), + u=curl_x.flatten(), + v=curl_y.flatten(), + w=curl_z.flatten(), + sizemode="raw", + anchor="tail", + hoverinfo='skip', + ) + ) + else: + fig.add_trace( + go.Cone( + x=x.flatten(), + y=y.flatten(), + z=z.flatten(), + u=fx.flatten(), + v=fy.flatten(), + w=fz.flatten(), + sizemode="raw", + anchor="tail", + hoverinfo='skip', + ) + ) + + fig.update_layout( + template=template, + scene=dict( + xaxis_title='X-axis', + yaxis_title='Y-axis', + zaxis_title='Z-axis', + xaxis_showspikes=False, + yaxis_showspikes=False, + zaxis_showspikes=False, + ), + height=700, + margin=dict(l=0, r=0, t=0, b=0), + ) + + return ui.HTML(fig.to_html()) + +def get_curl(x,y,z,u,v,w): + dx = x[0,:,0] + dy = y[:,0,0] + dz = z[0,0,:] + + dummy, dFx_dy, dFx_dz = np.gradient (u, dx, dy, dz, axis=[1,0,2]) + dFy_dx, dummy, dFy_dz = np.gradient (v, dx, dy, dz, axis=[1,0,2]) + dFz_dx, dFz_dy, dummy = np.gradient (w, dx, dy, dz, axis=[1,0,2]) + + rot_x = dFz_dy - dFy_dz + rot_y = dFx_dz - dFz_dx + rot_z = dFy_dx - dFx_dy + + return rot_x, rot_y, rot_z + +app = App(app_ui, server) diff --git a/docs/apps/NablaShowcase/requirements.txt b/docs/apps/NablaShowcase/curl/requirements.txt similarity index 100% rename from docs/apps/NablaShowcase/requirements.txt rename to docs/apps/NablaShowcase/curl/requirements.txt diff --git a/docs/apps/NablaShowcase/app.py b/docs/apps/NablaShowcase/gradient/app.py similarity index 79% rename from docs/apps/NablaShowcase/app.py rename to docs/apps/NablaShowcase/gradient/app.py index e4b1c08..0d2078b 100644 --- a/docs/apps/NablaShowcase/app.py +++ b/docs/apps/NablaShowcase/gradient/app.py @@ -9,20 +9,20 @@ "function", "Function f(x)", value="e**(-x**2 - y**2) * sin(x)", - placeholder="Enter function like: sin(x) * cos(y)." + placeholder="Enter function like: sin(x) * cos(y).", + update_on='blur', ), ui.input_checkbox('show_gradient', 'Show Gradient', value=True), ui.input_checkbox('align_gradient', 'Align Gradient', value=True), ui.input_dark_mode(id='dark_mode'), - open='always' ), - ui.card(ui.output_ui("plot"), full_screen=True), + ui.output_ui("plot") ) def server(input: Inputs, output: Outputs, session: Session): num_pix = 100 - limit = 5 + limit = np.pi x_axis = np.linspace(-limit, limit, num_pix) y_axis = np.linspace(-limit, limit, num_pix) x, y = np.meshgrid(x_axis, y_axis) @@ -34,20 +34,20 @@ def clean_function(): # Replace common mathematical functions with numpy equivalents replacements = { - 'sin': 'np.sin', - 'cos': 'np.cos', - 'tan': 'np.tan', - 'exp': 'np.exp', - 'log': 'np.log', - 'sqrt': 'np.sqrt', - 'abs': 'np.abs', + r'\b(sin)\b': 'np.sin', + r'\b(cos)\b': 'np.cos', + r'\b(tan)\b': 'np.tan', + r'\b(exp)\b': 'np.exp', + r'\b(log)\b': 'np.log', + r'\b(sqrt)\b': 'np.sqrt', + r'\b(abs)\b': 'np.abs', + r'\^': '**', # escaped caret for literal match } - # Apply replacements only to function names (not as part of other words) - for old, new in replacements.items(): - func_str = re.sub(r'\b' + old + r'\b', new, func_str) + # Apply all replacements + for pattern, replacement in replacements.items(): + func_str = re.sub(pattern, replacement, func_str) - # Replace 'x' with the actual variable name for evaluation return func_str @reactive.calc @@ -89,11 +89,9 @@ def plot(): u=gradient[1][skip].flatten(), v=gradient[0][skip].flatten(), w=np.sqrt(gradient[0][skip].flatten() ** 2 + gradient[1][skip].flatten() ** 2) if input.align_gradient() else np.zeros_like(gradient[0][skip].flatten()), - sizemode="absolute", - sizeref=0.2, - anchor="tip", - # colorscale='portland', - # showscale=True, + sizemode="raw", + anchor="tail", + hoverinfo='skip', ) if input.show_gradient() else go.Surface( @@ -103,7 +101,9 @@ def plot(): colorscale='turbo', colorbar_title_text='f(x,y)', showscale=True, + hoverinfo='skip' ), + ]) fig.update_layout( @@ -112,6 +112,9 @@ def plot(): xaxis_title='X-axis', yaxis_title='Y-axis', zaxis_title='f(x,y)', + xaxis_showspikes=False, + yaxis_showspikes=False, + zaxis_showspikes=False, ), height=700, margin=dict(l=0, r=0, t=0, b=0), diff --git a/docs/apps/NablaShowcase/gradient/requirements.txt b/docs/apps/NablaShowcase/gradient/requirements.txt new file mode 100644 index 0000000..51e83f6 --- /dev/null +++ b/docs/apps/NablaShowcase/gradient/requirements.txt @@ -0,0 +1,2 @@ +numpy +plotly \ No newline at end of file From dd8f3762eafb16f6464f53f66e90eea65403cf78 Mon Sep 17 00:00:00 2001 From: ptuemmler Date: Sun, 16 Nov 2025 22:51:53 +0100 Subject: [PATCH 07/22] added sliders for axis limits --- docs/apps/MinkowskiSpaceTime/app.py | 42 +++++++++++++++++++---------- 1 file changed, 28 insertions(+), 14 deletions(-) diff --git a/docs/apps/MinkowskiSpaceTime/app.py b/docs/apps/MinkowskiSpaceTime/app.py index 5a33152..fddf547 100644 --- a/docs/apps/MinkowskiSpaceTime/app.py +++ b/docs/apps/MinkowskiSpaceTime/app.py @@ -34,6 +34,8 @@ *[ui.nav_panel(id, ui.output_data_frame(f"{id}_event_data_frame")) for id in ["A", "B", "C"]], id="tab", ), + ui.input_slider("x_range", "x-Range", min=-5, max=5, value=[-5, 5]), + ui.input_slider("ct_range", "ct-Range", min=-5, max=5, value=[-5, 5]), ui.input_dark_mode(id='dark_mode'), open='always' ), @@ -51,9 +53,6 @@ def server(input, output, session): 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 # Update click data when plot is clicked, if same point is clicked - remove it @reactive.effect @@ -78,6 +77,13 @@ def _(): @render.plot() def plot(): + + x_axis = np.linspace(input.x_range()[0], input.x_range()[1], 251) + ct_axis = np.linspace(input.ct_range()[0], input.ct_range()[1], 251) + metric_x, metric_ct = np.meshgrid(x_axis, ct_axis) + minkowski_metric = metric_ct ** 2 - metric_x ** 2 + + if input.dark_mode() == "dark": style_label = 'dark_background' blue = 'lightsteelblue' @@ -101,15 +107,21 @@ def plot(): v = input.velocity() fig, ax = plt.subplots() - ax.set_xlim(-5, 5) - ax.set_ylim(-5, 5) + ax.set_xlim([x_axis[0], x_axis[-1]]) + ax.set_ylim([ct_axis[0], ct_axis[-1]]) ax.xaxis.set_major_locator(ticker.MultipleLocator(base=1)) ax.yaxis.set_major_locator(ticker.MultipleLocator(base=1)) - tick_positions = ax.get_xticks() + tick_positions = np.arange(-int(max(abs(input.x_range()[0]), abs(input.x_range()[1]), + abs(input.ct_range()[0]), abs(input.ct_range()[1]))), + int(max(abs(input.x_range()[0]), abs(input.x_range()[1]), + abs(input.ct_range()[0]), abs(input.ct_range()[1]))) + 1, 1) 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=alpha) + img = ax.imshow(np.sqrt(np.abs(minkowski_metric)) * np.sign(minkowski_metric), + extent=[x_axis[0], x_axis[-1], ct_axis[0], ct_axis[-1]], + origin='lower', cmap=cmap, alpha=alpha, + vmin=-np.max(np.abs(tick_positions)), vmax=np.max(np.abs(tick_positions))) + 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)}")) @@ -118,18 +130,20 @@ def plot(): 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) + t0 = np.sqrt(x_axis ** 2 + tick_pos ** 2) + x0 = np.sqrt(ct_axis ** 2 + tick_pos ** 2) + + ax.plot(x0, ct_axis, color='grey', linestyle='--', alpha=0.5) + ax.plot(-x0, ct_axis, color='grey', linestyle='--', alpha=0.5) + ax.plot(x_axis, t0, color='grey', linestyle='--', alpha=0.5) + ax.plot(x_axis, -t0, 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) + x_axis_transformed, ct_axis_transformed = lorentz_transform(x_axis, np.zeros_like(ct_axis), v) ax.plot(x_axis_transformed, ct_axis_transformed, color=red) ax.plot(ct_axis_transformed, x_axis_transformed, color=red) From c4b02747491f8aadd89b3acea5c812c3ba62ee73 Mon Sep 17 00:00:00 2001 From: ptuemmler Date: Mon, 17 Nov 2025 12:25:37 +0100 Subject: [PATCH 08/22] - finished minkowski app --- docs/apps/MinkowskiSpaceTime/app.md | 4 +- docs/apps/MinkowskiSpaceTime/app.py | 108 ++++++++++++++++++---------- 2 files changed, 72 insertions(+), 40 deletions(-) diff --git a/docs/apps/MinkowskiSpaceTime/app.md b/docs/apps/MinkowskiSpaceTime/app.md index f4c9324..5041331 100644 --- a/docs/apps/MinkowskiSpaceTime/app.md +++ b/docs/apps/MinkowskiSpaceTime/app.md @@ -7,7 +7,9 @@ categories: tags: - Relativity - Draft -date: 2025-11-03 +date: + created: 2025-11-03 + updated: 2025-11-17 hide: - toc draft: true diff --git a/docs/apps/MinkowskiSpaceTime/app.py b/docs/apps/MinkowskiSpaceTime/app.py index fddf547..5e1dec3 100644 --- a/docs/apps/MinkowskiSpaceTime/app.py +++ b/docs/apps/MinkowskiSpaceTime/app.py @@ -32,11 +32,21 @@ ), ui.navset_tab( *[ui.nav_panel(id, ui.output_data_frame(f"{id}_event_data_frame")) for id in ["A", "B", "C"]], + ui.nav_spacer(), + ui.nav_control( + ui.input_action_button("reset_events", "Reset"), + ), id="tab", ), - ui.input_slider("x_range", "x-Range", min=-5, max=5, value=[-5, 5]), - ui.input_slider("ct_range", "ct-Range", min=-5, max=5, value=[-5, 5]), + ui.accordion( + ui.accordion_panel("Plot options", + ui.input_slider("x_range", "x-Range", min=-5, max=5, value=[-5, 5]), + ui.input_slider("ct_range", "ct-Range", min=-5, max=5, value=[-5, 5]), + ui.input_checkbox("show_projections", "Show Projections", value=True), + ), + ), ui.input_dark_mode(id='dark_mode'), + width='300px', open='always' ), ui.output_plot( @@ -51,9 +61,6 @@ def server(input, output, session): click_data_B = reactive.value(None) click_data_C = reactive.value(None) - double_click_precision = 1e-1 - - # Update click data when plot is clicked, if same point is clicked - remove it @reactive.effect def _(): @@ -65,15 +72,15 @@ def _(): 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()) + click_data.set(input.plot_click()) + + # Reset click data when reset button is pressed + @reactive.effect + @reactive.event(input.reset_events) + def _(): + click_data_A.set(None) + click_data_B.set(None) + click_data_C.set(None) @render.plot() def plot(): @@ -158,61 +165,84 @@ def plot(): 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]): + for stored_click, color, name in zip([click_data_A(), click_data_B(), click_data_C()], + [color_A, color_B, color_C], + ["A", "B", "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=':') - + ax.text(eventx, eventy, f" {name}", color="grey", verticalalignment='bottom') 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=':') + if input.show_projections(): + # Draw lines from click to axes + ax.plot([eventx, eventx], [0, eventy], color=blue, linestyle=':') + ax.plot([0, eventx], [eventy, eventy], color=blue, linestyle=':') - ax.set_xlabel("x") - ax.set_ylabel("ct") + # Draw lines to transformed axes + if v != 0: + 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 in light-seconds") + ax.set_ylabel("ct in light-seconds") ax.set_aspect('equal') return fig @render.data_frame def A_event_data_frame(): - df = get_pdDataFrame(click_data_A(), input.velocity()) - return render.DataTable(df) + df, styles = get_pdDataFrame(click_data_A(), input.velocity(), input.dark_mode()) + return render.DataTable(df, height='150px', styles=styles) + @render.data_frame def B_event_data_frame(): - df = get_pdDataFrame(click_data_B(), input.velocity()) - return render.DataTable(df) + df, styles = get_pdDataFrame(click_data_B(), input.velocity(), input.dark_mode()) + return render.DataTable(df, height='150px', styles=styles) @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 :) + df, styles = get_pdDataFrame(click_data_C(), input.velocity(), input.dark_mode()) + return render.DataTable(df, height='150px', styles=styles) - def get_pdDataFrame(click_data, velocity): + #Look up how to use modules from shiny to clean this up :) + + def get_pdDataFrame(click_data, velocity, mode): 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}"], + "rest": [f"{click_data["x"]:.2f}", f"{click_data["y"]:.2f}", f"{np.imag(self_time):.2f}i" if np.imag(self_time) != 0 else f"{self_time:.2f}"], + "moving": [f"{x:.2f}", f"{t:.2f}", f"{np.imag(self_time):.2f}i" if np.imag(self_time) != 0 else f"{self_time:.2f}"], }) - #}, index=["x", "ct", "tau"]) else: df = pd.DataFrame({ " ": [r"x", r"ct", r"tau"], "rest": ['-', '-', '-'], "moving": ['-', '-', '-'], }) - return df + + if mode == "dark": + blue = 'lightsteelblue' + red = 'lightcoral' + else: + blue = 'navy' + red = 'firebrick' + + styles = [ + { + "cols": [1], # First column + "style": {"color": blue} + }, + { + "cols": [2], # Second column + "style": {"color": red} + } + ] + return df, styles def lorentz_transform(x, t, v): From f0de7cdac3c5a437025fb92282dd34b995cec9eb Mon Sep 17 00:00:00 2001 From: ptuemmler Date: Mon, 17 Nov 2025 12:25:51 +0100 Subject: [PATCH 09/22] - updated some templates --- docs/apps/TemplateMatplotlib/app.md | 6 ++- docs/apps/TemplateMatplotlib/automatic/app.py | 24 +++++++++++ .../automatic/requirements.txt | 3 ++ docs/apps/TemplatePlotly/app.md | 42 +++++++++++++++++-- docs/apps/TemplatePlotly/app.py | 7 ++++ 5 files changed, 77 insertions(+), 5 deletions(-) create mode 100644 docs/apps/TemplateMatplotlib/automatic/app.py create mode 100644 docs/apps/TemplateMatplotlib/automatic/requirements.txt diff --git a/docs/apps/TemplateMatplotlib/app.md b/docs/apps/TemplateMatplotlib/app.md index a132f64..4c3ed75 100644 --- a/docs/apps/TemplateMatplotlib/app.md +++ b/docs/apps/TemplateMatplotlib/app.md @@ -5,7 +5,9 @@ categories: - Templates tags: - Templates -date: 2025-07-02 +date: + created: 2025-07-02 + updated: 2025-11-17 hide: - toc --- @@ -14,6 +16,8 @@ hide: Quick example for a simple matplotlib app. Matplotlib is a popular Python library that can be used to create plots. This is a simple example to showcase different matplotlib apps using Shiny for Python. +## Automatic dark and light mode matplotlib themes (recommended!) +{{embed_app("100%", "500px", "automatic")}} ## Default matplotlib theme {{embed_app("100%", "500px", "default")}} ## Dark matplotlib theme diff --git a/docs/apps/TemplateMatplotlib/automatic/app.py b/docs/apps/TemplateMatplotlib/automatic/app.py new file mode 100644 index 0000000..43bd142 --- /dev/null +++ b/docs/apps/TemplateMatplotlib/automatic/app.py @@ -0,0 +1,24 @@ +import matplotlib.pyplot as plt +from palmerpenguins import load_penguins +from shiny.express import input, render, ui + +ui.input_slider("n", "Number of bins", 1, 100, 20) +ui.input_dark_mode(id="dark_mode") + +@render.plot(alt="A histogram") +def plot(): + if input.dark_mode() == "dark": + style_label = 'dark_background' + else: + style_label = 'seaborn-v0_8' + + df = load_penguins() + mass = df["body_mass_g"] + with plt.style.context(style_label): + 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") + + return fig \ No newline at end of file diff --git a/docs/apps/TemplateMatplotlib/automatic/requirements.txt b/docs/apps/TemplateMatplotlib/automatic/requirements.txt new file mode 100644 index 0000000..a46db3e --- /dev/null +++ b/docs/apps/TemplateMatplotlib/automatic/requirements.txt @@ -0,0 +1,3 @@ +numpy +palmerpenguins +matplotlib \ No newline at end of file diff --git a/docs/apps/TemplatePlotly/app.md b/docs/apps/TemplatePlotly/app.md index d22f3fd..6dfe0f4 100644 --- a/docs/apps/TemplatePlotly/app.md +++ b/docs/apps/TemplatePlotly/app.md @@ -5,13 +5,47 @@ categories: - Templates tags: - Templates -date: 2025-07-01 +date: + created: 2025-07-01 + updated: 2025-11-17 hide: - toc --- -# Plotly Penguins -Quick example for a simple plotly app. Plotly is an interactive graphics plotting library. +# Plotly Template +Quick example for a simple plotly app. -{{embed_app("100%", "500px")}} \ No newline at end of file +{{embed_app("100%", "550px")}} + +```python title="apps/TemplatePlotly/app.py" linenums="1" +import plotly.express as px +from palmerpenguins import load_penguins +from shiny.express import input, ui +from shinywidgets import render_widget + +penguins = load_penguins() + +ui.input_slider("n", "Number of bins", 1, 100, 20) +ui.input_dark_mode(id="dark_mode") + +@render_widget +def plot(): + if input.dark_mode() == "dark": + template = "plotly_dark" + else: + template = "plotly_white" + + scatterplot = px.histogram( + data_frame=penguins, + x="body_mass_g", + nbins=input.n(), + ).update_layout( + template=template, + title={"text": "Penguin Mass", "x": 0.5}, + yaxis_title="Count", + xaxis_title="Body Mass (g)", + ) + + return scatterplot +``` \ No newline at end of file diff --git a/docs/apps/TemplatePlotly/app.py b/docs/apps/TemplatePlotly/app.py index 987ddcc..4f5b7ee 100644 --- a/docs/apps/TemplatePlotly/app.py +++ b/docs/apps/TemplatePlotly/app.py @@ -6,14 +6,21 @@ penguins = load_penguins() ui.input_slider("n", "Number of bins", 1, 100, 20) +ui.input_dark_mode(id="dark_mode") @render_widget def plot(): + if input.dark_mode() == "dark": + template = "plotly_dark" + else: + template = "plotly_white" + scatterplot = px.histogram( data_frame=penguins, x="body_mass_g", nbins=input.n(), ).update_layout( + template=template, title={"text": "Penguin Mass", "x": 0.5}, yaxis_title="Count", xaxis_title="Body Mass (g)", From 5d41e980de50ab4e0f86b341487d80565a8fa51c Mon Sep 17 00:00:00 2001 From: ptuemmler Date: Fri, 21 Nov 2025 19:54:21 +0100 Subject: [PATCH 10/22] started adding minkowski applet for twin paradox --- docs/apps/MinkowskiSpaceTime/motion/app.py | 179 ++++++++++++++++++ .../{ => motion}/requirements.txt | 0 .../{ => stationary}/app.py | 0 .../stationary/requirements.txt | 3 + 4 files changed, 182 insertions(+) create mode 100644 docs/apps/MinkowskiSpaceTime/motion/app.py rename docs/apps/MinkowskiSpaceTime/{ => motion}/requirements.txt (100%) rename docs/apps/MinkowskiSpaceTime/{ => stationary}/app.py (100%) create mode 100644 docs/apps/MinkowskiSpaceTime/stationary/requirements.txt diff --git a/docs/apps/MinkowskiSpaceTime/motion/app.py b/docs/apps/MinkowskiSpaceTime/motion/app.py new file mode 100644 index 0000000..8ada0ff --- /dev/null +++ b/docs/apps/MinkowskiSpaceTime/motion/app.py @@ -0,0 +1,179 @@ +import matplotlib.pyplot as plt +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( + ui.input_slider("frame", "Frame of animation", min=1, max=512, value=0, step=1, animate=True), + ui.input_slider("turning_point", "Turning point (in light-seconds)", min=1, max=20, value=10, step=0.1), + ui.input_slider("acceleration", "Proper acceleration (in c/s)", min=0.01, max=0.25, value=0.15, step=0.001), + ui.input_dark_mode(id='dark_mode'), + ui.accordion( + ui.accordion_panel('Numerics Settings', + ui.input_slider("num_frames", "Number of frames in simulation", min=124, max=2048, value=512, step=16), + ui.input_slider("dtau", "Proper time step (s)", min=0.01, max=1.0, value=0.1, step=0.01), + ), + open=False, + ), + open='always' + ), + ui.output_plot( + "plot", + click=True, + width="100%", height="700px" + ), +) +def server(input, output, session): + simulation_data = reactive.Value(pd.DataFrame()) + + @reactive.effect + def _(): + ui.update_slider("frame", max=input.num_frames()) + + @reactive.effect + # @reactive.event(input.run_simulation) + def _(): + num_frames = input.num_frames() + dtau = input.dtau() + g = input.acceleration() # proper acceleration of the moving observer + + with ui.Progress(min=0, max=num_frames-1) as p: + p.set(message="Calculation in progress") + # Initialize arrays to hold data + times = [0.0] + positions = [0.0] + velocities = [0.0] + proper_times = [0.0] + + reached_first_turning_point = False + reached_second_turning_point = False + # Simulate motion of the accelerating observer + for i in range(num_frames): + p.set(i, message="Computing") + v_new, x_new, t_new = tauStep(dtau, velocities[-1], positions[-1], times[-1], g) + if x_new >= input.turning_point()/2 and not reached_first_turning_point and not reached_second_turning_point: + reached_first_turning_point = True + g = -g # Reverse acceleration at turning point + elif x_new <= input.turning_point()/2 and reached_first_turning_point and not reached_second_turning_point: + reached_second_turning_point = True + g = -g # Reverse acceleration to head back toward origin + if x_new < 0 and reached_second_turning_point: + g = 0 # Stop acceleration at origin + v_new, x_new, t_new = [0.0, 0.0, times[-1] + (dtau * (1. - velocities[-1] ** 2) ** 0.5)] + + velocities.append(v_new) + positions.append(x_new) + times.append(t_new) + proper_times.append(proper_times[-1] + dtau) + + data = pd.DataFrame({ + 'time': times, + 'position': positions, + 'velocity': velocities, + 'proper_time': proper_times + }) + simulation_data.set(data) + + + @render.plot() + def plot(): + if input.dark_mode() == "dark": + style_label = 'dark_background' + blue = 'lightsteelblue' + red = 'lightcoral' + cmap = berlin + else: + style_label = 'seaborn-v0_8' + blue = 'navy' + red = 'firebrick' + cmap = 'RdBu_r' + + with plt.style.context(style_label): + fig, ax = plt.subplots() + # + data = simulation_data() + frame_idx = input.frame() - 1 + frame_data = lambda: data.iloc[frame_idx] + ax.scatter(data['position'], data['time'], c=data['velocity'], vmin=-1, vmax=1, cmap=cmap) + ax.plot(data['position'], data['time'], color='grey') + + times = ax.get_yticks()[2:-1] # Exclude first and last tick to avoid clutter + # Interpolate positions of moving observer at these times to plot self times + times_at_this_proper_time = np.interp(times, data['proper_time'], data['time'], left=np.nan, right=np.nan) + positions_at_times = np.interp(times_at_this_proper_time, data['time'], data['position'], left=np.nan, right=np.nan) + + cbar = fig.colorbar(plt.cm.ScalarMappable(cmap=cmap, norm=plt.Normalize(vmin=-1, vmax=1)), ax=ax) + cbar.set_label('Velocity (in units of c)') + + + # Draw axes of moving observer of current frame + ax.axline((frame_data()['position'], frame_data()['time']), slope=frame_data()['velocity'], color=red) + ax.axline((frame_data()['position'], frame_data()['time']), slope=np.tan(np.pi/2 - np.atan(frame_data()['velocity'])), color=red) + + # Draw axes + ax.axhline(0, color=blue) + ax.axvline(0, color=blue) + ax.axvline(input.turning_point(), color='grey', linestyle='--', zorder=-1) + + ax.set_xlabel("x in light-seconds") + ax.set_ylabel("ct in light-seconds") + + # Pad the limits a bit + xlim = ax.get_xlim() + ylim = ax.get_ylim() + ax.set_xlim(xlim[0] - 1, xlim[1] + 7) + ax.set_ylim(ylim[0] - 2, ylim[1] + 2) + ax.set_aspect('equal') + + for t, x, tau in zip(times_at_this_proper_time, positions_at_times, times): + ax.text(x+1, t, f'τ={tau:.0f}s', color=red, verticalalignment='center', horizontalalignment='left') + ax.scatter(x, t, color=red, marker='x') + + return fig + +def hypTStep(dt, v0, x0, tau0, g): + ## Hyperbolic step. + ## If an object has proper acceleration g and starts at position x0 with speed v0 and proper time tau0 + ## as seen from an inertial frame, then return the new v, x, tau after time dt has elapsed. + if g == 0: + return v0, x0 + v0 * dt, tau0 + dt * (1. - v0 ** 2) ** 0.5 + + tinit = v0 / (g * (1 - v0 ** 2) ** 0.5) + B = (1 + (g ** 2 * (dt + tinit) ** 2)) ** 0.5 + + v1 = g * (dt + tinit) / B + x1 = x0 + (1.0 / g) * (B - 1. / (1. - v0 ** 2) ** 0.5) + tau1 = tau0 + (np.arcsinh(g * (dt + tinit)) - np.arcsinh(g * tinit)) / g + return v1, x1, tau1 + +def tauStep(dtau, v0, x0, t0, g): + ## linear step in proper time of clock. + ## If an object has proper acceleration g and starts at position x0 with speed v0 at time t0 + ## as seen from an inertial frame, then return the new v, x, t after proper time dtau has elapsed. + + ## Compute how much t will change given a proper-time step of dtau + gamma = (1. - v0 ** 2) ** -0.5 + if g == 0: + dt = dtau * gamma + else: + v0g = v0 * gamma + dt = (np.sinh(dtau * g + np.arcsinh(v0g)) - v0g) / g + + # return v0 + dtau * g, x0 + v0*dt, t0 + dt + v1, x1, t1 = hypTStep(dt, v0, x0, t0, g) + return v1, x1, t0 + dt + +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/motion/requirements.txt similarity index 100% rename from docs/apps/MinkowskiSpaceTime/requirements.txt rename to docs/apps/MinkowskiSpaceTime/motion/requirements.txt diff --git a/docs/apps/MinkowskiSpaceTime/app.py b/docs/apps/MinkowskiSpaceTime/stationary/app.py similarity index 100% rename from docs/apps/MinkowskiSpaceTime/app.py rename to docs/apps/MinkowskiSpaceTime/stationary/app.py diff --git a/docs/apps/MinkowskiSpaceTime/stationary/requirements.txt b/docs/apps/MinkowskiSpaceTime/stationary/requirements.txt new file mode 100644 index 0000000..fb0f9d3 --- /dev/null +++ b/docs/apps/MinkowskiSpaceTime/stationary/requirements.txt @@ -0,0 +1,3 @@ +numpy +pandas +matplotlib \ No newline at end of file From c86fca7776d1b3cc8b452d88af364ac686ec6b29 Mon Sep 17 00:00:00 2001 From: ptuemmler Date: Fri, 21 Nov 2025 19:54:43 +0100 Subject: [PATCH 11/22] removed redundant '@reactive.calc' --- docs/apps/TaylorExpansion/app.py | 1 - 1 file changed, 1 deletion(-) diff --git a/docs/apps/TaylorExpansion/app.py b/docs/apps/TaylorExpansion/app.py index fabd317..55ca186 100644 --- a/docs/apps/TaylorExpansion/app.py +++ b/docs/apps/TaylorExpansion/app.py @@ -54,7 +54,6 @@ def server(input: Inputs, output: Outputs, session: Session): - @reactive.calc @reactive.calc def clean_function(): """Clean and validate the input function""" From 174bff7d764e342e3dd5cd94a41cdd27faf51d27 Mon Sep 17 00:00:00 2001 From: ptuemmler Date: Fri, 21 Nov 2025 19:54:56 +0100 Subject: [PATCH 12/22] removed redundant color definition --- docs/apps/FourierTransforms/app.py | 2 -- 1 file changed, 2 deletions(-) diff --git a/docs/apps/FourierTransforms/app.py b/docs/apps/FourierTransforms/app.py index 2e24842..05e88b1 100644 --- a/docs/apps/FourierTransforms/app.py +++ b/docs/apps/FourierTransforms/app.py @@ -71,8 +71,6 @@ 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])) From 446b53fbb3b9b43f534fc3c3517291aa46a00a54 Mon Sep 17 00:00:00 2001 From: ptuemmler Date: Fri, 21 Nov 2025 19:55:15 +0100 Subject: [PATCH 13/22] fixed typo preventing app from loading --- docs/apps/NablaShowcase/app.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/apps/NablaShowcase/app.md b/docs/apps/NablaShowcase/app.md index 1170076..d9d4180 100644 --- a/docs/apps/NablaShowcase/app.md +++ b/docs/apps/NablaShowcase/app.md @@ -18,4 +18,4 @@ hide: {{embed_app("100%", "830px", "gradient")}} ## Curl -{{embed_app("100%", "830px", "Curl")}} \ No newline at end of file +{{embed_app("100%", "830px", "curl")}} \ No newline at end of file From 897ab9c7f72ec4245233c6e4cab536a4f88cda8e Mon Sep 17 00:00:00 2001 From: ptuemmler Date: Fri, 21 Nov 2025 19:55:44 +0100 Subject: [PATCH 14/22] embedded twin paradox minkowski app --- docs/apps/MinkowskiSpaceTime/app.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/docs/apps/MinkowskiSpaceTime/app.md b/docs/apps/MinkowskiSpaceTime/app.md index 5041331..1c6dfa9 100644 --- a/docs/apps/MinkowskiSpaceTime/app.md +++ b/docs/apps/MinkowskiSpaceTime/app.md @@ -16,4 +16,5 @@ draft: true --- # Minkowski Space-Time -{{embed_app("100%", "800px")}} +{{embed_app("100%", "800px", "stationary")}} +{{embed_app("100%", "800px", "motion")}} From 5963e06fa8f19cadb59babb30db161da2ab9c666 Mon Sep 17 00:00:00 2001 From: ptuemmler Date: Sat, 22 Nov 2025 10:43:09 +0100 Subject: [PATCH 15/22] added doppler app to minkowski --- docs/apps/MinkowskiSpaceTime/app.md | 1 + docs/apps/MinkowskiSpaceTime/doppler/app.py | 147 ++++++++++++++++++ .../doppler/requirements.txt | 3 + docs/apps/MinkowskiSpaceTime/motion/app.py | 97 +++++++----- 4 files changed, 211 insertions(+), 37 deletions(-) create mode 100644 docs/apps/MinkowskiSpaceTime/doppler/app.py create mode 100644 docs/apps/MinkowskiSpaceTime/doppler/requirements.txt diff --git a/docs/apps/MinkowskiSpaceTime/app.md b/docs/apps/MinkowskiSpaceTime/app.md index 1c6dfa9..63fe42e 100644 --- a/docs/apps/MinkowskiSpaceTime/app.md +++ b/docs/apps/MinkowskiSpaceTime/app.md @@ -17,4 +17,5 @@ draft: true # Minkowski Space-Time {{embed_app("100%", "800px", "stationary")}} +{{embed_app("100%", "800px", "doppler")}} {{embed_app("100%", "800px", "motion")}} diff --git a/docs/apps/MinkowskiSpaceTime/doppler/app.py b/docs/apps/MinkowskiSpaceTime/doppler/app.py new file mode 100644 index 0000000..9d881a5 --- /dev/null +++ b/docs/apps/MinkowskiSpaceTime/doppler/app.py @@ -0,0 +1,147 @@ +import matplotlib.pyplot as plt +from matplotlib.colors import LinearSegmentedColormap, Normalize +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) +max_iterations = 1e6 + + +app_ui = ui.page_sidebar( + ui.sidebar( + ui.input_slider( + "velocity", + "Velocity (units of c)", + min=-0.9, + max=0.9, + value=0.5, + step=0.01, + animate=True + ), + ui.input_slider("period", "Period of signal (self time)", min=1, max=3, value=2, step=0.1, animate=True), + ui.input_radio_buttons("signal_type", "Signal type", choices={"ping": "ping", "periodic": "periodic"}, selected="periodic", inline=True), + ui.input_dark_mode(id='dark_mode'), + open='always' + ), + ui.output_plot( + "plot", + click=True, + width="100%", height="700px" + ), +) + + +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 + + +def mirrored(maxval, inc=1): + x = np.arange(inc, maxval, inc) + return np.r_[-x[::-1], 0, x] + + +def server(input, output, session): + tlimits = (-10, 10) + points_per_period = 12 + color_norm = Normalize(vmin=-1, vmax=1) + + @render.plot() + def plot(): + if input.dark_mode() == "dark": + style_label = 'dark_background' + blue = 'lightsteelblue' + red = 'lightcoral' + cmap = berlin + else: + style_label = 'seaborn-v0_8' + blue = 'navy' + red = 'firebrick' + cmap = plt.get_cmap('RdBu_r') + + with plt.style.context(style_label): + fig, ax = plt.subplot_mosaic([['minkowski', 'sender'], ['minkowski', 'receiver']]) + + v = input.velocity() + period = input.period() + + signal_times = mirrored(tlimits[1], inc=period) + if input.signal_type() == 'ping': + signal_amplitude = np.ones_like(signal_times) + else: # input.signal_type() == 'periodic': + signal_times = np.linspace(signal_times[0], signal_times[-1], points_per_period * (len(signal_times) - 1) + 1) + signal_amplitude = np.cos(2 * np.pi * signal_times / period) + + for indx, signal in enumerate(signal_times): + + if input.signal_type() == 'ping': + color = 'grey' + else: # input.signal_type() == 'periodic': + # Color line according to amplitude by mapping to colormap between -1 and 1 + color = cmap(color_norm(signal_amplitude[indx])) + + ax['sender'].plot([signal, signal], [0, signal_amplitude[indx]], color=color) + + ct_axis_transformed, x_axis_transformed = lorentz_transform(signal, 0, v) + + sign = np.sign(signal) * np.sign(v) + + intersection = ct_axis_transformed + sign * x_axis_transformed + + # Extend signal to receiver worldline with slope 1 + ax['minkowski'].plot([x_axis_transformed , 0], [ct_axis_transformed, intersection], color=color) + ax['receiver'].plot([intersection, intersection], [0, signal_amplitude[indx]], color=color) + + + ax['minkowski'].axvline(0, color=blue, label='Reciever worldline') + ax['minkowski'].axline((0, 0), slope=np.tan(np.pi/2 - np.atan(v)), color=red, label='Sender worldline') + + ax['sender'].axhline(0, color=red) + ax['sender'].axvline(0, color=red) + ax['receiver'].axhline(0, color=blue) + ax['receiver'].axvline(0, color=blue) + + ax['sender'].set_title("Sender Frame (in motion)") + ax['receiver'].set_title("Receiver Frame (at rest)") + ax['minkowski'].set_title("Minkowski Spacetime Diagram") + + ax['sender'].set_xlabel("sender self time in seconds") + ax['sender'].set_ylabel("signal amplitude") + ax['receiver'].set_xlabel("receiver self time in seconds") + ax['receiver'].set_ylabel("signal amplitude") + # + ax['minkowski'].set_xlabel("x in light-seconds") + ax['minkowski'].set_ylabel("ct in light-seconds") + ax['minkowski'].set_aspect('equal') + + # # Add self time ticks according to x lims of sender and receiver plots + # sender_xticks = ax['sender'].get_xticks() + # for time in sender_xticks: + # sign = np.sign(time) * np.sign(v) + # ct_axis_transformed, x_axis_transformed = lorentz_transform(time, 0, v) + # if sign < 0: + # ax['minkowski'].text(x_axis_transformed, ct_axis_transformed, f'τ={time:.0f}s ', color=red, verticalalignment='center', + # horizontalalignment='right', ) + # else: + # ax['minkowski'].text(x_axis_transformed, ct_axis_transformed, f' τ={time:.0f}s', color=red, verticalalignment='center', + # horizontalalignment='left') + # + # receiver_xticks = ax['receiver'].get_xticks() + # for time in receiver_xticks: + # sign = np.sign(time) * np.sign(v) + # if sign > 0: + # ax['minkowski'].text(0, time, f'τ={time:.0f}s ', color=blue, verticalalignment='center', + # horizontalalignment='right', ) + # else: + # ax['minkowski'].text(0, time, f' τ={time:.0f}s', color=blue, verticalalignment='center', + # horizontalalignment='left') + return fig + + +app = App(app_ui, server, debug=True) diff --git a/docs/apps/MinkowskiSpaceTime/doppler/requirements.txt b/docs/apps/MinkowskiSpaceTime/doppler/requirements.txt new file mode 100644 index 0000000..fb0f9d3 --- /dev/null +++ b/docs/apps/MinkowskiSpaceTime/doppler/requirements.txt @@ -0,0 +1,3 @@ +numpy +pandas +matplotlib \ No newline at end of file diff --git a/docs/apps/MinkowskiSpaceTime/motion/app.py b/docs/apps/MinkowskiSpaceTime/motion/app.py index 8ada0ff..c6d5b6e 100644 --- a/docs/apps/MinkowskiSpaceTime/motion/app.py +++ b/docs/apps/MinkowskiSpaceTime/motion/app.py @@ -7,17 +7,18 @@ 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) +max_iterations = 1e6 + app_ui = ui.page_sidebar( ui.sidebar( - ui.input_slider("frame", "Frame of animation", min=1, max=512, value=0, step=1, animate=True), + ui.input_slider("frame", "Self time", min=0, max=1, value=0, step=0.5, animate=True), ui.input_slider("turning_point", "Turning point (in light-seconds)", min=1, max=20, value=10, step=0.1), ui.input_slider("acceleration", "Proper acceleration (in c/s)", min=0.01, max=0.25, value=0.15, step=0.001), ui.input_dark_mode(id='dark_mode'), ui.accordion( - ui.accordion_panel('Numerics Settings', - ui.input_slider("num_frames", "Number of frames in simulation", min=124, max=2048, value=512, step=16), - ui.input_slider("dtau", "Proper time step (s)", min=0.01, max=1.0, value=0.1, step=0.01), + ui.accordion_panel('Advanced settings', + ui.input_slider("dtau", "Proper time step (log10)", min=-5, max=-1, value=-2, step=0.1), ), open=False, ), @@ -34,16 +35,10 @@ def server(input, output, session): @reactive.effect def _(): - ui.update_slider("frame", max=input.num_frames()) - - @reactive.effect - # @reactive.event(input.run_simulation) - def _(): - num_frames = input.num_frames() - dtau = input.dtau() + dtau = 10 ** input.dtau() g = input.acceleration() # proper acceleration of the moving observer - with ui.Progress(min=0, max=num_frames-1) as p: + with ui.Progress(min=0, max=1) as p: p.set(message="Calculation in progress") # Initialize arrays to hold data times = [0.0] @@ -54,8 +49,8 @@ def _(): reached_first_turning_point = False reached_second_turning_point = False # Simulate motion of the accelerating observer - for i in range(num_frames): - p.set(i, message="Computing") + count = 0 + while g != 0 and count < max_iterations: v_new, x_new, t_new = tauStep(dtau, velocities[-1], positions[-1], times[-1], g) if x_new >= input.turning_point()/2 and not reached_first_turning_point and not reached_second_turning_point: reached_first_turning_point = True @@ -63,21 +58,47 @@ def _(): elif x_new <= input.turning_point()/2 and reached_first_turning_point and not reached_second_turning_point: reached_second_turning_point = True g = -g # Reverse acceleration to head back toward origin - if x_new < 0 and reached_second_turning_point: + if x_new <= 0 and reached_second_turning_point: g = 0 # Stop acceleration at origin v_new, x_new, t_new = [0.0, 0.0, times[-1] + (dtau * (1. - velocities[-1] ** 2) ** 0.5)] + max_time = t_new velocities.append(v_new) positions.append(x_new) times.append(t_new) proper_times.append(proper_times[-1] + dtau) + count += 1 + + if count >= max_iterations: + ui.notification_show("Maximum number of iterations reached. Consider increasing the proper time step.", type="error") + return + + # Keep appending zeros until max_time is reached + while proper_times[-1] < max_time: + velocities.append(0.0) + positions.append(0.0) + times.append(times[-1] + dtau) + proper_times.append(proper_times[-1] + dtau) + + final_count = len(times) + + # Fill trivial case of no acceleration + stationary_times = np.arange(0, final_count, 1) * dtau + stationary_positions = np.zeros(final_count) + stationary_velocities = np.zeros(final_count) + stationary_proper_times = np.arange(0, final_count, 1) * dtau data = pd.DataFrame({ - 'time': times, - 'position': positions, - 'velocity': velocities, - 'proper_time': proper_times + 'm_time': times, + 'm_position': positions, + 'm_velocity': velocities, + 'm_proper_time': proper_times, + 's_time': stationary_times, + 's_position': stationary_positions, + 's_velocity': stationary_velocities, + 's_proper_time': stationary_proper_times, }) + ui.update_slider("frame", max=np.ceil((len(data)-1) * dtau) - 1, value=0) simulation_data.set(data) @@ -98,26 +119,21 @@ def plot(): fig, ax = plt.subplots() # data = simulation_data() - frame_idx = input.frame() - 1 - frame_data = lambda: data.iloc[frame_idx] - ax.scatter(data['position'], data['time'], c=data['velocity'], vmin=-1, vmax=1, cmap=cmap) - ax.plot(data['position'], data['time'], color='grey') - - times = ax.get_yticks()[2:-1] # Exclude first and last tick to avoid clutter - # Interpolate positions of moving observer at these times to plot self times - times_at_this_proper_time = np.interp(times, data['proper_time'], data['time'], left=np.nan, right=np.nan) - positions_at_times = np.interp(times_at_this_proper_time, data['time'], data['position'], left=np.nan, right=np.nan) + ax.scatter(data['m_position'], data['m_time'], c=data['m_velocity'], vmin=-1, vmax=1, cmap=cmap) + ax.plot(data['m_position'], data['m_time'], color='grey') cbar = fig.colorbar(plt.cm.ScalarMappable(cmap=cmap, norm=plt.Normalize(vmin=-1, vmax=1)), ax=ax) cbar.set_label('Velocity (in units of c)') - # Draw axes of moving observer of current frame - ax.axline((frame_data()['position'], frame_data()['time']), slope=frame_data()['velocity'], color=red) - ax.axline((frame_data()['position'], frame_data()['time']), slope=np.tan(np.pi/2 - np.atan(frame_data()['velocity'])), color=red) + + frametime = input.frame() + frame_data = lambda: data.iloc[(data['m_proper_time'] - frametime).abs().argsort()[:1]].squeeze() + ax.axline((frame_data()['m_position'], frame_data()['m_time']), slope=frame_data()['m_velocity'], color=red) + ax.axline((frame_data()['m_position'], frame_data()['m_time']), slope=np.tan(np.pi/2 - np.atan(frame_data()['m_velocity'])), color=red) # Draw axes - ax.axhline(0, color=blue) + ax.axhline(frametime, color=blue) ax.axvline(0, color=blue) ax.axvline(input.turning_point(), color='grey', linestyle='--', zorder=-1) @@ -125,15 +141,22 @@ def plot(): ax.set_ylabel("ct in light-seconds") # Pad the limits a bit - xlim = ax.get_xlim() ylim = ax.get_ylim() - ax.set_xlim(xlim[0] - 1, xlim[1] + 7) + ax.set_xlim(ylim[0] - 2, ylim[1] + 2) ax.set_ylim(ylim[0] - 2, ylim[1] + 2) ax.set_aspect('equal') - for t, x, tau in zip(times_at_this_proper_time, positions_at_times, times): - ax.text(x+1, t, f'τ={tau:.0f}s', color=red, verticalalignment='center', horizontalalignment='left') - ax.scatter(x, t, color=red, marker='x') + times = ax.get_yticks() + for prefix, color in [('s', blue), ('m', red)]: + # Interpolate positions of moving observer at these times to plot self times + times_at_this_proper_time = np.interp(times, data[prefix + '_proper_time'], data[prefix + '_time'], left=np.nan, right=np.nan) + positions_at_times = np.interp(times_at_this_proper_time, data[prefix + '_time'], data[prefix + '_position'], left=np.nan, right=np.nan) + for t, x, tau in zip(times_at_this_proper_time, positions_at_times, times): + if prefix is 's': + ax.text(x, t, f'τ={tau:.0f}s ', color=color, verticalalignment='center', horizontalalignment='right',) + else: + ax.text(x, t, f' τ={tau:.0f}s', color=color, verticalalignment='center', horizontalalignment='left') + ax.scatter(x, t, color=color, marker='x') return fig From 8b471d9e1908918513ac821802add68e5c9b9945 Mon Sep 17 00:00:00 2001 From: ptuemmler Date: Sat, 22 Nov 2025 13:06:39 +0100 Subject: [PATCH 16/22] improved motion minkowski app --- docs/apps/MinkowskiSpaceTime/motion/app.py | 92 ++++++++++++---------- 1 file changed, 49 insertions(+), 43 deletions(-) diff --git a/docs/apps/MinkowskiSpaceTime/motion/app.py b/docs/apps/MinkowskiSpaceTime/motion/app.py index c6d5b6e..4a92f7d 100644 --- a/docs/apps/MinkowskiSpaceTime/motion/app.py +++ b/docs/apps/MinkowskiSpaceTime/motion/app.py @@ -12,6 +12,7 @@ app_ui = ui.page_sidebar( ui.sidebar( + ui.input_radio_buttons("frame_of_reference", "Frame of reference", choices={"rest": "rest", "motion": "motion"}, selected="rest", inline=True), ui.input_slider("frame", "Self time", min=0, max=1, value=0, step=0.5, animate=True), ui.input_slider("turning_point", "Turning point (in light-seconds)", min=1, max=20, value=10, step=0.1), ui.input_slider("acceleration", "Proper acceleration (in c/s)", min=0.01, max=0.25, value=0.15, step=0.001), @@ -30,6 +31,50 @@ width="100%", height="700px" ), ) + + +def hypTStep(dt, v0, x0, tau0, g): + ## Hyperbolic step. + ## If an object has proper acceleration g and starts at position x0 with speed v0 and proper time tau0 + ## as seen from an inertial frame, then return the new v, x, tau after time dt has elapsed. + if g == 0: + return v0, x0 + v0 * dt, tau0 + dt * (1. - v0 ** 2) ** 0.5 + + tinit = v0 / (g * (1 - v0 ** 2) ** 0.5) + B = (1 + (g ** 2 * (dt + tinit) ** 2)) ** 0.5 + + v1 = g * (dt + tinit) / B + x1 = x0 + (1.0 / g) * (B - 1. / (1. - v0 ** 2) ** 0.5) + tau1 = tau0 + (np.arcsinh(g * (dt + tinit)) - np.arcsinh(g * tinit)) / g + return v1, x1, tau1 + +def tauStep(dtau, v0, x0, t0, g): + ## linear step in proper time of clock. + ## If an object has proper acceleration g and starts at position x0 with speed v0 at time t0 + ## as seen from an inertial frame, then return the new v, x, t after proper time dtau has elapsed. + + ## Compute how much t will change given a proper-time step of dtau + gamma = (1. - v0 ** 2) ** -0.5 + if g == 0: + dt = dtau * gamma + else: + v0g = v0 * gamma + dt = (np.sinh(dtau * g + np.arcsinh(v0g)) - v0g) / g + + # return v0 + dtau * g, x0 + v0*dt, t0 + dt + v1, x1, t1 = hypTStep(dt, v0, x0, t0, g) + return v1, x1, t0 + dt + +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 + +def ceil_to_next_multiple(value, multiple): + return np.ceil(value / multiple) * multiple + def server(input, output, session): simulation_data = reactive.Value(pd.DataFrame()) @@ -74,7 +119,7 @@ def _(): return # Keep appending zeros until max_time is reached - while proper_times[-1] < max_time: + while proper_times[-1] < ceil_to_next_multiple(max_time, 5) + dtau: velocities.append(0.0) positions.append(0.0) times.append(times[-1] + dtau) @@ -98,7 +143,7 @@ def _(): 's_velocity': stationary_velocities, 's_proper_time': stationary_proper_times, }) - ui.update_slider("frame", max=np.ceil((len(data)-1) * dtau) - 1, value=0) + ui.update_slider("frame", max=ceil_to_next_multiple(max_time, 5), value=0) simulation_data.set(data) @@ -110,7 +155,7 @@ def plot(): red = 'lightcoral' cmap = berlin else: - style_label = 'seaborn-v0_8' + style_label = 'default' blue = 'navy' red = 'firebrick' cmap = 'RdBu_r' @@ -157,46 +202,7 @@ def plot(): else: ax.text(x, t, f' τ={tau:.0f}s', color=color, verticalalignment='center', horizontalalignment='left') ax.scatter(x, t, color=color, marker='x') - + ax.axis('off') return fig -def hypTStep(dt, v0, x0, tau0, g): - ## Hyperbolic step. - ## If an object has proper acceleration g and starts at position x0 with speed v0 and proper time tau0 - ## as seen from an inertial frame, then return the new v, x, tau after time dt has elapsed. - if g == 0: - return v0, x0 + v0 * dt, tau0 + dt * (1. - v0 ** 2) ** 0.5 - - tinit = v0 / (g * (1 - v0 ** 2) ** 0.5) - B = (1 + (g ** 2 * (dt + tinit) ** 2)) ** 0.5 - - v1 = g * (dt + tinit) / B - x1 = x0 + (1.0 / g) * (B - 1. / (1. - v0 ** 2) ** 0.5) - tau1 = tau0 + (np.arcsinh(g * (dt + tinit)) - np.arcsinh(g * tinit)) / g - return v1, x1, tau1 - -def tauStep(dtau, v0, x0, t0, g): - ## linear step in proper time of clock. - ## If an object has proper acceleration g and starts at position x0 with speed v0 at time t0 - ## as seen from an inertial frame, then return the new v, x, t after proper time dtau has elapsed. - - ## Compute how much t will change given a proper-time step of dtau - gamma = (1. - v0 ** 2) ** -0.5 - if g == 0: - dt = dtau * gamma - else: - v0g = v0 * gamma - dt = (np.sinh(dtau * g + np.arcsinh(v0g)) - v0g) / g - - # return v0 + dtau * g, x0 + v0*dt, t0 + dt - v1, x1, t1 = hypTStep(dt, v0, x0, t0, g) - return v1, x1, t0 + dt - -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) From cb1de1f5d4c4e89100238def74ba86950913acbc Mon Sep 17 00:00:00 2001 From: ptuemmler Date: Sat, 22 Nov 2025 14:28:49 +0100 Subject: [PATCH 17/22] improved motion minkowski app --- docs/apps/MinkowskiSpaceTime/motion/app.py | 129 +++++++++++++++------ 1 file changed, 91 insertions(+), 38 deletions(-) diff --git a/docs/apps/MinkowskiSpaceTime/motion/app.py b/docs/apps/MinkowskiSpaceTime/motion/app.py index 4a92f7d..4514fc9 100644 --- a/docs/apps/MinkowskiSpaceTime/motion/app.py +++ b/docs/apps/MinkowskiSpaceTime/motion/app.py @@ -9,6 +9,12 @@ berlin = LinearSegmentedColormap.from_list('berlin', berlin_cmap, N=256) max_iterations = 1e6 +# Generate random events for background defined in stationary frame +num_random_events = 1000 +random_generator = np.random.default_rng(42) +random_t = random_generator.uniform(-30, 200, num_random_events) +random_x = random_generator.uniform(-30, 30, num_random_events) +random_points = np.array([random_x, random_t]) app_ui = ui.page_sidebar( ui.sidebar( @@ -77,6 +83,7 @@ def ceil_to_next_multiple(value, multiple): def server(input, output, session): simulation_data = reactive.Value(pd.DataFrame()) + random_points = reactive.Value(np.array([0, 0])) @reactive.effect def _(): @@ -107,6 +114,7 @@ def _(): g = 0 # Stop acceleration at origin v_new, x_new, t_new = [0.0, 0.0, times[-1] + (dtau * (1. - velocities[-1] ** 2) ** 0.5)] max_time = t_new + ceiled_max_time = ceil_to_next_multiple(max_time, 5) velocities.append(v_new) positions.append(x_new) @@ -119,7 +127,7 @@ def _(): return # Keep appending zeros until max_time is reached - while proper_times[-1] < ceil_to_next_multiple(max_time, 5) + dtau: + while proper_times[-1] < ceiled_max_time + dtau: velocities.append(0.0) positions.append(0.0) times.append(times[-1] + dtau) @@ -143,10 +151,9 @@ def _(): 's_velocity': stationary_velocities, 's_proper_time': stationary_proper_times, }) - ui.update_slider("frame", max=ceil_to_next_multiple(max_time, 5), value=0) + ui.update_slider("frame", max=ceiled_max_time, value=0) simulation_data.set(data) - @render.plot() def plot(): if input.dark_mode() == "dark": @@ -162,47 +169,93 @@ def plot(): with plt.style.context(style_label): fig, ax = plt.subplots() - # data = simulation_data() - ax.scatter(data['m_position'], data['m_time'], c=data['m_velocity'], vmin=-1, vmax=1, cmap=cmap) - ax.plot(data['m_position'], data['m_time'], color='grey') - - cbar = fig.colorbar(plt.cm.ScalarMappable(cmap=cmap, norm=plt.Normalize(vmin=-1, vmax=1)), ax=ax) - cbar.set_label('Velocity (in units of c)') # Draw axes of moving observer of current frame - frametime = input.frame() frame_data = lambda: data.iloc[(data['m_proper_time'] - frametime).abs().argsort()[:1]].squeeze() - ax.axline((frame_data()['m_position'], frame_data()['m_time']), slope=frame_data()['m_velocity'], color=red) - ax.axline((frame_data()['m_position'], frame_data()['m_time']), slope=np.tan(np.pi/2 - np.atan(frame_data()['m_velocity'])), color=red) - - # Draw axes - ax.axhline(frametime, color=blue) - ax.axvline(0, color=blue) - ax.axvline(input.turning_point(), color='grey', linestyle='--', zorder=-1) - - ax.set_xlabel("x in light-seconds") - ax.set_ylabel("ct in light-seconds") - - # Pad the limits a bit - ylim = ax.get_ylim() - ax.set_xlim(ylim[0] - 2, ylim[1] + 2) - ax.set_ylim(ylim[0] - 2, ylim[1] + 2) - ax.set_aspect('equal') - - times = ax.get_yticks() - for prefix, color in [('s', blue), ('m', red)]: - # Interpolate positions of moving observer at these times to plot self times - times_at_this_proper_time = np.interp(times, data[prefix + '_proper_time'], data[prefix + '_time'], left=np.nan, right=np.nan) - positions_at_times = np.interp(times_at_this_proper_time, data[prefix + '_time'], data[prefix + '_position'], left=np.nan, right=np.nan) - for t, x, tau in zip(times_at_this_proper_time, positions_at_times, times): - if prefix is 's': - ax.text(x, t, f'τ={tau:.0f}s ', color=color, verticalalignment='center', horizontalalignment='right',) - else: - ax.text(x, t, f' τ={tau:.0f}s', color=color, verticalalignment='center', horizontalalignment='left') - ax.scatter(x, t, color=color, marker='x') + times = np.arange(0, ceil_to_next_multiple(data['m_proper_time'].max(), 5) + 1, 5) + + if input.frame_of_reference() == 'rest': + shift_pos, shift_time = frame_data()['s_position'], frame_data()['s_time'] + + ax.scatter(data['m_position'] - shift_pos, data['m_time'] - shift_time, c=data['m_velocity'], vmin=-1, vmax=1, cmap=cmap) + ax.plot(data['m_position'] - shift_pos, data['m_time'] - shift_time, color='grey') + ax.plot(data['s_position'] - shift_pos, data['s_time'] - shift_time, color=blue) + + cbar = fig.colorbar(plt.cm.ScalarMappable(cmap=cmap, norm=plt.Normalize(vmin=-1, vmax=1)), ax=ax) + cbar.set_label('Velocity (in units of c)') + + ax.scatter([frame_data()['m_position'] - shift_pos], [frame_data()['m_time'] - shift_time], color='grey', marker='o', zorder=5) + ax.scatter([frametime - shift_time], [0 - shift_pos], color='grey', marker='o', zorder=5) + + # # Draw axes + # ax.axline((frame_data()['m_position'] - shift_pos, frame_data()['m_time'] - shift_time), slope=frame_data()['m_velocity'], color=red) + # ax.axline((frame_data()['m_position'] - shift_pos, frame_data()['m_time'] - shift_time), slope=np.tan(np.pi/2 - np.atan(frame_data()['m_velocity'])), color=red) + # ax.axhline(frametime - shift_time, color=blue) + # ax.axvline(0 - shift_pos, color=blue) + + # ax.axvline(input.turning_point() - shift_pos, color='grey', linestyle='--', zorder=-1) + + for prefix, color in [('s', blue), ('m', red)]: + # Interpolate positions of moving observer at these times to plot self times + times_at_this_proper_time = np.interp(times, data[prefix + '_proper_time'], data[prefix + '_time'], left=np.nan, right=np.nan) + positions_at_times = np.interp(times_at_this_proper_time, data[prefix + '_time'], data[prefix + '_position'], left=np.nan, right=np.nan) + for t, x, tau in zip(times_at_this_proper_time, positions_at_times, times): + if prefix is 's': + ax.text(x - shift_pos, t - shift_time, f'τ={tau:.0f}s ', color=color, verticalalignment='center', horizontalalignment='right', clip_on=True) + else: + ax.text(x - shift_pos, t - shift_time, f' τ={tau:.0f}s', color=color, verticalalignment='center', horizontalalignment='left', clip_on=True) + ax.scatter(x - shift_pos, t - shift_time, color=color, marker='x') + + # Plot random events in background + ax.scatter(random_x - shift_pos, random_t - shift_time, color='grey', s=1, alpha=0.5, zorder=-1) + + else: # frame of reference is motion + # For this we have to Lorentz transform all points into the moving frame at the selected self time + v_frame = frame_data()['m_velocity'] + shift_pos, shift_time = frame_data()['m_position'], frame_data()['m_time'] + m_x_prime, m_t_prime = lorentz_transform(data['m_position'] - shift_pos, data['m_time'] - shift_time, -v_frame) + s_x_prime, s_t_prime = lorentz_transform(data['s_position'] - shift_pos, data['s_time'] - shift_time, -v_frame) + ax.scatter(m_x_prime, m_t_prime, c=data['m_velocity'], vmin=-1, vmax=1, cmap=cmap) + + cbar = fig.colorbar(plt.cm.ScalarMappable(cmap=cmap, norm=plt.Normalize(vmin=-1, vmax=1)), ax=ax) + cbar.set_label('Velocity (in units of c)') + ax.plot(m_x_prime, m_t_prime, color='grey') + ax.plot(s_x_prime, s_t_prime, color=blue) + + ax.scatter([0], [0], color='grey', marker='o', zorder=5) + + tmp = np.interp(frametime, data['m_proper_time'], s_t_prime, left=np.nan, right=np.nan) + ax.scatter([np.interp(tmp, s_t_prime, s_x_prime, left=np.nan, right=np.nan)], [tmp], color='grey', marker='o', zorder=5) + # # Draw axes + # ax.axhline(0, color=red) + # ax.axvline(0, color=red) + + for (pos, time, proper_time), color in [((s_x_prime, s_t_prime, data['s_proper_time']), blue), ((m_x_prime, m_t_prime, data['m_proper_time']), red)]: + # Interpolate positions of moving observer at these times to plot self times + times_at_this_proper_time = np.interp(times, proper_time, time, left=np.nan, right=np.nan) + positions_at_times = np.interp(times_at_this_proper_time, time, pos, left=np.nan, right=np.nan) + for t, x, tau in zip(times_at_this_proper_time, positions_at_times, times): + if color is blue: # Shift not needed here, as the transformed data is already centered + ax.text(x, t, f'τ={tau:.0f}s ', color=color, verticalalignment='center', horizontalalignment='right', clip_on=True) + else: + ax.text(x, t, f' τ={tau:.0f}s', color=color, verticalalignment='center', horizontalalignment='left', clip_on=True) + ax.scatter(x, t, color=color, marker='x') + + # Also transform random points + r_x_prime, r_t_prime = lorentz_transform(random_x - shift_pos, random_t - shift_time, -v_frame) + ax.scatter(r_x_prime, r_t_prime, color='grey', s=1, alpha=0.5, zorder=-1) + + if frametime == 0: + xlim = np.max([times[-1] * 0.5, input.turning_point() * 1.5]) + ax.set_xlim(-xlim, xlim) + ax.set_ylim(-5, times[-1] + 5) + else: + ax.set_xlim(-input.turning_point() * 1.3, input.turning_point() * 1.3) + ax.set_ylim(-input.turning_point() * 1.3, input.turning_point() * 1.3) ax.axis('off') + ax.set_aspect('equal') return fig app = App(app_ui, server, debug=True) From bcb58f0bccdaf84040386461c3c9d5c8baef2cd2 Mon Sep 17 00:00:00 2001 From: ptuemmler Date: Sat, 22 Nov 2025 14:51:33 +0100 Subject: [PATCH 18/22] improved motion minkowski app --- docs/apps/MinkowskiSpaceTime/motion/app.py | 25 ++++++++++++++++------ 1 file changed, 19 insertions(+), 6 deletions(-) diff --git a/docs/apps/MinkowskiSpaceTime/motion/app.py b/docs/apps/MinkowskiSpaceTime/motion/app.py index 4514fc9..4d4abd3 100644 --- a/docs/apps/MinkowskiSpaceTime/motion/app.py +++ b/docs/apps/MinkowskiSpaceTime/motion/app.py @@ -10,10 +10,16 @@ max_iterations = 1e6 # Generate random events for background defined in stationary frame -num_random_events = 1000 random_generator = np.random.default_rng(42) -random_t = random_generator.uniform(-30, 200, num_random_events) -random_x = random_generator.uniform(-30, 30, num_random_events) + +# num_random_events = int(1e3) # Reasonable for rest frame +# random_t = random_generator.uniform(-30, 200, num_random_events) +# random_x = random_generator.uniform(-30, 30, num_random_events) + + +num_random_events = int(1e6) +random_t = random_generator.uniform(-1000, 1000, num_random_events) +random_x = random_generator.uniform(-1000, 1000, num_random_events) random_points = np.array([random_x, random_t]) app_ui = ui.page_sidebar( @@ -174,6 +180,7 @@ def plot(): # Draw axes of moving observer of current frame frametime = input.frame() frame_data = lambda: data.iloc[(data['m_proper_time'] - frametime).abs().argsort()[:1]].squeeze() + v_frame = frame_data()['m_velocity'] times = np.arange(0, ceil_to_next_multiple(data['m_proper_time'].max(), 5) + 1, 5) if input.frame_of_reference() == 'rest': @@ -184,7 +191,6 @@ def plot(): ax.plot(data['s_position'] - shift_pos, data['s_time'] - shift_time, color=blue) cbar = fig.colorbar(plt.cm.ScalarMappable(cmap=cmap, norm=plt.Normalize(vmin=-1, vmax=1)), ax=ax) - cbar.set_label('Velocity (in units of c)') ax.scatter([frame_data()['m_position'] - shift_pos], [frame_data()['m_time'] - shift_time], color='grey', marker='o', zorder=5) ax.scatter([frametime - shift_time], [0 - shift_pos], color='grey', marker='o', zorder=5) @@ -213,14 +219,12 @@ def plot(): else: # frame of reference is motion # For this we have to Lorentz transform all points into the moving frame at the selected self time - v_frame = frame_data()['m_velocity'] shift_pos, shift_time = frame_data()['m_position'], frame_data()['m_time'] m_x_prime, m_t_prime = lorentz_transform(data['m_position'] - shift_pos, data['m_time'] - shift_time, -v_frame) s_x_prime, s_t_prime = lorentz_transform(data['s_position'] - shift_pos, data['s_time'] - shift_time, -v_frame) ax.scatter(m_x_prime, m_t_prime, c=data['m_velocity'], vmin=-1, vmax=1, cmap=cmap) cbar = fig.colorbar(plt.cm.ScalarMappable(cmap=cmap, norm=plt.Normalize(vmin=-1, vmax=1)), ax=ax) - cbar.set_label('Velocity (in units of c)') ax.plot(m_x_prime, m_t_prime, color='grey') ax.plot(s_x_prime, s_t_prime, color=blue) @@ -247,6 +251,15 @@ def plot(): r_x_prime, r_t_prime = lorentz_transform(random_x - shift_pos, random_t - shift_time, -v_frame) ax.scatter(r_x_prime, r_t_prime, color='grey', s=1, alpha=0.5, zorder=-1) + top_speed = np.max(np.abs(data['m_velocity'])) + cbar.ax.axhline(top_speed, color='grey', linestyle='--') + cbar.ax.text(0, top_speed, 'max ', color='grey', verticalalignment='center', horizontalalignment='right') + cbar.ax.axhline(-top_speed, color='grey', linestyle='--') + cbar.ax.text(0, -top_speed, 'max ', color='grey', verticalalignment='center', horizontalalignment='right') + cbar.ax.axhline(v_frame, color='grey') + + cbar.set_label('Velocity (in units of c)') + if frametime == 0: xlim = np.max([times[-1] * 0.5, input.turning_point() * 1.5]) ax.set_xlim(-xlim, xlim) From 23c096b27e95d4bd18eb66d4f3aa51a6b003b1f2 Mon Sep 17 00:00:00 2001 From: ptuemmler Date: Sat, 22 Nov 2025 22:19:06 +0100 Subject: [PATCH 19/22] started working on a lagrange point app --- docs/apps/LagrangianPoints/app.md | 16 +++++ docs/apps/LagrangianPoints/app.py | 69 +++++++++++++++++++++ docs/apps/LagrangianPoints/requirements.txt | 2 + docs/contributing.md | 2 +- 4 files changed, 88 insertions(+), 1 deletion(-) create mode 100644 docs/apps/LagrangianPoints/app.md create mode 100644 docs/apps/LagrangianPoints/app.py create mode 100644 docs/apps/LagrangianPoints/requirements.txt diff --git a/docs/apps/LagrangianPoints/app.md b/docs/apps/LagrangianPoints/app.md new file mode 100644 index 0000000..d1361c9 --- /dev/null +++ b/docs/apps/LagrangianPoints/app.md @@ -0,0 +1,16 @@ +--- +authors: + - ptuemmler +categories: + - Physics +tags: + - Draft +date: 2025-07-01 +hide: + - toc +--- + +# Lagrangian Points + + +{{embed_app("100%", "830px")}} diff --git a/docs/apps/LagrangianPoints/app.py b/docs/apps/LagrangianPoints/app.py new file mode 100644 index 0000000..73426cf --- /dev/null +++ b/docs/apps/LagrangianPoints/app.py @@ -0,0 +1,69 @@ +import numpy as np +import plotly.graph_objects as go +import re +from shiny import App, Inputs, Outputs, Session, render, ui, reactive + +app_ui = ui.page_sidebar( + ui.sidebar( + ui.input_slider("q", "Mass Ratio (q)", min=0.0, max=1.0, value=0.05, step=0.01), + # ui.input_slider("x", "x", min=0.0, max=2.0, value=1.0, step=0.01), + ui.input_dark_mode(id='dark_mode'), + ), + ui.output_ui("plot") +) + +def server(input: Inputs, output: Outputs, session: Session): + @render.ui + def plot(): + # Set template based on dark mode + if input.dark_mode() == "dark": + template = "plotly_dark" + else: + template = "plotly_white" + + fig = go.Figure() + # Add isosurface representing the potential field + x, y = np.meshgrid(np.linspace(-2, 2, 256), + np.linspace(-2, 2, 256)) + z = np.zeros_like(x) + + q = input.q() + # x_pos = input.x() + values = (x - q/(1+q))**2 + y**2 + 2/((1+q)*np.sqrt(x**2 + y**2 + z**2)) + 2*q/((1+q)*np.sqrt((x-1)**2 + y**2 + z**2)) + + + values -= np.min(values) + min_value = 1.5 + values[values > min_value] = np.nan # Mask values above a certain threshold + + fig.add_trace(go.Surface( + contours = { + "z": {"show": True, "start": -min_value, "end": 0.01, "size": 0.05} + }, + x=x, + y=y, + z=-values, # Offset for better visibility + colorscale='turbo', + colorbar_title_text='f(x,y)', + showscale=True, + hoverinfo='skip' + )) + + # Set layout + fig.update_layout( + template=template, + scene=dict( + xaxis_title='X-axis', + yaxis_title='Y-axis', + zaxis_title='Z-axis', + xaxis_showspikes=False, + yaxis_showspikes=False, + zaxis_showspikes=False, + ), + height=700, + margin=dict(l=0, r=0, t=0, b=0), + ) + + return ui.HTML(fig.to_html()) + +app = App(app_ui, server) diff --git a/docs/apps/LagrangianPoints/requirements.txt b/docs/apps/LagrangianPoints/requirements.txt new file mode 100644 index 0000000..51e83f6 --- /dev/null +++ b/docs/apps/LagrangianPoints/requirements.txt @@ -0,0 +1,2 @@ +numpy +plotly \ No newline at end of file diff --git a/docs/contributing.md b/docs/contributing.md index a2c5610..a9a344b 100644 --- a/docs/contributing.md +++ b/docs/contributing.md @@ -109,7 +109,7 @@ If you have multiple apps in a single tool, as is the case in the example above, To test your tool locally, you should build the full documentation using the following command in the root directory of your repository: ```bash mkdocs build --clean -python -m http.server --directory ./site --bind localhost 8008 +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/](http://[::1]:8008/) to see the documentation and test if everything works. From 95d77759decfea19b85888ca3cf43362d83bd1e5 Mon Sep 17 00:00:00 2001 From: ptuemmler Date: Sun, 23 Nov 2025 18:55:51 +0100 Subject: [PATCH 20/22] got side-tracked and added a simple orbital integrator using rk4 --- docs/apps/LagrangianPoints/app.md | 4 +- docs/apps/LagrangianPoints/app.py | 3 +- docs/apps/OrbitIntegrator/app.md | 15 + docs/apps/OrbitIntegrator/app.py | 328 +++++++++++++++++++++ docs/apps/OrbitIntegrator/requirements.txt | 2 + 5 files changed, 348 insertions(+), 4 deletions(-) create mode 100644 docs/apps/OrbitIntegrator/app.md create mode 100644 docs/apps/OrbitIntegrator/app.py create mode 100644 docs/apps/OrbitIntegrator/requirements.txt diff --git a/docs/apps/LagrangianPoints/app.md b/docs/apps/LagrangianPoints/app.md index d1361c9..c7f2569 100644 --- a/docs/apps/LagrangianPoints/app.md +++ b/docs/apps/LagrangianPoints/app.md @@ -5,12 +5,12 @@ categories: - Physics tags: - Draft -date: 2025-07-01 +date: 2025-11-23 hide: - toc --- # Lagrangian Points - {{embed_app("100%", "830px")}} +Underlying potential taken from: [https://doi.org/10.1086/381315](https://doi.org/10.1086/381315) diff --git a/docs/apps/LagrangianPoints/app.py b/docs/apps/LagrangianPoints/app.py index 73426cf..dcdd527 100644 --- a/docs/apps/LagrangianPoints/app.py +++ b/docs/apps/LagrangianPoints/app.py @@ -1,7 +1,6 @@ import numpy as np import plotly.graph_objects as go -import re -from shiny import App, Inputs, Outputs, Session, render, ui, reactive +from shiny import App, Inputs, Outputs, Session, render, ui app_ui = ui.page_sidebar( ui.sidebar( diff --git a/docs/apps/OrbitIntegrator/app.md b/docs/apps/OrbitIntegrator/app.md new file mode 100644 index 0000000..8f08461 --- /dev/null +++ b/docs/apps/OrbitIntegrator/app.md @@ -0,0 +1,15 @@ +--- +authors: + - ptuemmler +categories: + - Physics +tags: + - Draft +date: 2025-11-23 +hide: + - toc +--- + +# Oribit Integrator + +{{embed_app("100%", "830px")}} diff --git a/docs/apps/OrbitIntegrator/app.py b/docs/apps/OrbitIntegrator/app.py new file mode 100644 index 0000000..4c87712 --- /dev/null +++ b/docs/apps/OrbitIntegrator/app.py @@ -0,0 +1,328 @@ +import numpy as np +import plotly.graph_objects as go +from shiny import App, Inputs, Outputs, Session, render, ui, reactive +from copy import deepcopy + + +app_ui = ui.page_sidebar( + ui.sidebar( + ui.input_select('ref_frame', 'Reference Frame', choices=['Heliocentric', 'Geocentric'], selected='Geocentric'), + ui.input_selectize('bodies', 'Bodies to Simulate', {'Sun': 'Sun', 'Moon': 'Moon'}, + selected=['Sun', 'Earth', 'Moon'], multiple=True), + ui.input_slider('time_step', 'Time Step (hours)', min=1, max=24, value=5, step=0.01), + ui.input_slider('total_time', 'Total Simulation Time (days)', min=0, max=365, value=5, step=0.005), + ui.input_slider('max_frames', 'Maximum Animation Frames', min=100, max=10000, value=1000, step=100), + ui.input_dark_mode(id='dark_mode'), + ), + ui.output_ui("plot", height='100%') +) + +class Body: + def __init__(self, mass: float, position, velocity, name: str=None): + self.name = name + self.mass = mass + self.pos = position + self.velo = velocity + + def return_vec(self): + return np.concatenate((self.pos, self.velo)) + + +class Simulation: + def __init__(self, bodies: list[Body]): + self.calc_diff_eqs: callable = None + self.diff_eq_kwargs: dict = {} + + self.times = None + self.history = None + self.bodies = bodies + self.N_bodies = len(self.bodies) + + self.quant_vec = np.concatenate(np.array([i.return_vec() for i in self.bodies])) + self.mass_vec = np.array([i.mass for i in self.bodies]) + self.name_vec = [i.name for i in self.bodies] + + def set_diff_eq(self, calc_diff_eqs: callable, **kwargs): + """ + Method which assigns an external solver function as the diff-eq solver for RK4. + For N-body or gravitational setups, this is the function which calculates accelerations. + --------------------------------- + Params: + calc_diff_eqs: A function which returns a [y] vector for RK4 + **kwargs: Any additional inputs/hyperparameters the external function requires + """ + self.diff_eq_kwargs = kwargs + self.calc_diff_eqs = calc_diff_eqs + + def rk4(self, t:float, dt:float): + """ + RK4 integrator. Calculates the K values and returns a new y vector + -------------------------------- + Params: + t: a time. + dt: timestep. + """ + k1 = dt * self.calc_diff_eqs(t,self.quant_vec,self.mass_vec,**self.diff_eq_kwargs) + k2 = dt * self.calc_diff_eqs(t + 0.5*dt,self.quant_vec+0.5*k1,self.mass_vec,**self.diff_eq_kwargs) + k3 = dt * self.calc_diff_eqs(t + 0.5*dt,self.quant_vec+0.5*k2,self.mass_vec,**self.diff_eq_kwargs) + k4 = dt * self.calc_diff_eqs(t + dt,self.quant_vec + k2,self.mass_vec,**self.diff_eq_kwargs) + + y_new = self.quant_vec + ((k1 + 2*k2 + 2*k3 + k4) / 6.0) + + return y_new + + + def run(self, T, dt, t0=0): + """ + Method which runs the simulation on a given set of bodies. + --------------------- + Params: + T: total time (in simulation units) to run the simulation. + dt: timestep (in simulation units) to advance the simulation. + t0 (optional): set a non-zero start time to the simulation. + + Returns: + None, but leaves an attribute history accessed via + 'simulation.history' which contains all y vectors for the simulation. + These are of shape (Nstep,Nbodies * 6), so the x and y positions of particle 1 are + simulation.history[:,0], simulation.history[:,1], while the same for particle 2 are + simulation.history[:,6], simulation.history[:,7]. Velocities are also extractable. + """ + + if self.calc_diff_eqs is None: + raise AttributeError('You must set a differential equation to solve first.') + + self.history = [self.quant_vec] + nsteps = int((T - t0) / dt) + for step in range(nsteps): + y_new = self.rk4(step, dt) + self.history.append(y_new) + self.quant_vec = y_new + self.history = np.array(self.history) + self.times = np.arange(nsteps) * dt + + def translate_history_to_dict(self): + """ + Method which translates the history array into a dictionary of arrays for easier access. + ---------------------- + Params: + None + Returns: + A dictionary where each key is the name of a body, and each value is another dictionary + with keys 'pos' and 'velo' containing the position and velocity arrays over time. + """ + + if self.history is None: + raise AttributeError('You must run the simulation first.') + history_dict = {} + for i, name in enumerate(self.name_vec): + history_dict[name] = {'pos': self.history[:, i*6:i*6+3], + 'velo': self.history[:, i*6+3:i*6+6]} + return history_dict + + +grav_constant = 6.67430e-11 # m^3 kg^-1 s^-2 +def nbody_gravity(t, y, masses, progress_callback=None): + """ + y: 1D array with length 6*N in the layout [x,y,z,vx,vy,vz, x,y,z,vx,vy,vz, ...] + masses: array-like of length N + """ + + y = np.asarray(y) + masses = np.asarray(masses) + N = len(masses) + assert y.size == 6 * N, "y must have length 6*N" + + # reshape into (N,6): columns 0:3 => pos, 3:6 => vel + state = y.reshape(N, 6) + pos = state[:, 0:3] # (N,3) + vel = state[:, 3:6] # (N,3) + + # pairwise displacement: r_ij = pos[i] - pos[j] + rij = pos[:, None, :] - pos[None, :, :] # (N, N, 3) + + # distances + dist2 = np.sum(rij * rij, axis=2) # (N, N) + + # compute |r|^3 with safety for self-terms + dist3 = dist2 * np.sqrt(dist2) # (N, N) + + # avoid division by zero on diagonal by setting diagonal to inf so contribution is 0 + np.fill_diagonal(dist3, np.inf) + + # acceleration: -G * sum_j m_j * r_ij / |r_ij|^3 + # einsum sums over j: result shape (N,3) + acc = -grav_constant * np.einsum('ijk,ij->ik', rij, 1.0 / dist3 * masses[None, :]) + + # assemble derivative in same interleaved format + dydt = np.empty_like(state) + dydt[:, 0:3] = vel + dydt[:, 3:6] = acc + + if progress_callback is not None: + progress_callback(t) + + return dydt.reshape(-1) + +def server(input: Inputs, output: Outputs, session: Session): + Sun = Body(mass=1.989e30, # kg + position=np.array([0, 0, 0]), # m + velocity=np.array([0, 0, 0]), # m/s + name='Sun') + + Earth = Body(mass=5.972e24, # kg + position=np.array([1.496e11, 0., 0.]), # m + velocity=np.array([0, 29780, 0]), # m/s + name='Earth') + + Moon = Body(mass=7.347e22, # kg + position=np.array([1.496e11 + 3.844e8, 0., 0.]), # m + velocity=np.array([0, 29780 + 1022, 0]), # m/s + name='Moon') + + bodies = [Sun, Earth, Moon] + + @reactive.calc + def sim(): + with ui.Progress(min=0, max=input.total_time() * 86400) as p: + p.set(message='Solving...') + selected_bodies = input.bodies() + simulation = Simulation([Earth, *[body for body in [Sun, Earth, Moon] if body.name in selected_bodies]]) + simulation.set_diff_eq(nbody_gravity) + simulation.run(T=input.total_time() * 86400, dt=input.time_step() * 3600) + ui.notification_show("Simulation complete!", type="message") + return simulation.translate_history_to_dict() + + @render.ui + def plot(): + # Set template based on dark mode + if input.dark_mode() == "dark": + template = "plotly_dark" + else: + template = "plotly_white" + + + result = deepcopy(sim()) + if input.ref_frame() == 'Geocentric': + earth_pos = result['Earth']['pos'] + for body_name, data in result.items(): + data['pos'] = data['pos'] - earth_pos + + fig = go.Figure() + + # Initialize empty scatter for animation + for body_name, data in result.items(): + fig.add_trace(go.Scatter3d( + x=[], y=[], z=[], + mode="markers", marker=dict(size=10), name=body_name + )) # current position + + + # Create frames for animation + frames = [] + N_steps = result[body_name]['pos'].shape[0] + N_bodies = len(result.keys()) + + if N_steps > input.max_frames(): + indices = np.linspace(0, N_steps, input.max_frames(), endpoint=False).astype(int) + else: + indices = list(range(N_steps)) + + with ui.Progress(min=0, max=len(indices)) as p: + p.set(message='Creating frames...') + for k in indices: + frame_data = [] + for body_name, data in result.items(): + frame_data.append(go.Scatter3d( + x=[data['pos'][k,0]], + y=[data['pos'][k,1]], + z=[data['pos'][k,2]] + )) + frames.append(go.Frame(data=frame_data, traces=list(range(N_bodies)), name=f'frame{k}')) + p.set(k) + + fig.update(frames=frames) + + for body_name, data in result.items(): + fig.add_trace(go.Scatter3d( + x=data['pos'][:,0], + y=data['pos'][:,1], + z=data['pos'][:,2], + mode="lines", line=dict(color="grey", width=2), showlegend=False, + )) # full trajectory + + def frame_args(duration): + return { + "frame": {"duration": duration}, + "mode": "immediate", + "fromcurrent": True, + "transition": {"duration": duration, "easing": "linear"}, + } + + + sliders = [ + {"pad": {"b": 10, "t": 60}, + "len": 0.9, + "x": 0.1, + "y": 0, + + "steps": [ + {"args": [[f.name], frame_args(0)], + "label": str(k), + "method": "animate", + } for k, f in enumerate(fig.frames) + ] + } + ] + + fig.update_layout( + updatemenus = [{"buttons":[ + { + "args": [None, frame_args(50)], + "label": "Play", + "method": "animate", + }, + { + "args": [[None], frame_args(0)], + "label": "Pause", + "method": "animate", + }], + + "direction": "left", + "pad": {"r": 10, "t": 70}, + "type": "buttons", + "x": 0.1, + "y": 0, + } + ], + sliders=sliders + ) + + # Collect max x and y values for setting axis limits + max_range = 0 + for body_name, data in result.items(): + pos = data['pos'] + max_range = max(max_range, + np.max(np.abs(pos[:,0])), + np.max(np.abs(pos[:,1])), + np.max(np.abs(pos[:,2]))) + axis_limit = max_range * 1.2 + + fig.update_layout( + scene=dict( + xaxis_title='X Position (m)', + yaxis_title='Y Position (m)', + zaxis_title='Z Position (m)', + xaxis_showspikes=False, + yaxis_showspikes=False, + zaxis_showspikes=False, + xaxis=dict(range=[-axis_limit, axis_limit]), + yaxis=dict(range=[-axis_limit, axis_limit]), + ), + height=700, + template=template, + sliders = sliders + ) + return ui.HTML(fig.to_html()) + +app = App(app_ui, server) diff --git a/docs/apps/OrbitIntegrator/requirements.txt b/docs/apps/OrbitIntegrator/requirements.txt new file mode 100644 index 0000000..5c84b3c --- /dev/null +++ b/docs/apps/OrbitIntegrator/requirements.txt @@ -0,0 +1,2 @@ +numpy +plotly From 393ddb94ae6cb3cefec42f56973f22d96162b50a Mon Sep 17 00:00:00 2001 From: tuemmler Date: Mon, 24 Nov 2025 16:13:47 +0100 Subject: [PATCH 21/22] - updated xlimit --- docs/apps/MinkowskiSpaceTime/doppler/app.py | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/docs/apps/MinkowskiSpaceTime/doppler/app.py b/docs/apps/MinkowskiSpaceTime/doppler/app.py index 9d881a5..c30c753 100644 --- a/docs/apps/MinkowskiSpaceTime/doppler/app.py +++ b/docs/apps/MinkowskiSpaceTime/doppler/app.py @@ -141,6 +141,10 @@ def plot(): # else: # ax['minkowski'].text(0, time, f' τ={time:.0f}s', color=blue, verticalalignment='center', # horizontalalignment='left') + + xlims = ax['minkowski'].get_xlim() + new_lim = max(5, xlims[1]) + ax['minkowski'].set_xlim(-new_lim, new_lim) return fig From d162855ddd06031c70544d9a6c0bdf01d3a0de8e Mon Sep 17 00:00:00 2001 From: tuemmler Date: Mon, 24 Nov 2025 16:32:55 +0100 Subject: [PATCH 22/22] - added lightcones --- docs/apps/MinkowskiSpaceTime/motion/app.py | 21 +++++++++++++++++++-- 1 file changed, 19 insertions(+), 2 deletions(-) diff --git a/docs/apps/MinkowskiSpaceTime/motion/app.py b/docs/apps/MinkowskiSpaceTime/motion/app.py index 4d4abd3..f3b4173 100644 --- a/docs/apps/MinkowskiSpaceTime/motion/app.py +++ b/docs/apps/MinkowskiSpaceTime/motion/app.py @@ -28,6 +28,7 @@ ui.input_slider("frame", "Self time", min=0, max=1, value=0, step=0.5, animate=True), ui.input_slider("turning_point", "Turning point (in light-seconds)", min=1, max=20, value=10, step=0.1), ui.input_slider("acceleration", "Proper acceleration (in c/s)", min=0.01, max=0.25, value=0.15, step=0.001), + ui.input_checkbox('show_light_cones', 'Show light cones', value=True), ui.input_dark_mode(id='dark_mode'), ui.accordion( ui.accordion_panel('Advanced settings', @@ -195,6 +196,13 @@ def plot(): ax.scatter([frame_data()['m_position'] - shift_pos], [frame_data()['m_time'] - shift_time], color='grey', marker='o', zorder=5) ax.scatter([frametime - shift_time], [0 - shift_pos], color='grey', marker='o', zorder=5) + if input.show_light_cones(): + ax.axline([frame_data()['m_position'] - shift_pos, frame_data()['m_time'] - shift_time], color=red, slope=1, linestyle='--', alpha=0.5) + ax.axline([frame_data()['m_position'] - shift_pos, frame_data()['m_time'] - shift_time], color=red, slope=-1, linestyle='--', alpha=0.5) + + ax.axline([frametime - shift_time, 0 - shift_pos], color=blue, slope=1, linestyle='--', alpha=0.5) + ax.axline([frametime - shift_time, 0 - shift_pos], color=blue, slope=-1, linestyle='--', alpha=0.5) + # # Draw axes # ax.axline((frame_data()['m_position'] - shift_pos, frame_data()['m_time'] - shift_time), slope=frame_data()['m_velocity'], color=red) # ax.axline((frame_data()['m_position'] - shift_pos, frame_data()['m_time'] - shift_time), slope=np.tan(np.pi/2 - np.atan(frame_data()['m_velocity'])), color=red) @@ -229,9 +237,18 @@ def plot(): ax.plot(s_x_prime, s_t_prime, color=blue) ax.scatter([0], [0], color='grey', marker='o', zorder=5) + stationary_time = np.interp(frametime, data['m_proper_time'], s_t_prime, left=np.nan, right=np.nan) + stationary_pos = np.interp(stationary_time, s_t_prime, s_x_prime, left=np.nan, right=np.nan) + + ax.scatter([stationary_pos], [stationary_time], color='grey', marker='o', zorder=5) + + if input.show_light_cones(): + ax.axline([0, 0], color=red, slope=1, linestyle='--', alpha=0.5) + ax.axline([0, 0], color=red, slope=-1, linestyle='--', alpha=0.5) + + ax.axline([stationary_pos, stationary_time], color=blue, slope=1, linestyle='--', alpha=0.5) + ax.axline([stationary_pos, stationary_time], color=blue, slope=-1, linestyle='--', alpha=0.5) - tmp = np.interp(frametime, data['m_proper_time'], s_t_prime, left=np.nan, right=np.nan) - ax.scatter([np.interp(tmp, s_t_prime, s_x_prime, left=np.nan, right=np.nan)], [tmp], color='grey', marker='o', zorder=5) # # Draw axes # ax.axhline(0, color=red) # ax.axvline(0, color=red)