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