Skip to content

Instantly share code, notes, and snippets.

View thomasaarholt's full-sized avatar

Thomas Aarholt thomasaarholt

View GitHub Profile
@thomasaarholt
thomasaarholt / languages.toml
Created August 4, 2023 18:51
Helix languages.toml setup for Python with pyright, ruff and black
[[language]]
name = "python"
scope = "source.python"
injection-regex = "python"
file-types = ["py","pyi","py3","pyw",".pythonstartup",".pythonrc"]
shebangs = ["python"]
roots = [".", "pyproject.toml", "pyrightconfig.json"]
comment-token = "#"
language-servers = ["pyright", "ruff"]
indent = { tab-width = 4, unit = " " }
@thomasaarholt
thomasaarholt / plot_arc.py
Last active January 19, 2025 00:17
Create a matplotlib Arc patch to show the angle between two lines
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
Arc = matplotlib.patches.Arc
def halfangle(a, b):
"Gets the middle angle between a and b, when increasing from a to b"
if b < a:
b += 360
return (a + b)/2 % 360
@thomasaarholt
thomasaarholt / gaussian.py
Last active November 25, 2024 02:41
Fastest found numpy method of generating a 2D gaussian kernel of size n x n and standard deviation std.
import numpy as np
from scipy import signal
def gaussian_kernel(n, std, normalised=False):
'''
Generates a n x n matrix with a centered gaussian
of standard deviation std centered on it. If normalised,
its volume equals 1.'''
gaussian1D = signal.gaussian(n, std)
gaussian2D = np.outer(gaussian1D, gaussian1D)
@thomasaarholt
thomasaarholt / pymc_normal.py
Last active October 30, 2024 15:02
A rewrite of the pymc Normal class (in order to allow for static type hinting of function arguments)
# Use the pymc master branch
from collections.abc import Callable
from typing import Literal
from numpy._typing import ArrayLike
import pymc as pm
from numpy import ndarray
from pymc.distributions.shape_utils import (
Dims,
Shape,
@thomasaarholt
thomasaarholt / stash_hook.sh
Created October 29, 2024 11:23
The following code will print if you have any stashed code on a given branch. Add it to a repo's git/hooks/post-checkout to print whenever you change branch
# print stashes that exist for the currently switched-to branch
GREEN='\033[0;32m'
NC='\033[0m' # No Color
branch=$(git rev-parse --abbrev-ref HEAD)
stashes=`git stash list | grep "WIP on $branch"`
if [ "$stashes" ]
then
echo "${GREEN}You have the following stashes for this branch:"
echo "${stashes}${NC}"
@thomasaarholt
thomasaarholt / bench_list_comprehensions.py
Last active October 26, 2024 13:53
Benchmark for comparing python 3.12 and 3.13 on list comprehensions with a filter
import sys
from time import time
N_repeats = 100
def func(foo: list[int]):
return [x for x in foo if x % 2 == 0]
@thomasaarholt
thomasaarholt / Mn_whitelineratio
Created April 21, 2020 13:40 — forked from winston-song/Mn_whitelineratio
Mn L3/L2 white line ratio using gussian component plus H-S step edge
%matplotlib widget
import hyperspy.api as hs
import matplotlib.pyplot as plt
import numpy as np
ll_sum = hs.load('ll_sum.hspy')
s_sum = hs.load('s_sum.hspy')
s_sum.metadata.Acquisition_instrument.TEM.beam_energy=200
s_sum.metadata.Acquisition_instrument.TEM.convergence_angle=22.5
s_sum.metadata.Acquisition_instrument.TEM.Detector.EELS.collection_angle=37.9
@thomasaarholt
thomasaarholt / velox_k_factors.py
Created January 21, 2020 15:42
Export Velox EDS K-factors
# In Velox, choose a dataset and select all elements in the periodic table (This is a little tedious)
# From the Velox Menu, go "EDS" -> "Export Quantification Details..."
# This exports two files, one called "... Lines" and one called "... Composition". We want the former.
import pandas as pd
df = pd.read_csv(r"exported_eds_quant-Lines.csv")
DF = df.iloc[1:] # There was a single blank line in my dataset, so I get rid of it
DF.loc[:,'K-factor'] = DF['K-factor'].astype(float) # String to float on the k-factors
# Two functions that we map across the dataset to split the header into separate elements and line
def splitelement(entry):
@thomasaarholt
thomasaarholt / stash.zsh
Created March 14, 2024 18:38
A zsh function to list git stashes using fzf with a preview of the changed files for quickly identifying the relvant stash
function stash() {
# Check if stash is empty
if ! git stash list &>/dev/null; then
echo "No stashes found."
return
fi
# Fetch relative dates and messages from git stash
local relative_dates=$(git stash list --format="%ar")
local messages=$(git stash list --format="%gs" | sed 's/^On //; s/^WIP on //')
@thomasaarholt
thomasaarholt / polars_datatypes_json.py
Created December 20, 2023 14:04
Serialize and deserialize polars datatypes to json
import json
import polars as pl
def dtype_to_json(dtype: pl.DataType) -> str:
return json.dumps(str(dtype))
def json_to_dtype(json_dtype_str: str) -> pl.DataType:
from polars.datatypes.classes import ( # noqa F401
Array,