diff --git a/README.rst b/README.rst index 809cf3f..418161c 100644 --- a/README.rst +++ b/README.rst @@ -27,6 +27,10 @@ Branches * ``correction-module-a``: the solution of the module A (``DAQ_Move_Monochromator``, ``DAQ_0DViewer_PhotodiodeMonochromator``, ``DAQ_1DViewer_Spectrometer``). * ``correction-module-b``: the solution of the modules A and B (adds the beam profiler plugin, app and extension). +* ``correction-module-c``: the corrected notebooks of the module C. + +The module C (data and analysis) uses the notebooks of the ``notebooks`` folder (to complete: replace each ``...``) +and the measurement files of the ``data`` folder. Authors ======= diff --git a/data/continuous_spectra.h5 b/data/continuous_spectra.h5 new file mode 100644 index 0000000..92ba162 Binary files /dev/null and b/data/continuous_spectra.h5 differ diff --git a/data/scan_photodiode.h5 b/data/scan_photodiode.h5 new file mode 100644 index 0000000..db88ff0 Binary files /dev/null and b/data/scan_photodiode.h5 differ diff --git a/data/spectrum_naverage200.h5 b/data/spectrum_naverage200.h5 new file mode 100644 index 0000000..804a315 Binary files /dev/null and b/data/spectrum_naverage200.h5 differ diff --git a/notebooks/01_data_objects.ipynb b/notebooks/01_data_objects.ipynb new file mode 100644 index 0000000..785e860 --- /dev/null +++ b/notebooks/01_data_objects.ipynb @@ -0,0 +1,287 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Module C, sequence 1: the data objects (exercises)\n", + "\n", + "Replace each `...` by what its comment asks, then run the cell. The steps follow the TP 1 of the handout of the module C. The corrected notebook is in the branch `correction-module-c`." + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import numpy as np\n", + "from pymodaq_utils.math_utils import gauss1D\n", + "from pymodaq_data import Q_\n", + "from pymodaq_data.data import Axis, DataRaw, DataToExport" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## 0. A minimal example\n", + "\n", + "A data object holds a **list** of NumPy arrays of the same shape (one per channel), their axes, their labels and\n", + "their units. Here, five values of one detector measured at five positions of an actuator. Read it, run it, then\n", + "build your own data in the next cells." + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "position = Axis('position', 'mm', data=np.array([0., 1., 2., 3., 4.]), index=0) # index: the dimension of the array\n", + "minimal = DataRaw('minimal', data=[np.array([0.1, 0.4, 1.0, 0.4, 0.1])], axes=[position],\n", + " labels=['detector'], units='V')\n", + "print(minimal)\n", + "print(minimal.axes[0].label, minimal.axes[0].units, minimal.axes[0].get_data())\n", + "print(minimal.labels, minimal.units, minimal.data[0])" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## 1. Build the line\n", + "\n", + "The profile of a spectral line seen by the photodiode: 121 points from 500 to 560 nm, a gaussian centred at 528 nm,\n", + "4 nm wide at half maximum (`gauss1D(x, x0, fwhm)`), 3 V high, on a background of 0.1 V." + ] + }, + { + "cell_type": "code", + "metadata": { + "tags": [ + "exercise" + ] + }, + "source": [ + "wavelength = Axis('wavelength', ..., data=..., index=0) # units 'nm', 121 points from 500 to 560 nm (hint: np.linspace)\n", + "signal = 3 * gauss1D(..., 528, 4) + 0.1 # computed on the values of the axis (hint: get_data())\n", + "line = DataRaw('line', data=..., axes=..., labels=['photodiode'], units=...) # data and axes are lists\n", + "print(line)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## 2. A linear axis does not store its array" + ] + }, + { + "cell_type": "code", + "metadata": { + "tags": [ + "exercise" + ] + }, + "source": [ + "print(...) # the `data` attribute of `wavelength`: why is it None?\n", + "print(...) # the first three values of the array of `wavelength`" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## 3. Navigation and signal axes" + ] + }, + { + "cell_type": "code", + "metadata": { + "tags": [ + "exercise" + ] + }, + "source": [ + "print(line.dim, ..., ..., ...) # the shape, the navigation indexes and the signal indexes of `line`\n", + "assert len(...) == 0 # `line` has no navigation axis" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## 4. Plot with the PyMoDAQ viewer (needs a display)\n", + "\n", + "Find the centre of the line with the mouse." + ] + }, + { + "cell_type": "code", + "metadata": { + "tags": [ + "exercise" + ] + }, + "source": [ + "%gui qt\n", + "line.plot(...) # plot `line` in the PyMoDAQ viewer (Qt)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## 5. Slicing by values and by indices" + ] + }, + { + "cell_type": "code", + "metadata": { + "tags": [ + "exercise" + ] + }, + "source": [ + "by_value = line.vsig[...] # keep the points from 515 nm to 540 nm (vsig: by axis values, on the signal axis)\n", + "by_index = line.isig[...] # keep the ten first points (isig: by indices, on the signal axis)\n", + "print(by_value.shape, by_value.axes[0].get_data()[[0, -1]])\n", + "print(by_index.shape)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## 6. Units: remove the background" + ] + }, + { + "cell_type": "code", + "metadata": { + "tags": [ + "exercise" + ] + }, + "source": [ + "try:\n", + " ... # subtract the bare number 0.1 from `line`\n", + "except Exception as e:\n", + " print(type(e).__name__, e) # read the error\n", + "no_bkg = line - ... # subtract a background of 0.1 V (hint: Q_)\n", + "no_bkg.name = 'line_no_bkg'\n", + "print(no_bkg.units, no_bkg.data[0].max())" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## 7. The axis in eV (on a copy)" + ] + }, + { + "cell_type": "code", + "metadata": { + "tags": [ + "exercise" + ] + }, + "source": [ + "line_ev = ... # an independent copy of `line` (hint: deepcopy)\n", + "line_ev.axes[0] = line.axes[0].units_as(..., inplace=..., context=...) # in eV, without modifying `line`\n", + "print(line.axes[0].units, line.axes[0].get_data()[[0, -1]])\n", + "print(line_ev.axes[0].units, line_ev.axes[0].get_data()[[0, -1]])" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## 8. Errors follow the slicing" + ] + }, + { + "cell_type": "code", + "metadata": { + "tags": [ + "exercise" + ] + }, + "source": [ + "line.errors = [...] # an uncertainty of 0.05 V on each of the 121 points (a list of arrays, like `data`)\n", + "cropped = line.vsig[515.:540.]\n", + "print(cropped.errors[0].shape == ...) # the errors have the same shape as the data" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## 9. Gather in a DataToExport" + ] + }, + { + "cell_type": "code", + "metadata": { + "tags": [ + "exercise" + ] + }, + "source": [ + "mesure = DataToExport('mesure', data=...) # holding `line` and `no_bkg`\n", + "print(...) # get back `line` from `mesure` by its name (hint: get_data_from_name)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Control question 1\n", + "\n", + "What is the difference between `line.vsig[515.:540.]` and `line.isig[10:60]` for this axis from 500 to 560 nm with\n", + "a step of 0.5 nm? Check your answer in a cell below." + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 5 +} diff --git a/notebooks/02_saving_loading.ipynb b/notebooks/02_saving_loading.ipynb new file mode 100644 index 0000000..5580087 --- /dev/null +++ b/notebooks/02_saving_loading.ipynb @@ -0,0 +1,165 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Module C, sequence 2: saving and loading (exercises)\n", + "\n", + "Replace each `...` by what its comment asks, then run the cell. The steps follow the TP 2 of the handout of the module C. The corrected notebook is in the branch `correction-module-c`." + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import numpy as np\n", + "from pathlib import Path\n", + "from pymodaq_utils.math_utils import gauss1D\n", + "from pymodaq_data.data import Axis, DataRaw, DataToExport\n", + "from pymodaq_data.h5modules.saving import H5SaverLowLevel\n", + "from pymodaq_data.h5modules.data_saving import DataToExportSaver, DataLoader\n", + "\n", + "DATA = Path('../data')\n", + "\n", + "# the objects of the sequence 1\n", + "wavelength = Axis('wavelength', 'nm', data=np.linspace(500, 560, 121), index=0)\n", + "signal = 3 * gauss1D(wavelength.get_data(), 528, 4) + 0.1\n", + "line = DataRaw('line', data=[signal], axes=[wavelength], labels=['photodiode'], units='V')\n", + "line.errors = [np.full(121, 0.05)]\n", + "mesure = DataToExport('mesure', data=[line])" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## 1. Write the file\n", + "\n", + "Then open `line.h5` in H5Browser (`h5browser` in a terminal): plot the line and read its attributes." + ] + }, + { + "cell_type": "code", + "metadata": { + "tags": [ + "exercise" + ] + }, + "source": [ + "path = Path('line.h5')\n", + "path.unlink(missing_ok=True) # init_file appends to an existing file\n", + "\n", + "h5saver = H5SaverLowLevel()\n", + "... # create the file at `path`\n", + "... # add a detector group under '/RawData', titled 'Photodiode line'\n", + "... # save `mesure` in the group '/RawData/Detector000' (hint: DataToExportSaver)\n", + "for node in ...: # walk all the nodes of the file, from '/'\n", + " print(node)\n", + "h5saver.close_file()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## 2. Read it back and compare" + ] + }, + { + "cell_type": "code", + "metadata": { + "tags": [ + "exercise" + ] + }, + "source": [ + "loader = ... # open the file for reading\n", + "loaded = ... # load everything under '/RawData/Detector000' (a DataToExport)\n", + "loader.close_file()\n", + "back = ... # the data named 'line'\n", + "print(...) # is it equal to `line`? Print also its axes and its errors" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## 3. Read the continuous recording of the DAQ_Viewer (enlargeable arrays)\n", + "\n", + "Use your own recording (Do Save in the DAQ_Viewer of the spectrometer), or the file of the `data` folder." + ] + }, + { + "cell_type": "code", + "metadata": { + "tags": [ + "exercise" + ] + }, + "source": [ + "loader = DataLoader(DATA / 'continuous_spectra.h5') # or the path of your own recording\n", + "... # print the nodes of the file and find the enlargeable array (EnlData)\n", + "spectra = ... # load this array with its navigation axis (hint: load_data, load_all=True)\n", + "loader.close_file()\n", + "print(spectra.shape[0], 'spectra recorded, shape', spectra.shape)\n", + "timestamps = ... # the axis of the dimension 0 (hint: get_axis_from_index)\n", + "print(timestamps.label, timestamps.units, timestamps.get_data()[:3])" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## 4. Mean and standard deviation of the series" + ] + }, + { + "cell_type": "code", + "metadata": { + "tags": [ + "exercise" + ] + }, + "source": [ + "mean_spectrum = ... # the mean over the navigation axis (the acquisitions), as a data object\n", + "std_spectrum = spectra.data[0].std(axis=0, ddof=1)\n", + "wavelength = ... # the values of the signal axis (the wavelengths)\n", + "i_peak = int(np.argmax(mean_spectrum.data[0]))\n", + "print(wavelength[i_peak], mean_spectrum.data[0][i_peak], std_spectrum[i_peak])" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Control question 2\n", + "\n", + "Why does the file of the continuous recording not have the same layout as a snapshot file, and what would we lose\n", + "by saving each spectrum in a separate file?" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 5 +} diff --git a/notebooks/03_analysis.ipynb b/notebooks/03_analysis.ipynb new file mode 100644 index 0000000..295922d --- /dev/null +++ b/notebooks/03_analysis.ipynb @@ -0,0 +1,337 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Module C, sequence 3: analysis (exercises)\n", + "\n", + "Replace each `...` by what its comment asks, then run the cell. The steps follow the TP 3 of the handout of the module C. The corrected notebook is in the branch `correction-module-c`." + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from pathlib import Path\n", + "import numpy as np\n", + "import matplotlib.pyplot as plt\n", + "from scipy.optimize import curve_fit\n", + "from scipy.signal import find_peaks\n", + "from pymodaq_utils.math_utils import gauss1D\n", + "from pymodaq_data.h5modules.data_saving import DataLoader\n", + "\n", + "DATA = Path('../data')\n", + "SCAN = '/RawData/Scan000/Detector000/Data0D/CH00/Data00' # one scan\n", + "SCAN8 = '/RawData/Scan001/Detector000/Data0D/CH00/Data00' # the same scan repeated 8 times (scan_average = 8)\n", + "\n", + "\n", + "def model(x, amp, x0, fwhm, offset):\n", + " return amp * gauss1D(x, x0, fwhm) + offset # FWHM is the width parameter of gauss1D" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## 1. Load the scan file" + ] + }, + { + "cell_type": "code", + "metadata": { + "tags": [ + "exercise" + ] + }, + "source": [ + "loader = DataLoader(DATA / 'scan_photodiode.h5')\n", + "scan = ... # the data of SCAN, with its navigation axes\n", + "scan8 = ... # the data of SCAN8, with its navigation axes\n", + "loader.close_file()\n", + "print(scan, scan.axes) # compare the shapes and the axes: the Average axis is only in the second one\n", + "print(scan8, scan8.axes)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## 2. Look at it and find the lines" + ] + }, + { + "cell_type": "code", + "metadata": { + "tags": [ + "exercise" + ] + }, + "source": [ + "mean8 = ... # the mean over the first navigation axis (the repetitions)\n", + "wavelength = ... # the values of the wavelength axis of mean8\n", + "fig, ax = plt.subplots()\n", + "ax.plot(wavelength, scan.data[0], '.', label='one scan')\n", + "ax.plot(wavelength, mean8.data[0], '-', label='mean of 8 scans')\n", + "ax.set_xlabel('wavelength (nm)')\n", + "ax.legend()\n", + "peaks, _ = find_peaks(mean8.data[0], height=1.0)\n", + "print(wavelength[peaks]) # about 471, 529 and 590 nm" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## 3. Crop around the main line and fit with scipy (uncertainties from the covariance)" + ] + }, + { + "cell_type": "code", + "metadata": { + "tags": [ + "exercise" + ] + }, + "source": [ + "window = ... # mean8 between 505 and 555 nm (by values, on the navigation axis)\n", + "... # declare the navigation axis as a signal axis: `window` becomes a 1D data\n", + "x = window.get_axis_from_index(0)[0].get_data()\n", + "y = window.data[0]\n", + "p0 = [y.max() - y.min(), x[np.argmax(y)], 5., y.min()]\n", + "popt, pcov = ... # fit `model` to (x, y) starting from p0\n", + "perr = ... # the uncertainties of the parameters, from pcov\n", + "for name, value, error in zip(['amplitude', 'center (nm)', 'FWHM (nm)', 'offset'], popt, perr):\n", + " print(f'{name}: {value:.3f} +/- {error:.3f}')" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## 4. The same fit with DataWithAxes.fit" + ] + }, + { + "cell_type": "code", + "metadata": { + "tags": [ + "exercise" + ] + }, + "source": [ + "fit = ... # fit `window` with `model`, starting from p0, with the method of the data object\n", + "print(fit.fit_coeffs[0])\n", + "assert np.allclose(fit.fit_coeffs[0], popt, rtol=1e-3) # what is missing compared to curve_fit?" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## 5. Fit the whole scan, without cropping\n", + "\n", + "Compare the background (offset) with the one of the cropped fit: what do the satellite lines do? On the whole scan\n", + "you will also meet a point that the cropped window did not contain." + ] + }, + { + "cell_type": "code", + "metadata": { + "tags": [ + "exercise" + ] + }, + "source": [ + "full = ... # a copy of mean8...\n", + "... # ...whose navigation axis is declared as a signal axis\n", + "x_full = full.get_axis_from_index(0)[0].get_data()\n", + "y_full = full.data[0]\n", + "finite = ... # mask of the finite values: curve_fit refuses NaN (look at np.isnan(scan8.data[0]): what happened?)\n", + "popt_full, pcov_full = curve_fit(model, x_full[finite], y_full[finite], p0=p0)\n", + "print('offset, cropped:', popt[3], ' whole scan:', popt_full[3])" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## 6. Uncertainties from the repetitions, weighted fit" + ] + }, + { + "cell_type": "code", + "metadata": { + "tags": [ + "exercise" + ] + }, + "source": [ + "n_repeat = scan8.shape[0]\n", + "mean8.errors = ... # the standard error of the mean of the 8 repetitions (std with ddof=1, divided by sqrt(8))\n", + "window = ... # crop again between 505 and 555 nm: the errors follow the slicing\n", + "window.nav_indexes = ()\n", + "popt_w, pcov_w = ... # weighted fit: sigma from the errors of `window`, absolute_sigma=True\n", + "chi2_red = np.sum(((window.data[0] - model(x, *popt_w)) / window.errors[0]) ** 2) / (len(x) - len(popt_w))\n", + "print(popt_w, np.sqrt(np.diag(pcov_w)))\n", + "print('reduced chi2:', chi2_red) # larger than 1: why?" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## 7. The axis in eV" + ] + }, + { + "cell_type": "code", + "metadata": { + "tags": [ + "exercise" + ] + }, + "source": [ + "axis_ev = ... # the axis of `window` converted to eV, without modifying it (context 'spectroscopy')\n", + "window_ev = window.deepcopy()\n", + "window_ev.axes[0] = axis_ev\n", + "x_ev = axis_ev.get_data()\n", + "y_ev = window_ev.data[0]\n", + "p0_ev = [10., x_ev[np.argmax(y_ev)], 0.02, y_ev.min()]\n", + "popt_ev, pcov_ev = curve_fit(model, x_ev, y_ev, p0=p0_ev)\n", + "print(axis_ev.units, popt_ev[1], popt_ev[2], np.sqrt(np.diag(pcov_ev))[1:3]) # centre and FWHM in eV" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## 8. One spectrum with Naverage = 200: the errors come with the data (PyMoDAQ 5.3.9 or later)" + ] + }, + { + "cell_type": "code", + "metadata": { + "tags": [ + "exercise" + ] + }, + "source": [ + "loader = DataLoader(DATA / 'spectrum_naverage200.h5')\n", + "spectrum = ... # load everything under '/RawData/Detector000' and keep the data named 'Spectrum'\n", + "loader.close_file()\n", + "print(spectrum.errors[0][:3])" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## 9. Compare with the standard deviation of the continuous recording" + ] + }, + { + "cell_type": "code", + "metadata": { + "tags": [ + "exercise" + ] + }, + "source": [ + "loader = DataLoader(DATA / 'continuous_spectra.h5')\n", + "series = ... # the enlargeable array '/RawData/Detector000/Data1D/CH00/EnlData00', with its navigation axis\n", + "loader.close_file()\n", + "n_spectra = series.shape[0]\n", + "sem_series = ... # the standard deviation of the series over the acquisitions, divided by sqrt(n_spectra)\n", + "i_peak = int(np.argmax(spectrum.data[0]))\n", + "print('standard error at the peak, Naverage=200:', spectrum.errors[0][i_peak], ' series:', sem_series[i_peak])\n", + "print('standard error far from the peak, Naverage=200:', spectrum.errors[0][:10].mean(), ' series:', sem_series[:10].mean())\n", + "fig, ax = plt.subplots()\n", + "ax.plot(series.data[0][:, i_peak], '.-') # find the slow drift and estimate its period\n", + "ax.set_xlabel('acquisition number')\n", + "ax.set_ylabel('intensity at the peak')" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Control question 3\n", + "\n", + "At the top of the line, the standard error given by the DAQ_Viewer (200 acquisitions) and the standard deviation of\n", + "the series divided by √200 are close. Far from the line they are close too, but much smaller: why? What does the\n", + "comparison of the standard deviation at the top with the one far from the line say about the origin of the noise?" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## 10. Going further (open, for those who are done)\n", + "\n", + "No hole to fill here and no single answer: pick one or several items, write your own cells, and keep what you find\n", + "in your handout. Everything you need is in the files of the `data` folder and in the objects above.\n", + "\n", + "1. **Model the drift.** In the continuous recording, fit the intensity at the peak versus the acquisition number with\n", + " a sinusoid. What are its period (in acquisitions) and its relative depth? Divide the series by the fitted drift\n", + " and compute again the standard deviation at the peak: what is left?\n", + "2. **All the lines at once.** Fit the whole averaged scan with three gaussians and one background. Compare the\n", + " centre, the width and the background of the main line with the cropped fit of the part 3.\n", + "3. **The fit as a data object.** Build a `DataCalculated` holding the data of `window` and the fitted curve as two\n", + " channels (same axis, labels 'data' and 'fit'), plot it with the PyMoDAQ viewer (`.plot('qt')`), then save it\n", + " with its errors in an HDF5 file and open it in H5Browser.\n", + "4. **Navigation and signal on the series.** `series` has a navigation axis (time) and a signal axis (wavelength).\n", + " Keep 525 to 532 nm on the signal axis with `vsig`: why does PyMoDAQ refuse (look at `series.distribution`)? Do it\n", + " with `isig` instead (the axis has a `find_index` method), sum over the signal axis to get one number per\n", + " acquisition, and compare with the intensity at the peak of the part 9. Then keep the first 50 acquisitions only.\n", + "5. **Your own measurement.** Record a scan of the photodiode yourself in the DAQ_Scan (module A), with the satellite\n", + " lines and the drift switched on in the settings of the plugin, and run this notebook on your file." + ] + }, + { + "cell_type": "code", + "metadata": { + "tags": [ + "exercise" + ] + }, + "source": [ + "" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 5 +} diff --git a/pyproject.toml b/pyproject.toml index 37a8deb..b7ebe5f 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -18,6 +18,7 @@ dependencies = [ "pymodaq_data>=5.3.0", "pymodaq_plugins_mockexamples", # mock camera used in the module B "laserbeamsize", # beam analysis used in the module B + "matplotlib", # plots of the notebooks of the module C ] authors = [ diff --git a/tests/test_notebooks_exercises_module_c.py b/tests/test_notebooks_exercises_module_c.py new file mode 100644 index 0000000..0644d45 --- /dev/null +++ b/tests/test_notebooks_exercises_module_c.py @@ -0,0 +1,73 @@ +"""Check the exercise notebooks of the module C (the notebooks with holes `...` of the `notebooks` folder). + +Each code cell with a hole is tagged `exercise`. The cells before the first exercise (imports, paths, objects given +to the trainees) must run against the data files of the `data` folder, without display: the cells that need a Qt +viewer (magics and `.plot('qt')`) are skipped. The corrected notebooks are in the branch `correction-module-c`. +""" +import ast +import json +import shutil +from pathlib import Path + +import matplotlib +import pytest + +matplotlib.use('Agg') + +ROOT = Path(__file__).parent.parent +NOTEBOOKS = sorted((ROOT / 'notebooks').glob('0*.ipynb')) +DATA_FILES = ('scan_photodiode.h5', 'spectrum_naverage200.h5', 'continuous_spectra.h5') + + +def code_cells(notebook: Path) -> list[dict]: + cells = json.loads(notebook.read_text(encoding='utf-8'))['cells'] + return [cell for cell in cells if cell['cell_type'] == 'code'] + + +def source(cell: dict) -> str: + return ''.join(cell['source']) + + +def is_exercise(cell: dict) -> bool: + return 'exercise' in cell['metadata'].get('tags', []) + + +def needs_display(text: str) -> bool: + return text.lstrip().startswith('%') or ".plot('qt')" in text + + +def without_magics(text: str) -> str: + return '\n'.join(line for line in text.split('\n') if not line.lstrip().startswith('%')) + + +def test_there_are_notebooks(): + assert len(NOTEBOOKS) > 0 + + +@pytest.mark.parametrize('name', DATA_FILES) +def test_data_file_exists(name): + assert (ROOT / 'data' / name).is_file() + + +@pytest.mark.parametrize('notebook', NOTEBOOKS, ids=lambda path: path.stem) +def test_holes_are_tagged_and_cells_are_valid_python(notebook): + for cell in code_cells(notebook): + text = source(cell) + if '...' in text: + assert is_exercise(cell), f'untagged cell with a hole in {notebook.name}:\n{text}' + ast.parse(without_magics(text)) # a hole must not be a syntax error + + +@pytest.mark.parametrize('notebook', NOTEBOOKS, ids=lambda path: path.stem) +def test_given_cells_run(notebook, tmp_path, monkeypatch): + shutil.copytree(ROOT / 'notebooks', tmp_path / 'notebooks') + shutil.copytree(ROOT / 'data', tmp_path / 'data') + monkeypatch.chdir(tmp_path / 'notebooks') + namespace = {'__name__': '__main__'} + for cell in code_cells(tmp_path / 'notebooks' / notebook.name): + if is_exercise(cell): + break + text = source(cell) + if needs_display(text): + continue + exec(compile(text, notebook.name, 'exec'), namespace)