diff --git a/.github/workflows/sphinx.yml b/.github/workflows/sphinx.yml new file mode 100644 index 0000000..212d44f --- /dev/null +++ b/.github/workflows/sphinx.yml @@ -0,0 +1,29 @@ +name: documentation + +on: [push, pull_request, workflow_dispatch] + +permissions: + contents: write + +jobs: + docs: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4.2.2 + - uses: actions/setup-python@v5.4.0 + with: + python-version: '3.12' + - name: Install dependencies + run: pip install -r docs/requirements.txt + - name: Sphinx build + run: sphinx-build -W docs/source docs/build/html + - name: Create .nojekyll file + run: touch docs/build/html/.nojekyll + - name: Deploy to GitHub Pages + uses: peaceiris/actions-gh-pages@v4 + # only the default branch publishes: a force-orphan push from a feature branch would replace the site + if: ${{ github.event_name == 'push' && github.ref == 'refs/heads/5.3.x' }} + with: + github_token: ${{ secrets.GITHUB_TOKEN }} + publish_dir: docs/build/html + force_orphan: true diff --git a/README.rst b/README.rst index 03901ec..52f4ffb 100644 --- a/README.rst +++ b/README.rst @@ -29,11 +29,16 @@ Actuators * **Current**: current of the electromagnet, through a National Instruments analog output (needs ``pymodaq_plugins_daqmx``) * **CurrentMock**: simulated version of the above, with a magnetic hysteresis * **LedDC4104**: Thorlabs DC4104 four-channel LED driver of the Kerr microscope +* **MokeMagnetSim**: simulated electromagnet (field in mT, first order response), see *Simulated MOKE bench* below +* **MokeWavePlateSim**: simulated half-wave plate rotation mount (balance of the detection) +* **MokeSampleRotationSim**: simulated rotation of the sample about its normal +* **MokeGoniometerSim**: simulated angle of incidence Viewer0D ++++++++ * **ReadCurrent**: reads the electromagnet current on a National Instruments analog input +* **MokeBalancedSim**: simulated balanced detection (two photodiodes), see *Simulated MOKE bench* below Viewer1D ++++++++ @@ -53,6 +58,42 @@ Extensions * **MicroMOKE**: acquisition of Kerr microscope images with the sequence of LED illuminations +Simulated MOKE bench +==================== + +``MokeMagnetSim``, ``MokeWavePlateSim``, ``MokeSampleRotationSim``, ``MokeGoniometerSim`` and ``MokeBalancedSim`` simulate +a MOKE bench with balanced detection, to develop and test acquisitions, scans and extensions without hardware. +The five plugins share one simulated bench through the controller: give them the same *controller ID* in the Dashboard, +one as ``Master`` (it creates the bench) and the others as ``Slave``. A plugin alone works as a master on its own bench. + +* The magnet field (mT) drives the magnetisation of a simulated sample. Two models: Stoner-Wohlfarth (vector + magnetisation, uniaxial anisotropy ``Hk`` along an easy axis, switching when the energy minimum disappears) and a + scalar ``tanh`` loop (coercive field, width). +* The Kerr rotation is the sum of a polar term (magnetisation along the normal) and a longitudinal one (in the plane of + incidence, proportional to the sine of the angle of incidence). The geometry follows from the direction of the + field, the easy axis, the sample rotation and the angle of incidence. A transverse term changes the intensity (``p`` + polarisation only). +* The detector emits one 0D dataset with four channels in V: ``diode_A``, ``diode_B``, ``difference`` and ``sum``. + The balance is set by the half-wave plate angle (22.5 deg from its zero, an offset of which can be hidden), the + Kerr rotation is ``difference / (2 * sum)`` near the balance. The plugins add no Kerr rotation and no semantic + annotation: that is left to the extension or the analysis. +* Optional imperfections, each adjustable: shot noise, electronic noise, laser intensity noise (common mode), + gain imbalance between the diodes, Faraday rotation of the optics, slow drift. + +The angles that the plugins control, and how they are measured, are drawn below (``docs/make_angles_figure.py`` +regenerates the figure): the angle of incidence (goniometer), the direction of the field (settings of the magnet), +the azimuth of the sample (rotation stage) and of its easy axis, and the angle of the half-wave plate that balances the +detection. + +.. image:: docs/source/moke_bench_angles.png + :alt: Definition of the angles of the simulated MOKE bench + :width: 100% + +The equations, the settings and the limits of the model are described in ``docs/source/simulated_bench_model.md`` (published as a GitHub Pages site by the ``documentation`` workflow). + +The physics is approximate (see ``hardware/simulated_bench.py``) and has not been reviewed by MOKE experts yet. + + Installation instructions ========================= diff --git a/docs/make_angles_figure.py b/docs/make_angles_figure.py new file mode 100644 index 0000000..5987ce5 --- /dev/null +++ b/docs/make_angles_figure.py @@ -0,0 +1,140 @@ +"""Draws docs/source/moke_bench_angles.png / .svg: how the angles of the simulated MOKE bench are defined. + +Run ``python docs/make_angles_figure.py`` (needs matplotlib).""" +from pathlib import Path + +import matplotlib +matplotlib.use('Agg') +import matplotlib.pyplot as plt +import numpy as np +from matplotlib.patches import Arc, FancyArrowPatch, Polygon + +OUT = Path(__file__).parent / "source" +BEAM, FIELD, SAMPLE, POL, AXIS = '#c0392b', '#2471a3', '#444444', '#1e8449', '#7d3c98' + + +def arrow(ax, p0, p1, color, lw=2., style='-|>', ls='-', ms=14, z=3): + ax.add_patch(FancyArrowPatch(p0, p1, arrowstyle=style, mutation_scale=ms, color=color, lw=lw, ls=ls, zorder=z)) + + +def arc(ax, center, r, a0, a1, color, label=None, label_r=None, fs=11, lw=1.4): + ax.add_patch(Arc(center, 2 * r, 2 * r, theta1=a0, theta2=a1, color=color, lw=lw, zorder=4)) + if label: + a = np.radians((a0 + a1) / 2) + lr = label_r or r * 1.35 + ax.text(center[0] + lr * np.cos(a), center[1] + lr * np.sin(a), label, color=color, fontsize=fs, + ha='center', va='center', zorder=5) + + +def polar(r, deg): + return r * np.cos(np.radians(deg)), r * np.sin(np.radians(deg)) + + +def setup(ax, title, xlim, ylim): + ax.set_xlim(*xlim), ax.set_ylim(*ylim) + ax.set_aspect('equal'), ax.axis('off') + ax.set_title(title, fontsize=12, fontweight='bold', loc='left') + + +fig, axes = plt.subplots(1, 3, figsize=(17, 6.2), gridspec_kw=dict(width_ratios=[1.15, 1, 1])) + +# ---------------------------------------------------------------- A: side view, plane of incidence (x-z) +ax = axes[0] +setup(ax, 'A Side view, in the plane of incidence (x, z)', (-2.3, 2.6), (-1.75, 2.9)) +ax.add_patch(Polygon([(-2, 0), (2.1, 0), (2.1, -0.18), (-2, -0.18)], color='#d5d8dc', zorder=1)) +ax.plot([-2, 2.1], [0, 0], color=SAMPLE, lw=2.5, zorder=2) +ax.text(-2.2, -0.42, 'sample surface', color=SAMPLE, fontsize=10) +arrow(ax, (0, 0), (0, 2.5), SAMPLE, lw=1.2, ls='--') +ax.text(0.07, 2.55, 'z (sample normal)', fontsize=10, color=SAMPLE) +arrow(ax, (0, 0), (2.4, 0), SAMPLE, lw=1.2, ls='--', style='-|>') +ax.text(2.2, -0.34, 'x', fontsize=10, color=SAMPLE) +ti = 32 +bx, bz = polar(2.3, 90 + ti) +arrow(ax, (bx, bz), (0, 0), BEAM, lw=2.5) +ex, ez = polar(2.3, 90 - ti) +arrow(ax, (0, 0), (ex, ez), BEAM, lw=2.5, ls=(0, (4, 2))) +ax.text(bx - 0.35, bz + 0.12, 'probe beam\n(polarisation s or p)', color=BEAM, fontsize=10, ha='center') +ax.text(ex + 0.1, ez + 0.1, 'reflected\nbeam', color=BEAM, fontsize=10, ha='center') +arc(ax, (0, 0), 1.05, 90, 90 + ti, BEAM, r'$\theta_i$', 1.3, fs=13) +ax.text(-2.2, -0.85, 'Goniometer:\n' r'$\theta_i$ = angle of incidence', color=BEAM, fontsize=10.5, va='top') +tH = 62 +fx, fz = polar(1.95, 90 - tH) +arrow(ax, (0, 0), (fx, fz), FIELD, lw=3.5) +arc(ax, (0, 0), 0.62, 90 - tH, 90, FIELD, r'$\theta_H$', 0.8, fs=13) +ax.text(fx + 0.12, fz - 0.05, 'B\n(field)', color=FIELD, fontsize=11, fontweight='bold') +ax.text(0.2, -0.85, 'Magnet: B (mT) is the actuator value;\n' r'$\theta_H$ = "Field direction from the normal":' '\n0° polar geometry, 90° in plane', + color=FIELD, fontsize=10, va='top') + +# ---------------------------------------------------------------- B: top view (x-y) +ax = axes[1] +setup(ax, 'B Top view (x, y): sample, easy axis, field', (-2.4, 2.7), (-3.2, 2.5)) +ax.add_patch(Polygon([(-2.3, -0.28), (2.5, -0.28), (2.5, 0.28), (-2.3, 0.28)], color='#fdedec', zorder=0)) +ax.text(-2.25, 0.4, 'plane of incidence (x)', color=BEAM, fontsize=9.5) +arrow(ax, (-2.2, 0), (-0.05, 0), BEAM, lw=2.2) +ax.text(-2.2, -0.2, 'beam', color=BEAM, fontsize=9.5, va='top') +psi, phi_e, phi_h = 28, 40, -35 +rot = np.radians(psi) +R = np.array([[np.cos(rot), -np.sin(rot)], [np.sin(rot), np.cos(rot)]]) +sq = np.array([[-1, -1], [1, -1], [1, 1], [-1, 1]]) * 0.95 +ax.add_patch(Polygon((R @ sq.T).T, closed=True, fc='#eaecee', ec=SAMPLE, lw=2, zorder=1)) +ax.text(*(R @ np.array([0.45, -0.7])), 'sample', color=SAMPLE, fontsize=10, rotation=psi, ha='center', va='center') +arrow(ax, (0, 0), (2.4, 0), SAMPLE, lw=1.1, ls='--') +ax.text(2.45, -0.17, 'x', fontsize=10, color=SAMPLE) +arrow(ax, (0, 0), (0, 2.05), SAMPLE, lw=1.1, ls='--') +ax.text(0.07, 2.08, 'y', fontsize=10, color=SAMPLE) +xs = polar(1.85, psi) +arrow(ax, (0, 0), xs, SAMPLE, lw=1.4, ls=(0, (3, 2)), ms=10) +ax.text(xs[0] + 0.08, xs[1] + 0.02, r'$x_s$ (sample)', fontsize=9.5, color=SAMPLE) +arc(ax, (0, 0), 1.25, 0, psi, SAMPLE, r'$\psi$', 1.5, fs=13) +ea = polar(2.15, psi + phi_e) +arrow(ax, (-ea[0] * 0.55, -ea[1] * 0.55), ea, AXIS, lw=2.6, style='<|-|>', ms=14) +ax.text(ea[0] + 0.05, ea[1] + 0.12, 'easy axis', color=AXIS, fontsize=10.5) +arc(ax, (0, 0), 0.8, psi, psi + phi_e, AXIS, r'$\phi_e$', 1.05, fs=13) +fh = polar(2.2, phi_h) +arrow(ax, (0, 0), fh, FIELD, lw=3.5) +arc(ax, (0, 0), 1.6, phi_h, 0, FIELD, r'$\phi_H$', 1.88, fs=13) +ax.text(fh[0] + 0.1, fh[1] - 0.12, 'B (in-plane\ncomponent)', color=FIELD, fontsize=10, ha='left', va='top') +ax.text(-2.35, -1.95, + r'Sample rotation stage: $\psi$ = azimuth of the sample (from x)' '\n' + r'Sample setting "Easy axis azimuth": $\phi_e$, measured from $x_s$' '\n' + r'Magnet setting "Field azimuth": $\phi_H$, from x, in the lab' '\n' + 'The easy axis is at ' r'$\psi + \phi_e$' ' from x in the lab', + fontsize=9.5, va='top', linespacing=1.5) + +# ---------------------------------------------------------------- C: polarisation, half-wave plate, PBS +ax = axes[2] +setup(ax, 'C Polarisation in front of the polarising beam splitter', (-2.2, 2.6), (-2.5, 2.4)) +arrow(ax, (-2.0, 0), (2.1, 0), SAMPLE, lw=1.2) +ax.text(1.55, -0.3, 'port B axis', color=SAMPLE, fontsize=10) +arrow(ax, (0, -0.9), (0, 2.0), SAMPLE, lw=1.2, style='-|>') +ax.text(0.08, 2.05, 'port A axis', color=SAMPLE, fontsize=10) +al = 14 +fa = polar(2.0, al) +ax.plot([-fa[0], fa[0]], [-fa[1], fa[1]], color=AXIS, lw=3, solid_capstyle='round', zorder=2, alpha=.8) +ax.text(-fa[0] - 0.05, -fa[1] - 0.12, 'fast axis of the\nhalf-wave plate', color=AXIS, fontsize=9.5, va='top') +arc(ax, (0, 0), 0.62, 0, al, AXIS, r'$\alpha_{eff}$', 0.95, fs=12) +ph0 = polar(1.7, 0) +ax.plot([0, 1.7], [0, 0], color=POL, lw=0, zorder=0) +phi = 2 * al + 6 +pv = polar(1.95, phi) +arrow(ax, (0, 0), pv, POL, lw=3.5) +ax.plot([0, polar(1.95, 45)[0]], [0, polar(1.95, 45)[1]], color=SAMPLE, lw=1.2, ls=':') +ax.text(*polar(2.5, 52), 'balance\n45°', fontsize=9.5, color=SAMPLE, ha='center', va='center') +arc(ax, (0, 0), 1.3, 0, phi, POL, r'$\varphi$', 1.55, fs=13) +arc(ax, (0, 0), 1.75, 2 * al, phi, BEAM, None, lw=2.2) +ax.text(*polar(2.1, (2 * al + phi) / 2 + 3), r'$\theta_K$', color=BEAM, fontsize=12, ha='left', va='center') +ax.text(pv[0] - 0.05, pv[1] + 0.22, 'polarisation', color=POL, fontsize=10.5, fontweight='bold', ha='right') +ax.text(-2.15, -1.25, + r'$\alpha_{eff}$ = waveplate angle $-$ zero offset (hidden defect)' '\n' + r'The plate rotates the polarisation by $2\alpha_{eff}$;' '\n' + r'the sample adds the Kerr rotation $\theta_K$: $\varphi = 2\alpha_{eff} + \theta_K$' '\n' + r'$I_A = P\,\sin^2\varphi$, $I_B = P\,\cos^2\varphi$' '\n' + r'Balanced when $\varphi$ = 45°, i.e. $\alpha_{eff}$ = 22.5°:' '\n' + r'$A - B \approx P \sin 2\theta_K$', + fontsize=9.5, va='top', linespacing=1.5) +ax.text(-2.15, 2.4, 'Waveplate rotation mount:\n' r'$\alpha$ = angle of the plate', color=AXIS, fontsize=10.5, va='top') + +fig.suptitle('Angles of the simulated MOKE bench and the plugin that sets each of them', fontsize=14, y=0.995) +fig.tight_layout() +fig.savefig(OUT / 'moke_bench_angles.png', dpi=130) +fig.savefig(OUT / 'moke_bench_angles.svg') diff --git a/docs/requirements.txt b/docs/requirements.txt new file mode 100644 index 0000000..3dd64d0 --- /dev/null +++ b/docs/requirements.txt @@ -0,0 +1,3 @@ +sphinx +sphinx_rtd_theme +myst_parser diff --git a/docs/source/_static/.gitkeep b/docs/source/_static/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/docs/source/conf.py b/docs/source/conf.py new file mode 100644 index 0000000..6e0eac2 --- /dev/null +++ b/docs/source/conf.py @@ -0,0 +1,9 @@ +project = 'pymodaq_plugins_moke' +copyright = '2025, CEMES' +author = 'Sébastien Weber' +extensions = ['myst_parser'] +myst_enable_extensions = ['dollarmath', 'amsmath'] +templates_path = [] +exclude_patterns = ['_build'] +html_theme = 'sphinx_rtd_theme' +html_static_path = ['_static'] diff --git a/docs/source/index.rst b/docs/source/index.rst new file mode 100644 index 0000000..d101cf1 --- /dev/null +++ b/docs/source/index.rst @@ -0,0 +1,13 @@ +pymodaq_plugins_moke documentation +================================== + +PyMoDAQ plugins for a magneto-optical Kerr effect (MOKE) bench. This site documents the +**simulated MOKE bench** (plugins ``MokeMagnetSim``, ``MokeWavePlateSim``, ``MokeSampleRotationSim``, +``MokeGoniometerSim`` and ``MokeBalancedSim``), which runs scans and gives realistic hysteresis loops +without any hardware. + +.. toctree:: + :maxdepth: 2 + :caption: Contents: + + simulated_bench_model diff --git a/docs/source/moke_bench_angles.png b/docs/source/moke_bench_angles.png new file mode 100644 index 0000000..254a605 Binary files /dev/null and b/docs/source/moke_bench_angles.png differ diff --git a/docs/source/moke_bench_angles.svg b/docs/source/moke_bench_angles.svg new file mode 100644 index 0000000..6982f73 --- /dev/null +++ b/docs/source/moke_bench_angles.svg @@ -0,0 +1,3533 @@ + + + + + + + + 2026-11-25T20:39:17.251052 + image/svg+xml + + + Matplotlib v3.11.2, https://matplotlib.org/ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/docs/source/simulated_bench_model.md b/docs/source/simulated_bench_model.md new file mode 100644 index 0000000..8fe32eb --- /dev/null +++ b/docs/source/simulated_bench_model.md @@ -0,0 +1,218 @@ +# Model of the simulated MOKE bench + +This page describes what the five `Moke...Sim` plugins compute (`src/pymodaq_plugins_moke/hardware/simulated_bench.py`), +so that a user can choose the settings, check a result by hand, and know what is not simulated. The physics is a +**deliberately simple model**, written from general knowledge of the magneto-optical Kerr effect. It has **not been +reviewed by MOKE experts** yet, and nothing in it was compared with a real bench. + +The angles are drawn below. + +![Angles of the simulated MOKE bench](moke_bench_angles.png) + +## 1. Overview + +``` + magnet B(t) ──► magnetisation m ──► Kerr rotation θ_K ──► polarisation ──► half-wave plate ──► beam splitter ──► diodes A, B + (MokeMagnetSim) (sample model) (geometry: θ_i, ψ) φ = 2α_eff + θ_K (MokeWavePlateSim) (MokeBalancedSim) +``` + +All the plugins share one object, the *bench* (`MokeBench`), through the PyMoDAQ controller: give them the same +controller ID, one as `Master` (it creates the bench), the others as `Slave`. A plugin alone is its own master. + +Lab frame: `z` is the normal of the sample, `x` lies in the plane of incidence, `y` is perpendicular to both. + +| Plugin | Quantity | Unit | Default | Where it enters | +|---|---|---|---|---| +| `MokeMagnetSim` | field `B` | mT | 0 | magnet (section 2) | +| `MokeMagnetSim` setting | response time `tau` | ms | 50 | magnet | +| `MokeMagnetSim` settings | field direction `θ_H` (from the normal) and `φ_H` (azimuth) | deg | 0, 0 | magnet, magnetisation | +| `MokeSampleRotationSim` | sample azimuth `ψ` | deg | 0 | easy axis in the lab frame | +| `MokeGoniometerSim` | angle of incidence `θ_i` | deg | 45 | Kerr rotation | +| `MokeWavePlateSim` | plate angle `α` | deg | 22.5 | balance | +| `MokeBalancedSim` settings | sample, optics, imperfections | see sections 3 to 6 | | | + +Settings of the detector are sent to the bench when they change (`commit_settings`) and at initialisation. Several +detectors or actuators do not conflict: each plugin only sets its own settings. + +## 2. Magnet + +The applied field `B` (mT) follows its target `B_t` with a first-order response: + +$$B(t + \Delta t) = B_t + \left(B(t) - B_t\right) e^{-\Delta t/\tau}$$ + +The bench computes this lazily, each time somebody asks for the field or for a signal, from the time elapsed since +the previous call. `tau = 0` is an instantaneous magnet. The actuator is polled by PyMoDAQ until the field is within +`epsilon` (0.5 mT by default) of the target, as for a real power supply. + +The field is a vector of norm `B` along the direction given by the polar angle `θ_H` (0°: along the normal, polar +geometry; 90°: in the plane) and the azimuth `φ_H` (0°: in the plane of incidence). + +**B and H.** The simulation uses the applied field `B = μ0 H` in vacuum or air: 1 mT corresponds to 795.8 A/m, or +10 Oe. The actuator axis is in mT; `pint` converts mT to A/m but not directly to Oe (CGS). Which of `B` or `H` is the +right quantity to record is still to be decided with the experts. + +## 3. Magnetisation of the sample + +The state of the sample is a unit vector `m = (m_x, m_y, m_z)` in the lab frame. Two models, chosen in the detector +setting *Magnetisation model*. + +The easy axis `e` is fixed in the sample: its polar angle `θ_e` (*Easy axis from the normal*) and its azimuth `φ_e` +(*Easy axis azimuth*) are given in the sample frame. The sample rotation `ψ` turns it about `z`, so in the lab frame +its azimuth is `φ_e + ψ`. + +### 3.1 Stoner-Wohlfarth (default) + +A single magnetic domain with a uniaxial anisotropy along `e` and a Zeeman term. With `h = B / H_k` the reduced field +vector (`H_k`, in mT, is the setting *Anisotropy field*), the energy density divided by `2K` is: + +$$ e(\mathbf m) = -\tfrac12 (\mathbf m\cdot\mathbf e)^2 - \mathbf h\cdot\mathbf m $$ + +`m` always sits in a **local minimum** of `e` on the unit sphere, the one it was already in. When the field changes, +the simulation moves the minimum with the field and lets `m` relax to it (gradient descent, step 0.4, at most 600 +iterations, the field change being cut into steps of at most 2% of `H_k`). The minimum disappears at the switching +field and `m` jumps to the other one. **This is what produces the hysteresis**: the state depends on the history of +the field, not only on its present value. A tiny random tilt of `m` (1e-4 rad, a stand-in for thermal fluctuations) +is added before each relaxation: without it `m` would stay forever on an unstable point when the field is exactly +along the easy axis. + +Checks that the model reproduces (they are in the tests): + +| Angle ψ_H between the field and the easy axis | Switching field | Loop | +|---|---|---| +| 0° | `H_k` | square | +| 45° | `H_k / 2` | open, rounded | +| 90° | none (saturation at `H_k`) | closed, no hysteresis | + +The general switching field is `H_k / (cos^{2/3}ψ_H + sin^{2/3}ψ_H)^{3/2}` (the Stoner-Wohlfarth astroid). + +This is a **coherent rotation** model: no domains, no domain-wall propagation, no thermal activation, no minor-loop +memory beyond what the single minimum gives. Real thin films with a square loop switch by nucleation and wall motion at +a field below `H_k`: use the *tanh* model to put a measured coercive field. + +### 3.2 tanh loop + +A scalar loop along the easy axis, for a quick and readable hysteresis. The field component along the easy axis is +`h = B (\mathbf{B}_{dir} \cdot \mathbf e)`. Two branches limit the amplitude `a = \mathbf m \cdot \mathbf e`: + +$$ a_\uparrow(h) = \tanh\frac{h - H_c}{w}, \qquad a_\downarrow(h) = \tanh\frac{h + H_c}{w} $$ + +with the coercive field `H_c` and the switching width `w` (settings, in mT). When the field increases `a` becomes +`max(a, a_↑(h))`, when it decreases `a` becomes `min(a, a_↓(h))`. `m = a e`. The loop is symmetric, saturates at +`|a| = 1`, and has no angle dependence other than the projection of the field on the easy axis. + +## 4. Kerr rotation + +For the magnetisation `m` and the angle of incidence `θ_i`, the polarisation rotation (rad) is: + +$$ \theta_K = K_\mathrm{pol}\, m_z + K_\mathrm{long} \sin\theta_i\; m_x $$ + +`K_pol` (*Polar Kerr rotation*, default 0.5 mrad) is the rotation at saturation with `m` along `+z`. `K_long` +(*Longitudinal Kerr rotation*, default 0.3 mrad) is the rotation at saturation and 90° incidence with `m` along `+x`, +in the plane of incidence. So: + +* the polar term is independent of the angle of incidence (a simplification), +* the longitudinal term grows as `sin θ_i` and vanishes at normal incidence, +* the component `m_y`, perpendicular to the plane of incidence (transverse geometry), gives no rotation. + +For **s polarisation** the rotation is multiplied by *Kerr s / p ratio* (default 1). This is a placeholder: a real +sample has different Kerr rotations in s and p, to be measured. + +The **transverse** term changes the reflected intensity, in p polarisation only: + +$$ P \;\to\; P\,\left(1 + K_\mathrm{trans}\, \sin\theta_i\; m_y\right) $$ + +with *Transverse reflectivity change* `K_trans` (default 1e-3), visible on the `sum` channel. + +Not simulated: Kerr ellipticity, wavelength dependence, quadratic MOKE (terms in `cos 2φ`), temperature, dependence +of `K` on the angle of incidence beyond `sin θ_i`. + +## 5. Balanced detection + +After the sample the beam crosses a half-wave plate and a polarising beam splitter (Wollaston) that sends the +components along its two axes to photodiodes A and B. + +A half-wave plate whose fast axis makes an angle `α_eff` with the axis of port B rotates the polarisation by +`2 α_eff`. The beam starts polarised along the axis of port B, so the angle `φ` of the polarisation to that axis is: + +$$ \varphi = 2\,\alpha_\mathrm{eff} + \theta_K, \qquad \alpha_\mathrm{eff} = \alpha - \alpha_0 $$ + +where `α` is the angle of the plate (`MokeWavePlateSim`) and `α_0` the **zero offset** of the plate (detector setting +*Waveplate zero offset*, default 0°; the user does not know it and finds the balance by looking for a zero +difference). With `P` the power on the diodes (section 5.1), Malus' law gives: + +$$ P_A = P \sin^2\varphi, \qquad P_B = P \cos^2\varphi, \qquad P_A - P_B = -P\cos 2\varphi $$ + +At the **balance**, `α_eff = 22.5°` (`φ = 45°`), `P_A = P_B` when `θ_K = 0` and + +$$ P_A - P_B = P \sin 2\theta_K \approx 2 P \theta_K $$ + +Away from the balance by `δ` (in polarisation angle, `δ = 2 α_eff - 45°`): + +$$ P_A - P_B = P \sin\!\big(2(\theta_K + \delta)\big) $$ + +* **offset** at zero field: `P sin 2δ`; +* **sensitivity** to `θ_K`: multiplied by `cos 2δ` (maximal at the balance; 10° of plate is `δ = 20°`, a factor 0.77); +* the laser intensity noise cancels in the difference only at `δ = 0` (section 6). + +### 5.1 From power to volts + +$$ P = P_0\, R\,\big(1 + \text{transverse term}\big) $$ + +with `P_0` the *Power on the sample* (1 mW) and `R` the *Sample reflectivity* (0.5). Each diode converts power to +voltage with the *responsivity* `ρ` (0.5 A/W) and the *amplifier gain* `G` (1 kV/A by default, setting in kV/A): + +$$ V_A = G \rho P_A, \qquad V_B = G \rho P_B $$ + +The detector emits one 0D dataset, in V, with four channels: + +| Channel | Content | +|---|---| +| `diode_A` | `V_A` | +| `diode_B` | `V_B` | +| `difference` | `V_A - V_B` | +| `sum` | `V_A + V_B` | + +**Recovering the Kerr rotation.** The plugins do not compute it, so that any digitiser can be used with the same +analysis. With equal gains, near the balance: `θ_K ≈ difference / (2 sum)` (rad). In general: +`θ_K = ½ arccos(−difference / sum) − 2 α_eff`. With the default values, `θ_K = 0.5 mrad` gives a difference of +250 µV on a sum of 250 mV. + +## 6. Imperfections + +The group *Imperfections* has a master switch (*Enabled*) and one switch per defect, each with its own value. Nothing +is added when the master switch is off, and `grab_data` is then deterministic. + +| Defect (setting) | Default | Model | +|---|---|---| +| Shot noise | on | white noise on each diode current, `σ_i = sqrt(2 q I B_w)`, with `I = ρ P_{A,B}` and the bandwidth `B_w = 1/(2 t_int)` from the *Integration time* (10 ms by default) | +| Electronic noise | on, 20 µV rms | independent Gaussian noise on each channel voltage | +| Laser intensity noise | on, 0.1 % rms | the power `P` is multiplied by `1 + ε`, `ε` Gaussian: **common** to both diodes, so it appears in `sum` and cancels in `difference` only when `P_A = P_B` (balanced, no gain imbalance) | +| Gain imbalance A/B | off, 2 % | the gain of A is multiplied by `1 + g/2` and that of B by `1 - g/2`, `g` being the difference: the difference signal does not vanish at the balance and the laser noise leaks into it | +| Faraday rotation of the optics | off, 5 µrad/mT | `θ_K` receives a linear term `k_F B` (field-dependent background that has to be subtracted from the loops) | +| Slow drift of the polarisation | off, 0.2 mrad, 60 s | `θ_K` receives `A sin(2π t / T)` | + +`Naverage` in `grab_data` averages that number of independent readings. + +## 7. What the model does not do + +* No domain structure, no minor loops with return-point memory, no thermal or viscous effects, no dependence on the + sweep rate other than through the magnet response time. +* No Kerr ellipticity, quarter-wave compensator, PEM or lock-in (a modulated detection is planned as a separate + detector). +* No dependence on the wavelength or the temperature, which exist in the MOKE ontology (`moke:Wavelength`, + `moke:SampleTemperature`). +* No drift or hysteresis of the magnet itself (remanent field, heating), no Hall probe: the field read back is the + modelled field. +* The simulation gives **no semantic annotation**; adding the role, quantity kind and unit of the data is the job of the + extension that uses the plugins. + +## 8. Using it + +1. Add the five plugins to a Dashboard experiment with the same *controller ID*, the magnet as `Master`. +2. Set the sample (anisotropy field, easy axis, Kerr rotations) and, if wanted, the imperfections in the detector. +3. Look for the balance: scan the plate angle and find `difference = 0` (22.5° plus the hidden offset). +4. Scan the field with the magnet as the scan axis and the detector as the signal: a hysteresis loop of the + `difference` channel. Change `θ_i`, `ψ`, the field direction or the plate to see how the loop changes. + +The tests in `tests/test_simulated_bench.py` check the loop, the balance, the sensitivity, the geometry and the +imperfections; `tests/test_simulated_plugins.py` drives the plugins as the Dashboard does (not through its GUI). diff --git a/src/pymodaq_plugins_moke/daq_move_plugins/daq_move_MokeGoniometerSim.py b/src/pymodaq_plugins_moke/daq_move_plugins/daq_move_MokeGoniometerSim.py new file mode 100644 index 0000000..1756008 --- /dev/null +++ b/src/pymodaq_plugins_moke/daq_move_plugins/daq_move_MokeGoniometerSim.py @@ -0,0 +1,24 @@ +from pymodaq.control_modules.move_utility_classes import comon_parameters_fun, main + +from pymodaq_plugins_moke.hardware.simulated_move import SimulatedBenchMove + + +class DAQ_Move_MokeGoniometerSim(SimulatedBenchMove): + """Simulated goniometer: angle of incidence of the probe beam on the sample, in degrees (0 is normal incidence). + + The longitudinal Kerr signal grows as the sine of this angle, the polar one is not changed in this model. + + Compatible devices: none, this is a simulation shared with the other ``MokeXxxSim`` plugins through the + controller (master/slave, same controller ID). Nothing was tested on a real instrument. + Tested with PyMoDAQ 5.3.13 on Linux. No driver to install. + """ + _axis_names = ['incidence'] + _controller_units = 'deg' + _epsilons = [0.01] + _bench_attribute = 'incidence' + _home_value = 45. + params = comon_parameters_fun(is_multiaxes=False, axis_names=_axis_names, epsilon=_epsilons) + + +if __name__ == '__main__': + main(__file__) diff --git a/src/pymodaq_plugins_moke/daq_move_plugins/daq_move_MokeMagnetSim.py b/src/pymodaq_plugins_moke/daq_move_plugins/daq_move_MokeMagnetSim.py new file mode 100644 index 0000000..4627375 --- /dev/null +++ b/src/pymodaq_plugins_moke/daq_move_plugins/daq_move_MokeMagnetSim.py @@ -0,0 +1,44 @@ +from pymodaq.control_modules.move_utility_classes import comon_parameters_fun, main + +from pymodaq_plugins_moke.hardware.simulated_move import SimulatedBenchMove + + +class DAQ_Move_MokeMagnetSim(SimulatedBenchMove): + """Simulated electromagnet of the MOKE bench: the axis is the applied field, in mT. + + The field follows its target with a first order response (time constant ``tau``) and drives the magnetisation of + the simulated sample, which gives the hysteresis. The direction of the field in the lab frame is set by two + angles: 0 deg from the sample normal is the polar geometry, 90 deg is in plane (longitudinal geometry when the + azimuth is 0, in the plane of incidence). + + Compatible devices: none, this is a simulation shared with the other ``MokeXxxSim`` plugins through the + controller (master/slave, same controller ID). Nothing was tested on a real instrument. + Tested with PyMoDAQ 5.3.13 on Linux. No driver to install. + """ + _axis_names = ['field'] + _controller_units = 'mT' + _epsilons = [0.5] + _bench_attribute = 'field' + _bench_parameters = { + 'tau': ('bench', 'field_tau', 1e-3), + 'field_polar': ('bench', 'field_polar', 1.), + 'field_azimuth': ('bench', 'field_azimuth', 1.), + } + params = [ + {'title': 'Response time (ms):', 'name': 'tau', 'type': 'float', 'value': 50., 'min': 0., + 'tip': 'First order response of the field to its target'}, + {'title': 'Field direction from the normal (deg):', 'name': 'field_polar', 'type': 'float', 'value': 0., + 'tip': '0: perpendicular to the sample (polar geometry), 90: in plane'}, + {'title': 'Field azimuth (deg):', 'name': 'field_azimuth', 'type': 'float', 'value': 0., + 'tip': 'Azimuth in the lab frame, 0: in the plane of incidence'}, + ] + comon_parameters_fun(is_multiaxes=False, axis_names=_axis_names, epsilon=_epsilons) + + def _read(self) -> float: + return self.controller.get_field() + + def _write(self, value: float): + self.controller.set_field_target(value) + + +if __name__ == '__main__': + main(__file__) diff --git a/src/pymodaq_plugins_moke/daq_move_plugins/daq_move_MokeSampleRotationSim.py b/src/pymodaq_plugins_moke/daq_move_plugins/daq_move_MokeSampleRotationSim.py new file mode 100644 index 0000000..fa72214 --- /dev/null +++ b/src/pymodaq_plugins_moke/daq_move_plugins/daq_move_MokeSampleRotationSim.py @@ -0,0 +1,24 @@ +from pymodaq.control_modules.move_utility_classes import comon_parameters_fun, main + +from pymodaq_plugins_moke.hardware.simulated_move import SimulatedBenchMove + + +class DAQ_Move_MokeSampleRotationSim(SimulatedBenchMove): + """Simulated rotation stage of the sample about its normal (azimuth of the sample), in degrees. + + It rotates the easy axis of the simulated sample with respect to the plane of incidence and to the field, which + changes the mix of polar and longitudinal contributions and the shape of the loop. + + Compatible devices: none, this is a simulation shared with the other ``MokeXxxSim`` plugins through the + controller (master/slave, same controller ID). Nothing was tested on a real instrument. + Tested with PyMoDAQ 5.3.13 on Linux. No driver to install. + """ + _axis_names = ['azimuth'] + _controller_units = 'deg' + _epsilons = [0.01] + _bench_attribute = 'sample_rotation' + params = comon_parameters_fun(is_multiaxes=False, axis_names=_axis_names, epsilon=_epsilons) + + +if __name__ == '__main__': + main(__file__) diff --git a/src/pymodaq_plugins_moke/daq_move_plugins/daq_move_MokeWavePlateSim.py b/src/pymodaq_plugins_moke/daq_move_plugins/daq_move_MokeWavePlateSim.py new file mode 100644 index 0000000..25495fc --- /dev/null +++ b/src/pymodaq_plugins_moke/daq_move_plugins/daq_move_MokeWavePlateSim.py @@ -0,0 +1,26 @@ +from pymodaq.control_modules.move_utility_classes import comon_parameters_fun, main + +from pymodaq_plugins_moke.hardware.simulated_move import SimulatedBenchMove + + +class DAQ_Move_MokeWavePlateSim(SimulatedBenchMove): + """Simulated rotation mount of the half-wave plate in front of the polarising beam splitter (balance adjustment). + + The axis is the angle of the plate, in degrees. The plate rotates the polarisation by twice its angle: the two + photodiodes of the balanced detector are balanced when the angle, counted from the (hidden) zero of the plate, + is 22.5 deg. The offset of this zero is a setting of the balanced detector plugin. + + Compatible devices: none, this is a simulation shared with the other ``MokeXxxSim`` plugins through the + controller (master/slave, same controller ID). Nothing was tested on a real instrument. + Tested with PyMoDAQ 5.3.13 on Linux. No driver to install. + """ + _axis_names = ['waveplate'] + _controller_units = 'deg' + _epsilons = [0.01] + _bench_attribute = 'waveplate_angle' + _home_value = 22.5 + params = comon_parameters_fun(is_multiaxes=False, axis_names=_axis_names, epsilon=_epsilons) + + +if __name__ == '__main__': + main(__file__) diff --git a/src/pymodaq_plugins_moke/daq_viewer_plugins/plugins_0D/daq_0Dviewer_MokeBalancedSim.py b/src/pymodaq_plugins_moke/daq_viewer_plugins/plugins_0D/daq_0Dviewer_MokeBalancedSim.py new file mode 100644 index 0000000..30c265e --- /dev/null +++ b/src/pymodaq_plugins_moke/daq_viewer_plugins/plugins_0D/daq_0Dviewer_MokeBalancedSim.py @@ -0,0 +1,149 @@ +import numpy as np + +from pymodaq_data.data import DataToExport +from pymodaq_gui.parameter import Parameter +from pymodaq_utils.utils import ThreadCommand +from pymodaq.control_modules.viewer_utility_classes import DAQ_Viewer_base, comon_parameters, main +from pymodaq.utils.data import DataFromPlugins + +from pymodaq_plugins_moke.hardware.simulated_bench import MokeBench, MODELS + +LABELS = ['diode_A', 'diode_B', 'difference', 'sum'] + +# setting name -> (bench settings group, attribute, factor from the displayed unit to the bench unit) +BENCH_PARAMETERS = { + 'model': ('sample', 'model', 1), 'hk': ('sample', 'hk', 1.), 'hc': ('sample', 'hc', 1.), + 'width': ('sample', 'width', 1.), 'easy_polar': ('sample', 'easy_polar', 1.), + 'easy_azimuth': ('sample', 'easy_azimuth', 1.), 'kerr_polar': ('sample', 'kerr_polar', 1e-3), + 'kerr_long': ('sample', 'kerr_long', 1e-3), 'kerr_trans': ('sample', 'kerr_trans', 1e-3), + 'polarization': ('sample', 'polarization', 1), 'kerr_s_over_p': ('sample', 'kerr_s_over_p', 1.), + 'power': ('optics', 'power', 1.), 'reflectivity': ('optics', 'reflectivity', 1.), + 'responsivity': ('optics', 'responsivity', 1.), 'gain': ('optics', 'gain', 1e3), + 'waveplate_zero': ('optics', 'waveplate_zero', 1.), + 'imperfections_enabled': ('imperfections', 'enabled', 1), + 'shot_noise': ('imperfections', 'shot_noise', 1), + 'electronic_noise': ('imperfections', 'electronic_noise', 1), + 'electronic_noise_rms': ('imperfections', 'electronic_noise_rms', 1e-6), + 'laser_noise': ('imperfections', 'laser_noise', 1), + 'laser_noise_rms': ('imperfections', 'laser_noise_rms', 1e-2), + 'imbalance': ('imperfections', 'imbalance', 1), + 'imbalance_percent': ('imperfections', 'imbalance_percent', 1.), + 'faraday': ('imperfections', 'faraday', 1), 'faraday_slope': ('imperfections', 'faraday_slope', 1e-6), + 'drift': ('imperfections', 'drift', 1), 'drift_amplitude': ('imperfections', 'drift_amplitude', 1e-3), + 'drift_period': ('imperfections', 'drift_period', 1.), +} + + +def _num(title, name, value, **kwargs): + return {'title': title, 'name': name, 'type': 'float', 'value': value, **kwargs} + + +def _check(title, name, value): + return {'title': title, 'name': name, 'type': 'bool', 'value': value} + + +class DAQ_0DViewer_MokeBalancedSim(DAQ_Viewer_base): + """Simulated balanced detection of a MOKE bench: two photodiodes behind a polarising beam splitter. + + Emits one 0D dataset with four channels in V: ``diode_A``, ``diode_B``, ``difference`` and ``sum``. The signal + depends on the instruments of the shared simulated bench (magnet field, half-wave plate angle, sample + rotation, angle of incidence) that are controlled by the ``MokeXxxSim`` actuator plugins, on the settings of + the simulated sample and optics, and on optional imperfections. The Kerr rotation is deliberately not + computed here: ``difference / (2 * sum)`` gives it (in rad) near the balance, an extension or an analysis does + that for any digitiser. No semantic annotation either. + + Compatible devices: none, this is a simulation. Nothing was tested on a real instrument. + Tested with PyMoDAQ 5.3.13 on Linux. No driver to install. + """ + params = comon_parameters + [ + {'title': 'Sample:', 'name': 'sample', 'type': 'group', 'children': [ + {'title': 'Magnetisation model:', 'name': 'model', 'type': 'list', 'limits': MODELS, 'value': MODELS[0], + 'tip': 'Stoner-Wohlfarth: vector magnetisation, uniaxial anisotropy. tanh: scalar loop along the easy axis'}, + _num('Anisotropy field Hk (mT):', 'hk', 40., min=0.1, tip='Stoner-Wohlfarth: switching field along the easy axis'), + _num('Coercive field (mT):', 'hc', 15., min=0., tip='tanh model'), + _num('Switching width (mT):', 'width', 4., min=0.01, tip='tanh model'), + _num('Easy axis from the normal (deg):', 'easy_polar', 0.), + _num('Easy axis azimuth (deg):', 'easy_azimuth', 0.), + _num('Polar Kerr rotation (mrad):', 'kerr_polar', 0.5, tip='At saturation, magnetisation along +z'), + _num('Longitudinal Kerr rotation (mrad):', 'kerr_long', 0.3, + tip='At saturation and 90 deg incidence, magnetisation along +x; scales as sin(incidence)'), + _num('Transverse reflectivity change (1e-3):', 'kerr_trans', 1., + tip='Intensity change at saturation, magnetisation along +y, p polarisation only'), + {'title': 'Polarisation:', 'name': 'polarization', 'type': 'list', 'limits': ['p', 's'], 'value': 'p'}, + _num('Kerr s / p ratio:', 'kerr_s_over_p', 1., tip='Simple model: the rotation in s polarisation is this factor times that in p'), + ]}, + {'title': 'Optics and detection:', 'name': 'optics', 'type': 'group', 'children': [ + _num('Power on the sample (mW):', 'power', 1., min=0.), + _num('Sample reflectivity:', 'reflectivity', 0.5, min=0., max=1.), + _num('Photodiode responsivity (A/W):', 'responsivity', 0.5, min=0.), + _num('Amplifier gain (kV/A):', 'gain', 1., min=0.), + _num('Waveplate zero offset (deg):', 'waveplate_zero', 0., + tip='Hidden defect: the plate zero is not where its scale says, find the balance by looking for a zero difference'), + _num('Integration time (ms):', 'integration', 10., min=0.01, tip='Sets the detection bandwidth, 1 / (2 t), for the shot noise'), + ]}, + {'title': 'Imperfections:', 'name': 'imperfections', 'type': 'group', 'children': [ + _check('Enabled', 'imperfections_enabled', True), + _check('Shot noise', 'shot_noise', True), + _check('Electronic noise', 'electronic_noise', True), + _num(' rms per channel (uV):', 'electronic_noise_rms', 20., min=0.), + _check('Laser intensity noise', 'laser_noise', True), + _num(' rms (%):', 'laser_noise_rms', 0.1, min=0., tip='Common to both diodes, rejected by the balance except when unbalanced'), + _check('Gain imbalance A/B', 'imbalance', False), + _num(' gain difference (%):', 'imbalance_percent', 2.), + _check('Faraday rotation of the optics', 'faraday', False), + _num(' slope (urad/mT):', 'faraday_slope', 5.), + _check('Slow drift of the polarisation', 'drift', False), + _num(' amplitude (mrad):', 'drift_amplitude', 0.2, min=0.), + _num(' period (s):', 'drift_period', 60., min=0.1), + ]}, + ] + + def ini_attributes(self): + self.controller: MokeBench = None + + def ini_detector(self, controller=None): + if self.is_master: + self.controller = MokeBench() + else: + self.controller = controller + for name in BENCH_PARAMETERS: + self._forward(self._find(name)) + self.dte_signal_temp.emit(self._dte(np.zeros(len(LABELS)))) + return 'Simulated balanced detection of the MOKE bench, no hardware', True + + def close(self): + if self.is_master and self.controller is not None: + self.controller.close() + + def _find(self, name: str) -> Parameter: + for group in ('sample', 'optics', 'imperfections'): + if name in self.settings.child(group).names: + return self.settings.child(group, name) + raise KeyError(name) + + def _forward(self, param: Parameter): + group, attribute, factor = BENCH_PARAMETERS[param.name()] + value = param.value() if factor == 1 and not isinstance(param.value(), float) else param.value() * factor + self.controller.set_parameter(group, attribute, value) + + def commit_settings(self, param: Parameter): + if param.name() in BENCH_PARAMETERS: + self._forward(param) + + @staticmethod + def _dte(values) -> DataToExport: + return DataToExport('MokeBalanced', data=[DataFromPlugins( + name='MokeBalanced', data=[np.array([v]) for v in values], dim='Data0D', labels=LABELS, units='V')]) + + def grab_data(self, Naverage=1, **kwargs): + t_int = self.settings['optics', 'integration'] * 1e-3 + reads = [self.controller.read_diodes(t_int) for _ in range(max(int(Naverage), 1))] + values = [float(np.mean([r[label] for r in reads])) for label in LABELS] + self.dte_signal.emit(self._dte(values)) + + def stop(self): + return '' + + +if __name__ == '__main__': + main(__file__) diff --git a/src/pymodaq_plugins_moke/hardware/simulated_bench.py b/src/pymodaq_plugins_moke/hardware/simulated_bench.py new file mode 100644 index 0000000..62262f1 --- /dev/null +++ b/src/pymodaq_plugins_moke/hardware/simulated_bench.py @@ -0,0 +1,263 @@ +"""Simulated MOKE bench with balanced detection (no hardware needed). + +The bench is the *controller* shared by the simulated instruments (magnet, half-wave plate, sample rotation, +goniometer, balanced detector): the first plugin initialised is the master and creates it, the others receive it +as slaves. + +Physics, in short (all of it approximate, to be reviewed by MOKE experts, see ``DOC`` below): + +* Lab frame: ``z`` is the sample normal, ``x`` lies in the plane of incidence, ``y`` is perpendicular to it. +* Magnetisation: unit vector ``m``. ``stoner_wohlfarth`` model: uniaxial anisotropy field ``Hk`` along an easy axis + fixed in the sample, ``m`` follows the local minimum of the energy and jumps when this minimum disappears (this + gives the hysteresis). ``tanh`` model: ``m`` stays along the easy axis, its amplitude follows two tanh branches + (coercive field, width). +* Kerr rotation (rad): ``K_polar * mz + K_long * sin(incidence) * mx`` (``K_*`` are the values at saturation). + A transverse term changes the reflected intensity (p polarisation only): ``K_trans * sin(incidence) * my``. +* Balanced detection: a half-wave plate at angle ``alpha`` rotates the polarisation by ``2 alpha`` in front of a + polarising beam splitter. Photodiode A gets ``P sin^2(phi)`` and B gets ``P cos^2(phi)`` with + ``phi = 2 (alpha - alpha_zero) + theta_K``. The beams are balanced at ``alpha - alpha_zero = 22.5 deg`` where + ``A - B = P sin(2 theta_K)``; away from it the offset grows and the sensitivity drops as ``cos(2 delta)``. +""" +from dataclasses import dataclass, field, fields +import math +import threading +import time +from typing import Callable, Optional + +import numpy as np + +DOC = __doc__ + +ELECTRON_CHARGE = 1.602176634e-19 # C +MT_TO_A_PER_M = 1e-3 / (4e-7 * math.pi) # B = mu0 H in vacuum: 1 mT <-> 795.77 A/m +MODELS = ['Stoner-Wohlfarth', 'tanh'] + + +def unit_vector(polar_deg: float, azimuth_deg: float) -> np.ndarray: + """Unit vector from a polar angle (from z) and an azimuth (from x), in degrees""" + t, p = math.radians(polar_deg), math.radians(azimuth_deg) + return np.array([math.sin(t) * math.cos(p), math.sin(t) * math.sin(p), math.cos(t)]) + + +@dataclass +class SampleSettings: + model: str = MODELS[0] + hk: float = 40. # mT, anisotropy field (Stoner-Wohlfarth): the switching field is Hk along the easy axis, Hk/2 at 45 deg + hc: float = 15. # mT, coercive field (tanh model) + width: float = 4. # mT, width of the switching (tanh model) + easy_polar: float = 0. # deg, easy axis from the normal (0: perpendicular anisotropy, 90: in plane) + easy_azimuth: float = 0. # deg, easy axis azimuth in the sample frame + kerr_polar: float = 0.5e-3 # rad, polar Kerr rotation at saturation (m = +z) + kerr_long: float = 0.3e-3 # rad, longitudinal Kerr rotation at saturation and 90 deg incidence (m = +x) + kerr_trans: float = 1e-3 # relative reflectivity change at saturation (m = +y, p polarisation) + kerr_s_over_p: float = 1. # ratio of the Kerr rotations in s and p polarisation (simple model) + polarization: str = 'p' # incident polarisation, 'p' or 's' + + +@dataclass +class OpticsSettings: + power: float = 1. # mW, power of the probe beam on the sample + reflectivity: float = 0.5 + responsivity: float = 0.5 # A/W of the photodiodes + gain: float = 1e3 # V/A, transimpedance of each diode amplifier + bandwidth: float = 50. # Hz, detection bandwidth (sets the shot noise) + waveplate_zero: float = 0. # deg, unknown offset of the zero of the half-wave plate (hidden defect) + + +@dataclass +class ImperfectionSettings: + enabled: bool = True # master switch + shot_noise: bool = True + electronic_noise: bool = True + electronic_noise_rms: float = 20e-6 # V on each channel + laser_noise: bool = True + laser_noise_rms: float = 1e-3 # relative intensity noise (common to both diodes) + imbalance: bool = False + imbalance_percent: float = 2. # % gain difference between diodes A and B + faraday: bool = False + faraday_slope: float = 5e-6 # rad/mT, linear rotation of the optics in the field + drift: bool = False + drift_amplitude: float = 0.2e-3 # rad, slow oscillation of the polarisation + drift_period: float = 60. # s + + +class MokeBench: + """Simulated MOKE bench: magnet, sample, optics and balanced photodetector""" + + def __init__(self, clock: Callable[[], float] = time.monotonic, seed: Optional[int] = None): + self._lock = threading.RLock() + self._clock = clock + self.rng = np.random.default_rng(seed) + self.sample = SampleSettings() + self.optics = OpticsSettings() + self.imperfections = ImperfectionSettings() + # instruments + self.field_tau = 0.05 # s, first order response of the magnet + self.field_polar = 0. # deg, direction of the field from the sample normal (0: polar geometry, 90: in plane) + self.field_azimuth = 0. # deg, in the lab frame (0: in the plane of incidence) + self.waveplate_angle = 22.5 # deg + self.sample_rotation = 0. # deg, rotation of the sample about its normal + self.incidence = 45. # deg, angle of incidence + # state + self._field = 0. + self._field_target = 0. + self._t_field = clock() + self._t0 = self._t_field + self._m = unit_vector(self.sample.easy_polar, self.sample.easy_azimuth + self.sample_rotation) + self._branch = 1. # tanh model: last sweep direction + self._h_projected_last = 0. + self.closed = False + + # ------------------------------------------------------------------ settings + def set_parameter(self, group: str, name: str, value): + """Set ``name`` of the settings ``group`` ('sample', 'optics', 'imperfections') or of the bench ('bench')""" + with self._lock: + target = self if group == 'bench' else getattr(self, group) + if not hasattr(target, name): + raise KeyError(f'{group}.{name} is not a parameter of the simulated bench') + setattr(target, name, value) + + def get_parameters(self, group: str) -> dict: + target = getattr(self, group) + return {f.name: getattr(target, f.name) for f in fields(target)} + + # ------------------------------------------------------------------ magnet + def set_field_target(self, value: float): + with self._lock: + self._advance_field() + self._field_target = float(value) + + def get_field(self) -> float: + with self._lock: + self._advance_field() + return self._field + + def _advance_field(self): + """Move the field toward its target (first order response) and let the magnetisation follow""" + now = self._clock() + dt = max(now - self._t_field, 0.) + self._t_field = now + f0, target = self._field, self._field_target + if self.field_tau <= 0: + f1 = target + else: + f1 = target + (f0 - target) * math.exp(-dt / self.field_tau) + if f1 != f0: + self._follow_field(f0, f1) + self._field = f1 + + # ------------------------------------------------------------------ magnetisation + def _easy_axis(self) -> np.ndarray: + return unit_vector(self.sample.easy_polar, self.sample.easy_azimuth + self.sample_rotation) + + def _field_direction(self) -> np.ndarray: + return unit_vector(self.field_polar, self.field_azimuth) + + def _follow_field(self, f0: float, f1: float): + s = self.sample + if s.model == 'tanh': + self._follow_tanh(f1) + return + hk = max(s.hk, 1e-9) + n_sub = int(min(abs(f1 - f0) / (0.02 * hk), 400)) + 1 + for f in np.linspace(f0, f1, n_sub + 1)[1:]: + self._m = self._relax(self._m, self._field_direction() * f / hk, self._easy_axis()) + + def _relax(self, m: np.ndarray, h: np.ndarray, easy: np.ndarray, max_iter: int = 600) -> np.ndarray: + """Follow the local minimum of e(m) = -(m.easy)^2 / 2 - h.m on the unit sphere (h in units of Hk) + + A tiny random tilt (a stand-in for thermal fluctuations) lets m leave a stationary point that has become + unstable, which would otherwise be kept forever when the field is exactly along the easy axis. + """ + m = m + 1e-4 * self.rng.standard_normal(3) + m = m / np.linalg.norm(m) + for _ in range(max_iter): + grad = -np.dot(m, easy) * easy - h + grad_t = grad - np.dot(grad, m) * m + if np.dot(grad_t, grad_t) < 1e-18: + break + m = m - 0.4 * grad_t + m = m / np.linalg.norm(m) + return m + + def _follow_tanh(self, f1: float): + s = self.sample + easy = self._easy_axis() + h = f1 * float(np.dot(self._field_direction(), easy)) # field component along the easy axis + if h > self._h_projected_last: + self._branch = 1. + elif h < self._h_projected_last: + self._branch = -1. + self._h_projected_last = h + w = max(s.width, 1e-9) + m_up = math.tanh((h - s.hc) / w) # ascending branch + m_down = math.tanh((h + s.hc) / w) # descending branch + amplitude = float(np.dot(self._m, easy)) + amplitude = max(amplitude, m_up) if self._branch > 0 else min(amplitude, m_down) + self._m = easy * amplitude + + def magnetisation(self) -> np.ndarray: + """Unit vector (tanh model: reduced) of the magnetisation in the lab frame""" + with self._lock: + self._advance_field() + return self._m.copy() + + # ------------------------------------------------------------------ optics and detection + def kerr_rotation(self, m: Optional[np.ndarray] = None) -> float: + """Kerr rotation (rad) of the sample for the magnetisation ``m`` and the present geometry""" + s = self.sample + if m is None: + m = self.magnetisation() + sin_i = math.sin(math.radians(self.incidence)) + rotation = s.kerr_polar * m[2] + s.kerr_long * sin_i * m[0] + if s.polarization == 's': + rotation *= s.kerr_s_over_p + return float(rotation) + + def read_diodes(self, t_int: float = 0.0) -> dict: + """Voltages (V) of photodiodes A and B, their difference and sum, with the enabled imperfections""" + with self._lock: + m = self.magnetisation() + field = self._field + theta_k = self.kerr_rotation(m) + o, s, imp = self.optics, self.sample, self.imperfections + active = imp.enabled + rng = self.rng + sin_i = math.sin(math.radians(self.incidence)) + + if active and imp.faraday: + theta_k += imp.faraday_slope * field + if active and imp.drift: + theta_k += imp.drift_amplitude * math.sin(2 * math.pi * (self._clock() - self._t0) / imp.drift_period) + + power = o.power * 1e-3 * o.reflectivity # W + if s.polarization == 'p': + power *= 1 + s.kerr_trans * sin_i * m[1] + if active and imp.laser_noise: + power *= 1 + imp.laser_noise_rms * rng.standard_normal() + + alpha = self.waveplate_angle - o.waveplate_zero + phi = math.radians(2 * alpha) + theta_k + p_a, p_b = power * math.sin(phi) ** 2, power * math.cos(phi) ** 2 + + gain_a = gain_b = o.gain * o.responsivity # V/W + if active and imp.imbalance: + gain_a *= 1 + imp.imbalance_percent / 200. + gain_b *= 1 - imp.imbalance_percent / 200. + v_a, v_b = gain_a * p_a, gain_b * p_b + + bandwidth = o.bandwidth if t_int <= 0 else 1. / (2. * t_int) + if active and imp.shot_noise: + for name, p in (('a', p_a), ('b', p_b)): + sigma_i = math.sqrt(2 * ELECTRON_CHARGE * max(o.responsivity * p, 0.) * bandwidth) + if name == 'a': + v_a += o.gain * sigma_i * rng.standard_normal() + else: + v_b += o.gain * sigma_i * rng.standard_normal() + if active and imp.electronic_noise: + v_a += imp.electronic_noise_rms * rng.standard_normal() + v_b += imp.electronic_noise_rms * rng.standard_normal() + return dict(diode_A=float(v_a), diode_B=float(v_b), difference=float(v_a - v_b), sum=float(v_a + v_b)) + + def close(self): + self.closed = True diff --git a/src/pymodaq_plugins_moke/hardware/simulated_move.py b/src/pymodaq_plugins_moke/hardware/simulated_move.py new file mode 100644 index 0000000..e4cbeab --- /dev/null +++ b/src/pymodaq_plugins_moke/hardware/simulated_move.py @@ -0,0 +1,87 @@ +"""Common code of the simulated actuators of the MOKE bench (see :mod:`.simulated_bench`)""" +import time +from typing import Dict, Tuple + +from pymodaq.control_modules.move_utility_classes import DAQ_Move_base, DataActuatorType +from pymodaq.control_modules.daq_move_ui.utils import UiType +from pymodaq.utils.data import DataActuator +from pymodaq_gui.parameter import Parameter +from pymodaq_utils.utils import ThreadCommand + +from pymodaq_plugins_moke.hardware.simulated_bench import MokeBench + + +class SimulatedBenchMove(DAQ_Move_base): + """Base of the simulated actuators: one instrument of the shared simulated bench. + + The first module initialised (master) creates the bench, the others (slaves, same controller ID) receive it. + A subclass sets ``_bench_attribute`` (the attribute of the bench the actuator drives) and may list in + ``_bench_parameters`` the settings it forwards to the bench: ``{setting name: (group, attribute, factor)}``. + """ + is_multiaxes = False + data_actuator_type = DataActuatorType.DataActuator + ui_type = UiType.NONE + has_encoder = True + + _bench_attribute: str = '' + _home_value: float = 0. + _bench_parameters: Dict[str, Tuple[str, str, float]] = {} + + def ini_attributes(self): + self.controller: MokeBench = None + + def ini_stage(self, controller=None): + if self.is_master: + self.controller = MokeBench() + else: + self.controller = controller + for name in self._bench_parameters: + self._forward(self.settings.child(name)) + return f'Simulated {self._axis_names[0]} actuator of the MOKE bench, no hardware', True + + def close(self): + if self.is_master and self.controller is not None: + self.controller.close() + + # to be overridden when the instrument has a response time + def _read(self) -> float: + return getattr(self.controller, self._bench_attribute) + + def _write(self, value: float): + setattr(self.controller, self._bench_attribute, value) + + def get_actuator_value(self) -> DataActuator: + pos = DataActuator(data=self._read(), units=self.axis_unit) + return self.get_position_with_scaling(pos) + + def move_abs(self, value: DataActuator): + value = self.check_bound(value) + self.target_value = value + value = self.set_position_with_scaling(value) + self._write(value.value(self.axis_unit)) + + def move_rel(self, value: DataActuator): + value = self.check_bound(self.current_value + value) - self.current_value + self.target_value = value + self.current_value + value = self.set_position_relative_with_scaling(value) + self._write(self._read() + value.value(self.axis_unit)) + + def move_home(self): + self._write(self._home_value) + deadline = time.monotonic() + 5. + while abs(self._read() - self._home_value) > self.settings['epsilon'] and time.monotonic() < deadline: + time.sleep(0.01) + self.emit_status(ThreadCommand('Update_Status', [f'{self._axis_names[0]} at home'])) + self.move_done() + + def stop_motion(self): + self._write(self._read()) + self.move_done() + + def _forward(self, param: Parameter): + group, attribute, factor = self._bench_parameters[param.name()] + self.controller.set_parameter(group, attribute, param.value() * factor) + + def commit_settings(self, param: Parameter): + if param.name() in self._bench_parameters: + self._forward(param) diff --git a/tests/test_simulated_bench.py b/tests/test_simulated_bench.py new file mode 100644 index 0000000..6a26ed9 --- /dev/null +++ b/tests/test_simulated_bench.py @@ -0,0 +1,157 @@ +"""Physics of the simulated MOKE bench (no PyMoDAQ module needed): loops, balance, geometry, imperfections.""" +import numpy as np +import pytest + +from pymodaq_plugins_moke.hardware.simulated_bench import MokeBench, MODELS + + +class FakeClock: + def __init__(self): + self.t = 0. + + def __call__(self): + return self.t + + def advance(self, dt): + self.t += dt + + +def make_bench(model=MODELS[0], imperfections=False, **sample): + clock = FakeClock() + bench = MokeBench(clock=clock, seed=3) + bench.imperfections.enabled = imperfections + bench.sample.model = model + for key, value in sample.items(): + setattr(bench.sample, key, value) + bench._m = bench._easy_axis() + bench.clock = clock + return bench + + +def sweep(bench, fields): + """Difference signal (V) at each field once the magnet has settled""" + out = [] + for field in fields: + bench.set_field_target(field) + bench.clock.advance(10 * bench.field_tau + 1e-3) + out.append(bench.read_diodes()['difference']) + return np.array(out) + + +FIELDS_UP = np.linspace(-100, 100, 41) +FIELDS = np.concatenate([FIELDS_UP, FIELDS_UP[::-1]]) + + +@pytest.mark.parametrize('model', MODELS) +def test_loop_is_a_hysteresis_with_the_expected_coercive_field(model): + bench = make_bench(model, hk=40., hc=15.) + signal = sweep(bench, FIELDS) + up, down = signal[:41], signal[41:][::-1] + assert np.sign(up[0]) == -1 and np.sign(up[-1]) == 1 # saturates on both sides + zero = 20 + assert up[zero] * down[zero] < 0 # opposite remanent states at zero field + switch_up = FIELDS_UP[np.argmax(up > 0)] + expected = 40. if model == MODELS[0] else 15. + assert switch_up == pytest.approx(expected, abs=5.) + + +def test_balance_is_at_22_5_degrees_and_offset_grows_away_from_it(): + bench = make_bench(kerr_polar=0.) + bench.waveplate_angle = 22.5 + balanced = bench.read_diodes() + assert balanced['difference'] == pytest.approx(0., abs=1e-9) + assert balanced['diode_A'] == pytest.approx(balanced['diode_B']) + bench.waveplate_angle = 24.5 + assert bench.read_diodes()['difference'] > 1e-3 * balanced['sum'] + + +def test_difference_gives_the_kerr_rotation_at_balance(): + bench = make_bench(model='tanh', kerr_polar=0.5e-3) + sweep(bench, [100.]) + out = bench.read_diodes() + assert out['difference'] / (2 * out['sum']) == pytest.approx(0.5e-3, rel=1e-3) + + +def test_sensitivity_drops_away_from_balance(): + """The slope of the difference with the Kerr rotation is cos(2 delta) of its maximum, delta being the rotation of + the polarisation away from the balance: 10 deg of waveplate is 20 deg of polarisation, factor sin(130 deg)""" + def sensitivity(waveplate_angle): + bench = make_bench(model='tanh', kerr_polar=0.) + bench.waveplate_angle = waveplate_angle + base = bench.read_diodes() + bench.sample.kerr_polar = 1e-3 + bench._m = np.array([0., 0., 1.]) + shifted = bench.read_diodes() + return (shifted['difference'] - base['difference']) / base['sum'] + + assert sensitivity(32.5) / sensitivity(22.5) == pytest.approx(np.sin(np.radians(130)), rel=1e-3) + + +def test_hidden_waveplate_zero_shifts_the_balance(): + bench = make_bench(kerr_polar=0.) + bench.optics.waveplate_zero = 3. + assert abs(bench.read_diodes()['difference']) > 1e-4 + bench.waveplate_angle = 22.5 + 3. + assert bench.read_diodes()['difference'] == pytest.approx(0., abs=1e-9) + + +def test_longitudinal_signal_scales_with_the_sine_of_the_incidence(): + amplitudes = {} + for incidence in (0., 30., 60.): + bench = make_bench(model='tanh', easy_polar=90., kerr_polar=0., kerr_long=0.4e-3) + bench.field_polar = 90. + bench.incidence = incidence + sweep(bench, [100.]) + amplitudes[incidence] = bench.read_diodes()['difference'] + assert amplitudes[0.] == pytest.approx(0., abs=1e-9) + assert amplitudes[60.] / amplitudes[30.] == pytest.approx(np.sin(np.radians(60)) / np.sin(np.radians(30)), rel=1e-3) + + +def test_sample_rotation_changes_the_stoner_wohlfarth_loop(): + """In plane easy axis, field in the plane of incidence: the loop is square when the axis is along the field and + closes (no coercivity) when the sample is rotated by 90 deg""" + widths = {} + for rotation in (0., 90.): + bench = make_bench(easy_polar=90., kerr_polar=0., kerr_long=0.4e-3, hk=40.) + bench.field_polar = 90. + bench.sample_rotation = rotation + bench._m = bench._easy_axis() + signal = sweep(bench, FIELDS) + up, down = signal[:41], signal[41:][::-1] + widths[rotation] = np.sum(np.abs(up - down)) / np.max(np.abs(signal)) + assert widths[0.] > 10 * max(widths[90.], 1e-3) + + +def test_field_follows_its_target_with_the_response_time(): + bench = make_bench() + bench.field_tau = 0.1 + bench.set_field_target(50.) + bench.clock.advance(0.1) + assert bench.get_field() == pytest.approx(50. * (1 - np.exp(-1)), rel=1e-6) + bench.clock.advance(2.) + assert bench.get_field() == pytest.approx(50., rel=1e-6) + + +def test_imperfections_only_when_enabled(): + quiet = make_bench(imperfections=False) + assert quiet.read_diodes()['difference'] == quiet.read_diodes()['difference'] # deterministic + noisy = make_bench(imperfections=True) + values = [noisy.read_diodes()['difference'] for _ in range(200)] + assert 1e-6 < np.std(values) < 1e-3 + + +def test_laser_noise_is_rejected_by_the_balance_but_not_by_the_sum(): + bench = make_bench(imperfections=True, kerr_polar=0.) + bench.imperfections.shot_noise = False + bench.imperfections.electronic_noise = False + bench.imperfections.laser_noise_rms = 0.01 + reads = [bench.read_diodes() for _ in range(300)] + std_sum = np.std([r['sum'] for r in reads]) / np.mean([r['sum'] for r in reads]) + std_diff = np.std([r['difference'] for r in reads]) / np.mean([r['sum'] for r in reads]) + assert std_sum == pytest.approx(0.01, rel=0.2) + assert std_diff < 0.01 * std_sum # perfectly balanced: no laser noise in the difference + + +def test_unknown_parameter_is_refused(): + with pytest.raises(KeyError): + MokeBench().set_parameter('sample', 'not_a_parameter', 1) diff --git a/tests/test_simulated_plugins.py b/tests/test_simulated_plugins.py new file mode 100644 index 0000000..f647831 --- /dev/null +++ b/tests/test_simulated_plugins.py @@ -0,0 +1,130 @@ +"""Behaviour of the simulated MOKE plugins as the Dashboard drives them, with the harness of PyMoDAQ. + +The magnet, half-wave plate, sample rotation and goniometer actuators and the balanced detector share one bench: +the first plugin initialised is the master and the others receive its controller (slaves).""" +import numpy as np +import pytest + +from pymodaq.utils.plugin_testing import (make_actuator, make_detector, move_abs_and_wait, move_rel_and_wait, + move_home_and_wait, grab_and_wait, assert_units) + +from pymodaq_plugins_moke.daq_move_plugins.daq_move_MokeMagnetSim import DAQ_Move_MokeMagnetSim +from pymodaq_plugins_moke.daq_move_plugins.daq_move_MokeWavePlateSim import DAQ_Move_MokeWavePlateSim +from pymodaq_plugins_moke.daq_move_plugins.daq_move_MokeSampleRotationSim import DAQ_Move_MokeSampleRotationSim +from pymodaq_plugins_moke.daq_move_plugins.daq_move_MokeGoniometerSim import DAQ_Move_MokeGoniometerSim +from pymodaq_plugins_moke.daq_viewer_plugins.plugins_0D.daq_0Dviewer_MokeBalancedSim import ( + DAQ_0DViewer_MokeBalancedSim, LABELS) + +ACTUATORS = {DAQ_Move_MokeMagnetSim: 'mT', DAQ_Move_MokeWavePlateSim: 'deg', + DAQ_Move_MokeSampleRotationSim: 'deg', DAQ_Move_MokeGoniometerSim: 'deg'} + + +def set_setting(plugin, path, value): + """Change a setting as the module does: set the value, then let the plugin apply it (commit_settings)""" + param = plugin.settings.child(*path) + param.setValue(value) + plugin.commit_settings(param) + + +@pytest.fixture +def bench_plugins(): + """All the plugins on one bench: the magnet is the master, the others are slaves""" + magnet = make_actuator(DAQ_Move_MokeMagnetSim, tau=1.) # 1 ms response time, fast tests + plugins = [magnet] + for cls in (DAQ_Move_MokeWavePlateSim, DAQ_Move_MokeSampleRotationSim, DAQ_Move_MokeGoniometerSim): + plugins.append(make_actuator(cls, controller=magnet.controller)) + detector = make_detector(DAQ_0DViewer_MokeBalancedSim, controller=magnet.controller) + plugins.append(detector) + yield magnet, plugins[1:-1], detector + for plugin in reversed(plugins): + plugin.close() + + +@pytest.mark.parametrize('cls, unit', list(ACTUATORS.items())) +def test_each_actuator_moves_and_reports_its_unit(cls, unit): + actuator = make_actuator(cls) + assert actuator.initialized + pos = move_abs_and_wait(actuator, 10.) + assert pos.units == unit + assert pos.value(unit) == pytest.approx(10., abs=0.6) + pos = move_rel_and_wait(actuator, 2.) + assert pos.value(unit) == pytest.approx(12., abs=0.6) + actuator.close() + + +def test_home_positions(): + magnet = make_actuator(DAQ_Move_MokeMagnetSim, tau=1.) + move_abs_and_wait(magnet, 30.) + assert move_home_and_wait(magnet).value('mT') == pytest.approx(0., abs=0.6) + waveplate = make_actuator(DAQ_Move_MokeWavePlateSim) + move_abs_and_wait(waveplate, 5.) + assert move_home_and_wait(waveplate).value('deg') == pytest.approx(22.5, abs=0.02) + + +def test_all_plugins_share_one_controller(bench_plugins): + magnet, others, detector = bench_plugins + assert all(p.controller is magnet.controller for p in others) + assert detector.controller is magnet.controller + + +def test_slaves_do_not_close_the_shared_bench(bench_plugins): + magnet, others, detector = bench_plugins + others[0].close() + detector.close() + assert not magnet.controller.closed + + +def test_detector_returns_four_channels_in_volts(bench_plugins): + _, _, detector = bench_plugins + dte = grab_and_wait(detector) + assert len(dte) == 1 + assert dte[0].labels == LABELS + assert dte[0].dim.name == 'Data0D' + assert_units(dte, 'V') + + +def test_hysteresis_loop_through_the_plugins(bench_plugins): + magnet, _, detector = bench_plugins + set_setting(detector, ('imperfections', 'imperfections_enabled',), False) + set_setting(detector, ('sample', 'model',), 'tanh') + fields = np.concatenate([np.linspace(-60, 60, 13), np.linspace(60, -60, 13)]) + signal = [] + for field in fields: + move_abs_and_wait(magnet, field) + data = grab_and_wait(detector) + signal.append(float(data.get_data_from_full_name('MokeBalanced/MokeBalanced').data[2][0])) + signal = np.array(signal) + up, down = signal[:13], signal[13:][::-1] + assert up[0] < 0 < up[-1] + assert up[6] * down[6] < 0 # the remanent state depends on the history + + +def test_waveplate_balances_the_detection(bench_plugins): + _, (waveplate, *_), detector = bench_plugins + set_setting(detector, ('imperfections', 'imperfections_enabled',), False) + set_setting(detector, ('optics', 'waveplate_zero',), 3.) + move_abs_and_wait(waveplate, 22.5) + unbalanced = grab_and_wait(detector)[0].data + move_abs_and_wait(waveplate, 25.5) + balanced = grab_and_wait(detector)[0].data + assert abs(balanced[2][0]) < abs(unbalanced[2][0]) + + +def test_settings_reach_the_bench(bench_plugins): + magnet, _, detector = bench_plugins + set_setting(detector, ('sample', 'hk',), 55.) + set_setting(detector, ('imperfections', 'laser_noise_rms',), 0.5) # in % + set_setting(detector, ('imperfections', 'electronic_noise_rms',), 30.) # in uV + assert magnet.controller.sample.hk == 55. + assert magnet.controller.imperfections.laser_noise_rms == pytest.approx(5e-3) + assert magnet.controller.imperfections.electronic_noise_rms == pytest.approx(30e-6) + set_setting(magnet, ('tau',), 200.) + assert magnet.controller.field_tau == pytest.approx(0.2) + + +def test_detector_alone_works_as_master(): + detector = make_detector(DAQ_0DViewer_MokeBalancedSim) + assert detector.initialized + dte = grab_and_wait(detector) + assert dte[0].labels == LABELS + detector.close()