diff --git a/config/_default/menus.toml b/config/_default/menus.toml index 475f63126fb..bf0275b1561 100644 --- a/config/_default/menus.toml +++ b/config/_default/menus.toml @@ -8,6 +8,11 @@ url = "#about" weight = 10 +[[main]] + name = "Mind Bytes" + url = "https://blog.galactic-forensics.space/posts/" + weight = 20 + [[main]] name = "Research" url = "menu-projects/" @@ -27,12 +32,6 @@ name = "Resources" weight = 90 -[[main]] - parent = "Resources" - name = "Mind bytes" - url = "resources/mind-bytes/" - weight = 92 - [[main]] parent = "Resources" name = "Courses" diff --git a/content/resources/mind-bytes/_index.md b/content/resources/mind-bytes/_index.md deleted file mode 100644 index 4dca222986c..00000000000 --- a/content/resources/mind-bytes/_index.md +++ /dev/null @@ -1,21 +0,0 @@ ---- -title: Mind bytes - -# View. -# 1 = List -# 2 = Compact -# 3 = Card -view: 2 - -# Optional header image (relative to `static/img/` folder). -header: - caption: "" - image: "" ---- - -Here you find some randomly assorted articles, -how-tos, and tutorials for automating stuff on your computer, -evaluating data, etc. -There is / will be stuff on python, statistics, science, etc. -that you might find useful, or maybe not. Either way: -Happy browsing! diff --git a/content/resources/mind-bytes/atoms_in_sic_grain/atoms_in_sic_grain.md b/content/resources/mind-bytes/atoms_in_sic_grain/atoms_in_sic_grain.md deleted file mode 100644 index b935d751f57..00000000000 --- a/content/resources/mind-bytes/atoms_in_sic_grain/atoms_in_sic_grain.md +++ /dev/null @@ -1,133 +0,0 @@ -+++ -title = "The number of atoms in a SiC stardust grain" -date = "2022-03-26" -author = "reto" -categories = "Presolar Grains" -tags = ["Stardust", "Introduction", "Jupyter"] -+++ - - -[![Binder](https://mybinder.org/badge_logo.svg)](https://mybinder.org/v2/gh/galactic-forensics/mindbytes/HEAD?labpath=atoms_in_sic_grains%2Fatoms_in_sic_grain.ipynb) - -In this article, we will analyze how many atoms of a given trace element are in a presolar SiC grain of a given size. Furthermore, the Jupyter notebook in which this article was written is available via [`binder`](https://mybinder.org/), so you can adjust it at any point to change the calculations and adopt it to your needs. Click on the icon on top to run this notebook in [`binder`](https://mybinder.org/). Throughout this notebook we will be using SI units. - -First, let us calculate the mass of a given SiC grain. We therefore need to define its radius \\(r\\) and it's typical density \\(\\rho = 3160\\,\\)kg m\\(^{-3}\\) (according to [Wikipedia](https://en.wikipedia.org/wiki/Silicon_carbide)). Via the volume \\(V\\) for a spherical grain - -\begin{equation} - V = \frac{4}{3} \pi r^3, -\end{equation} - -we can calculate the mass of the grain as: - -\begin{equation} - m = V\rho = \frac{4}{3} \pi r^3 \rho -\end{equation} - -For a given radius, we can now write a `python` function to calculate the mass as following: - - -```python -import math - -rho = 3160 # kg / m**3 -def mass(r: float) -> float: - """Calculate mass of spherical grain with density `rho`. - - :param r: Radius in meters - - :return: Mass in kg - """ - return 4/3 * math.pi * r**3 * rho -``` - -The approximate molar mass of SiC is the molar mass of a silicon atom plus the molar mass of a carbon atom, therefore \\(M\_\\mathrm{SiC} = 40\\,\\)g mol\\(^{-1}\\). Let us assume we have some trace element, e.g., iron, given at a concentration of 10 ppm. If the concentration is by weight \\(c\_{wt}\\), we can directly calculate the mass of all the iron as: - -\begin{equation} - m_\mathrm{Fe} = c_{wt} \times m -\end{equation} - -If the concentration is given by number of atoms \\(c\_n\\), we first have to convert it first in order to calculate the mass of iron of the grain. For this, we need to know the molar mass of iron, which is approximately \\(M\_\\mathrm{Fe} = 56\\,\\)g mol\\(^{-1}\\). The mass of iron can in this case be calculated as: - -\begin{equation} - m_\mathrm{Fe} = c_n \frac{M_\mathrm{Fe}}{M_\mathrm{SiC}} \times m -\end{equation} - -Let us now calculate the mass of the species of interest with `python`: - - -```python -molar_mass_sic = 40 * 1e-3 # kg / mol - -# calculate mass of a species of interest -def mass_species(r: float, mol_mass: float, conc: float, conc_as_weight: bool) -> float: - """Calculate mass of the given species in a SiC grain. - - :param r: Radius of the SiC grain in m. - :param mol_mass: Molar mass of the species of interest in kg / mol. - :param conc: Concentration of the species of interest. - :param conc_as_weight: Is the concentration per weight (`True`) or by number (`False`). - - :return: Mass of species in kg - """ - cwt = conc if conc_as_weight else conc * mol_mass / molar_mass_sic - mass_species = cwt * mass(r) - return mass_species -``` - -Finally, we know that per mol of material, Avogadro's number \\(N\_A = 6.0221415 \\times 10^{23}\\) of atoms are present. For iron, we could therefore calculate the number of atoms as: - -\begin{equation} - n_\mathrm{Fe} = N_A \frac{m_\mathrm{Fe}}{M_\mathrm{Fe}} -\end{equation} - -Here, \\(M\_\\mathrm{Fe}\\) is again the molar mass of iron. We can now create our final function in `python`: - - -```python -n_a = 6.0221415e23 - -def number_of_atoms(r: float, mol_mass: float, conc: float, conc_as_weight: bool) -> float: - """Calculate the number of atoms for a given species in a presolar SiC grain. - - :param r: Radius of the SiC grain. - :param mol_mass: Molar mass of the species of interest in kg / mol. - :param conc: Concentration of the species of interest. - :param conc_as_weight: Is the concentration per weight (`True`) or by number (`False`). - - :return: Mass of species in kg - """ - m_species = mass_species(r, mol_mass, conc, conc_as_weight) - n_species = n_a * m_species / mol_mass - return n_species -``` - -We can now run some examples using the everything we just created. - -**Example 1:** Assume we have 10 ppm by weight of iron in a grain with 1 µm radius. We can then calculate the number of atoms as: - - -```python -r = 1e-6 -mol_mass = 56e-3 -conc = 10e-6 -conc_as_weight = True - -n_fe = number_of_atoms(r, mol_mass, conc, conc_as_weight) -print(f"Number of iron atoms per grain: {n_fe:.3e}") -``` - - Number of iron atoms per grain: 1.423e+06 - - -**Example 2:** We can perform the same calculation, assuming that the concentration is per number. Since the molar mass of iron is heavier than the molar mass of SiC, we would expect the total number of atoms to be larger than in example 1. Let's see if that is true: - - -```python -n_fe = number_of_atoms(r, mol_mass, conc, False) -print(f"Number of iron atoms per grain: {n_fe:.3e}") -``` - - Number of iron atoms per grain: 1.993e+06 - - -This simple Jupyter Notebook allows you to determine how many atoms of a species you would expect in a SiC stardust grain. If you then want to measure the atoms, you'll know what you're up against. Good luck! diff --git a/content/resources/mind-bytes/radiolab_stochasticity/radiolab_stochasticity.md b/content/resources/mind-bytes/radiolab_stochasticity/radiolab_stochasticity.md deleted file mode 100644 index 3ac0bca4079..00000000000 --- a/content/resources/mind-bytes/radiolab_stochasticity/radiolab_stochasticity.md +++ /dev/null @@ -1,160 +0,0 @@ -+++ -title = "Seven in a row" -date = "2024-03-01" -author = "reto" -categories = "Python, Probability" -tags = ["Python", "Probability", "Jupyter"] -+++ - -[![Binder](https://mybinder.org/badge_logo.svg)](https://mybinder.org/v2/gh/galactic-forensics/mindbytes/HEAD?labpath=radiolab_stochasticity%2Fradiolab_stochasticity.ipynb) - -One of my favorite radio shows is [Radiolab](https://radiolab.org/), which always presents the listener with an interesting scientific question from across the board. In a recent rerun, Radiolab discussed [Stochasticity](https://radiolab.org/podcast/91684-stochasticity/transcript). Something struck me as odd, so I decided to do some math and figure out what was going on. And of course, what is simply math without thinking about how to also do this in python! - -## Randomness - -In the episode, they present an experiment of flipping a coin one hundred times and recording the outcome on a board. One group actually flips the coin and writes the actual results down, the other group makes up the results and writes down those results. Afterwards, the examiner walks in to evaluate the results and immediately points out which one is the true random sequence. The way she discovered it is by looking at the longest streaks. The true random group had a much longer streak - a seven in a row - than the group that made the results up. - -The probability to get seven tails in a row can be calculated as - -$$p = 0.5^{7} = 0.78\%,$$ - -which is very low. However, remember that they flipped one hundred times. This - according to the episode - will increase the chance of getting seven in row to about one in six. - -## The problem - -My issue with the episode was the following dialog (transcript taken directly from [here](https://radiolab.org/podcast/91684-stochasticity/transcript): - -> JAD: And then Jay explained it to us: if you're just doing seven flips then yeah, getting seven in a row is really unlikely. But if you're doing multiple sets of seven ... -> -> JAY KOEHLER: Fourteen of those sets of seven. -> -> JAD: ... which we were, because we were doing a hundred. Then the probabilities start to add up. And we start small, like one percent. But then that one becomes two, which becomes four, which becomes eight until, when it's all said and done, the chances of getting seven tails in a row somewhere in a set of a hundred is—don't hold your breath. - -This statement didn't make much sense to me, since any seven in a row in the series of 100 flips would work and not just one of the fourteen! - -## Let's do the math - -To calculate the probability of getting seven in a row out of one hundred flips, let's first define what this even means: In order to have exactly seven in a row, the flip before and after (if we are somewhere in between flip one and flip 100) must be of the opposite side. This means that to have seven tails, the flip before and after must be heads. Therefore, we need to get in fact nine in a row correct! The probability that the first or last seven flips are of the same suit requires the flip after or before that row to be different, thus for these edge cases we only need to get eight in a row correct. - -As so often with probability calculations, let us turn the problem around and ask the question of what is the probability that the two edge cases are not seven in a row. We can calculate the edge cases as following: - -$$p_\mathrm{edge} = 1-0.5^8$$ - -For one hundred flips, to not get seven in a row at the beginning and the end, i.e., for the two edge cases, the probability then becomes: - -$$p_\mathrm{edges} = (p_\mathrm{edge})^2 = (1-0.5^8)^2$$ - -For every case in between - remember we need nine in a row correct - the probability to not have seven in a row can be calculated as: - -$$p_\mathrm{inside} = 1-0.5^9$$ - -In a series of 100, we have a total of 92 times seven flips in a row that could fit the bill, i.e., flips 2 through 8 (with 1 and 9 being of a different face), flips 3 through 9 (with 2 and 10 being of a different face), ... This gets us to a probability of not having seven in a row of the same face for the in-between cases as: - -$$p_\mathrm{inside-cases} = (1-0.5^9)^{92}$$ - -Now that we have all cases covered, we can determine the total probability of not having seven in a row as - -$$p_\mathrm{not} = p_\mathrm{edges} \cdot p_\mathrm{inside-cases} = (1-0.5^8)^2 \cdot (1-0.5^9)^{92}$$ - -Finally, we can turn this around again and determine the probability that we get at least one time seven in a row in one hundred flips as - -$$p_\mathrm{result} = 1 - p_\mathrm{not} = 17.11\%.$$ - -This is pretty close to the answer on the show of one in six, which would be around 16.67%. - -## Flipping coins in python - -Let's do a simulation of this experiment in python. We are going to simulate `nmc` times `nflips` coin flips in a row and count how many times we get at least one seven in a row. Dividing the total count by `nmc` should then give us the same result as we have determined in the calculation above. - - -```python -from numba import njit -import numpy as np - -@njit -def check_flips(all_flips: np.ndarray) -> np.ndarray: - """Count how many times we get seven in a row. - - The routine is decorated with the `@njit` decorator, which we - import from `numba`. This does a just-in-time compilation - of the function in order to speed things up. - Feel free to remove the decorator and see the difference! - - The routine is provided an array of all flips with `nmc` - rows and `nflips` columns. - - :param all_flips: An array of all flips, either 0 or 1. - Dimension: `nmc` times `nflips` - - :return: An array of length `nmc` stating how many times - seven in a row occured in this set of `nflips`. - """ - results = np.zeros(all_flips.shape[0]) - - for it, series in enumerate(all_flips): - # check first 7 - if np.sum(series[:7]) == 7 and series[7] == 0: - results[it] += 1 - - # check last 7 - if np.sum(series[-7:]) == 7 and series [-8] == 0: - results[it] += 1 - - # check all in between - for jt in range(1, nflips - 1 - 7): - if np.sum(series[jt:jt+7]) == 7: # row is 7 - # check that bounds are not 1 - if series[jt-1] == 0 and series[jt+7] == 0: - results[it] += 1 - - return results -``` - - -```python -# some starting values -nmc = 10_000_000 -nflips = 100 -``` - - -```python -# let's generate all the flips using numpy's random.randint routine -all_flips = np.random.randint(0, 2, size=(nmc, nflips)) -``` - - -```python -# get the result from our routine that we defined above -seven_in_a_row = check_flips(all_flips) -``` - - -```python -# Calculate the probability to get at least one seven in a row -prob = len(np.where(seven_in_a_row > 0)[0]) / nmc -print(f"Probability for at least one time seven in a row in {nflips} flips is {prob * 100:.2f}%.") -``` - - Probability for at least one time seven in a row in 100 flips is 17.13%. - - - -```python -# Calculate the probability to get exactly one time seven in a row -prob = len(np.where(seven_in_a_row == 1)[0]) / nmc -print(f"Probability for one time seven in a row in {nflips} flips is {prob * 100:.2f}%.") -``` - - Probability for one time seven in a row in 100 flips is 15.77%. - - -## Comparison of the results - -As you can see, we get the same result from the Monte Carlo calculation as we got from the analytical calculation. If you are interested in why we used `@njit` before the `check_flips` function, please have a look at the docstring in that function and check out [`numba`](https://numba.pydata.org/). Without this decorator, we would wait a lot longer to simulate 10 million times one hundred flips. Numba was also used in this blog post [here](https://galactic-forensics.space/resources/mind-bytes/suncrash/), where more details are given. - -Also, feel free to play with this example! Some questions you might ask: - -- How many streaks of at least seven in a row are in the set? -- How many streaks *insert you number here* are in the set? -- How well has the result converged after ten million tries? diff --git a/content/resources/mind-bytes/resources_programming/index.md b/content/resources/mind-bytes/resources_programming/index.md deleted file mode 100644 index 0031b59c52f..00000000000 --- a/content/resources/mind-bytes/resources_programming/index.md +++ /dev/null @@ -1,229 +0,0 @@ ---- -# Documentation: https://sourcethemes.com/academic/docs/managing-content/ - -title: "Resources for Programming" -subtitle: "Python and Git" -summary: "" -authors: ["reto"] -tags: ["python", "git"] -categories: ["Coding"] -date: "2022-01-25" -lastmod: "2022-01-27" -featured: false -draft: false - -# Featured image -# To use, add an image named `featured.jpg/png` to your page's folder. -# Focal points: Smart, Center, TopLeft, Top, TopRight, Left, Right, BottomLeft, Bottom, BottomRight. -image: - caption: "" - focal_point: "" - preview_only: false - -# Projects (optional). -# Associate this post with one or more of your projects. -# Simply enter your project's folder or file name without extension. -# E.g. `projects = ["internal-project"]` references `content/project/deep-learning/index.md`. -# Otherwise, set `projects = []`. -projects: [] ---- - -Sooner or later, most scientist have to automate certain tasks. -It is generally advisable to leave such repetitive things that can be -automated to the computer. Here we have a look at tools that might help with -this task. - - - -First things first: this is by no means going to be a comprehensive article, -but will rather be my own, fairly biased view, which heavily focuses on -[`python`](https://www.python.org/) and [`git`](https://git-scm.com/). -It hopefully starts simple, and then gets more advanced fast. - -## Python - -Python is a scripted computer language that allows you to do many scientific -tasks, e.g., data evaluation, automatically. It is a fairly simple language to -learn, and you can get going fast, however, be open to learn more advanced -techniques later on. This means: Never stop learning! Python has many advanced -capabilities that can make your life easier and faster. - -### Learning Python - -[Software Carpentry](https://software-carpentry.org/lessons/) has two great -lessons on `python`, which are especially suited for beginners. These lessons -should give you an introduction and overview of the language, but also teach -you how to plot figures using `matplotlib`. - -A great book to introduce you python was written by Allen Downy and can -be found [here](https://greenteapress.com/wp/think-python-2e/). It is available -for free. The book gives an in-depth introduction into `python`, but also into -the basics behind the language. Such knowledge is always helpful later on, -since it gives you a deeper understanding of certain behavior. - -### Working with Python - -The official `python` distribution is distributed from -[python.org](https://www.python.org). -If you install this distribution, you can add further packages using -[`pip`](https://pip.pypa.io/en/stable/). -However, this is not always the most straight forward way to work with `python`. - -#### Virtual environments -Virtual environments should be considered for all your projects. Depending -on what `python` environment you are using, these environments will be -created different. It is worth looking into it. - -#### Anaconda -For data processing and scientific python, check out -[Anaconda](https://www.anaconda.com/products/individual). This gives you a -`conda` environment for `python`. Furthermore, Anaconda comes with many -packages pre-installed and has a graphical manager to handle your distribution. -This can be advantageous, depending on what you need. - -#### `pyenv` -If you need to handle multiple different python versions and want -to easily manage virtual environments, check out -[`pyenv`](https://github.com/pyenv/pyenv). - -#### Jupyter -Finally, Jupyter Notebooks give a straight forward interface -to `python` that allow you to play and develop code in a browser, as well as -to document it in [Markdown](https://www.markdownguide.org/). -Googles flavor of Jupyter is called -[Google Collab](https://colab.research.google.com/) and run on the web. -JetBrains, the creator of PyCharm, also has an online Jupyter Notebook -Server with is especially great for developing at the same time. It is -called [Datalore](https://datalore.jetbrains.com/). - -For Astrophysics, especially if you are interested in -[NuGrid](https://nugrid.github.io/) data, check out the -[Astrohub](https://astrohub.uvic.ca/). You can log into the public outreach -server with your GitHub account and then use a JupyterLab environment to run -your astrophysics models. - -#### Editors -Many good python editors exist. Personally, I prefer -[PyCharm](https://www.jetbrains.com/pycharm/), however, many other options. -PyCharm is a fully integrated developer environment (IDE) and comes with many -more tools than you need in the beginning, it can therefore be overwhelming at -first. - -Other notable editors are [Spyder](https://www.spyder-ide.org/), which is a full -IDE that comes pre-installed with Anaconda. Also notable is -[Sublime Text](https://www.sublimetext.com/), which works in my workflow -especially well for scripting. -[Here](https://www.tabnine.com/blog/python-on-sublime-text/) -is a great article on how to set up Sublime Text for python. - -### GUIs - -If you are interested in creating graphical user interfaces for your programs, -it is worth looking into GUIs. Two potential GUI creation packages that you -might want to consider using are -[`PyQt`](https://www.riverbankcomputing.com/software/pyqt/intro/) or -[`PySide`](https://wiki.qt.io/PySide2). -Great tutorials on Qt can be found [here](https://www.pythonguis.com/pyqt5-tutorial/). - -If you want to package your GUIs with installers, -check out [`fbs`](https://build-system.fman.io/). Note that the open / free -version only supports `python-3.6` and is restricted to `PyQt5`. If you want -to dabble with the pro version, let me know. - - -### Advanced Python - -#### Auto-formatting -Formatting `python` code should adhere - for readability - to certain rules. -These are often also referred as linting requirements. While it is tedious to -format code by hand, automatic formatters are very helpful. I generally use -[`black`](https://github.com/psf/black) to format my `python` code. -The beauty of this is that it there are not many possibilities to format your -code, therefore, most of the decisions are already made, and it always looks -awesome. Various plugins exist that can be used in editors and IDEs. -[Search engines](https://www.duckduckgo.com) are useful to find them. - -#### Test your code! -Testing of code is crucial, since you generally want to make sure that your -scripts, functions, classes, etc., do what you want them to do. -An amazing package to test your python code is -[`pytest`](https://docs.pytest.org/en/6.2.x/). If you are interested in -learning testing with python, check out Brian Okken's book -[here](https://pythontest.com/pytest-book/). - - -## Git - -When working with code, version control should be an integral part of your -workflow. One way of controlling versions is with `git`. -The Galactic Forensics Laboratory has its `git` repositories hosted -[here on GitHub](https://github.com/galactic-forensics). Lab members get -access to all repositories of the lab. - -### Learning `git` - -The best way to learn `git` and / or to review your skill is by going through -[this course on Software Carpentry](https://swcarpentry.github.io/git-novice/). -The next step is then to use `git` and, if you want to keep your repos online, -a service such as [GitHub](https://github.com). You can also browse the `git` -book, which is available for free [here](https://git-scm.com/book/en/v2). - -The beauty of `git` is that you can most of the time go back in time if you -made a mistake. So don't worry if something happens! A good resource for -these weird cases is [Dangit Git](https://dangitgit.com/). - - -### Good practices - -If you want to contribute code to a repository of which you are not a -maintainer, you should fork the repository to your own GitHub account. -Then create a branch with an appropriate name for the feature you want to -contribute. Add your changes, push your branch to your fork, and then create -a pull request where you describe what you have changed and why. Keep it short, -but descriptive. - -Most projects, e.g., the [`iniabu`](https://github.com/galactic-forensics/iniabu) -project have a developers guide that gives you additional information on -how to contribute. For `iniabu`, you can find the guide, e.g., -[here in the docs](https://iniabu.readthedocs.io/en/latest/dev/index.html). - -### Advanced `git` and GitHub - -#### `pre-commit` - -If you are using `git` regularly, especially on public projects, `pre-commit` -can help you to automate tasks. You can install so-called `hooks` that help -you perform various tasks, e.g., formatting, etc. Check out the -[`pre-commit` website](https://pre-commit.com/). - -#### GitHub Actions - -For automatic testing on GitHub, consider using -[GitHub Actions](https://github.com/features/actions). These actions can -especially help when using continuous integration (CI). - -## Some more advanced resources - -### Code coverage - -When testing your python code, it is useful to know how many lines of your -code are actually tested by your test suite. To automate this process, -you can, e.g., use GitHub hooks for [`coveralls`](https://coveralls.io/). - -### Documentation - -Last, but surely not least, you will likely make extensive use of great -documentations that you can find online. For `python` code, automatic -documentation using your doc strings can be really helpful. One tool to do so -is [`sphinx`](https://www.sphinx-doc.org/en/master/). -This is especially powerful in combination with -[ReadTheDocs](https://readthedocs.org/), which can also be implemented with -a GitHub hook. - -### Hypermodern Python - -Finally, if you want to code in `python` using many bells and whistles, -check out the blog articles on hypermodern python by Claudio Jolowicz. -The series can be found [here](https://cjolowicz.github.io/posts/), the -first article -[here](https://cjolowicz.github.io/posts/hypermodern-python-01-setup/). \ No newline at end of file diff --git a/content/resources/mind-bytes/suncrash/featured.jpg b/content/resources/mind-bytes/suncrash/featured.jpg deleted file mode 100644 index 87e62e0b4f2..00000000000 Binary files a/content/resources/mind-bytes/suncrash/featured.jpg and /dev/null differ diff --git a/content/resources/mind-bytes/suncrash/index.md b/content/resources/mind-bytes/suncrash/index.md deleted file mode 100644 index fdb470dd006..00000000000 --- a/content/resources/mind-bytes/suncrash/index.md +++ /dev/null @@ -1,273 +0,0 @@ ---- -# Documentation: https://sourcethemes.com/academic/docs/managing-content/ - -title: "The day the Earth stood still" -subtitle: "The advantages an ease of just-in-time compilation in Python" -summary: "" -authors: ["reto"] -tags: ["python", "physics"] -categories: ["Physics", "Coding"] -date: "2023-09-06" -lastmod: "2023-09-06" -featured: false -draft: false - -# Featured image -# To use, add an image named `featured.jpg/png` to your page's folder. -# Focal points: Smart, Center, TopLeft, Top, TopRight, Left, Right, BottomLeft, Bottom, BottomRight. -image: - caption: "" - focal_point: "" - preview_only: false - -# Projects (optional). -# Associate this post with one or more of your projects. -# Simply enter your project's folder or file name without extension. -# E.g. `projects = ["internal-project"]` references `content/project/deep-learning/index.md`. -# Otherwise, set `projects = []`. -projects: [] ---- - -Assume the following thought experiment: -The Earth circling the Sun at a cozy distance of 1 AU (around 150 million km) -suddenly stands still and doesn't move anymore. -The only force left on the Earth is now the Sun's gravitational pull. -The question we want to answer here is: How long will it take for the Earth to crash into the Sun? - - - -## An analytical solution - -The Sun with mass \$m\_s\$ and the Earth with mass \$m\_e\$ are located at distance \$r\$ from each other. -In this scenario (an leaving all vector arrows away since everything takes place in one dimension here), -the gravitational force between the two bodies can be written as - -\begin{equation} - F = G \frac{m_s m_e}{r^{2}}. -\end{equation} - -The force and acceleration the Earth is feeling is - -\begin{equation} - F = m_e a -\end{equation} - -and setting both equations equal we get - -\begin{equation} - a = \ddot{r} = G \frac{m_s}{r^2}. -\end{equation} - -Note that the mass of the Earth dropped out of the equation. -We now have a differential equation that we could solve in order to determine the free fall time. -The solution when solving for the time as a function of position can be seen, -e.g., on [Wikipedia](https://en.wikipedia.org/wiki/Free_fall#Inverse-square_law_gravitational_field). - - -## Kepler's third law - -A common way to solve this problem in astronomy is -by using -[Kepler's third law](https://en.wikipedia.org/wiki/Kepler%27s_laws_of_planetary_motion) -of planetary motions, -which states that the square of a planet's orbital period -is proportional to the cube of the length of the semi-major axis of the planet's orbit. -Let us assume that the Earth's orbit is a circle -(which is close to reality). -The semi-major axis is therefore simply twice the previously defined distance \$r\$. -Furthermore, the orbital period of the Earth is 1 year (or 365.24 days). - -The free fall time \$t\$ can be calculated by imagining that the Earth travels around the Sun -in a degenerate elliptic orbit, -such that it travels radially inward towards it and then on the same line back out again. -Using Kepler's third law allows us to write the following equation: - -\begin{equation} - \frac{(2t)^2}{r^3} = \frac{p_e^2}{(2r)^3} -\end{equation} - -Here, \$p\_e\$ is the orbital period of the Earth, -i.e., 1 year. -Solving this equation for \$t\$ results in - -\begin{equation} - t = \sqrt{\frac{p_e^2}{32}} = 64.52\\,\\mathrm{d}. -\end{equation} - - -## A numerical solution - -If we do not know about Kepler's third law and do not want to solve the differential equation, -we can still solve this problem numerically. -The difficulty we need to keep in mind is that the acceleration of Earth is not constant -but depends on the distance \$r\$. -We can split the distance between the Sun and the Earth into small segments \$dr\$. -Within such a segment, we can assume that the acceleration is constant. -This allows us to apply the equation for distance traveled under constant acceleration: - -\begin{equation} - dr = \frac{a}{2} dt^2 + v_0 dt -\end{equation} - -Here, \$v\_0\$ is the initial velocity of the Earth at the beginning of the segment under consideration -and is zero for the first step (see the title of this post). -The time it takes to traverse segment \$dr\$ is \$dt\$. -Rewriting above equation and solving for the time \$dt\$ results in - -\begin{align} - \frac{a}{2} dt^2 + v_0 dt - dr &= 0 \\\\ - dt_{1,2} &= \frac{-v_0 \pm \sqrt{v_0^2 + 2 a dr}}{a}. -\end{align} - -Clearly, only the positive solution is of interest here -since it is the only one that results in a positive time \$t\$. - -To calculate the time it takes for the Earth to crash into the Sun -we can now simply sum over all segments \$dr_i\$, -calculate the time \$dt_i\$ it takes to cross segment \$i\$, -and then calculate the total time \$t\$ as: - -\begin{equation} - t = \sum dt_i. -\end{equation} - -### An implementation in Python - -The following Python code implements this algorithm: - -```python -import time - -import numpy as np - -# Constants -GRAV = 6.67408e-11 # m^3 kg^-1 s^-2 -M_SUN = 1.98847e30 # kg -R_START = 1.495979e11 # m - -# Step size -dr = 1e3 # m - -def total_time(dr): - # Initial conditions - t_total = 0 # s: total time - v_curr = 0 # m/s: initial velocity - r_curr = R_START # m: initial distance - - # Calculate time until Earth crashes into the Sun - while r_curr > 0: - # Calculate acceleration - a_curr = GRAV * M_SUN / r_curr**2 - - # Calculate time it takes to travel dr - t_curr = (-v_curr + np.sqrt(v_curr**2 + 2 * a_curr * dr)) / a_curr - - # Update total time - t_total += t_curr - - # Update velocity - v_curr += a_curr * t_curr - - # Update distance - r_curr -= dr - - return t_total - -# Print result - -tic = time.time() -t_total = total_time(dr) -toc = time.time() -print(f"Time until Earth crashes into the Sun: {t_total / 3600 / 24:.2f} days") -print(f"Computation time: {toc - tic:.2f} seconds") -``` - -Here we wrote the actual calculation into a little function, -which makes it easier to time it. -Running this routine on my computer results in the following output: - -``` -Time until Earth crashes into the Sun: 64.57 days -Computation time: 136.57 seconds -``` - -While we get the correct answer, -the computation time is over two minutes. -Let's see if we can speed this up a bit. - - -### A faster implementation in Python using [`numba`](https://numba.pydata.org/) - -The -[`numba`](https://numba.pydata.org/) -package allows us to take the function `total_time(dr)` -and compile it to machine code before running it. -Here, just-in-time compilation is used, -which means that the compilation happens at runtime when the function is used for the first time. - -The only thing we need to change is to import the package -and add a decorator to the function: - -```python -... - -from numba import njit - -... - -@njit -def total_time(dr): - ... -``` - -Three dots in above example indicate that the rest of the code is unchanged. -Running the code again results in the following output: - -``` -Time until Earth crashes into the Sun: 64.57 days -Computation time: 1.84 seconds -``` - -The computation time is now only 1.84 seconds, -which is a speedup of a factor of 74! - -We can ask the question how long it actually took to compile the function. -To find out, we can simply run the calculation twice and only measure the time for the second run: -The output from this is: - -``` -Time until Earth crashes into the Sun: 64.57 days -Computation time: 1.57 seconds -``` - -Just-in-time compilation thus took around 250 ms. - -### A comparison with Rust - -Just as a comparison, here is the output when implementing the same algorithm in Rust -and building the code with the `--release` flag: - - -``` -Time until Earth crashes into the Sun: 64.56 days -Computation time: 1.58s. -``` - -The computation time is basically identical to the -[`numba`](https://numba.pydata.org/) -implementation in Python. - -This clearly shows the power of -[`numba`](https://numba.pydata.org/) -and just-in-time compilation. - -### Source code - -The final python and Rust source code can be found -[here on GitHub](https://gist.github.com/trappitsch/35d04ef43a8a53a2bd9ea513032da61a). - - -### Resources - -- [Website for `numba`](https://numba.pydata.org/) -- [Documentation for `numba`](https://numba.readthedocs.io/en/stable/user/index.html) \ No newline at end of file diff --git a/content/resources/mind-bytes/writing_abstract/featured.jpg b/content/resources/mind-bytes/writing_abstract/featured.jpg deleted file mode 100644 index 6fe5fb5363c..00000000000 Binary files a/content/resources/mind-bytes/writing_abstract/featured.jpg and /dev/null differ diff --git a/content/resources/mind-bytes/writing_abstract/index.md b/content/resources/mind-bytes/writing_abstract/index.md deleted file mode 100644 index 62fa829cc73..00000000000 --- a/content/resources/mind-bytes/writing_abstract/index.md +++ /dev/null @@ -1,79 +0,0 @@ ---- -# Documentation: https://sourcethemes.com/academic/docs/managing-content/ - -title: "Writing an Abstract" -# subtitle: "" -summary: "" -authors: ["reto"] -tags: ["writing"] -categories: ["Writing"] -date: "2023-11-23" -lastmod: "2023-11-23" -featured: false -draft: false - -# Featured image -# To use, add an image named `featured.jpg/png` to your page's folder. -# Focal points: Smart, Center, TopLeft, Top, TopRight, Left, Right, BottomLeft, Bottom, BottomRight. -image: - caption: "Credit: picjumbo.com via [Pexels](https://www.pexels.com/photo/person-holding-blue-ballpoint-pen-writing-in-notebook-210661/)." - focal_point: "" - preview_only: false - -# Projects (optional). -# Associate this post with one or more of your projects. -# Simply enter your project's folder or file name without extension. -# E.g. `projects = ["internal-project"]` references `content/project/deep-learning/index.md`. -# Otherwise, set `projects = []`. -projects: [] ---- - -Writing is an important part of everybody's scientific work -since we all like to share our findings and discoveries. -I have taken several writing courses over the years. -My approach to writing has thus been by these courses, -plus some of my own experiences. -Is it great now? Surely not, but better than it used to be! -No approach works for everybody. -However, I hope that you might find some interesting things -in my opinion on how to write an abstract. - - - -## The abstract - -The abstract of a paper is the first exposure a reader usually has with the manuscript. -It often decides if the reader keeps on reading or simply gives up. -The abstract thus should convey a very brief summary of the paper -and point out the major findings. - -## Structure - -In my opinionk, an ideal abstract structure is as following: - -| Part | Content | Description | -|----------|-------------|-----------------------------------------------------------------------------| -| Foreword | Context | Optional: Show the importance, discuss the missing part of the puzzle | -| | Need | Why is what we do important | -| | Tasks | What was undertaken in order to fulfill the described need | -| Summary | Findings | What did we find, what are the major takeaways | -| | Conclusion | What are the conclusions of this work | -| | Perspective | Optional: Beyond this work, what are the limitations, potential future work | - -The first and last parts (context and perspective) -will be very dependent on the topic you are writing about -and might not be necessary. - -## Who is the abstract for? - -The abstract is literally for everybody! -It is what people read, expert might go on to read the full paper, -but most people are happy with the abstract. -Therefore, it is important that you bring your message across. - - - -## Resources - -- The course and book I was referring to that most of this is described in can be found [here](https://principiae.be/X0100.php). -- Another fantastic resource is the book ["How to Write and Publish a Scientific Paper"](https://www.cambridge.org/us/universitypress/subjects/general-science/science-handbooks/how-write-and-publish-scientific-paper-8th-edition). All parts are highly digestable and can be read very selectively. Plus, there are many more things in there on how to write letters of recommendations, applications, etc. diff --git a/content/resources/presentations/2024-07-10-Python_Packaging/index.html b/content/resources/presentations/2024-07-10-Python_Packaging/index.html new file mode 100644 index 00000000000..98a43535bce --- /dev/null +++ b/content/resources/presentations/2024-07-10-Python_Packaging/index.html @@ -0,0 +1,17 @@ +Packaging Python CLIs and GUIs for air-gapped computers
+

Python is an amazing language when it comes to rapidly developing instrument control or data evaluation programs. However, when you want to package your program such that it can run on an air-gapped computer, the situation becomes a bit more tricky. In this very brief talk I give an overview of what tools are available and talk in more detail about PyApp and box, two tools that might can help with these tasks.

+
+
\ No newline at end of file diff --git a/content/resources/presentations/2024-07-10-Python_Packaging/python_packaging.pdf b/content/resources/presentations/2024-07-10-Python_Packaging/python_packaging.pdf new file mode 100644 index 00000000000..fad2966349e Binary files /dev/null and b/content/resources/presentations/2024-07-10-Python_Packaging/python_packaging.pdf differ