Render all notebooks

This commit is contained in:
Rahix 2025-09-10 07:05:35 +02:00
parent 47c001529a
commit 3f862231b5
14 changed files with 632 additions and 0 deletions

View file

@ -0,0 +1,25 @@
```python
from pint import UnitRegistry
unit = UnitRegistry()
unit.formatter.default_format = "~"
preload_m4 = 3000 * unit.N
n_screws = 4 # 2 on each side
friction_coeff = 0.21 # Al on Al
safety_factor = 1.5
max_load = preload_m4 * friction_coeff * n_screws / safety_factor / unit.standard_gravity
max_load.to(unit.kg)
```
171.312323780292 kg
```python
```

View file

@ -0,0 +1,139 @@
```python
import magpylib as magpy
from scipy.spatial.transform import Rotation as R
import pyvista as pv
import numpy as np
# Creation of our magnets including place and orientation in the space (all dimensions guessed, need to put in correct ones)
# magnetic polarization of 1.5 T pointing in x-direction
# Dimensions assumed are 0.5, 1.5 and 3 cm (x,y,z)
# Question: Is there a more elegant way to do this? Should I make a for-loop for creating our magnet array?
magnet1 = magpy.magnet.Cuboid(polarization=(1.5, 0, 0), dimension=(0.005, 0.015, 0.03))
magnet1.position = (0, 0, 0)
magnet1.orientation = R.from_euler("y", 90, degrees=True)
magnet2 = magpy.magnet.Cuboid(polarization=(1.5, 0, 0), dimension=(0.005, 0.015, 0.03))
magnet2.position = (0.04, 0, 0)
magnet2.orientation = R.from_euler("y", 90, degrees=True)
magnet3 = magpy.magnet.Cuboid(polarization=(1.5, 0, 0), dimension=(0.005, 0.015, 0.03))
magnet3.position = (0, 0.04, 0)
magnet3.orientation = R.from_euler("y", 90, degrees=True)
magnet4 = magpy.magnet.Cuboid(polarization=(1.5, 0, 0), dimension=(0.005, 0.015, 0.03))
magnet4.position = (0.04, 0.04, 0)
magnet4.orientation = R.from_euler("y", 90, degrees=True)
magnet5 = magpy.magnet.Cuboid(polarization=(1.5, 0, 0), dimension=(0.005, 0.015, 0.03))
magnet5.position = (0, 0.08, 0)
magnet5.orientation = R.from_euler("y", 90, degrees=True)
magnet6 = magpy.magnet.Cuboid(polarization=(1.5, 0, 0), dimension=(0.005, 0.015, 0.03))
magnet6.position = (0.04, 0.08, 0)
magnet6.orientation = R.from_euler("y", 90, degrees=True)
magnet7 = magpy.magnet.Cuboid(polarization=(1.5, 0, 0), dimension=(0.005, 0.015, 0.03))
magnet7.position = (0, 0.12, 0)
magnet7.orientation = R.from_euler("y", 90, degrees=True)
magnet8 = magpy.magnet.Cuboid(polarization=(1.5, 0, 0), dimension=(0.005, 0.015, 0.03))
magnet8.position = (0.04, 0.12, 0)
magnet8.orientation = R.from_euler("y", 90, degrees=True)
# Grouping the magnets to collection
coll = magpy.Collection(magnet1, magnet2, magnet3, magnet4, magnet5, magnet6, magnet7, magnet8)
# Plotting the magnet array
magpy.show(coll, backend="plotly")
```
```python
# Just for visualization: Showing the magnetic field vectors in 3D
spacing = np.array([0.003, 0.003, 0.003]) # defines the grid where the magnetic field is calculated
# The following is for getting the right dimensions and position of the grid
magnets = [magnet1, magnet2, magnet3, magnet4, magnet5, magnet6, magnet7, magnet8]
all_mins = []
all_maxs = []
for m in magnets:
pos = np.array(m.position)
dim = np.array(m.dimension) / 2
all_mins.append(pos - dim)
all_maxs.append(pos + dim)
global_min = np.min(all_mins, axis=0) - 0.02 # add 2cm as buffer
global_max = np.max(all_maxs, axis=0) + 0.02
dimensions = ((global_max - global_min) / spacing).astype(int)
grid = pv.ImageData(
spacing=tuple(spacing),
dimensions=tuple(dimensions),
origin=(-0.02, -0.02, -0.02),
)
# Calculation of the B-field in mT
grid["B"] = coll.getB(grid.points) * 1000
pl = pv.Plotter()
pl.add_mesh(grid.outline(), color="blue", line_width=1)
pl.add_points(grid.points, render_points_as_spheres=True, point_size=2, color='black')
# Add magnetic field vectors as arrows (glyphs)
pl.add_mesh(
grid.glyph(orient="B", scale=True, factor=0.00001), # use "B" vectors, scaling according to field strength, factor to make arrows smaller for visibility
color="blue",
label="Magnetic field vectors"
)
magpy.show(coll, canvas=pl, units_length="m", backend="pyvista")
pl.show()
```
Widget(value='<iframe src="http://localhost:40551/index.html?ui=P_0x7d5c280f7fa0_15&reconnect=auto" class="pyv…
```python
# Introducing the aluminium plate
z_position=0.01 # z_position = distance to the magnets (put in real number here!)
plate_center = [0, 0, z_position]
plate_size = [0.15, 0.40, 0.005] # [b,l, h]
plate = pv.Box(bounds=(
plate_center[0] - plate_size[0]/2, plate_center[0] + plate_size[0]/2,
plate_center[1] - plate_size[1]/2, plate_center[1] + plate_size[1]/2,
plate_center[2] - plate_size[2]/2, plate_center[2] + plate_size[2]/2
))
pl.add_mesh(plate, color="silver", opacity=0.5, label="Aluminum plate")
pl.show()
```
A view with name (P_0x7d5c280f7fa0_15) is already registered
=> returning previous one
Widget(value='<iframe src="http://localhost:40551/index.html?ui=P_0x7d5c280f7fa0_15&reconnect=auto" class="pyv…
```python
```

View file

@ -0,0 +1,132 @@
```python
import imageio.v2 as imageio
import matplotlib.pyplot as plt
import numpy as np
from scipy import ndimage
# sensor horizontal size
sensor_width = 7.75
# image file
laser = imageio.imread("laser-img/2025-09-07-012621-2mm-aperture.jpg")
```
```python
dimensions = np.array([sensor_width * laser.shape[0] / laser.shape[1], sensor_width])
half_size = dimensions / 2
# Mean of all color channels as an approximation of the monochrome image
laser_monochrome = np.mean(laser, axis=2)
# Normalized intensity map
intensity_map = laser_monochrome / np.max(laser_monochrome)
# Summed intensity in each axis
intensity_x = np.sum(laser_monochrome, axis=0)
intensity_y = np.sum(laser_monochrome, axis=1)
# Center of mass of the laser beam
center = (
(ndimage.center_of_mass(laser_monochrome) / np.array(laser_monochrome.shape) - 0.5)
* dimensions
* [-1, 1]
)
print(f"Center of the beam is at {center[0]:.3f}/{center[1]:.3f}")
# Calculate FWHM in each axis
def fwhm(curve, width):
assert curve.ndim == 1
half_max = (np.max(curve) + np.min(curve)) / 2
diff = curve - half_max
indices = np.where(diff > 0)[0]
return (indices[-1] - indices[0]) / curve.size * width
fwhm_y = fwhm(intensity_y, dimensions[0])
fwhm_x = fwhm(intensity_x, dimensions[1])
print(f"FWHM in X/Y: {fwhm_x:.2f}/{fwhm_y:.2f}")
eccentricity = np.sqrt(1 - (min(fwhm_y, fwhm_x) ** 2 / max(fwhm_y, fwhm_x) ** 2))
print(f"Eccentricity (along cartesian axes): {eccentricity:.5f}")
```
Center of the beam is at -0.088/0.238
FWHM in X/Y: 2.16/1.46
Eccentricity (along cartesian axes): 0.73687
```python
with plt.style.context("dark_background"):
fig, ax = plt.subplots(figsize=(14, 14))
im = ax.imshow(
intensity_map,
cmap="magma",
extent=(-half_size[1], half_size[1], -half_size[0], half_size[0]),
interpolation="none",
vmin=0,
)
ax.set_xlim(-np.max(half_size), np.max(half_size))
ax.set_ylim(-np.max(half_size), np.max(half_size))
xy_scale = max(np.max(intensity_x), np.max(intensity_y))
ax.plot(
np.linspace(-half_size[1], half_size[1], intensity_x.size),
intensity_x / xy_scale - np.max(half_size),
color="red",
)
ax.plot(
intensity_y / xy_scale - np.max(half_size),
np.linspace(half_size[0], -half_size[0], intensity_y.size),
color="red",
)
# reticle
ax.axvline(x=center[1], color="white", linestyle=":")
ax.axhline(y=center[0], color="white", linestyle=":")
ax.axvline(x=center[1] - fwhm_x / 2, color="gray", linestyle=":")
ax.axvline(x=center[1] + fwhm_x / 2, color="gray", linestyle=":")
ax.axhline(y=center[0] - fwhm_y / 2, color="gray", linestyle=":")
ax.axhline(y=center[0] + fwhm_y / 2, color="gray", linestyle=":")
cax = fig.add_axes(
[
ax.get_position().x1 + 0.01,
ax.get_position().y0,
0.02,
ax.get_position().height,
]
)
fig.colorbar(im, cax=cax)
text = (
f"FWHM X/Y: {fwhm_x:.2f} mm/{fwhm_y:.2f} mm\n"
f"Eccentricity: {eccentricity:.5f}\n"
f"Offset X/Y: {center[1]:+.3f} mm/{center[0]:+.3f} mm"
)
fig.text(0.5, 0.05, text, ha="center")
fig
```
![png](Laserbeam_files/Laserbeam_2_0.png)
![png](Laserbeam_files/Laserbeam_2_1.png)
```python
```

BIN
Calculations/rendered/Laserbeam_files/Laserbeam_2_0.png (Stored with Git LFS) Normal file

Binary file not shown.

BIN
Calculations/rendered/Laserbeam_files/Laserbeam_2_1.png (Stored with Git LFS) Normal file

Binary file not shown.

View file

@ -0,0 +1,52 @@
```python
import matplotlib.pyplot as plt
import numpy as np
from pint import UnitRegistry
unit = UnitRegistry()
unit.formatter.default_format = "~"
unit.setup_matplotlib()
gain_first_stage = 10e6 * unit.V / unit.A
gain_second_stage = 100e3 / 1e3
tunnel_current_in = np.linspace(1e-12, 10e-9, 100) * unit.A
volts_out = tunnel_current_in * gain_first_stage * gain_second_stage
plt.xscale("log")
plt.plot(tunnel_current_in, volts_out)
xticks = [1e-12, 10e-12, 100e-12, 1e-9, 10e-9] * unit.A
plt.xticks(xticks, [f'{t.to("nA"):.3f~}' for t in xticks], minor=False)
plt.xlabel("Tunneling Current")
plt.yscale("log")
yticks = [0.001, 0.010, 0.1, 1.0, 5] * unit.V
plt.yticks(yticks, [f'{t.to("V"):.3f~}' for t in yticks], minor=False)
plt.ylabel("Preamp Voltage")
plt.grid(True, "both")
```
![png](Preamp-Current_files/Preamp-Current_0_0.png)
```python
v = 0.359 * unit.V
a = v / (gain_first_stage * gain_second_stage)
a.to("pA")
```
359.0 pA
```python
```

Binary file not shown.

View file

@ -0,0 +1,138 @@
```python
import math
import numpy as np
from pint import UnitRegistry
unit = UnitRegistry()
unit.formatter.default_format = "~"
# Parameters
spring_constant = 1.1 * 4 * unit.N / unit.mm
spring_length_resting = 112 * unit.mm
weight_total = 14 * unit.kg
dampening = 1 * unit.N / (unit.m / unit.s)
def spring_length_at(weight):
return (weight * unit.standard_gravity / spring_constant + spring_length_resting).to(unit.mm)
def resonant_freq_at(weight):
return (1 / (2 * math.pi) * np.sqrt(spring_constant / weight)).to(unit.Hz)
spring_length = spring_length_at(weight_total)
f0 = resonant_freq_at(weight_total)
print(f"Length: {spring_length:~.1f}")
print(f"Freq: {f0:~.3f}")
```
Length: 143.2 mm
Freq: 2.822 Hz
```python
def lehr_dampening_factor(d, k, m):
return d / (2 * np.sqrt(m * k))
lehr_dampening = lehr_dampening_factor(dampening, spring_constant, weight_total)
lehr_dampening.ito_reduced_units()
lehr_dampening
```
0.00201455741006345
```python
def amplitude_ratio(lehr, f0, f):
eta = f / f0
return 1 / np.sqrt((1 - eta**2)**2 + (2 * eta * lehr)**2)
f_in = np.geomspace(0.5, 90, 100) * unit.Hz
ratio = amplitude_ratio(lehr_dampening, f0, f_in)
import matplotlib.pyplot as plt
plt.plot(f_in, ratio)
def transmissibility_plot_setup(plt):
plt.xscale('log')
xticks = [1, 3, 10, 50]
plt.xticks(xticks, [f"{t} Hz" for t in xticks], minor=False)
plt.xlabel("Excitation Frequency")
plt.ylim(0.001, 10)
plt.yscale('log')
plt.ylabel("Transmissibility Ratio")
plt.grid(True, "both")
transmissibility_plot_setup(plt)
```
/usr/lib/python3.13/site-packages/matplotlib/cbook.py:1355: UnitStrippedWarning: The unit of the quantity is stripped when downcasting to ndarray.
return np.asarray(x, float)
![png](Spring-Dimensioning_files/Spring-Dimensioning_2_1.png)
```python
def ratio_for_dkm(d, k, m, f_in):
f0 = (1 / (2 * math.pi) * np.sqrt(k / m)).to(unit.Hz)
lehr = lehr_dampening_factor(d, k, m)
return amplitude_ratio(lehr, f0, f_in)
d = dampening
k = [
spring_constant,
spring_constant / 4,
]
m = [
weight_total,
24 * unit.kg,
]
import matplotlib.pyplot as plt
for k_ in k:
m_ = m[0]
plt.plot(f_in, ratio_for_dkm(d, k_, m_, f_in), label=f"{k_:~.1f}, {m_:~.1f}")
for m_ in m[1:]:
k_ = k[0]
plt.plot(f_in, ratio_for_dkm(d, k_, m_, f_in), label=f"{k_:~.1f}, {m_:~.1f}")
ref_thorlabs_f = [3, 4, 4.42, 5, 6, 7, 8, 9, 10, 40]
ref_thorlabs_r = [2, 5, 15.0, 4, 1.5, 0.7, 0.5, 0.35, 0.28, 0.018]
plt.plot(ref_thorlabs_f, ref_thorlabs_r, label="Thorlabs PTP702 (Passive)")
ref_thorlabs_f = [1, 1.35, 2, 3, 5, 9, 20, 27, 30]
ref_thorlabs_r = [2, 3, 0.9, 0.3, 0.1, 0.02, 0.009, 0.007, 0.0023]
plt.plot(ref_thorlabs_f, ref_thorlabs_r, label="Thorlabs PTS601 (Active)")
plt.legend(loc="upper right")
transmissibility_plot_setup(plt)
```
/usr/lib/python3.13/site-packages/matplotlib/cbook.py:1355: UnitStrippedWarning: The unit of the quantity is stripped when downcasting to ndarray.
return np.asarray(x, float)
![png](Spring-Dimensioning_files/Spring-Dimensioning_3_1.png)
```python
```

Binary file not shown.

Binary file not shown.

View file

@ -0,0 +1,72 @@
```python
import matplotlib.pyplot as plt
import numpy as np
from pint import UnitRegistry
# Set up unit system
unit = UnitRegistry()
unit.formatter.default_format = "~"
unit.setup_matplotlib()
# Physical constants
e=-1.602176634e-19 * unit.C # electron charge
m=9.109e-31 * unit.kg # electron mass
hbar=6.62607015e-34/2/np.pi * unit.joule * unit.second # Planck constant
phi=4 * unit.eV # Work function (see table)
phi_joule=phi.to("joule")
U=5 *unit.V
# Table working functions different metals
# Metal F(eV)
# (Work Function)
# Ag (silver) 4.26
# Al (aluminum) 4.28
# Au (gold) 5.1
# Cs (cesium) 2.14
# Cu (copper) 4.65
# Li (lithium) 2.9
# Pb (lead) 4.25
# Sn (tin) 4.42
# Chromium 4.6
# Molybdenum 4.37
# Stainless Steel 4.4
# Gold 4.8
# Tungsten 4.5
# Copper 4.5
# Nickel 4.6
# Distance range
Distance_tip_sample=np.linspace(10e-13,2e-10,100)* unit.m
Tunneling_current=U*np.exp(-2*np.sqrt(2*m*phi_joule)/hbar*Distance_tip_sample) /unit.V #please note: This is not the tunneling current as this formular gives just the proportionality. Calculating the current constant is difficult as there are for us unknown parameters
Distance_tip_sample_nm=Distance_tip_sample.to("nm")
plt.plot(Distance_tip_sample_nm, Tunneling_current)
plt.xlabel(f"Distance tip sample [{Distance_tip_sample_nm.units:~P}]")
plt.ylabel(f"Tunneling-Proportionality [arb. Unit]")
plt.xticks(ticks=np.linspace(0, 0.2, 5), labels=[f"{x:.2f}" for x in np.linspace(0, 0.2, 5)])
#plt.yscale("log")
```
([<matplotlib.axis.XTick at 0x7e10b04929b0>,
<matplotlib.axis.XTick at 0x7e10b04b0310>,
<matplotlib.axis.XTick at 0x7e10b034ba60>,
<matplotlib.axis.XTick at 0x7e10b0328670>,
<matplotlib.axis.XTick at 0x7e10b0329360>],
[Text(0.0, 0, '0.00'),
Text(0.05, 0, '0.05'),
Text(0.1, 0, '0.10'),
Text(0.15000000000000002, 0, '0.15'),
Text(0.2, 0, '0.20')])
![png](Tunneling-Current-Distance_files/Tunneling-Current-Distance_0_1.png)