From b02e59fd1d1d570966f3c56bbffe37e61fa08aa8 Mon Sep 17 00:00:00 2001 From: Hugo Karas Date: Tue, 2 Dec 2025 10:02:47 +0100 Subject: [PATCH 01/55] Updated Gitignore --- .gitignore | 2 ++ pyepr/hardware/Bruker_AWG.py | 2 +- 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/.gitignore b/.gitignore index a720cb0..4f62601 100644 --- a/.gitignore +++ b/.gitignore @@ -125,3 +125,5 @@ dmypy.json .pyre/ .DS_Store + +poetry.lock diff --git a/pyepr/hardware/Bruker_AWG.py b/pyepr/hardware/Bruker_AWG.py index c6f2503..dbcabfd 100644 --- a/pyepr/hardware/Bruker_AWG.py +++ b/pyepr/hardware/Bruker_AWG.py @@ -71,7 +71,7 @@ def __init__(self, config_file:dict) -> None: self.savefolder = str(Path.home()) self.setup_flag=False - super().__init__() + super().__init__(config_file) def connect(self, d0=None) -> None: From b5d79ddf118300411e87a9cb2e3c7a89f08f60ce Mon Sep 17 00:00:00 2001 From: Hugo Karas Date: Tue, 2 Dec 2025 15:27:15 +0100 Subject: [PATCH 02/55] Big Documentation Update --- .gitignore | 2 + citation.rst | 39 ++ docsrc/API_docs.rst | 4 +- docsrc/README.md | 6 + docsrc/_static/Hardware_Interface_Diagram.svg | 583 ++++++++++++++++++ docsrc/citation.rst | 1 + docsrc/conf.py | 9 +- docsrc/dataset.rst | 10 - docsrc/examples/GALLERY_HEADER.rst | 4 + .../config_files/BrukerElexSys_config.yaml | 22 + .../examples/config_files/Dummy_config.yaml | 20 + .../config_files/ETHmatlab_config.yaml | 16 + docsrc/index.rst | 13 +- docsrc/install.rst | 18 + docsrc/licence.rst | 4 + docsrc/sequencer.rst | 0 docsrc/sg_execution_times.rst | 37 ++ docsrc/tutorial.rst | 39 +- docsrc/tutorial_hardware.md | 95 +++ docsrc/tutorial_loading.md | 93 +++ docsrc/tutorial_sequencer.md | 103 ++++ pyepr/hardware/Bruker_AWG.py | 4 +- pyepr/sequences.py | 39 +- pyproject.toml | 2 + 24 files changed, 1139 insertions(+), 24 deletions(-) create mode 100644 citation.rst create mode 100644 docsrc/README.md create mode 100644 docsrc/_static/Hardware_Interface_Diagram.svg create mode 100644 docsrc/citation.rst delete mode 100644 docsrc/dataset.rst create mode 100644 docsrc/examples/GALLERY_HEADER.rst create mode 100644 docsrc/examples/config_files/BrukerElexSys_config.yaml create mode 100644 docsrc/examples/config_files/Dummy_config.yaml create mode 100644 docsrc/examples/config_files/ETHmatlab_config.yaml create mode 100644 docsrc/licence.rst delete mode 100644 docsrc/sequencer.rst create mode 100644 docsrc/sg_execution_times.rst create mode 100644 docsrc/tutorial_hardware.md create mode 100644 docsrc/tutorial_loading.md create mode 100644 docsrc/tutorial_sequencer.md diff --git a/.gitignore b/.gitignore index 4f62601..7acebdd 100644 --- a/.gitignore +++ b/.gitignore @@ -127,3 +127,5 @@ dmypy.json .DS_Store poetry.lock + +docsrc/auto_examples/ diff --git a/citation.rst b/citation.rst new file mode 100644 index 0000000..aecb3c1 --- /dev/null +++ b/citation.rst @@ -0,0 +1,39 @@ +Citation +-------- + +Citation of scientific software is important to give credit to the developers and to help track the impact of the software in research. + +To cite PyEPR in publications, please currently use the Zenodo general DOI: + +.. image:: https://zenodo.org/badge/888368760.svg + :target: https://doi.org/10.5281/zenodo.17107010 + :alt: DOI + +Specific PyEPR versions will also have uniquie DOIs that can be found on the respective Zenodo release page. +The associated Zotero entry is available `here `_. + +A paper describing PyEPR is currently in preparation and will be linked here once published. + +Bibtex Entry +++++++++++++ + +.. code-block:: bibtex + + @software{pyepr_2025, + author = {Hugo, Karas and + Jeschke, Gunnar and + Stoll, Stefan}, + title = {JeschkeLab/PyEPR: Version 1.0}, + month = sep, + year = 2025, + publisher = {Zenodo}, + version = {v1.0}, + doi = {10.5281/zenodo.17107011}, + url = {https://doi.org/10.5281/zenodo.17107011}, + swhid = {swh:1:dir:d3ae7fdd8041eb365003ea3e40db8bbb31a6c741 + ;origin=https://doi.org/10.5281/zenodo.17107010;vi + sit=swh:1:snp:5c1894da8cabcaf89397959130c3ff4badea + 5b87;anchor=swh:1:rel:316cb6fc9c055bd7058460f5559a + 8342d326ebd4;path=JeschkeLab-PyEPR-c194a75 + }, + } diff --git a/docsrc/API_docs.rst b/docsrc/API_docs.rst index 2d26e95..2c625c4 100644 --- a/docsrc/API_docs.rst +++ b/docsrc/API_docs.rst @@ -19,6 +19,7 @@ Analysis Modules .. autoapisummary:: pyepr.FieldSweepAnalysis + pyepr.HahnEchoRelaxationAnalysis pyepr.ResonatorProfileAnalysis pyepr.CarrPurcellAnalysis pyepr.ReptimeAnalysis @@ -29,7 +30,7 @@ Sequences .. autoapisummary:: pyepr.sequences.HahnEchoSequence - pyepr.sequences.T2RelaxationSequence + pyepr.sequences.HahnEchoRelaxationSequence pyepr.sequences.FieldSweepSequence pyepr.sequences.ReptimeScan pyepr.sequences.CarrPurcellSequence @@ -44,7 +45,6 @@ Pulses pyepr.pulses.Pulse pyepr.pulses.Detection - pyepr.pulses.Delay pyepr.pulses.RectPulse pyepr.pulses.GaussianPulse pyepr.pulses.HSPulse diff --git a/docsrc/README.md b/docsrc/README.md new file mode 100644 index 0000000..0b040ec --- /dev/null +++ b/docsrc/README.md @@ -0,0 +1,6 @@ + + +To build the documentation and serve it with live reloading, run: +``` +sphinx-autobuild docsrc docsrc/_build/html +``` \ No newline at end of file diff --git a/docsrc/_static/Hardware_Interface_Diagram.svg b/docsrc/_static/Hardware_Interface_Diagram.svg new file mode 100644 index 0000000..99cc327 --- /dev/null +++ b/docsrc/_static/Hardware_Interface_Diagram.svg @@ -0,0 +1,583 @@ + + + + + + + + + + + + + + + + + + + BRUKER_Interface + + + + + + + + ETH_Interface + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + XeprAPI + + + + + + Matlab + + + Engine + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Spectrometer + + + Control + + + Software + + + + + API + + + + + Interface + + + + + Script + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + AWG + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Py + + + EPR + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/docsrc/citation.rst b/docsrc/citation.rst new file mode 100644 index 0000000..1ca04dd --- /dev/null +++ b/docsrc/citation.rst @@ -0,0 +1 @@ +.. include:: ../citation.rst \ No newline at end of file diff --git a/docsrc/conf.py b/docsrc/conf.py index f70d163..f0a7cec 100644 --- a/docsrc/conf.py +++ b/docsrc/conf.py @@ -21,13 +21,16 @@ # https://www.sphinx-doc.org/en/master/usage/configuration.html#general-configuration extensions = ['sphinx.ext.viewcode', + 'sphinx_design', + 'myst_parser', 'sphinx.ext.intersphinx', 'autoapi.extension', 'sphinx_toolbox.collapse', 'sphinx_toolbox.code', 'sphinx_copybutton', 'numpydoc', - 'sphinx_favicon'] + 'sphinx_favicon', + 'sphinx_gallery.gen_gallery'] templates_path = ['_templates'] exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store'] @@ -44,6 +47,10 @@ autoapi_python_use_implicit_namespaces = True autoapi_own_page_level = 'class' +sphinx_gallery_conf = { + 'examples_dirs': 'examples', # path to your example scripts + 'gallery_dirs': 'auto_examples', # path to where to save gallery generated output +} # -- Options for HTML output ------------------------------------------------- # https://www.sphinx-doc.org/en/master/usage/configuration.html#options-for-html-output diff --git a/docsrc/dataset.rst b/docsrc/dataset.rst deleted file mode 100644 index 9306ee6..0000000 --- a/docsrc/dataset.rst +++ /dev/null @@ -1,10 +0,0 @@ -Dataset Tutorial -================ - -PyEPR uses an advanced object-oriented dataset object. This has many advantages over the traditional numpy array. - -1. **Axes**: The dataset object has named axes, which makes it easier to keep track of what each axis represents. This is especially useful when working with multidimensional data. -2. **MetaData**: The dataset object stores critical MetaData in the same object. -3. **Methods**: We are able to create EPR specific methods, allowing users to easily perform regular EPR tasks such as phase correction. - - diff --git a/docsrc/examples/GALLERY_HEADER.rst b/docsrc/examples/GALLERY_HEADER.rst new file mode 100644 index 0000000..216728d --- /dev/null +++ b/docsrc/examples/GALLERY_HEADER.rst @@ -0,0 +1,4 @@ +PyEPR Example Scripts +===================== + +Work in Progress: This gallery is under construction and will be expanded with more examples in the future. \ No newline at end of file diff --git a/docsrc/examples/config_files/BrukerElexSys_config.yaml b/docsrc/examples/config_files/BrukerElexSys_config.yaml new file mode 100644 index 0000000..d363272 --- /dev/null +++ b/docsrc/examples/config_files/BrukerElexSys_config.yaml @@ -0,0 +1,22 @@ +Spectrometer: + Type: Complete Spectrometer + Manufacturer: Bruker + Model: E580 + Local Name: Bruker E580 + + AWG: True + + + Bridge: + Min Freq: 33 #GHz + Max Freq: 35 #GHz + Digital Source: False # Analogue or Digital Source (for Q-band standalone) + d0: 650 #ns + Sample Freq: 1 # GSa/s + DutyCycle: 3 # Max amplifier duty cycle % + Pulse dt: 2 #ns + Det dt: 0.5 #ns + Det res: 8 #bit + Video BW: 125 #MHz on VAMP-III this changes the time base + On Board Pcyc: False # Use on-board phase cycling generally + On Board Pcyc (EDFS): True # Use on-board phase cycling for EDFS experiments diff --git a/docsrc/examples/config_files/Dummy_config.yaml b/docsrc/examples/config_files/Dummy_config.yaml new file mode 100644 index 0000000..962176c --- /dev/null +++ b/docsrc/examples/config_files/Dummy_config.yaml @@ -0,0 +1,20 @@ +Spectrometer: + Type: Complete Spectrometer + Manufacturer: Dummy + Model: DummyV1 + Local Name: Dummy + + AWG: True + + Bridge: + Min Freq: 33 #GHz + Max Freq: 35 #GHz + Sample Freq: 8 #GSa/s + Det Freq: 2 #GSa/s + Det Res: 12 #bit + + Dummy: + speedup: 1000 # Default: 100 + SNR: 150 + ESEEM_depth: 0.15 + noise_level: 0.005 diff --git a/docsrc/examples/config_files/ETHmatlab_config.yaml b/docsrc/examples/config_files/ETHmatlab_config.yaml new file mode 100644 index 0000000..c01ff0e --- /dev/null +++ b/docsrc/examples/config_files/ETHmatlab_config.yaml @@ -0,0 +1,16 @@ +Spectrometer: + Type: Complete Spectrometer + Manufacturer: ETH + Model: Matlab + Local Name: F243_AWG + + AWG: True + + Bridge: + Min Freq: 33 #GHz + Max Freq: 36 #GHz + Sample Freq: 8 # GSa/s + Det Freq: 2 #GSa/s + Det Res: 12 #bit + + Waveform Precision: 1 #ns diff --git a/docsrc/index.rst b/docsrc/index.rst index 46a00fe..d714c0c 100644 --- a/docsrc/index.rst +++ b/docsrc/index.rst @@ -15,16 +15,17 @@ PyEPR's Key Features - Fully python based, open-source and free to use - Intuitive object-oriented pulse sequencer -- Pre-defined common EPR experiments (CW, Hahn Echo, Inversion Recovery, Carr-Purcell, DEER, etc.) +- Pre-defined common EPR experiments (CW, Hahn Echo, Inversion Recovery, Carr-Purcell, etc.) - Easy to define custom experiments - Pre-defined common pulse shapes (rectangular, Gaussian, sech/tanh, etc.) - Easy to define custom pulse shapes - Hardware abstraction layer for interfacing with different spectrometers - BRUKER PulseSpel compiler from PyEPR sequences -.. warning:: - PyEPR is an actively developed software package, that is still very much a work in process. Please consider this to be a beta release. - +.. image:: _static/Hardware_Interface_Diagram.svg + :align: center + :width: 90% + .. toctree:: :maxdepth: 1 :hidden: @@ -39,8 +40,10 @@ PyEPR's Key Features :caption: About ./releasenotes.rst - ./contributing.rst + citation.rst + licence.rst Github autoDEER + diff --git a/docsrc/install.rst b/docsrc/install.rst index a1d9354..e431c7a 100644 --- a/docsrc/install.rst +++ b/docsrc/install.rst @@ -20,5 +20,23 @@ or with poetry: To install PyEPR from source, clone the repository and run the following command: .. code-block:: bash + + git clone https://github.com/JeschkeLab/PyEPR pip install . + +Requirements +++++++++++++ + +PyEPR requires: + - Python >= 3.11 < 3.13 + - Numpy + - Scipy + - Matplotlib + - pyyaml + - xarray + - h5netcdf + - toml + - deerlab (https://github.com/JeschkeLab/DeerLab) + - numba + - psutil diff --git a/docsrc/licence.rst b/docsrc/licence.rst new file mode 100644 index 0000000..43e1b54 --- /dev/null +++ b/docsrc/licence.rst @@ -0,0 +1,4 @@ +License +------- + +.. literalinclude:: ../LICENSE \ No newline at end of file diff --git a/docsrc/sequencer.rst b/docsrc/sequencer.rst deleted file mode 100644 index e69de29..0000000 diff --git a/docsrc/sg_execution_times.rst b/docsrc/sg_execution_times.rst new file mode 100644 index 0000000..78433a9 --- /dev/null +++ b/docsrc/sg_execution_times.rst @@ -0,0 +1,37 @@ + +:orphan: + +.. _sphx_glr_sg_execution_times: + + +Computation times +================= +**00:00.000** total execution time for 0 files **from all galleries**: + +.. container:: + + .. raw:: html + + + + + + + + .. list-table:: + :header-rows: 1 + :class: table table-striped sg-datatable + + * - Example + - Time + - Mem (MB) + * - N/A + - N/A + - N/A diff --git a/docsrc/tutorial.rst b/docsrc/tutorial.rst index 7939ecb..78c5cfe 100644 --- a/docsrc/tutorial.rst +++ b/docsrc/tutorial.rst @@ -10,7 +10,7 @@ To get started, we will first import the PyEPR package. .. code-block:: python - import pyepr as esr + import pyepr as epr This will import the PyEPR package, except for the hardware modules. Importing of hardware modules is included hardware-control tutorial. @@ -18,4 +18,39 @@ Tutorial Overview ----------------- The following tutorials are available: -1. \ No newline at end of file +.. grid:: 2 + :gutter: 3 + + .. grid-item-card:: Loading and Analysing Data + :link: tutorial_loading + :link-type: doc + + Learn how to load data from the PyEPR format and other common formats, and perform basic analysis with PyEPR. + + .. grid-item-card:: Sequencer + :link: tutorial_sequencer + :link-type: doc + + Explore how to create pulse sequences, and use default sequences provided by PyEPR. + + .. grid-item-card:: Hardware Control + :link: tutorial_hardware + :link-type: doc + + Interface with physical hardware devices. + + .. grid-item-card:: Examples + :link: auto_examples/index + :link-type: doc + + View practical examples and use cases. + + +.. toctree:: + :maxdepth: 1 + :hidden: + + tutorial_loading.md + tutorial_sequencer.md + tutorial_hardware.md + auto_examples/index.rst \ No newline at end of file diff --git a/docsrc/tutorial_hardware.md b/docsrc/tutorial_hardware.md new file mode 100644 index 0000000..90abf79 --- /dev/null +++ b/docsrc/tutorial_hardware.md @@ -0,0 +1,95 @@ +# Interfacing with Hardware + +PyEPR has been designed to interface with a range of different EPR spectrometers, providing a hardware abstraction layer that allows users to write experiments in a hardware-agnostic manner. Currently, PyEPR supports the following hardware interfaces: + - Bruker ElexSys AWG based spectrometers + - ETH Zürich Matlab based homebuilt spectrometers + +For homebuilt spectrometers, there can be additional packages required. Please refer to the respective hardware interface documentation for more details. + +## Initializing Hardware Interfaces +The hardware interfaces can be initialized by importing the respective classes from the `pyepr.hardware` module and providing a configuration file that specifies the hardware settings. +```{eval-rst} +.. tab-set:: + + .. tab-item:: Bruker AWG + + .. code-block:: python + + from pyepr.hardware.Bruker_AWG import BrukerAWG + # Initialize the Bruker AWG interface with a configuration file + interface = BrukerAWG('path/to/config_file.yaml') + + .. tab-item:: ETH Matlab + + .. code-block:: python + + from pyepr.hardware.ETH_awg import ETH_awg_interface + # Initialize the ETH Matlab interface with a configuration file + interface = ETH_awg_interface('path/to/config_file.yaml') + + +``` + +### Configuration Files + +```{eval-rst} +.. tab-set:: + + .. tab-item:: Bruker AWG + + .. literalinclude:: examples/config_files/BrukerElexSys_config.yaml + :language: yaml + + + .. tab-item:: ETH Matlab + + .. literalinclude:: examples/config_files/ETHmatlab_config.yaml + :language: yaml + + .. tab-item:: Dummy + + .. literalinclude:: examples/config_files/Dummy_config.yaml + :language: yaml + +``` + +### First Tests +After initializing the hardware interface, it is recommended to run some basic tests to ensure that the connection to the spectrometer is working correctly. + + + +## Pulse Tuning + +The hardware interface can be used to create and tune pulses for the spectrometer. + +### Creating rectangular pulse pairs +Often we just need a pair of rectangular pulses. These can be quickly created though an amplitude sweep. + +```python +p90, p180 = interface.tune_rectpulse( + tp = 16, # Pulse length of pi/2 pulse in ns + B = 12200, # Magnetic field in Gauss + freq = 34.0, # Microwave frequency in GHz + reptime = 3000, # Repetition time in us + shots = 20, # Number of shots per point + ) +``` +This will create and return a pi/2 and pi rectangular pulse tuned to the specified field and frequency. The pulses can then be used directly in sequences, and have the correct scale (amplitude) set for the hardware. + +### Tuning pre-defined pulse shapes +Often a specific pulse shape is required, and it is better to tune that pulse directly. This can be done using the `tune_pulse` method of the hardware interface. +This is done as an amplitude sweep, either as a Hahn Echo (`amp_hahn`) or more commonly as a hole-buring recovery experiment (`amp_nut`). +When a hole-burning recovery experiment is used, a pair of on-resonance rectangular pulses are first created using the `tune_rectpulse` method. + +```python +from pyepr.pulses import GaussPulse +pulse = GaussPulse(tp=32, freq=0, flipangle=np.pi) # Create a Gaussian pulse with length 32 ns +tuned_pulse = interface.tune_pulse( + pulse, + 'amp_nut', + B = 12200, # Magnetic field in Gauss + freq = 34.0, # Microwave frequency in GHz + reptime = 3000, # Repetition time in us + shots = 20, # Number of shots per point + ) +``` \ No newline at end of file diff --git a/docsrc/tutorial_loading.md b/docsrc/tutorial_loading.md new file mode 100644 index 0000000..1d9f42d --- /dev/null +++ b/docsrc/tutorial_loading.md @@ -0,0 +1,93 @@ +# Loading and Analysing Data + +The PyEPR package normally saves data in the HDF5 format, which is a widely used file format for storing large amounts of numerical data. Files which are saved in this format typically have the file extension `.h5` or `.hdf5`, and if created by PyEPR will have the metadata stored in an easily accessible format for PyEPR to read. Nonetheless, PyEPR can also load data from other file formats, such as text files (`.txt`, `.csv`), Bruker Elexsys files (`.dta`, `.dsc`). + +Data is loaded into the xarray `Dataarray` object, which is a powerful data structure for handling multi-dimensional arrays with labeled axes and coordinates. This allows for easy manipulation, analysis, and visualization of the data. + +## Loading Data + +```python +import pyepr as epr +# Load data from an HDF5 file +data = epr.eprload('path/to/datafile.h5') +# Load data from a text file +data_txt = epr.eprload('path/to/datafile.txt') +``` + +## Viewing Data +Once the data is loaded, you can view its contents and metadata using standard xarray methods. + +```python +# Print the data array +print(data) +# Access metadata +print(data.attrs) +``` +The data can also be quickly visualized using the built-in plotting functions. + +```python +# Plot the data +data.real.plot(label='Re') +data.imag.plot(label='Im') +``` + +Xarray has been extended to include some convient EPR methods, such as `correctphase`. + +```python +# Correct the phase of the EPR signal +data_corrected = data.epr.correctphase() +data_corrected.plot(label='Corrected Re') +``` + +## Saving Data +After processing and analyzing the data, you can save it back to an HDF5 file for future use. +```python +# Save the processed data to an HDF5 file +data_corrected.epr.save('path/to/processed_datafile') +``` + +## PyEPR Automated Data Analysis +Since in EPR we often have to perform standard data analysis routines, PyEPR includes a set of automated data analysis functions that can be applied to the loaded data. These functions are designed to streamline the process of extracting the necessary information to move onto the next experiment. +A list of currently implemented automated data analysis functions can be found in the [API documentation](API_docs.rst). + +### Field Sweep Analysis + +```python +fieldsweep_data = epr.eprload('path/to/fieldsweep_datafile.h5') +fieldsweep = epr.FieldSweepAnalysis(fieldsweep_data) +# Determine the gyromagnetic ratio +gyro = fieldsweep.calc_gyro() +# Plot the results +fieldsweep.plot() +``` + +### Relaxation Analysis + +```{eval-rst} +.. tab-set:: + + .. tab-item:: Repetition Time T1 Recovery + + .. code-block:: python + + t1_data = epr.eprload('path/to/t1_datafile.h5') + t1_analysis = epr.ReptimeAnalysis(t1_data) + # Calculate T1 relaxation time + t1_result = t1_analysis.fit() + # Plot the results + t1_analysis.plot() + + .. tab-item:: Hahn Echo Tm Relaxation + + .. code-block:: python + + tm_data = epr.eprload('path/to/tm_datafile.h5') + t2_analysis = epr.HahnEchoRelaxationAnalysis(t2_data) + # Calculate T2 relaxation time + t2_result = t2_analysis.fit() + # Plot the results + t2_analysis.plot() + +``` + +### Resonator Profile Analysis diff --git a/docsrc/tutorial_sequencer.md b/docsrc/tutorial_sequencer.md new file mode 100644 index 0000000..a78d50c --- /dev/null +++ b/docsrc/tutorial_sequencer.md @@ -0,0 +1,103 @@ +# Pulse Sequencer + +PyEPR provides an intuitive object-oriented pulse programmer allowing the user to design pulsesequences in a hardware-agnostic manner. Additionally, several common EPR experiments are pre-defined and can be easily instantiated and modified. + +PyEPR uses ns, GHz and G as the default time, frequency and field units. Very occasionally, other units such as µs or MHz are used, in which case it will be explicitly mentioned. + +## Seqeunce Construction + +First we must import the pyepr package, and set our waveform precision. This waveform precision determines the time resolution of the pulse length and positons. If values are given that are not multiples of the waveform precision, they will be rounded. + +```python +import pyepr as epr +epr.set_waveform_precision(2) # Set waveform precision to 2 ns +``` + +Next, we want to create a sequence object. Here we are aiming to create a simple Hahn Echo sequence. +It is normally recommened, to set the field `B` and frequency `freq` as external variables. +```python +B = 12200 # Magnetic field in Gauss +freq = 34.0 # Microwave frequency in GHz +seq = epr.Sequence(name='Hahn Echo Sequence', + B = B, + freq = freq, + reptime = 3e3,# Repetition time in us + averages = 1, + shots = 20, # Number of shots per point + ) +``` +Now we need to define some pulses that can be used in our sequence. Here we create a 90 degree and a 180 degree rectangular pulse. +These pulses will eventually need a scale (amplitude), before the sequence can be run on hardware. +A Detection window is also created +```python +p90 = epr.RectPulse(tp=16, + freq=0, # Frequency offset in MHz, w.r.t the sequence frequency, + flipangle=np.pi/2, # Flip angle in degrees + pcyc = {"phases":[0, np.pi], "dets":[1,-1]} + ) +p180 = epr.RectPulse(tp=32, + freq=0, # Frequency offset in MHz, w.r.t the sequence frequency, + flipangle=np.pi, # Flip angle in degrees + ) +det = epr.Detetction(tp=32, + freq=0, # Frequency offset in MHz, w.r.t the sequence frequency, + ) +``` +We now need a time axis for our sequence and to add them to the sequence object. +When a pulse is copied into the sequence using the `add_pulse` method, parameters can be modified allowing the same pulse can be used multiple times with different timings or amplitudes. +```python +t = epr.Parameter(name='Interpulse Delay', + value=400, # Initial interpulse delay in ns + step=8, # Step size in ns + dim=1024 # Number of points, + unit='ns' # Unit of the parameter + description='Interpulse delay between the pi/2 and pi pulse' + ) + +# Adding the pulses to the sequence +seq.add_pulse(p90.copy(t=0)) +seq.add_pulse(p180.copy(t=t)) +seq.add_pulse(det.copy(t=2*t)) + +# Defining the evolution +seq.evolution([t]) +``` +### Advanced Sequences +The sequence class is capable of more advanced features such as: +- Linked axes +- Reduced axes +- Non-linear axes + +## Default Experiments +For convienience, several common EPR experiments are pre-defined and can be easily instantiated and modified. +A list of currently implemented experiments can be found in the [API documentation](API_docs.rst). +Here we show how to create a simple Hahn Echo Relaxation experiment. +```python +HE_Seq = epr.HahnEchoRelaxationSequence( + B = B, + freq = freq, + reptime = 3e3, # Repetition time in us + averages = 1, + shots = 20, # Number of shots per point + start = 400, # Initial interpulse delay in ns + step = 8, # Step size in ns + dim = 1024 # Number of points + pi2_pulse = p90, # The 90 degree pulse + pi_pulse = p180 # The 180 degree pulse +) +``` + +## Advanced Pulses +More complex pulse shapes can be created using the pulse classes provided in the `pyepr.pulses` module. A list of currently implemented pulse shapes, and their necessary inputs can be found in the [API documentation](API_docs.rst). + +Here we show how to create a simple chirp pulse +```python +from pyepr.pulses import ChirpPulse + +pulse = ChirpPulse( + tp = 128, # Pulse length in ns + init_freq = -0.1, # Frequency offset in GHz, w.r.t the sequence frequency, + final_freq = 0.1, # Frequency offset in GHz, w.r.t the sequence frequency, + flipangle = np.pi, # Flip angle in radians +) +``` diff --git a/pyepr/hardware/Bruker_AWG.py b/pyepr/hardware/Bruker_AWG.py index dbcabfd..52fac3f 100644 --- a/pyepr/hardware/Bruker_AWG.py +++ b/pyepr/hardware/Bruker_AWG.py @@ -29,7 +29,7 @@ class BrukerAWG(Interface): Spectrometers. """ - def __init__(self, config_file:dict) -> None: + def __init__(self, config_file) -> None: """An interface for connecting to AWG based Bruker ELEXSYS-II Spectrometers. @@ -44,7 +44,7 @@ def __init__(self, config_file:dict) -> None: Parameters ---------- - config_file : dict + config_file : str The path to a YAML configuration file. Attributes diff --git a/pyepr/sequences.py b/pyepr/sequences.py index 74cbfad..55b7f74 100644 --- a/pyepr/sequences.py +++ b/pyepr/sequences.py @@ -755,9 +755,10 @@ class T1InversionRecoverySequence(Sequence): """ # ============================================================================= -class T2RelaxationSequence(HahnEchoSequence): + +class HahnEchoRelaxationSequence(HahnEchoSequence): """ - Represents a T2 relaxation sequence. A Hahn Echo where the interpulse delay increases + Represents a Hahn Echo relaxation sequence for measureing Tm. A Hahn Echo where the interpulse delay increases Parameters ---------- @@ -805,6 +806,40 @@ def simulate(self,ESEEM_depth=0.1, Tm=1e3): data *= _gen_ESEEM(xaxis, 7.842, ESEEM_depth) return xaxis, data +class T2RelaxationSequence(HahnEchoRelaxationSequence): + """ + Represents a T2 relaxation sequence. This is an alias for HahnEchoRelaxationSequence. + A Hahn Echo where the interpulse delay increases. + + Parameters + ---------- + B : int or float + The B0 field, in Guass + freq : int or float + The freq frequency in GHz + reptime : _type_ + The shot repetition time in us + averages : int + The number of scans. + shots : int + The number of shots per point + start : float + The minimum interpulse delay in ns, by default 500 ns + step : float + The step size of the interpulse delay in ns, by default 40 ns + dim : int + The number of points in the X axis + + Optional Parameters + ------------------- + pi2_pulse : Pulse + An autoEPR Pulse object describing the excitation pi/2 pulse. If + not specified a RectPulse will be created instead. + pi_pulse : Pulse + An autoEPR Pulse object describing the refocusing pi pulses. If + not specified a RectPulse will be created instead. + """ + pass # ============================================================================= diff --git a/pyproject.toml b/pyproject.toml index 199806c..36c793b 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -36,6 +36,8 @@ sphinx-toolbox = "^3.8.1" sphinx-copybutton = "^0.5.2" numpydoc = "^1.8.0" sphinx-favicon = "^1.0.1" +sphinx-autobuild = "^2025.8.25" +sphinx-gallery = "^0.19.0" [build-system] requires = ["poetry-core"] From 2953b4d13376b8f5155573f45c80d45b218741ac Mon Sep 17 00:00:00 2001 From: Hugo Karas Date: Tue, 2 Dec 2025 15:31:27 +0100 Subject: [PATCH 03/55] New doc test github action --- .github/workflows/TestBuild_Docs.yml | 38 ++++++++++++++++++++++++++++ 1 file changed, 38 insertions(+) create mode 100644 .github/workflows/TestBuild_Docs.yml diff --git a/.github/workflows/TestBuild_Docs.yml b/.github/workflows/TestBuild_Docs.yml new file mode 100644 index 0000000..bbed943 --- /dev/null +++ b/.github/workflows/TestBuild_Docs.yml @@ -0,0 +1,38 @@ +name: Test Build Docs + +on: + push: + branches: + - develop + - main + workflow_dispatch: + +jobs: + build: + runs-on: ubuntu-latest + + steps: + - name: Checkout repository + uses: actions/checkout@v3 + + - name: Set up Python + uses: actions/setup-python@v4 + with: + python-version: '3.12' + + - name: Install Poetry + run: | + curl -sSL https://install.python-poetry.org | python - + echo "${HOME}/.local/bin" >> $GITHUB_PATH + + - name: Install dependencies + run: poetry install --with doc + + - name: Build documentation + run: poetry run sphinx-build -b html docsrc/ docsrc/_build/html > sphinx_build.log 2>&1 + - name: Upload build log + uses: actions/upload-artifact@v4.6.2 + with: + name: sphinx-build-log + path: sphinx_build.log + From 949370db8e981963604fb501a166deb232fa25d6 Mon Sep 17 00:00:00 2001 From: Hugo Karas Date: Tue, 2 Dec 2025 15:35:57 +0100 Subject: [PATCH 04/55] Update sphinx packages --- pyproject.toml | 2 ++ 1 file changed, 2 insertions(+) diff --git a/pyproject.toml b/pyproject.toml index 36c793b..bbd42c1 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -38,6 +38,8 @@ numpydoc = "^1.8.0" sphinx-favicon = "^1.0.1" sphinx-autobuild = "^2025.8.25" sphinx-gallery = "^0.19.0" +myst-parser = "^4.0.1" +sphinx-design = "^0.6.1" [build-system] requires = ["poetry-core"] From 66e471f9b826d1de9ba050ebd4761abaa100904b Mon Sep 17 00:00:00 2001 From: Hugo Karas Date: Tue, 2 Dec 2025 16:55:50 +0100 Subject: [PATCH 05/55] Update github action --- .github/workflows/Build_Deploy_Docs.yml | 1 + .gitignore | 1 + 2 files changed, 2 insertions(+) diff --git a/.github/workflows/Build_Deploy_Docs.yml b/.github/workflows/Build_Deploy_Docs.yml index 353f287..a8070f3 100644 --- a/.github/workflows/Build_Deploy_Docs.yml +++ b/.github/workflows/Build_Deploy_Docs.yml @@ -28,6 +28,7 @@ jobs: run: poetry run sphinx-build -b html docsrc/ docsrc/_build/html > sphinx_build.log 2>&1 - name: Upload build log uses: actions/upload-artifact@v4.6.2 + if: always() with: name: sphinx-build-log path: sphinx_build.log diff --git a/.gitignore b/.gitignore index 7acebdd..50aa696 100644 --- a/.gitignore +++ b/.gitignore @@ -105,6 +105,7 @@ venv/ ENV/ env.bak/ venv.bak/ +.venv* # Spyder project settings .spyderproject From 02b639185d223143f173fca5bb77ef43972b489a Mon Sep 17 00:00:00 2001 From: Hugo Karas Date: Tue, 2 Dec 2025 16:58:20 +0100 Subject: [PATCH 06/55] Another githuh action fix --- .github/workflows/TestBuild_Docs.yml | 1 + 1 file changed, 1 insertion(+) diff --git a/.github/workflows/TestBuild_Docs.yml b/.github/workflows/TestBuild_Docs.yml index bbed943..df5bf6a 100644 --- a/.github/workflows/TestBuild_Docs.yml +++ b/.github/workflows/TestBuild_Docs.yml @@ -32,6 +32,7 @@ jobs: run: poetry run sphinx-build -b html docsrc/ docsrc/_build/html > sphinx_build.log 2>&1 - name: Upload build log uses: actions/upload-artifact@v4.6.2 + if: always() with: name: sphinx-build-log path: sphinx_build.log From dd9c382ed0d5a5e05640fe01fbc7d486cf785ffe Mon Sep 17 00:00:00 2001 From: Hugo Karas Date: Mon, 26 Jan 2026 10:38:58 +0100 Subject: [PATCH 07/55] Update ETH AWG for new software --- pyepr/hardware/ETH_awg.py | 32 ++++++++++++++++++++++++-------- pyepr/hardware/ETH_awg_load.py | 11 +++++++++-- 2 files changed, 33 insertions(+), 10 deletions(-) diff --git a/pyepr/hardware/ETH_awg.py b/pyepr/hardware/ETH_awg.py index 3604529..fbcd3ec 100644 --- a/pyepr/hardware/ETH_awg.py +++ b/pyepr/hardware/ETH_awg.py @@ -141,7 +141,7 @@ def acquire_dataset_from_matlab(self, verbosity=0,**kwargs): # filename = cur_exp['savename'] # files = os.listdir(folder_path) - curexpname = self.workspace['currexpname'] + curexpname = self.workspace['currfilename'] # def extract_date_time(str): # output = re.findall(r"(\d{8})_(\d{4})", str) # if output != []: @@ -255,7 +255,7 @@ def get_buffer(self, verbosity=0,**kwargs): def read_dataset(self, verbosity=0,savenow=False, **kwargs): cur_exp = self.workspace['currexp'] folder_path = cur_exp['savepath'] - curexpname = self.workspace['currexpname'] + curexpname = self.workspace['currfilename'] path = folder_path + "\\" + curexpname + ".mat" @@ -459,7 +459,7 @@ def launch_long(self, sequence , savename: str, IFgain: int = 0, axID=-1): def isrunning(self) -> bool: if self.bg_thread is None: # state = bool(self.engine.dig_interface('savenow')) - _,_,_,state = self.engine.dig_interface('progress', nargout=4) + _,_,_,state,_ = self.engine.dig_interface('progress', nargout=5) if state == 0: state = False @@ -473,7 +473,7 @@ def isrunning(self) -> bool: state= self.bg_thread.is_alive() return state - def tune_rectpulse(self,*,tp, freq, B, reptime, shots=400): + def tune_rectpulse(self,*,tp, freq, B, reptime, shots=400,step=0.02, dim=45): """Generates a rectangular pi and pi/2 pulse of the given length at the given field position. This value is stored in the pulse cache. @@ -489,6 +489,10 @@ def tune_rectpulse(self,*,tp, freq, B, reptime, shots=400): Shot repetion time in us. shots: int The number of shots + step: float + The step size for the amplitude tuning, default 0.02 + dim: int + The dimension of the amplitude axis, default 45 Returns ------- @@ -502,7 +506,10 @@ def tune_rectpulse(self,*,tp, freq, B, reptime, shots=400): B=B, freq=freq, reptime=reptime, averages=1, shots=shots ) - scale = Parameter("scale",0,dim=45,step=0.02) + max_val = step * (dim -1) + if max_val > 1.0: + raise ValueError("Step and dim values result in scale > 1.0") + scale = Parameter("scale",0,dim=dim,step=step) amp_tune.pulses[0].tp.value = tp amp_tune.pulses[0].scale = scale amp_tune.pulses[1].tp.value = tp * 2 @@ -533,7 +540,7 @@ def tune_rectpulse(self,*,tp, freq, B, reptime, shots=400): return p90, p180 - def tune_pulse(self, pulse, mode, freq, B , reptime, shots=400): + def tune_pulse(self, pulse, mode, freq, B , reptime, shots=400,step=0.02, dim=45): """Tunes a single pulse a range of methods. Parameters @@ -550,6 +557,10 @@ def tune_pulse(self, pulse, mode, freq, B , reptime, shots=400): Shot repetion time in us. shots: int The number of shots + step: float + The step size for the amplitude tuning, default 0.02 + dim: int + The dimension of the amplitude axis, default 45 Returns ------- @@ -573,6 +584,10 @@ def tune_pulse(self, pulse, mode, freq, B , reptime, shots=400): c_frq = 0.5*(pulse.final_freq.value + pulse.final_freq.value) + freq # Find rect pulses + max_val = step * (dim -1) + if max_val > 1.0: + raise ValueError("Step and dim values result in scale > 1.0") + if mode == "amp_hahn": if pulse.flipangle.value == np.pi: tp = pulse.tp.value / 2 @@ -586,7 +601,7 @@ def tune_pulse(self, pulse, mode, freq, B , reptime, shots=400): pi2_pulse = pulse, pi_pulse=pi_pulse ) - scale = Parameter('scale',0,unit=None,step=0.02, dim=45, description='The amplitude of the pulse 0-1') + scale = Parameter('scale',0,unit=None,step=step, dim=dim, description='The amplitude of the pulse 0-1') amp_tune.pulses[0].scale = scale amp_tune.evolution([scale]) @@ -626,7 +641,7 @@ def tune_pulse(self, pulse, mode, freq, B , reptime, shots=400): freq=c_frq-freq)) nut_tune.addPulse(Detection(t=3e3, tp=512, freq=c_frq-freq)) - scale = Parameter('scale',0,unit=None,step=0.02, dim=45, description='The amplitude of the pulse 0-1') + scale = Parameter('scale',0,unit=None,step=step, dim=dim, description='The amplitude of the pulse 0-1') nut_tune.pulses[0].scale = scale nut_tune.evolution([scale]) @@ -803,6 +818,7 @@ def _build_pulse(self, pulse) -> dict: elif type(pulse) is ChirpPulse: event["pulsedef"]["type"] = 'chirp' + event["pulsedef"]["t_rise"] = float(pulse.rise_time.value) if hasattr(pulse, "init_freq"): event["pulsedef"]["nu_init"] = pulse.init_freq.value +\ diff --git a/pyepr/hardware/ETH_awg_load.py b/pyepr/hardware/ETH_awg_load.py index 39aed04..b12fde3 100644 --- a/pyepr/hardware/ETH_awg_load.py +++ b/pyepr/hardware/ETH_awg_load.py @@ -26,7 +26,11 @@ def uwb_load(matfile: np.ndarray, options: dict = dict(), verbosity=0, # Extract Data estr = matfile[matfile['expname']] - conf = matfile['conf'] + if 'settings' in matfile.keys(): + conf = matfile['settings']['conf'] + else: + conf = matfile['conf'] + def extract_data(matfile): if "dta" in matfile.keys(): @@ -559,7 +563,10 @@ def uwb_eval_match(matfile, sequence=None, scans=None, mask=None,filter_pulse=No # imports Andrin Doll AWG datafiles using a matched filter estr = matfile[matfile['expname']] - conf = matfile['conf'] + if 'settings' in matfile.keys(): + conf = matfile['settings']['conf'] + else: + conf = matfile['conf'] def extract_data(matfile,scans): if "dta" in matfile.keys() and not kwargs.get('ignore_dta',False): From 22b5f4f2cf5af7bc2a9239a2c8a3f6df6b5d353a Mon Sep 17 00:00:00 2001 From: Hugo Karas Date: Wed, 4 Feb 2026 16:58:27 +0100 Subject: [PATCH 08/55] Added rise time to linear chirp pulses --- pyepr/pulses.py | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/pyepr/pulses.py b/pyepr/pulses.py index 380a2a4..f1d5682 100644 --- a/pyepr/pulses.py +++ b/pyepr/pulses.py @@ -1108,15 +1108,22 @@ class ChirpPulse(FrequencySweptPulse): Represents a linear frequency-swept pulse. """ - def __init__(self, *, tp=128, **kwargs) -> None: + def __init__(self, *, tp=128,rise_time=10, **kwargs) -> None: FrequencySweptPulse.__init__(self, tp=tp,name='ChirpPulse', **kwargs) + self.rise_time = Parameter("rise_time", rise_time, "ns", "The rise time of the pulse") self._buildFMAM(self.func) pass def func(self, ax): nx = ax.shape[0] + # Use a quarter sine wave for the rise and fall + rise_pts = int(self.rise_time.value/(ax[1]-ax[0])) + if rise_pts > nx/2: + rise_pts = int(nx/2) AM = np.ones(nx) + AM[0:rise_pts] = np.sin((np.pi/2)*(ax[0:rise_pts]/self.rise_time.value))**2 + AM[-rise_pts:] = np.sin((np.pi/2)*((self.tp.value-ax[-rise_pts:])/self.rise_time.value))**2 FM = np.linspace( self.init_freq.value, self.final_freq.value, nx) From a5d5dcbf355b5b6f337184ae7a86bf096717b63d Mon Sep 17 00:00:00 2001 From: Hugo Karas Date: Thu, 18 Sep 2025 13:45:21 +0200 Subject: [PATCH 09/55] F236 update --- pyepr/classes.py | 3 +- pyepr/hardware/PyEPR_control.py | 113 ++++++++++++++++++++++------ pyepr/resonator_profile_analysis.py | 13 +++- pyepr/sequences.py | 20 +++-- 4 files changed, 117 insertions(+), 32 deletions(-) diff --git a/pyepr/classes.py b/pyepr/classes.py index 4a20401..6a47b5f 100644 --- a/pyepr/classes.py +++ b/pyepr/classes.py @@ -153,7 +153,8 @@ def terminate_at(self, criterion, test_interval=2, keep_running=True, verbosity= data = self.acquire_dataset() if autosave: self.log.debug(f"Autosaving to {os.path.join(self.savefolder,self.savename)}") - data.to_netcdf(os.path.join(self.savefolder,self.savename),engine='h5netcdf',invalid_netcdf=True) + # data.to_netcdf(os.path.join(self.savefolder,self.savename),engine='h5netcdf',invalid_netcdf=True) + data.epr.save(os.path.join(self.savefolder,self.savename)) try: # nAvgs = data.num_scans.value diff --git a/pyepr/hardware/PyEPR_control.py b/pyepr/hardware/PyEPR_control.py index 692eba5..b6bff9f 100644 --- a/pyepr/hardware/PyEPR_control.py +++ b/pyepr/hardware/PyEPR_control.py @@ -11,7 +11,7 @@ # PyEPR imports from pyepr.classes import Interface, Parameter from pyepr.pulses import Delay, Detection -from pyepr.sequences import Sequence, HahnEchoSequence +from pyepr.sequences import Sequence, HahnEchoSequence, FieldSweepSequence log = logging.getLogger("interface") @@ -33,11 +33,12 @@ def __init__(self,config_file_path:str): super().__init__() - self.IFgain_options = np.array([0, 20, 40]) - self.IFgain = 2 + self.IFgain_options = np.array([0,20]) #np.array([0, 20, 40]) + self.IFgain = 1 #2 self.config_file = config_file_path self.server = None + self.cur_exp = None @property def savefolder(self): @@ -88,12 +89,21 @@ def disconnect(self): return True def acquire_dataset(self,verbosity=0,sum_scans=True, **kwargs): + + if isinstance(self.cur_exp, FieldSweepSequence): + kwargs['filter_type'] = kwargs.pop('filter_type', 'boxcar') + kwargs['filter_width'] = kwargs.pop('filter_width', 250) + + else: + kwargs['filter_type'] = kwargs.get('filter_type', 'cheby') + kwargs['filter_width'] = kwargs.get('filter_width', 100) for i in range(60): args = kwargs.copy() - args['downconvert'] = True + if 'downconvert' not in args: + args['downconvert'] = True - response = requests.get(self.server + '/get_data', json={'downconvert': True}) + response = requests.get(self.server + '/get_data', json=args) if 'error' in response.json(): if verbosity > 0: log.warning(response.json()['error']) @@ -101,7 +111,9 @@ def acquire_dataset(self,verbosity=0,sum_scans=True, **kwargs): continue elif 'data' in response.json(): break - time.sleep(2) + else: + log.error(f"Unexpected response: {response.json()}") + time.sleep(2) if 'data' in response.json(): data = pickle.loads(response.json()['data'].encode('latin1')) #xr.datarray @@ -110,12 +122,15 @@ def acquire_dataset(self,verbosity=0,sum_scans=True, **kwargs): else: return data else: + log.error(f"No data found in response. {response.json()}") + raise RuntimeError("No data returned from server") def get_buffer(self,verbosity=0,sum_scans=True, **kwargs): for i in range(60): args = kwargs.copy() - args['downconvert'] = False + if 'downconvert' not in args: + args['downconvert'] = False response = requests.get(self.server + '/get_databuffer', json=args) if 'error' in response.json(): @@ -136,6 +151,25 @@ def get_buffer(self,verbosity=0,sum_scans=True, **kwargs): else: raise RuntimeError("No data returned from server") + def status(self): + """Returns the status of the spectrometer. + + Returns + ------- + dict + A dictionary containing the status of the spectrometer. + """ + response = requests.get(self.server + '/status') + if 'error' in response.json(): + raise RuntimeError(response.json()['error']) + else: + # Depickle + status = response.json() + data = pickle.loads(status['status'].encode('latin1')) + return data + + + def set_param(self, param: str, value: float): """Set a parameter for the spectrometer. @@ -160,12 +194,12 @@ def terminate(self): def launch(self, sequence: Sequence , savename: str, IFgain=None, *args,**kwargs): - + self.savefolder = self.savefolder # increase the detection length to a minimum 1024ns for pulse in sequence.pulses: if isinstance(pulse, Detection): - if pulse.tp.value < 128: - pulse.tp.value = 128 + if pulse.tp.value < 256: + pulse.tp.value = 256 if (IFgain is None) or (IFgain is True): test_IF = True @@ -248,7 +282,7 @@ def isrunning(self) -> bool: return response.json()['isrunning'] - def tune_rectpulse(self,*,tp, freq, B, reptime, shots=400): + def tune_rectpulse(self,*,tp, freq, B, reptime, shots=400,IFgain=None): """Generates a rectangular pi and pi/2 pulse of the given length at the given field position. This value is stored in the pulse cache. @@ -277,19 +311,21 @@ def tune_rectpulse(self,*,tp, freq, B, reptime, shots=400): B=B, freq=freq, reptime=reptime, averages=1, shots=shots ) - scale = Parameter("scale",0,dim=45,step=0.02) + scale = Parameter("scale",0.01,dim=45,step=0.02) amp_tune.pulses[0].tp.value = tp amp_tune.pulses[0].scale = scale amp_tune.pulses[1].tp.value = tp * 2 amp_tune.pulses[1].scale = scale + amp_tune.pulses[2].tp.value = 512 + amp_tune.evolution([scale]) - self.launch(amp_tune, "autoDEER_amptune") + self.launch(amp_tune, "autoDEER_amptune",IFgain=IFgain) while self.isrunning(): - time.sleep(10) - dataset = self.acquire_dataset() + time.sleep(2) + dataset = self.acquire_dataset(downconvert=True,reduce=True,filter_type='boxcar',filter_width=250) dataset = dataset.epr.correctphase data = np.abs(dataset.data) @@ -301,15 +337,15 @@ def tune_rectpulse(self,*,tp, freq, B, reptime, shots=400): if scale == 0: warnings.warn("Pulse tuned with a scale of zero!") p90 = amp_tune.pulses[0].copy( - scale=scale, freq=amp_tune.freq) + scale=scale, freq=0) p180 = amp_tune.pulses[1].copy( - scale=scale, freq=amp_tune.freq) + scale=scale, freq=0) return p90, p180 - def tune_pulse(self, pulse, mode, freq, B , reptime, shots=400): + def tune_pulse(self, pulse, mode, freq, B , reptime, shots=400, IFgain=None): """Tunes a single pulse a range of methods. Parameters @@ -355,7 +391,7 @@ def tune_pulse(self, pulse, mode, freq, B , reptime, shots=400): elif pulse.flipangle.value == np.pi/2: tp = pulse.tp.value - pi2_pulse, pi_pulse = self.tune_rectpulse(tp=tp, B=B, freq=c_frq, reptime=reptime) + pi2_pulse, pi_pulse = self.tune_rectpulse(tp=tp, B=B, freq=c_frq, reptime=reptime, IFgain=IFgain) amp_tune =HahnEchoSequence( B=B, freq=freq, reptime=reptime, averages=1, shots=shots, @@ -367,7 +403,7 @@ def tune_pulse(self, pulse, mode, freq, B , reptime, shots=400): amp_tune.evolution([scale]) - self.launch(amp_tune, "autoDEER_amptune") + self.launch(amp_tune, "autoDEER_amptune", IFgain=IFgain) while self.isrunning(): time.sleep(10) @@ -386,7 +422,8 @@ def tune_pulse(self, pulse, mode, freq, B , reptime, shots=400): return pulse elif mode == "amp_nut": - pi2_pulse, pi_pulse = self.tune_rectpulse(tp=12, B=B, freq=c_frq, reptime=reptime) + + pi2_pulse, pi_pulse = self.tune_rectpulse(tp=16, B=B, freq=c_frq, reptime=reptime, IFgain=IFgain) nut_tune = Sequence( name="nut_tune", B=(B/freq*c_frq), freq=freq, reptime=reptime, averages=1,shots=shots @@ -413,7 +450,7 @@ def tune_pulse(self, pulse, mode, freq, B , reptime, shots=400): # axis_id = 0, # axis= np.arange(0,0.9,0.02) # ) - self.launch(nut_tune, "autoDEER_amptune") + self.launch(nut_tune, "autoDEER_amptune", IFgain=IFgain) while self.isrunning(): time.sleep(10) @@ -436,7 +473,9 @@ def tune_pulse(self, pulse, mode, freq, B , reptime, shots=400): pulse.scale = Parameter('scale',new_amp,unit=None,description='The amplitude of the pulse 0-1') return pulse - + + else: + raise ValueError(f"Mode {mode} not recognised. Available modes are: 'amp_hahn', 'amp_nut'") def tune(self,*, sequence=None, mode="amp_hahn", freq=None, gyro=None): if mode == "rect_tune": @@ -527,3 +566,31 @@ def tune(self,*, sequence=None, mode="amp_hahn", freq=None, gyro=None): return sequence + def get_config(self): + """Returns the current configuration of the spectrometer.""" + try: + response = requests.get(f"{self.server}/get_config") + if response.status_code == 200: + config_pkl = response.json()['config'] + config = pickle.loads(config_pkl.encode('latin1')) + return config + except Exception as e: + print(f"Error getting config: {e}") + return None + + def set_config(self, config): + """Sets the configuration of the spectrometer. + + Parameters + ---------- + config : dict + The configuration to set. + """ + try: + config_pkl = pickle.dumps(config) + response = requests.post(f"{self.server}/set_config", data=config_pkl) + if response.status_code == 200: + return True + except Exception as e: + print(f"Error setting config: {e}") + return False diff --git a/pyepr/resonator_profile_analysis.py b/pyepr/resonator_profile_analysis.py index 5a550b2..59eeb88 100644 --- a/pyepr/resonator_profile_analysis.py +++ b/pyepr/resonator_profile_analysis.py @@ -40,7 +40,7 @@ def __init__( Fitting fuction: - .. math:: \\nu(t) = a \cos(2\pi f (t - x_0)) e^{-(t - x_0)/\tau} + k + .. math:: \\nu(t) = a \\cos(2\\pi f (t - x_0)) e^{-(t - x_0)/\\tau} + k where :math:`a` is the amplitude, :math:`f` is the nutation frequency, :math:`\\tau` is the decay time, :math:`x_0` is the offset and :math:`k` is a constant offset. @@ -64,6 +64,15 @@ def __init__( p0 : list, optional The initial guess for the fit, by default None. If not given the guess is set to [50e-3,150,1,0] """ + # Rotate the dataset so that first axis is 'pulse0_tp' and second is 'LO' + + + tp_dim = dataset.coords['pulse0_tp'].dims[0] + B_dim = dataset.coords['B'].dims[0] + if tp_dim != dataset.dims[0]: + dataset = dataset.transpose(tp_dim,B_dim, transpose_coords=True) + + if np.iscomplexobj(dataset): self.dataset = phase_correct_respro(dataset) @@ -155,7 +164,7 @@ def _process_fit(self,R_limit=0.5,mask=None,debug=False): frequency in the dataset. Function used for fitting: - .. math:: \\nu(t) = a \cos(2\pi f (t - x_0)) e^{-(t - x_0)/\tau} + k + .. math:: \\nu(t) = a \\cos(2\\pi f (t - x_0)) e^{-(t - x_0)/\\tau} + k where :math:`a` is the amplitude, :math:`f` is the nutation frequency, :math:`\\tau` is the decay time, :math:`x_0` is the offset and :math:`k` is a constant offset. diff --git a/pyepr/sequences.py b/pyepr/sequences.py index 55b7f74..b1a9884 100644 --- a/pyepr/sequences.py +++ b/pyepr/sequences.py @@ -78,11 +78,11 @@ def __init__( "The shot repetition time") self.averages = Parameter( - "averages", averages, "None", + "averages", int(averages), "None", "The number of averages to perform.") self.shots = Parameter( - "shots", shots, "None", + "shots", int(shots), "None", "The number of shots per scan.") if "det_window" in kwargs: @@ -363,7 +363,15 @@ def shape(self): else: axes_dim = [1] - return [nAvgs]+ axes_dim +[nPcyc] + # Flip the axes dim so it is Z,Y,X... + axes_dim = axes_dim[::-1] + + shape = [nAvgs]+ axes_dim +[nPcyc] + + # Force list output to all be int + shape = np.array(shape).astype(int).tolist() + + return shape @@ -714,7 +722,7 @@ def __init__(self, *, B, freq, reptime, averages, shots, **kwargs) -> None: if hasattr(self, "det_event"): self.addPulse(self.det_event.copy(t=2*tau)) else: - self.addPulse(Detection(t=2*tau, tp=self.det_window.value)) + self.addPulse(Detection(t=2*tau, tp=512)) # ============================================================================= @@ -957,7 +965,7 @@ def __init__(self, *, B, freq, reptime, reptime_max, averages, shots, start=20, step = np.around(step,decimals=-1) step = np.around(step,decimals=-1) reptime = Parameter( - "reptime", reptime, start = min_reptime-reptime, step=step, dim=100, unit="us", + "reptime", reptime, start = min_reptime-reptime, step=step, dim=dim, unit="us", description = "The shot repetition time") super().__init__( @@ -1231,7 +1239,7 @@ def _build_sequence(self): t=tau1+tau2, tp=32, freq=0, flipangle=np.pi )) - self.addPulse(Detection(t=tau1+2*tau2, tp=64)) + self.addPulse(Detection(t=tau1+2*tau2, tp=512)) self.pulses[0].scale.value = 1 From 0272a2e64387a8da479e87a0f73892df61007c77 Mon Sep 17 00:00:00 2001 From: hkaras Date: Wed, 3 Dec 2025 17:14:15 +0100 Subject: [PATCH 10/55] Updated F236 Interface --- pyepr/classes.py | 2 +- pyepr/hardware/ETH_awg.py | 2 +- pyepr/hardware/PyEPR_control.py | 43 +++++++++++++++++++++------------ 3 files changed, 30 insertions(+), 17 deletions(-) diff --git a/pyepr/classes.py b/pyepr/classes.py index 6a47b5f..568cc89 100644 --- a/pyepr/classes.py +++ b/pyepr/classes.py @@ -27,7 +27,7 @@ def __init__(self,config_file:dict=None,log=None) -> None: with open(config_file, 'r') as f: config_file = yaml.safe_load(f) - self.config = config_file if isinstance(config_file, dict) else {} + self.config = config_file if isinstance(config_file, dict) else {"Spectrometer":{"Bridge":{}}} self.pulses = {} self.savefolder = str(Path.home()) diff --git a/pyepr/hardware/ETH_awg.py b/pyepr/hardware/ETH_awg.py index fbcd3ec..70fdee5 100644 --- a/pyepr/hardware/ETH_awg.py +++ b/pyepr/hardware/ETH_awg.py @@ -581,7 +581,7 @@ def tune_pulse(self, pulse, mode, freq, B , reptime, shots=400,step=0.02, dim=45 elif hasattr(pulse, "final_freq") & hasattr(pulse, "BW"): c_frq = pulse.final_freq.value - 0.5*pulse.BW.value + freq elif hasattr(pulse, "init_freq") & hasattr(pulse, "final_freq"): - c_frq = 0.5*(pulse.final_freq.value + pulse.final_freq.value) + freq + c_frq = 0.5*(pulse.init_freq.value + pulse.final_freq.value) + freq # Find rect pulses max_val = step * (dim -1) diff --git a/pyepr/hardware/PyEPR_control.py b/pyepr/hardware/PyEPR_control.py index b6bff9f..60e33d3 100644 --- a/pyepr/hardware/PyEPR_control.py +++ b/pyepr/hardware/PyEPR_control.py @@ -192,7 +192,13 @@ def terminate(self): log.debug(response.json()['message']) return True - + def status(self): + try: + response = requests.get(self.server + "/status", timeout=10) + except Exception as e: + print(f"Error updating status: {e}") + return pickle.loads(response['status'].encode('latin1')) + def launch(self, sequence: Sequence , savename: str, IFgain=None, *args,**kwargs): self.savefolder = self.savefolder # increase the detection length to a minimum 1024ns @@ -317,7 +323,7 @@ def tune_rectpulse(self,*,tp, freq, B, reptime, shots=400,IFgain=None): amp_tune.pulses[1].tp.value = tp * 2 amp_tune.pulses[1].scale = scale - amp_tune.pulses[2].tp.value = 512 + amp_tune.pulses[2].tp.value = 256 amp_tune.evolution([scale]) @@ -382,7 +388,7 @@ def tune_pulse(self, pulse, mode, freq, B , reptime, shots=400, IFgain=None): elif hasattr(pulse, "final_freq") & hasattr(pulse, "BW"): c_frq = pulse.final_freq.value - 0.5*pulse.BW.value + freq elif hasattr(pulse, "init_freq") & hasattr(pulse, "final_freq"): - c_frq = 0.5*(pulse.final_freq.value + pulse.final_freq.value) + freq + c_frq = 0.5*(pulse.init_freq.value + pulse.final_freq.value) + freq # Find rect pulses if mode == "amp_hahn": @@ -391,7 +397,7 @@ def tune_pulse(self, pulse, mode, freq, B , reptime, shots=400, IFgain=None): elif pulse.flipangle.value == np.pi/2: tp = pulse.tp.value - pi2_pulse, pi_pulse = self.tune_rectpulse(tp=tp, B=B, freq=c_frq, reptime=reptime, IFgain=IFgain) + pi2_pulse, pi_pulse = self.tune_rectpulse(tp=tp, B=B, freq=c_frq, reptime=reptime, IFgain=IFgain,shots=shots) amp_tune =HahnEchoSequence( B=B, freq=freq, reptime=reptime, averages=1, shots=shots, @@ -423,27 +429,33 @@ def tune_pulse(self, pulse, mode, freq, B , reptime, shots=400, IFgain=None): elif mode == "amp_nut": - pi2_pulse, pi_pulse = self.tune_rectpulse(tp=16, B=B, freq=c_frq, reptime=reptime, IFgain=IFgain) + pi2_pulse, pi_pulse = self.tune_rectpulse(tp=16, B=(B/freq*c_frq), freq=c_frq, reptime=reptime, IFgain=IFgain,shots=shots) nut_tune = Sequence( - name="nut_tune", B=(B/freq*c_frq), freq=freq, reptime=reptime, + name="nut_tune", B=(B/freq*c_frq), freq=c_frq, reptime=reptime, averages=1,shots=shots ) - nut_tune.addPulse(pulse.copy( - t=0, pcyc={"phases":[0],"dets":[1]}, scale=0)) + f_shift = freq - c_frq + test_pulse = pulse.copy( + t=0, pcyc={"phases":[0],"dets":[1]}, scale=0) + if hasattr(test_pulse,"freq"): + test_pulse.freq.value = pulse.freq.value + f_shift + elif hasattr(test_pulse, "init_freq") & hasattr(pulse, "final_freq"): + test_pulse = pulse.init_freq.value + f_shift + test_pulse = pulse.final_freq.value - f_shift + nut_tune.addPulse(test_pulse) nut_tune.addPulse( - pi2_pulse.copy(t=2e3, - pcyc={"phases":[0, np.pi],"dets":[1, -1]}, - freq=c_frq-freq)) + pi2_pulse.copy(t=2000, + pcyc={"phases":[0],"dets":[1]}, + freq=0)) nut_tune.addPulse( - pi_pulse.copy(t=2.5e3, pcyc={"phases":[0],"dets":[1]}, - freq=c_frq-freq)) - nut_tune.addPulse(Detection(t=3e3, tp=512, freq=c_frq-freq)) + pi_pulse.copy(t=2500, pcyc={"phases":[0],"dets":[1]}, + freq=0)) + nut_tune.addPulse(Detection(t=3000, tp=256, freq=c_frq-freq)) scale = Parameter('scale',0,unit=None,step=0.02, dim=45, description='The amplitude of the pulse 0-1') nut_tune.pulses[0].scale = scale nut_tune.evolution([scale]) - # nut_tune.addPulsesProg( # pulses=[0], # variables=["scale"], @@ -476,6 +488,7 @@ def tune_pulse(self, pulse, mode, freq, B , reptime, shots=400, IFgain=None): else: raise ValueError(f"Mode {mode} not recognised. Available modes are: 'amp_hahn', 'amp_nut'") + def tune(self,*, sequence=None, mode="amp_hahn", freq=None, gyro=None): if mode == "rect_tune": From c13e47b40fa351543bfeeb11953a0ef496b98cc6 Mon Sep 17 00:00:00 2001 From: Hugo Karas Date: Wed, 3 Dec 2025 17:10:02 +0100 Subject: [PATCH 11/55] GaussPulse Improvements --- docsrc/conf.py | 11 ++++++++++- pyepr/pulses.py | 32 ++++++++++++++++++++++++++++---- 2 files changed, 38 insertions(+), 5 deletions(-) diff --git a/docsrc/conf.py b/docsrc/conf.py index f0a7cec..5524a89 100644 --- a/docsrc/conf.py +++ b/docsrc/conf.py @@ -11,6 +11,8 @@ from pyepr import __version__, __copyright__ sys.path.insert(0, os.path.abspath('..')) +import matplotlib +matplotlib.use('Agg') # Use non-interactive backend project = 'PyEPR' copyright = __copyright__ @@ -30,7 +32,10 @@ 'sphinx_copybutton', 'numpydoc', 'sphinx_favicon', - 'sphinx_gallery.gen_gallery'] + 'sphinx_gallery.gen_gallery', + 'matplotlib.sphinxext.plot_directive', + 'sphinx.ext.imgmath' +] templates_path = ['_templates'] exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store'] @@ -41,6 +46,10 @@ autodoc_typehints = "description" autoapi_template_dir = "_templates/autoapi" +plot_include_source = True +plot_html_show_source_code = False +plot_formats = [('png', 100)] + autoapi_keep_files = True autoapi_add_toctree_entry = False autoapi_python_class_content= "both" diff --git a/pyepr/pulses.py b/pyepr/pulses.py index f1d5682..aa641a0 100644 --- a/pyepr/pulses.py +++ b/pyepr/pulses.py @@ -964,20 +964,41 @@ class GaussianPulse(Pulse): Represents a Gaussian monochromatic pulse. """ - def __init__(self, *, tp=32,FWHM=16, freq=0, **kwargs) -> None: - """ Represents a Gaussian monochromatic pulse. + def __init__(self, *, tp=32,FWHM=None, freq=0, **kwargs) -> None: + """ + By default, the FWHM is set to tp/(2*np.sqrt(2*np.log(2))). + Parameters ---------- tp : float - Pulse length in ns, by default 128 + Pulse length in ns, by default 32 FWHM : float, - The full width at half maximum of the pulse + The full width at half maximum of the pulse. Defaults to tp/(2*np.sqrt(2*np.log(2))). freq : float, optional The frequency of the pulse, by default 0 + + + Examples + -------- + + .. plot:: + :include-source: + + import pyepr as epr + import matplotlib.pyplot as plt + + GuassPulse = epr.GaussianPulse(tp=32) + GuassPulse.plot(pad=0) + plt.annotate('', xy=(-GuassPulse.FWHM.value/2, 0.5), xytext=(GuassPulse.FWHM.value/2, 0.5), color='C1',arrowprops=dict(arrowstyle='<|-|>', color='C1',lw=2)) + plt.annotate('FWHM', xy=(0, 0.51), xytext=(0, 0.51), color='C1', ha='center', fontsize=12) """ Pulse.__init__(self, tp=tp,name='GaussianPulse', **kwargs) self.freq = Parameter("Freq", freq, "GHz", "Frequency of the Pulse") + + if FWHM is None: + FWHM = tp / (2 * np.sqrt(2 * np.log(2))) + self.FWHM = Parameter("FWHM", FWHM, "ns", "Full Width at Half Maximum of the Pulse") self._buildFMAM(self.func) pass @@ -988,6 +1009,9 @@ def func(self, ax): AM = np.exp(-ax**2 / (2 * sigma**2)) FM = np.zeros(nx) + self.freq.value return AM, FM + + def plot(self, pad=1000): + return super().plot(pad) # ============================================================================= class FrequencySweptPulse(Pulse): """ From 163055ae8e0c85ebdc8e87aceef56a4ad37e1f8e Mon Sep 17 00:00:00 2001 From: hkaras Date: Wed, 21 Jan 2026 16:22:33 +0100 Subject: [PATCH 12/55] Added tau to tune mode + bug fixes --- pyepr/hardware/PyEPR_control.py | 22 +++++++++++++++------- pyproject.toml | 1 + 2 files changed, 16 insertions(+), 7 deletions(-) diff --git a/pyepr/hardware/PyEPR_control.py b/pyepr/hardware/PyEPR_control.py index 60e33d3..bef93a7 100644 --- a/pyepr/hardware/PyEPR_control.py +++ b/pyepr/hardware/PyEPR_control.py @@ -197,7 +197,7 @@ def status(self): response = requests.get(self.server + "/status", timeout=10) except Exception as e: print(f"Error updating status: {e}") - return pickle.loads(response['status'].encode('latin1')) + return pickle.loads(response.json()['status'].encode('latin1')) def launch(self, sequence: Sequence , savename: str, IFgain=None, *args,**kwargs): self.savefolder = self.savefolder @@ -288,7 +288,7 @@ def isrunning(self) -> bool: return response.json()['isrunning'] - def tune_rectpulse(self,*,tp, freq, B, reptime, shots=400,IFgain=None): + def tune_rectpulse(self,*,tp, freq, B, reptime, shots=400,tau=500,IFgain=None): """Generates a rectangular pi and pi/2 pulse of the given length at the given field position. This value is stored in the pulse cache. @@ -314,7 +314,7 @@ def tune_rectpulse(self,*,tp, freq, B, reptime, shots=400,IFgain=None): """ amp_tune =HahnEchoSequence( - B=B, freq=freq, reptime=reptime, averages=1, shots=shots + B=B, freq=freq, reptime=reptime, averages=1, shots=shots, tau=tau ) scale = Parameter("scale",0.01,dim=45,step=0.02) @@ -323,15 +323,22 @@ def tune_rectpulse(self,*,tp, freq, B, reptime, shots=400,IFgain=None): amp_tune.pulses[1].tp.value = tp * 2 amp_tune.pulses[1].scale = scale - amp_tune.pulses[2].tp.value = 256 + amp_tune.pulses[2].tp.value = 512 amp_tune.evolution([scale]) self.launch(amp_tune, "autoDEER_amptune",IFgain=IFgain) - + time.sleep(15) while self.isrunning(): time.sleep(2) dataset = self.acquire_dataset(downconvert=True,reduce=True,filter_type='boxcar',filter_width=250) + # Check if zero's in data + if np.any(dataset.data == 0): + warnings.warn("Zero values found in dataset. This may indicate an error in acquisition.") + time.sleep(5) + while self.isrunning(): + time.sleep(2) + dataset = self.acquire_dataset(downconvert=True,reduce=True,filter_type='boxcar',filter_width=250) dataset = dataset.epr.correctphase data = np.abs(dataset.data) @@ -342,6 +349,7 @@ def tune_rectpulse(self,*,tp, freq, B, reptime, shots=400,IFgain=None): if scale == 0: warnings.warn("Pulse tuned with a scale of zero!") + print("Pulse tuned with a scale of zero!") p90 = amp_tune.pulses[0].copy( scale=scale, freq=0) @@ -450,7 +458,7 @@ def tune_pulse(self, pulse, mode, freq, B , reptime, shots=400, IFgain=None): nut_tune.addPulse( pi_pulse.copy(t=2500, pcyc={"phases":[0],"dets":[1]}, freq=0)) - nut_tune.addPulse(Detection(t=3000, tp=256, freq=c_frq-freq)) + nut_tune.addPulse(Detection(t=3000, tp=512, freq=c_frq-freq)) scale = Parameter('scale',0,unit=None,step=0.02, dim=45, description='The amplitude of the pulse 0-1') nut_tune.pulses[0].scale = scale @@ -463,7 +471,7 @@ def tune_pulse(self, pulse, mode, freq, B , reptime, shots=400, IFgain=None): # axis= np.arange(0,0.9,0.02) # ) self.launch(nut_tune, "autoDEER_amptune", IFgain=IFgain) - + time.sleep(10) while self.isrunning(): time.sleep(10) dataset = self.acquire_dataset() diff --git a/pyproject.toml b/pyproject.toml index bbd42c1..b77ae52 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -20,6 +20,7 @@ toml = "^0.10.2" deerlab = "^1.1.4" numba = ">=0.60.0" psutil = "^7.1.3" +requests = ">=2.32" [tool.poetry.group.dev.dependencies] From 898d7ad14f7d07e67b7e7cfe5cd465fa3c18f73f Mon Sep 17 00:00:00 2001 From: hkaras Date: Wed, 11 Feb 2026 14:38:19 +0100 Subject: [PATCH 13/55] Bug Fixes --- pyepr/classes.py | 8 ++++++++ pyepr/hardware/PyEPR_control.py | 2 +- pyproject.toml | 3 ++- 3 files changed, 11 insertions(+), 2 deletions(-) diff --git a/pyepr/classes.py b/pyepr/classes.py index 568cc89..ac49b91 100644 --- a/pyepr/classes.py +++ b/pyepr/classes.py @@ -23,6 +23,14 @@ class Interface: """ def __init__(self,config_file:dict=None,log=None) -> None: + """ + Parameters + ---------- + config_file : dict or str or Path, optional + The configuration file or dict for the spectrometer interface, by default None. If None, a default configuration will be used. + log : logging.Logger, optional + The logger to be used, by default None. If None, a default logger will be created. + """ if isinstance(config_file, (str,Path)): with open(config_file, 'r') as f: config_file = yaml.safe_load(f) diff --git a/pyepr/hardware/PyEPR_control.py b/pyepr/hardware/PyEPR_control.py index bef93a7..6785e32 100644 --- a/pyepr/hardware/PyEPR_control.py +++ b/pyepr/hardware/PyEPR_control.py @@ -33,7 +33,7 @@ def __init__(self,config_file_path:str): super().__init__() - self.IFgain_options = np.array([0,20]) #np.array([0, 20, 40]) + self.IFgain_options = np.array([0,20,40]) #np.array([0, 20, 40]) self.IFgain = 1 #2 self.config_file = config_file_path diff --git a/pyproject.toml b/pyproject.toml index b77ae52..64a0735 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -15,7 +15,8 @@ scipy = "^1.14.1" matplotlib = "^3.9.2" pyyaml = "^6.0.2" xarray = ">=2025" -h5netcdf = "^1.4.0" +h5py = ">3.15" +h5netcdf = ">1.4.0" toml = "^0.10.2" deerlab = "^1.1.4" numba = ">=0.60.0" From 44b8f95f7d9029f81195bfc5f437a2ed95650dec Mon Sep 17 00:00:00 2001 From: hkaras Date: Tue, 31 Mar 2026 09:37:43 +0200 Subject: [PATCH 14/55] Better NUS handling of parameter rounding --- pyepr/classes.py | 27 ++++++++++++++++----------- 1 file changed, 16 insertions(+), 11 deletions(-) diff --git a/pyepr/classes.py b/pyepr/classes.py index ac49b91..08bc784 100644 --- a/pyepr/classes.py +++ b/pyepr/classes.py @@ -287,7 +287,7 @@ def __init__(self, name, value, unit="", description="", virtual=False, self.value = value self.NUS = False # uniform sampling elif isinstance(value, np.ndarray): - self.value = np.median(value) + self.value = value[0] axis = value - self.value self.NUS = True # non-uniform sampling elif value is None: @@ -391,17 +391,22 @@ def adjust_step(self, waveform_precision, keep_dim=True): current_step =old_axis[1] - old_axis[0] # test if uniformally sampled if not np.allclose(np.diff(self.axis[i]["axis"]), current_step): - raise ValueError("This only works for uniformaly sampled data at the moment") - new_step = round_step(current_step, waveform_precision) - - if new_step == 0: - new_step = waveform_precision - - if keep_dim: - dim = old_axis.shape[0] - new_axis = np.arange(self.axis[i]["axis"][0], self.axis[i]["axis"][0]+new_step*dim, new_step) + tolerance = 1e-9 + new_axis = copy.deepcopy(old_axis) + remainders = np.abs(new_axis % waveform_precision) + not_multiples = ~(np.isclose(remainders, 0, atol=1e-9) | np.isclose(remainders, waveform_precision, atol=1e-9)) + new_axis[not_multiples] = np.round(new_axis[not_multiples] / waveform_precision) * waveform_precision else: - new_axis = np.arange(self.axis[i]["axis"][0], self.axis[i]["axis"][-1]+new_step, new_step) + new_step = round_step(current_step, waveform_precision) + + if new_step == 0: + new_step = waveform_precision + + if keep_dim: + dim = old_axis.shape[0] + new_axis = np.arange(self.axis[i]["axis"][0], self.axis[i]["axis"][0]+new_step*dim, new_step) + else: + new_axis = np.arange(self.axis[i]["axis"][0], self.axis[i]["axis"][-1]+new_step, new_step) self.axis[i]["axis"] = new_axis if isinstance(self.value, numbers.Number): From 4703370d6d742b8a8e516a832e041834dd258e15 Mon Sep 17 00:00:00 2001 From: hkaras Date: Tue, 28 Apr 2026 09:43:27 +0200 Subject: [PATCH 15/55] Removed div 0 warnings --- pyepr/hardware/PyEPR_control.py | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/pyepr/hardware/PyEPR_control.py b/pyepr/hardware/PyEPR_control.py index 6785e32..f7c66bc 100644 --- a/pyepr/hardware/PyEPR_control.py +++ b/pyepr/hardware/PyEPR_control.py @@ -253,7 +253,7 @@ def launch(self, sequence: Sequence , savename: str, IFgain=None, *args,**kwargs self._launch(sequence,savename,IFgain, *args,**kwargs) else: - raise ValueError(f"IFgain must be of type [None, bool, int, float]. {IFgain} is not valid.") + raise ValueError(f"IFgain must be of type [None, bool, int, float]. Type {type(IFgain)}_{IFgain} is not valid.") def _launch(self, sequence: Sequence , savename: str, IFgain=0,reset_cur_exp=True,*args,**kwargs): @@ -359,7 +359,7 @@ def tune_rectpulse(self,*,tp, freq, B, reptime, shots=400,tau=500,IFgain=None): return p90, p180 - def tune_pulse(self, pulse, mode, freq, B , reptime, shots=400, IFgain=None): + def tune_pulse(self, pulse, mode, freq, B , reptime, shots=400, IFgain=None,tau=500): """Tunes a single pulse a range of methods. Parameters @@ -409,7 +409,7 @@ def tune_pulse(self, pulse, mode, freq, B , reptime, shots=400, IFgain=None): amp_tune =HahnEchoSequence( B=B, freq=freq, reptime=reptime, averages=1, shots=shots, - pi2_pulse = pulse, pi_pulse=pi_pulse + pi2_pulse = pulse, pi_pulse=pi_pulse,tau=tau ) scale = Parameter('scale',0,unit=None,step=0.02, dim=45, description='The amplitude of the pulse 0-1') @@ -456,7 +456,7 @@ def tune_pulse(self, pulse, mode, freq, B , reptime, shots=400, IFgain=None): pcyc={"phases":[0],"dets":[1]}, freq=0)) nut_tune.addPulse( - pi_pulse.copy(t=2500, pcyc={"phases":[0],"dets":[1]}, + pi_pulse.copy(t=2000+tau, pcyc={"phases":[0],"dets":[1]}, freq=0)) nut_tune.addPulse(Detection(t=3000, tp=512, freq=c_frq-freq)) From 1aeb5bd4dc75b968b8ed58e10bf978feda5e8c43 Mon Sep 17 00:00:00 2001 From: Hugo Karas Date: Wed, 27 May 2026 17:33:27 +0200 Subject: [PATCH 16/55] Patch13 dev (#19) - Added `AmplifierLinearityAnalysis` class for characterizing amplifier non-linearity. - Added `T1InversionRecovery` sequence. - Added rise time to linear chirp pulses. - Added right based arithmatic. - Fixed Version Detection Bug - Fixed Dependency issues - Improved Documentation - Removed Numba dependency --- docsrc/API_docs.rst | 2 + docsrc/install.rst | 1 - docsrc/releasenotes.rst | 13 ++ docsrc/tutorial_sequencer.md | 24 ++-- pyepr/classes.py | 12 +- pyepr/dataset.py | 129 ++++++++++++++++++-- pyepr/hardware/Bruker_AWG.py | 45 +++++-- pyepr/hardware/Bruker_MPFU.py | 2 +- pyepr/hardware/Bruker_tools.py | 4 +- pyepr/hardware/ETH_awg.py | 13 +- pyepr/hardware/ETH_awg_load.py | 181 +++++++++++++++++++++++++++- pyepr/hardware/XeprAPI_link.py | 19 ++- pyepr/hardware/dummy.py | 2 +- pyepr/hardware/dummy_xepr.py | 2 +- pyepr/pulses.py | 53 +++++--- pyepr/relaxation_analysis.py | 6 +- pyepr/resonator_profile_analysis.py | 96 ++++++++++++++- pyepr/sequences.py | 78 ++++++++++-- pyepr/tools.py | 39 ++++-- pyepr/utils.py | 2 +- pyproject.toml | 6 +- tests/test_pulses.py | 72 +++++++++++ tests/test_respro.py | 134 ++++++++++++++++++++ tests/test_utils.py | 93 ++++++++++++++ 24 files changed, 930 insertions(+), 98 deletions(-) create mode 100644 tests/test_pulses.py create mode 100644 tests/test_respro.py create mode 100644 tests/test_utils.py diff --git a/docsrc/API_docs.rst b/docsrc/API_docs.rst index 2c625c4..c6c4340 100644 --- a/docsrc/API_docs.rst +++ b/docsrc/API_docs.rst @@ -36,6 +36,7 @@ Sequences pyepr.sequences.CarrPurcellSequence pyepr.sequences.ResonatorProfileSequence pyepr.sequences.TWTProfileSequence + pyepr.sequences.T1InversionRecoverySequence Pulses ~~~~~~ @@ -90,6 +91,7 @@ I/O pyepr.dataset.create_dataset_from_sequence pyepr.dataset.create_dataset_from_axes pyepr.dataset.create_dataset_from_bruker + pyepr.dataset.downconvert_dataset Utilities ~~~~~~~~~ diff --git a/docsrc/install.rst b/docsrc/install.rst index e431c7a..f10a207 100644 --- a/docsrc/install.rst +++ b/docsrc/install.rst @@ -38,5 +38,4 @@ PyEPR requires: - h5netcdf - toml - deerlab (https://github.com/JeschkeLab/DeerLab) - - numba - psutil diff --git a/docsrc/releasenotes.rst b/docsrc/releasenotes.rst index 1c3a3be..9070159 100644 --- a/docsrc/releasenotes.rst +++ b/docsrc/releasenotes.rst @@ -1,6 +1,19 @@ Release Notes ============= +Version 1.1 (2026-05-27): +++++++++++++++++++++++++++++ +- Added `AmplifierLinearityAnalysis` class for characterizing amplifier non-linearity. +- Added `T1InversionRecovery` sequence. +- Added rise time to linear chirp pulses. +- Added right based arithmatic. +- Fixed Version Detection Bug +- Fixed Dependency issues +- Improved Documentation +- Removed Numba dependency + + + Version 1.0.0 (2025-09-12): ++++++++++++++++++++++++++++ - All references to `LO` have been changed to `freq` in the frequency object and related. diff --git a/docsrc/tutorial_sequencer.md b/docsrc/tutorial_sequencer.md index a78d50c..784cbf3 100644 --- a/docsrc/tutorial_sequencer.md +++ b/docsrc/tutorial_sequencer.md @@ -1,6 +1,6 @@ # Pulse Sequencer -PyEPR provides an intuitive object-oriented pulse programmer allowing the user to design pulsesequences in a hardware-agnostic manner. Additionally, several common EPR experiments are pre-defined and can be easily instantiated and modified. +PyEPR provides an intuitive object-oriented pulse programmer allowing the user to design pulse sequences in a hardware-agnostic manner. Additionally, several common EPR experiments are pre-defined and can be easily instantiated and modified. PyEPR uses ns, GHz and G as the default time, frequency and field units. Very occasionally, other units such as µs or MHz are used, in which case it will be explicitly mentioned. @@ -31,33 +31,33 @@ These pulses will eventually need a scale (amplitude), before the sequence can b A Detection window is also created ```python p90 = epr.RectPulse(tp=16, - freq=0, # Frequency offset in MHz, w.r.t the sequence frequency, + freq=0, # Frequency offset in GHz, w.r.t the sequence frequency, flipangle=np.pi/2, # Flip angle in degrees pcyc = {"phases":[0, np.pi], "dets":[1,-1]} ) p180 = epr.RectPulse(tp=32, - freq=0, # Frequency offset in MHz, w.r.t the sequence frequency, + freq=0, # Frequency offset in GHz, w.r.t the sequence frequency, flipangle=np.pi, # Flip angle in degrees ) -det = epr.Detetction(tp=32, - freq=0, # Frequency offset in MHz, w.r.t the sequence frequency, +det = epr.Detection(tp=32, + freq=0, # Frequency offset in GHz, w.r.t the sequence frequency, ) ``` We now need a time axis for our sequence and to add them to the sequence object. -When a pulse is copied into the sequence using the `add_pulse` method, parameters can be modified allowing the same pulse can be used multiple times with different timings or amplitudes. +When a pulse is copied into the sequence using the `addPulse` method, parameters can be modified allowing the same pulse can be used multiple times with different timings or amplitudes. ```python t = epr.Parameter(name='Interpulse Delay', value=400, # Initial interpulse delay in ns step=8, # Step size in ns - dim=1024 # Number of points, - unit='ns' # Unit of the parameter + dim=1024, # Number of points, + unit='ns', # Unit of the parameter description='Interpulse delay between the pi/2 and pi pulse' ) # Adding the pulses to the sequence -seq.add_pulse(p90.copy(t=0)) -seq.add_pulse(p180.copy(t=t)) -seq.add_pulse(det.copy(t=2*t)) +seq.addPulse(p90.copy(t=0)) +seq.addPulse(p180.copy(t=t)) +seq.addPulse(det.copy(t=2*t)) # Defining the evolution seq.evolution([t]) @@ -81,7 +81,7 @@ HE_Seq = epr.HahnEchoRelaxationSequence( shots = 20, # Number of shots per point start = 400, # Initial interpulse delay in ns step = 8, # Step size in ns - dim = 1024 # Number of points + dim = 1024, # Number of points pi2_pulse = p90, # The 90 degree pulse pi_pulse = p180 # The 180 degree pulse ) diff --git a/pyepr/classes.py b/pyepr/classes.py index 08bc784..b0df3bf 100644 --- a/pyepr/classes.py +++ b/pyepr/classes.py @@ -45,7 +45,10 @@ def __init__(self,config_file:dict=None,log=None) -> None: else: self.log = log self.resonator = None - self.amp_nonlinearity = self.config["Spectrometer"]["Bridge"].get('Amplifier Non-Linearity',None) + if self.config != {}: + self.amp_nonlinearity = self.config["Spectrometer"]["Bridge"].get('Amplifier Non-Linearity',None) + else: + self.amp_nonlinearity = None pass def connect(self) -> None: @@ -510,6 +513,10 @@ def __add__(self, __o:object): raise RuntimeError( "Both parameters axis and the array must have the same shape") + def __radd__(self, __o:object): + return self.__add__(__o) + + def __sub__(self, __o:object): if type(__o) is Parameter: @@ -578,6 +585,9 @@ def __sub__(self, __o:object): raise RuntimeError( "Both parameters axis and the array must have the same shape") + def __rsub__(self, __o:object): + return self.__sub__(__o) + def __mul__(self, __o:object): if type(__o) is Parameter: if self.unit != __o.unit: diff --git a/pyepr/dataset.py b/pyepr/dataset.py index 868200e..1bf4c2f 100644 --- a/pyepr/dataset.py +++ b/pyepr/dataset.py @@ -102,7 +102,8 @@ def create_dataset_from_sequence(data, sequence: Sequence,extra_params={}): attr.update({'autoDEER_Version':__version__}) return xr.DataArray(data, dims=dims, coords=coords,attrs=attr) -def create_dataset_from_axes(data, axes, params: dict = {},axes_labels=None): +def create_dataset_from_axes(data, axes, params: dict = {},extra_coords:dict = None, + axes_labels=None): """ Create an xarray dataset from a numpy array and a list of axes. @@ -129,7 +130,9 @@ def create_dataset_from_axes(data, axes, params: dict = {},axes_labels=None): if not isinstance(axes, list): axes = [axes] coords = {default_labels.pop(0):a for a in axes} - params.update({'autoDEER_Version':__version__}) + if extra_coords is not None: + coords.update(extra_coords) + params.update({'PyEPR_Version':__version__}) return xr.DataArray(data, dims=dims, coords=coords, attrs=params) @@ -143,7 +146,7 @@ def create_dataset_from_bruker(filepath): labels = [] for i in range(ndims): ax_label = default_labels[i] - axis_string = params['DESC'][f'{ax_label}UNI'] + axis_string = params['DESC'].get(f'{ax_label}UNI',"") if "'" in axis_string: axis_string = axis_string.replace("'", "") if axis_string == 'G': @@ -162,11 +165,12 @@ def create_dataset_from_bruker(filepath): coords = {labels[i]:(default_labels[i],a) for i,a in enumerate(axes)} attr = {} - attr['LO'] = float(params['SPL']['MWFQ']) / 1e9 - attr['B'] = float(params['SPL']['B0VL']) * 1e4 - attr['reptime'] = float(params['DSL']['ftEpr']['ShotRepTime'].replace('us','')) - attr['nAvgs'] = int(params['DSL']['recorder']['NbScansAcc']) - attr['shots'] = int(params['DSL']['ftEpr']['ShotsPLoop']) + if 'DSL' in params: + attr['LO'] = float(params['SPL']['MWFQ']) / 1e9 + attr['B'] = float(params['SPL']['B0VL']) * 1e4 + attr['reptime'] = float(params['DSL']['ftEpr']['ShotRepTime'].replace('us','')) + attr['nAvgs'] = int(params['DSL']['recorder']['NbScansAcc']) + attr['shots'] = int(params['DSL']['ftEpr']['ShotsPLoop']) attr.update({'autoDEER_Version':__version__}) return xr.DataArray(data, dims=dims, coords=coords, attrs=attr) @@ -183,7 +187,7 @@ def save(self, filename, type='netCDF',overwrite=True): Parameters ---------- - filename : str + filename : str, file-like object The name of the file to save the dataset type : str, optional The type of file to save, by default 'netCDF' (including .h5) @@ -196,7 +200,7 @@ def save(self, filename, type='netCDF',overwrite=True): mode = "a" #if filename doesn't have the extension .h5, add it - if not filename.endswith('.h5'): + if isinstance(filename,str) and not filename.endswith('.h5'): filename = filename + '.h5' if 'Scan' in self._obj.dims: @@ -375,3 +379,108 @@ def merge(self,other,ignore_errors=True): +def downconvert_dataset(dataset, filter_type='boxcar',IF=None,reduce=True,sampling_rate=None,**kwargs): + """ + Downconvert a dataset to baseband using a filter + Parameters + ---------- + dataset : xr.DataArray + The dataset to downconvert + filter_type : str, optional + The type of filter to use, by default 'boxcar'. Other options are 'cheby' and a Pulse object + filter_width : float, optional + The width of the filter in MHz or ns depending on filter tyre, by default 20 ns for boxcar and 50 MHz for cheby. + IF : float, optional + The intermediate frequency to use, by default 0.15 + reduce : bool, optional + If True, the dataset is reduced to a single point, by default True + **kwargs : dict + Extra arguments to pass to the filter function + + Returns + ------- + xr.DataArray + The downconverted dataset + """ + + if IF is None: + if 'IF_freq' in dataset.attrs: + IF = dataset.attrs.get('IF_freq') # GHz + elif 'if_freq' in dataset.attrs: + IF = dataset.attrs.get('if_freq') # GHz + elif 'IFfreq' in dataset.attrs: + IF = dataset.attrs.get('IFfreq') # GHz + else: + raise ValueError('IFfreq not found in dataset attributes, please provide IF value') + + if sampling_rate is None: + if 'det_rate' in dataset.attrs: + sampling_rate = dataset.attrs.get('det_rate') # GHz + elif 'sampling_rate' in dataset.attrs: + sampling_rate = dataset.attrs.get('sampling_rate') # GHz + else: + raise ValueError('sampling_rate not found in dataset attributes, please provide sampling_rate value') + if filter_type is None: + dc_first=True + elif filter_type not in ['boxcar','cheby']: + filter_type = 'cheby' + filter_width = 50 + + + if filter_type == 'boxcar': + filter_width = kwargs.get('filter_width',20) + funct = lambda data: np.convolve(data,np.ones(filter_width),mode='same') + dc_first=True + elif isinstance(filter_type, ad_pulses.Pulse): # match filter to a epr Pulse + raise NotImplementedError('Match filter to a pulse not implemented yet') + elif filter_type == 'cheby': + from scipy.signal import cheby1,sosfiltfilt + filter_width = kwargs.get('filter_width',50) # MHz + filter_width /= 1e3 + + Wn = np.array([IF-filter_width,IF+filter_width]) + Wn[Wn<=0] = 0.001 + order = 5 + + a = cheby1(order,0.5,Wn,'bandpass',analog=False,fs=sampling_rate,output='sos') + funct = lambda data: sosfiltfilt(a,data) + dc_first=False + elif filter_type is None: + dc_first=True + + else: + raise ValueError('Filter not recognised') + + if dc_first: + data_array_dc = dataset*np.exp(-1j*2*np.pi*IF*dataset.tx/sampling_rate) + if filter_type is None: + return data_array_dc + data_array_dc.data = np.apply_along_axis(funct,-1,data_array_dc.data) + else: + data_array_dc = xr.apply_ufunc(funct,dataset) + data_array_dc = data_array_dc*np.exp(-1j*2*np.pi*IF*data_array_dc.tx/sampling_rate) + + # if data_array_dc.ndim == 3: + # max_echo_pos = np.unravel_index(np.argmax(np.abs(data_array_dc.data[0,0,20:-20])),data_array_dc.shape[-1])[0] + 20 + # else: + # max_echo_pos = np.unravel_index(np.argmax(np.abs(data_array_dc.data[0,20:-20])),data_array_dc.shape[-1])[0] + 20 + if reduce: + if 'max_echo_pos' in kwargs: + max_echo_pos = kwargs['max_echo_pos'] + else: + max_echo_pos = np.unravel_index(np.abs(data_array_dc).argmax(),data_array_dc.shape)[-1] + return data_array_dc[...,max_echo_pos] + else: + return data_array_dc + +def find_peak(dataset, freq,freq_axis=None,search_range=4): + if freq/1e3 < freq_axis.min() or freq/1e3 > freq_axis.max(): + return "N/A", "N/A" + + if freq_axis is None: + freq_axis = dataset.offset_frequency.values + n_points = dataset.shape[0] + loc = np.argmin(np.abs(freq_axis-freq/1e3)) + loc = loc-search_range + dataset.values[loc-search_range:loc+search_range].argmax() + peak = dataset[loc].values + return loc,peak diff --git a/pyepr/hardware/Bruker_AWG.py b/pyepr/hardware/Bruker_AWG.py index 52fac3f..e900e06 100644 --- a/pyepr/hardware/Bruker_AWG.py +++ b/pyepr/hardware/Bruker_AWG.py @@ -75,6 +75,17 @@ def __init__(self, config_file) -> None: def connect(self, d0=None) -> None: + """ + Connects to the spectrometer through the XeprAPI. Automatically sets + up the spectrometer for pulse experiments. + + Parameters + ---------- + d0: float, optional + The d0 value to be used. If None, the d0 will be calculated + upon connection. By default None. + + """ self.api.connect() @@ -84,17 +95,36 @@ def connect(self, d0=None) -> None: return super().connect() def setup(self,d0=None): + """ + Sets up the spectrometer for pulse experiments. + The video bandwidth is read from the configuration file, and the timebase + is set accordingly. + + Parameters + ---------- + d0: float, optional + The d0 value to be used. If None, the d0 will be calculated + upon connection. By default None. + + """ + # Check if needs to switch to pulse mode, only if needed as slow + if not self.api.hidden['BrPlsMode'].value: + hw_log.info('Switching to Pulse Mode') + temp_mw_amp = self.api.get_MW_amp() + + self.api.hidden['BrPlsMode'].value = True # Turns the mw (video) amplifier on + time.sleep(3) # Wait for bridge to actually switch to pulse mode + self.api.set_MW_amp(temp_mw_amp) - self.api.hidden['BrPlsMode'].value = True self.api.hidden['OpMode'].value = 'Operate' # self.api.hidden['RefArm'].value = 'On' - # TODO add detection of VAMP-III model video_bw = self.bridge_config.get('Video BW') # self.api.cur_exp['VideoBW'].value = 20 self.time_base = 1/(video_bw*2e-3) self.api.hidden['specJet.TimeBase'].value = self.time_base + if d0 is None: @@ -282,13 +312,14 @@ def launch(self, sequence: Sequence, savename: str, start=True, tune=True, def tune_rectpulse(self,*,tp, freq, B, reptime, shots=400): - """Generates a rectangular pi and pi/2 pulse of the given length at - the given field position. This value is stored in the pulse cache. + """ + Generates a rectangular pi/2 and pi pulse at the given frequency and field. + The pulses are of equal amplitude ($t_p$ for pi/2 and $2*t_p$ for pi) and are tuned using a Hahn echo sequence. Parameters ---------- tp : float - Pulse length in ns + $pi/2$ Pulse length in ns freq : float Central frequency of this pulse in GHz B : float @@ -303,7 +334,7 @@ def tune_rectpulse(self,*,tp, freq, B, reptime, shots=400): p90: RectPulse A tuned rectangular pi/2 pulse of length tp p180: RectPulse - A tuned rectangular pi pulse of length tp + A tuned rectangular pi pulse of length 2*tp """ time.sleep(5) amp_tune =HahnEchoSequence( @@ -335,7 +366,7 @@ def tune_rectpulse(self,*,tp, freq, B, reptime, shots=400): data = np.abs(dataset.data) scale_amp = np.around(dataset.pulse0_scale[data.argmax()].data,2) if scale_amp > 0.95: - raise RuntimeError("Not enough power avaliable.") + raise RuntimeError("Not enough power available.") if scale_amp == 0: warnings.warn("Pulse tuned with a scale of zero!") diff --git a/pyepr/hardware/Bruker_MPFU.py b/pyepr/hardware/Bruker_MPFU.py index 973a0fe..2f50c48 100644 --- a/pyepr/hardware/Bruker_MPFU.py +++ b/pyepr/hardware/Bruker_MPFU.py @@ -957,7 +957,7 @@ def ELDORtune(interface, sequence, freq, MPFU=True, for i,x in enumerate(atten_axis): interface.api.set_attenuator('ELDOR',x) # Set phase to value time.sleep(1) - data[i] = np.trapz(get_specjet_data(interface)) + data[i] = np.trapezoid(get_specjet_data(interface)) data = correctphase(data) if data[np.abs(data).argmax()].max() < 1: diff --git a/pyepr/hardware/Bruker_tools.py b/pyepr/hardware/Bruker_tools.py index 7d419ab..cc945da 100644 --- a/pyepr/hardware/Bruker_tools.py +++ b/pyepr/hardware/Bruker_tools.py @@ -1287,9 +1287,7 @@ def write_pulsespel_file(sequence,d0, AWG=False, MPFU=False,MaxGate=40): pcyc_hash = pcyc.pcyc_hash pcyc_str = pcyc.__str__() else: - pcyc = PSPhaseCycle(sequence, MPFU) - pcyc_hash = pcyc.pcyc_hash - pcyc_str = pcyc.__str__() + raise ValueError("Either AWG must be True or MPFU must be supplied") # Add Pulse Sequence pulse_str = "d9\n" for id, pulse in enumerate(sequence.pulses): diff --git a/pyepr/hardware/ETH_awg.py b/pyepr/hardware/ETH_awg.py index 70fdee5..ad1b653 100644 --- a/pyepr/hardware/ETH_awg.py +++ b/pyepr/hardware/ETH_awg.py @@ -480,7 +480,7 @@ def tune_rectpulse(self,*,tp, freq, B, reptime, shots=400,step=0.02, dim=45): Parameters ---------- tp : float - Pulse length of pi/2 pulse in ns + $pi/2$ Pulse length in ns freq : float Central frequency of this pulse in GHz B : float @@ -499,9 +499,8 @@ def tune_rectpulse(self,*,tp, freq, B, reptime, shots=400,step=0.02, dim=45): p90: RectPulse A tuned rectangular pi/2 pulse of length tp p180: RectPulse - A tuned rectangular pi pulse of length tp + A tuned rectangular pi pulse of length 2*tp """ - amp_tune =HahnEchoSequence( B=B, freq=freq, reptime=reptime, averages=1, shots=shots ) @@ -527,7 +526,7 @@ def tune_rectpulse(self,*,tp, freq, B, reptime, shots=400,step=0.02, dim=45): data = np.abs(dataset.data) scale = np.around(dataset.pulse0_scale[data.argmax()].data,2) if scale > 0.9: - raise RuntimeError("Not enough power avaliable.") + raise RuntimeError("Not enough power available.") if scale == 0: warnings.warn("Pulse tuned with a scale of zero!") @@ -616,7 +615,7 @@ def tune_pulse(self, pulse, mode, freq, B , reptime, shots=400,step=0.02, dim=45 new_amp = np.around(dataset.pulse0_scale[dataset.data.argmax()].data,2) if new_amp > 0.9: - raise RuntimeError("Not enough power avaliable.") + raise RuntimeError("Not enough power available.") if new_amp == 0: warnings.warn("Pulse tuned with a scale of zero!") @@ -709,7 +708,7 @@ def tune(self,*, sequence=None, mode="amp_hahn", freq=None, gyro=None): dataset = self.read_dataset() scale = np.around(dataset.pulse0_scale[dataset.data.argmax()].data,2) if scale > 0.9: - raise RuntimeError("Not enough power avaliable.") + raise RuntimeError("Not enough power available.") self.pulses[f"p90_{tp}"] = amp_tune.pulses[0].copy( scale=scale, freq=0) @@ -1107,4 +1106,4 @@ def set_params_by_uuid(new_seq, progTable,uuid,index): interface.bg_data.attrs['diglevel'] = dig_level interface.bg_data.attrs['nAvgs'] = iavg+1 - print("Background thread finished") \ No newline at end of file + print("Background thread finished") diff --git a/pyepr/hardware/ETH_awg_load.py b/pyepr/hardware/ETH_awg_load.py index b12fde3..ef52432 100644 --- a/pyepr/hardware/ETH_awg_load.py +++ b/pyepr/hardware/ETH_awg_load.py @@ -2,7 +2,7 @@ import scipy.signal as sig from pyepr.classes import Parameter from pyepr.dataset import create_dataset_from_axes, create_dataset_from_sequence -from pyepr.pulses import Pulse +import pyepr.pulses as pulses from scipy.integrate import cumulative_trapezoid from deerlab import correctphase from warnings import warn @@ -547,7 +547,7 @@ def uwb_eval_match(matfile, sequence=None, scans=None, mask=None,filter_pulse=No The scans to be loaded. mask : list, optional The mask to be used. - filter_pulse : ad.Pulse, optional + filter_pulse : epr.Pulse, optional The pulse to be used as a matched filter. If None, the maximum pulse width will be used. This is only used if filter_type is 'match' filter_type : str, optional The type of filter to be used. Options are 'match', 'cheby2' and 'butter. Default is 'match' @@ -856,12 +856,12 @@ def extract_data(matfile,scans): filter_func = lambda dta, det_frq: match_filter_dc(dta,t,complex_shape,det_frq) - elif isinstance(filter_pulse,Pulse): + elif isinstance(filter_pulse,pulses.Pulse): complex_shape = filter_pulse.build_shape(t) filter_func = lambda dta, det_frq: match_filter_dc(dta,t,complex_shape,det_frq) - elif (filter_type.lower() == 'cheby2') or (filter_type.lower() == 'butter'): + elif filter_type.lower() in ['cheby2','butter','boxcar']: if filter_width is None: raise ValueError('You must provide a filter width for the cheby2 or butter filter') @@ -961,7 +961,180 @@ def scipy_filter_dc(dta,t,filter_width,offset_freq,sampling_freq,filter_type='ch filter_sos = sig.cheby2(10,40,(offset_freq-filter_width,offset_freq+filter_width),fs=sampling_freq,btype="bandpass",output='sos') elif filter_type == 'butter': filter_sos = sig.butter(10,(offset_freq-filter_width,offset_freq+filter_width),fs=sampling_freq,btype="bandpass",output='sos') + elif filter_type == 'boxcar': + # A boxcar is just a moving average, so we can implement it with a convolution + boxcar_len = int(2*filter_width*sampling_freq) + if boxcar_len % 2 == 0: + boxcar_len += 1 + boxcar = np.ones(boxcar_len)/boxcar_len + filtered = sig.convolve(dta,boxcar,mode='same') + filtered_dc = digitally_upconvert(t,filtered,-offset_freq) + return filtered_dc + filtered = sig.sosfilt(filter_sos,dta) filtered_dc = digitally_upconvert(t,filtered,-offset_freq) return filtered_dc +# --------------------------------------------------------------------------- +# ETH UWB data to xarray +# --------------------------------------------------------------------------- + +def extract_data(matfile,estr): + if "dta" in matfile.keys(): + nAvgs = matfile["nAvgs"] + dta = [matfile["dta"]] + + elif "dta_001" in matfile.keys(): + dta = [] + nAvgs = 0 + for ii in range(1, estr["avgs"]+1): + actname = 'dta_%03u' % ii + if actname in matfile.keys(): + single_scan = matfile[actname] + # Only keep it if the average is complete, unless it is + # the first + if np.sum(single_scan[..., -1]) == 0 and ii > 1: # incomplete scan + if (nAvgs+1) != ii: + print(f"Scan {ii} is incomplete and will be skipped.") + continue + elif np.sum(single_scan[..., -1]) == 0 and ii == 1: + nAvgs = 0 + else: + nAvgs += 1 + dta.append(single_scan) + dta = np.array(dta) + dta = np.atleast_2d(dta) + if dta.ndim > 2: + dta = np.swapaxes(dta,-1,-2) + return dta, nAvgs + + +def get_metadata(estr,conf): + metadata = {} + metadata['averages'] = estr['avgs'] + metadata['reptime'] = estr['reptime'] + metadata['shots'] = estr['shots'] + metadata['B'] = estr['B'] + metadata['name'] = estr['name'] + metadata['freq'] = estr['LO'] + for i,event in enumerate(estr['events']): + metadata.update(get_pulse_metadata(event,i)) + metadata['dig_rate'] = conf['std']['dig_rate'] + return metadata + +def detect_pulse_type(pulse): + if 'det_len' in pulse: + return pulses.Detection + if pulse['pulsedef']['type'] == 'chirp': + if 'nu_final' in pulse['pulsedef']: + return pulses.ChirpPulse + else: + return pulses.RectPulse + +def get_pulse_metadata(pulse,i): + pulse_type = detect_pulse_type(pulse) + fixed_params = {} + if issubclass(pulse_type, pulses.Detection): + type_str="det" + else: + type_str="pulse" + + fixed_params[f"{type_str}{i}_t"] = pulse['t'] + + if issubclass(pulse_type,pulses.Detection): + fixed_params[f"{type_str}{i}_tp"] = pulse['det_len'] + else: + fixed_params[f"{type_str}{i}_tp"] = pulse['pulsedef']['tp'] + fixed_params[f"{type_str}{i}_scale"] = pulse['pulsedef']['scale'] + + if issubclass(pulse_type,pulses.Detection): + fixed_params[f"{type_str}{i}_freq"] = pulse['det_frq'] + elif issubclass(pulse_type, pulses.FrequencySweptPulse): + fixed_params[f"{type_str}{i}_init_freq"] = pulse['pulsedef']['nu_init'] + fixed_params[f"{type_str}{i}_final_freq"] = pulse['pulsedef']['nu_final'] + else: # Monochromatic pulse + fixed_params[f"{type_str}{i}_freq"] = pulse['pulsedef']['nu_init'] + return fixed_params + +def get_dig_level(data,metadata,conf): + max_val = data.max() + dig_max = conf['std']['dig_max'] + acqs = metadata['shots'] * metadata['nAvgs']* metadata['nPcyc'] + dig_pc = max_val/(dig_max*acqs) + return dig_pc + +def get_nPcyc(estr): + nPcyc = 1 + if not isinstance(estr['parvars'],list): + estr['parvars'] = [estr['parvars']] + for parvar in estr['parvars']: + if 'reduce' in parvar and parvar['reduce'] == 1: + nPcyc *= parvar['axis'].size + return nPcyc + +default_labels = ['X','Y','Z','T'] +def get_coords(parvars): + coords = {} + i=-1 + if not isinstance(parvars,list): + parvars = [parvars] + for parvar in parvars: + if 'reduce' in parvar and parvar['reduce'] == 1: + continue + i += 1 + for variable in np.atleast_1d(parvar['variables']): + if '.' in variable: + event,var = variable.split('.') + event_num = int(event.split('{')[1].split('}')[0]) + + coord_name = f"pulse{event_num}_{var}" + else: + coord_name = f"{variable}" + coord_axis = np.array(parvar['axis']).astype(float) + coords[coord_name] = (default_labels[i],coord_axis) + + return coords + +def ETHUWB_xarray_load(matfile, sum_scans=True,): + """ + This function reads data from an Andrin Doll ETH UWB EPR spectrometer + and converts it into an xarray.Dataset format compatible with PyEPR. + + Parameters + ---------- + matfile : dict + The data file to be loaded. + sum_scans : bool, optional + Whether to sum all scans or not. Default is True. + Returns + ------- + output : xarray.Dataset + The data in the xarray format. + + Notes and Limitations + --------------------------- + + - This function currently only supports experiments with reduced phase cycles. + """ + estr = matfile[matfile['expname']] + conf = matfile['conf'] + + data,nAvgs = extract_data(matfile,estr) + metadata = get_metadata(estr,conf) + metadata['nPcyc'] = get_nPcyc(estr) + metadata['nAvgs'] = nAvgs + metadata['dig_pc'] = get_dig_level(data,metadata,conf) + data_shape = data.shape # [nAvgs, ..., tx] + axes_labels = default_labels[:len(data_shape)-2] + ['tx'] + base_axes = [np.arange(data_shape[i+1]) for i in range(len(data_shape)-1)] + + if sum_scans: + data = data.sum(axis=0) + # Add scan axis label + else: + axes_labels = ['scan'] + axes_labels + base_axes = [np.arange(nAvgs)] + base_axes + dataset = create_dataset_from_axes(data,base_axes,params=metadata, + extra_coords=get_coords(estr['parvars']), + axes_labels=axes_labels) + return dataset diff --git a/pyepr/hardware/XeprAPI_link.py b/pyepr/hardware/XeprAPI_link.py index 074cafd..546c023 100644 --- a/pyepr/hardware/XeprAPI_link.py +++ b/pyepr/hardware/XeprAPI_link.py @@ -23,12 +23,25 @@ class XeprAPILink: - def __init__(self, config_file: str = None) -> None: + def __init__(self, config_file: str = None, **kwargs) -> None: + """ + This class links to the Bruker Xepr API to control the spectrometer. + Parameters + ---------- + config_file : str, optional + Path to a PyEPR spectrometer configuration file, by default None + kwargs : dict, optional + Additional keyword arguments: + - retry_attempts : int + Number of times to retry getting a Xepr parameter before + raising an exception. Default is 50. + """ self.Xepr = None self.cur_exp = None self.hidden = None self._tmp_dir = None self.XeprCmds = None + self.retry_attempts = kwargs.get('retry_attempts', 50) if config_file is not None: with open(config_file, mode='r') as file: config = yaml.safe_load(file) @@ -66,7 +79,7 @@ def connect(self) -> None: def log_xepr_version(self): """Logs the Xepr and Linacq versions for debugging purposes.""" - packages = ['xper','linacq'] + packages = ['xepr','linacq'] for package in packages: details = get_package_version_from_dnf(package) @@ -87,7 +100,7 @@ def _get_Xepr_global(self): def _xepr_retry(self, func, *args, **kwargs): - for i in range(0, 50): + for i in range(0, self.retry_attempts): try: return func(*args, **kwargs) except Exception as e: diff --git a/pyepr/hardware/dummy.py b/pyepr/hardware/dummy.py index a4bdd4f..e5cf50f 100644 --- a/pyepr/hardware/dummy.py +++ b/pyepr/hardware/dummy.py @@ -162,7 +162,7 @@ def __init__(self,config_file) -> None: self.mode = self.dummyResonator.mode - super().__init__(log=hw_log) + super().__init__(self.config,log=hw_log) def launch(self, sequence, savename: str, **kwargs): hw_log.info(f"Launching {sequence.name} sequence") diff --git a/pyepr/hardware/dummy_xepr.py b/pyepr/hardware/dummy_xepr.py index 546fa93..ae24b8f 100644 --- a/pyepr/hardware/dummy_xepr.py +++ b/pyepr/hardware/dummy_xepr.py @@ -232,7 +232,7 @@ def generate_phase_experiment(numpoints,pg,phase,phase_offset=0.2): t = range(0,numpoints) for i in t: ta,V = generate_hahn_echo_transient(pg,phase,phase_offset) - vals[i,] = np.trapz(V,x=ta) + vals[i,] = np.trapezoid(V,x=ta) return t, vals diff --git a/pyepr/pulses.py b/pyepr/pulses.py index aa641a0..e9148e5 100644 --- a/pyepr/pulses.py +++ b/pyepr/pulses.py @@ -13,9 +13,7 @@ import copy from functools import reduce from itertools import accumulate -from numba import njit -#@njit def compute_upulses_not_trajectory(dUs): n_offsets, n_steps, _, _ = dUs.shape Upulses = np.empty((n_offsets, 2, 2), dtype=np.complex128) @@ -26,7 +24,6 @@ def compute_upulses_not_trajectory(dUs): Upulses[i] = U return Upulses -#@njit def compute_upulses_trajectory(dUs): n_offsets, n_steps, _, _ = dUs.shape Upulses = np.empty((n_offsets, n_steps + 1, 2, 2), dtype=np.complex128) @@ -39,7 +36,6 @@ def compute_upulses_trajectory(dUs): Upulses[i, j + 1] = U return Upulses -#@njit def compute_magnetization_not_trajectory(Upulses, density0, Mmag): n_offsets = Upulses.shape[0] density = np.empty((n_offsets, 2, 2), dtype=np.complex128) @@ -71,7 +67,6 @@ def compute_magnetization_not_trajectory(Upulses, density0, Mmag): return Mag * Mmag[:, None] -#@njit def compute_magnetization_trajectory(Upulses, density0): n_offsets, n_steps = Upulses.shape[:2] density = np.empty((n_offsets, n_steps, 2, 2), dtype=np.complex128) @@ -329,7 +324,7 @@ def flip(self): @property def amp_factor(self): """ The B1 amplitude factor (nutation frequency) for the pulse in GHz""" - amp_factor_value= self.flipangle.value / (2 * np.pi * np.trapz(self.AM,self.ax)) + amp_factor_value= self.flipangle.value / (2 * np.pi * np.trapezoid(self.AM,self.ax)) return Parameter("amp_factor", amp_factor_value, "GHz", "Amplitude factor for the pulse") @@ -341,8 +336,7 @@ def exciteprofile_old(self, freqs=None, resonator = None): This function is ported from EasySpin (https://easyspin.org/easyspin/documentation/sop.html) [1-2], - and based upon the method from Gunnar Jeschke, Stefan Pribitzer and - Andrin Doll[3]. + and based upon the method from Gunnar Jeschke, Stefan Pribitzer and Andrin Doll[3]. References: +++++++++++ @@ -478,13 +472,27 @@ def exciteprofile(self, freqs=None, resonator=None, trajectory=False): offsets = np.linspace(-2*BW, 2*BW, 100) + c_freq else: offsets = freqs - - ISignal = np.real(self.complex) * self.amp_factor.value - QSignal = np.imag(self.complex) * self.amp_factor.value + + if self.scale is None or self.scale.value is None: + scale=None + amp_factor = self.amp_factor.value + elif (self.scale.unit is not None) and (self.scale.unit.lower() in ['ghz','mhz']): + scale = 1.0 + if self.scale.unit.lower() == 'mhz': + amp_factor = self.scale.value/1000 + else: + amp_factor = self.scale.value + elif self.scale is not None: + scale = self.scale.value + amp_factor = self.amp_factor.value + else: + scale=None + amp_factor = self.amp_factor.value if resonator is not None: + # Apply resonator correction to the pulse AM function FM = self.FM - if self.scale is None or self.scale.value is None: + if scale is None: amp_factor = np.interp(FM, resonator.freqs-resonator.freq_c, resonator.profile) amp_factor = np.min([amp_factor,np.ones_like(amp_factor)*self.amp_factor.value],axis=0) else: @@ -496,6 +504,12 @@ def exciteprofile(self, freqs=None, resonator=None, trajectory=False): ISignal = np.real(self.complex) * amp_factor QSignal = np.imag(self.complex) * amp_factor + + else: + # No resonator correction so use a constant amplitude + ISignal = np.real(self.complex) * amp_factor # In GHz + QSignal = np.imag(self.complex) * amp_factor # In GHz + t= self.ax M0=[0, 0, 1] @@ -610,7 +624,7 @@ def _pcyc_str(self): def __str__(self): # Build header line - header = "#" * 79 + "\n" + "autoDEER Pulse Definition" + \ + header = "#" * 79 + "\n" + "PyEPR Pulse Definition" + \ "\n" + "#" * 79 + "\n" # Build Overviews @@ -685,7 +699,7 @@ def __str__(self): # Build Footer footer = "#" * 79 + "\n" +\ - f"Built by autoDEER Version: {__version__}" + "\n" + "#" * 79 + f"Built by PyEPR Version: {__version__}" + "\n" + "#" * 79 # Combine All string = header + overview_params + param_table + prog_table +\ @@ -1032,8 +1046,12 @@ def __init__(self, *, tp, t=None, scale=None, flipangle=None, pcyc=[0], name=Non elif "final_freq" in kwargs: self.final_freq = Parameter("final_freq", kwargs["final_freq"], "GHz", "Final frequency of pulse") self.init_freq = Parameter("init_freq", self.final_freq.value - BW, "GHz", "Initial frequency of pulse") + elif "freq" in kwargs: + # Assumes symmetric sweep about central frequency + self.init_freq = Parameter("init_freq", kwargs["freq"] - BW/2, "GHz", "Initial frequency of pulse") + self.final_freq = Parameter("final_freq", kwargs["freq"] + BW/2, "GHz", "Final frequency of pulse") else: - raise ValueError("Bandwidth must be combined with either an initial or final frequency") + raise ValueError("Bandwidth must be combined with either an initial, final or center frequency") elif ("init_freq" in kwargs) & ("final_freq" in kwargs): self.init_freq = Parameter("init_freq", kwargs["init_freq"], "GHz", "Initial frequency of pulse") self.final_freq = Parameter("final_freq", kwargs["final_freq"], "GHz", "Final frequency of pulse") @@ -1102,7 +1120,7 @@ def func(self, ax): # beta**beta_exp2 * (ax[cut:-1]/tp)**order2) # FM = BW * cumulative_trapezoid(AM**2,ax,initial=0) /\ - # np.trapz(AM**2,ax) + self.init_freq.value + # np.trapezoid(AM**2,ax) + self.init_freq.value sech = lambda x: 1/np.cosh(x) cut = round(nx/2) AM = np.zeros_like(ti) @@ -1124,6 +1142,8 @@ def sweeprate(self): """ The sweep rate of the pulse in GHz/ns""" sweeprate_value = self.beta.value * self.bandwidth.value / (2*self.tp.value) return Parameter("sweeprate", sweeprate_value, "GHz/ns", "Sweep rate of the pulse") + + # ============================================================================= @@ -1153,6 +1173,7 @@ def func(self, ax): self.init_freq.value, self.final_freq.value, nx) return AM, FM + @property def sweeprate(self): diff --git a/pyepr/relaxation_analysis.py b/pyepr/relaxation_analysis.py index 93d0b17..fd3a2b0 100644 --- a/pyepr/relaxation_analysis.py +++ b/pyepr/relaxation_analysis.py @@ -10,7 +10,7 @@ from pyepr.colors import primary_colors # =========================================================================== - +# T2-type relaxation analysis classes class CarrPurcellAnalysis(): def __init__(self, dataset, sequence: Sequence = None) -> None: @@ -485,7 +485,9 @@ def __call__(self, x, norm=True, SNR=False, source=None): return V[0] else: return V - + +# T1-type relaxation analysis classes + class ReptimeAnalysis(): def __init__(self, dataset, sequence: Sequence = None) -> None: diff --git a/pyepr/resonator_profile_analysis.py b/pyepr/resonator_profile_analysis.py index 59eeb88..734f868 100644 --- a/pyepr/resonator_profile_analysis.py +++ b/pyepr/resonator_profile_analysis.py @@ -74,7 +74,7 @@ def __init__( - if np.iscomplexobj(dataset): + if np.iscomplexobj(dataset) and not kwargs.get('skip_phase_correction',False): self.dataset = phase_correct_respro(dataset) else: self.dataset = dataset @@ -159,7 +159,7 @@ def process_nutations( return self.prof_data, self.prof_frqs - def _process_fit(self,R_limit=0.5,mask=None,debug=False): + def _process_fit(self,R_limit=0.5,mask=None,debug=False,**kwargs): """Processes the nutation data by fitting a cosine function to each frequency in the dataset. @@ -229,6 +229,7 @@ def _process_fit(self,R_limit=0.5,mask=None,debug=False): self.profile_ci[i] = np.nan # Remove nan + old_freqs=self.freqs self.freqs = self.freqs[~np.isnan(self.profile)] self.profile = self.profile[~np.isnan(self.profile)] self.profile_ci = self.profile_ci[~np.isnan(self.profile_ci)] @@ -251,7 +252,7 @@ def _process_fit(self,R_limit=0.5,mask=None,debug=False): for i in range(n_excluded): key = int(list(excluded.keys())[i]) nutation = self.dataset[:,key] - freq = self.freqs[key].values + freq = old_freqs[key].values if np.iscomplexobj(nutation): nutation = nutation.real nutation = nutation/np.max(nutation) @@ -590,11 +591,11 @@ def calc_overlap(x, func1, func2): """ y1 = func1(x) y2 = func2(x) - area_1 = np.trapz(y1, x) - area_2 = np.trapz(y2, x) + area_1 = np.trapezoid(y1, x) + area_2 = np.trapezoid(y2, x) y1 /= area_1 y2 /= area_2 - area_12 = np.trapz(y1*y2, x) + area_12 = np.trapezoid(y1*y2, x) return area_12 def BSpline_extra(tck_s): @@ -642,3 +643,86 @@ def optimise_spectra_position(resonator_profile, fieldsweep, verbosity=0): return new_LO + +class AmplifierLinearityAnalysis: + + def __init__(self, dataset,attenuator=0) -> None: + self.dataset = dataset + self.attenuator = attenuator + + if "pulse0_scale" in self.dataset.coords: + self.scales= self.dataset.pulse0_scale + + if "pulse0_tp" in self.dataset.coords: + self.tp = self.dataset.pulse0_tp + + self._process_fit() + + + def _process_fit(self,R_limit=0.5,mask=None): + self.n_scales = self.scales.shape[0] + + self.profile = np.zeros(self.n_scales) + self.profile_ci = np.zeros(self.n_scales) + + fun = lambda x, f, tau,a,k: a*np.cos(2*np.pi*f*x)*np.exp(-x/tau)+ k + bounds = ([5e-3,10,0,-1],[0.3,2000,2,1]) + p0 = [50e-3,150,1,0] + + R2 = lambda y, yhat: 1 - np.sum((y - yhat)**2) / np.sum((y - np.mean(y))**2) + + for i in range(self.n_scales): + if mask is not None: + nutation = self.dataset[mask,i] + x = self.tp[mask] + else: + nutation = self.dataset[:,i] + x = self.tp + if np.iscomplexobj(nutation): + nutation = nutation.epr.correctphase + nutation = nutation/np.max(nutation) + + try: + results = curve_fit(fun, x, nutation, bounds=bounds,xtol=1e-4,ftol=1e-4,p0=p0) + if R2(nutation,fun(x,*results[0])) > R_limit: + self.profile[i] = results[0][0] + + self.profile_ci[i] = np.sqrt(np.diag(results[1]))[0]*1.96 + else: + self.profile[i] = np.nan + self.profile_ci[i] = np.nan + except RuntimeError: + self.profile[i] = np.nan + self.profile_ci[i] = np.nan + + # Remove nan + self.scales = self.scales[~np.isnan(self.profile)] + self.profile = self.profile[~np.isnan(self.profile)] + self.profile_ci = self.profile_ci[~np.isnan(self.profile_ci)] + + # Adjust for attenuator + self.profile = self.profile * 10**(self.attenuator/20) + self.profile_ci = self.profile_ci * 10**(self.attenuator/20) + + def fit(self,order=5): + """ 5th order polynomial fit to the profile """ + if hasattr(self, 'profile'): + self.coefficients = np.polyfit(self.scales, self.profile/self.profile.max(), order) + self.model = np.polyval(self.coefficients, self.scales) + else: + raise ValueError("Profile not calculated. Run _process_fit() first.") + + def plot(self, axs= None, fig=None): + + if axs is None and fig is None: + fig, axs = plt.subplots(1,1,constrained_layout=True,figsize=(8,8)) + + axs.plot(self.scales, self.profile*1e3, label="Profile", color=primary_colors[0], marker='o', markersize=5, linewidth=0,alpha=0.7) + + if hasattr(self, 'model'): + axs.plot(self.scales, self.model*1e3*self.profile.max(), label="Model", color=primary_colors[0], linewidth=2) + axs.text(0.05, 0.95, f"Fit Coeff: {[f'{i:.3g}' for i in self.coefficients]}", transform=axs.transAxes, fontsize=10, verticalalignment='top',bbox=dict(facecolor='white', alpha=0.5, edgecolor='black')) + + axs.legend() + axs.set_xlabel("Pulse amplitude / A.U.") + axs.set_ylabel("Nutation frequency / MHz") \ No newline at end of file diff --git a/pyepr/sequences.py b/pyepr/sequences.py index b1a9884..6899f7e 100644 --- a/pyepr/sequences.py +++ b/pyepr/sequences.py @@ -654,7 +654,7 @@ def __init__(self, *, B, freq, reptime, averages, shots, **kwargs) -> None: Parameters ---------- B : int or float - The B0 field, in Guass + The B0 field, in Gauss freq : int or float The freq frequency in GHz reptime : _type_ @@ -731,12 +731,12 @@ class T1InversionRecoverySequence(Sequence): Represents a T1 Inversion Recovery Sequence. Sequence: - [\pi - \tau - \pi/2 - \tau - echo] + [\pi - t - \pi/2 - \tau - \pi - \tau - echo] Parameters ---------- B : int or float - The B0 field, in Guass + The B0 field, in Gauss LO : int or float The LO frequency in GHz reptime : _type_ @@ -751,6 +751,8 @@ class T1InversionRecoverySequence(Sequence): The step size of the interpulse delay in ns, by default 50 ns dim : int The number of points in the X axis + tau: float + The Hahn echo interpulse delay in ns, by default 500 ns Optional Parameters ------------------- @@ -761,6 +763,62 @@ class T1InversionRecoverySequence(Sequence): An autoEPR Pulse object describing the refocusing pi pulses. If not specified a RectPulse will be created instead. """ + + def __init__(self, *, B, freq, reptime, averages, shots,start=500, step=40, dim=200, **kwargs) -> None: + name = "T1InversionRecoverySequence" + tp = kwargs.get("tp", 12) + + self.tau = Parameter(name="tau", value=500, unit="ns", description="The hahn ehco interpulse delay",virtual=True) + self.t = Parameter(name="t", value=start, step=step, dim=dim, unit="ns", description="The inversion recovery delay",virtual=True) + super().__init__(name=name,B=B, freq=freq, reptime=reptime, averages=averages, shots=shots, **kwargs) + + if "pi_pulse" in kwargs: + self.pi_pulse = kwargs["pi_pulse"] + if "pi2_pulse" in kwargs: + self.pi2_pulse = kwargs["pi2_pulse"] + if "det_event" in kwargs: + self.det_event = kwargs["det_event"] + + if hasattr(self, "pi_pulse"): + pi_pulse = self.addPulse(self.pi_pulse.copy( + t=0, pcyc={"phases":[0], "dets": [1]})) + else: + pi_pulse = self.addPulse(RectPulse( # Pump 1 pulse + t=0, tp=tp, freq=0, flipangle=np.pi + )) + + if hasattr(self, "pi2_pulse"): + self.addPulse(self.pi2_pulse.copy( + t=self.t, pcyc={"phases":[0, np.pi], "dets": [1, -1]})) + else: + self.addPulse(RectPulse( # Exc pulse + t=self.t, tp=tp, freq=0, flipangle=np.pi/2, + pcyc={"phases":[0, np.pi], "dets":[1, -1]} + )) + + if hasattr(self, "pi_pulse"): + pi_pulse = self.addPulse(self.pi_pulse.copy( + t=self.t+self.tau, pcyc={"phases":[0], "dets": [1]})) + else: + pi_pulse = self.addPulse(RectPulse( # Pump 1 pulse + t=self.t+self.tau, tp=tp, freq=0, flipangle=np.pi + )) + if hasattr(self, "det_event"): + self.addPulse(self.det_event.copy(t=self.t+2*self.tau)) + else: + self.addPulse(Detection(t=self.t+2*self.tau, tp=self.det_window.value)) + + self.evolution([self.t]) + + def simulate(self, T1=1e4): + """ + Simulates the T1 recovery as a simple exponential recovery. + """ + func = lambda x, a, T1: a*(1 - 2*np.exp(-x/T1)) + xaxis = val_in_ns(self.t) + data = func(xaxis,1,T1) + data = add_phaseshift(data, 0.05) + return xaxis, data # ============================================================================= @@ -771,7 +829,7 @@ class HahnEchoRelaxationSequence(HahnEchoSequence): Parameters ---------- B : int or float - The B0 field, in Guass + The B0 field, in Gauss freq : int or float The freq frequency in GHz reptime : _type_ @@ -822,7 +880,7 @@ class T2RelaxationSequence(HahnEchoRelaxationSequence): Parameters ---------- B : int or float - The B0 field, in Guass + The B0 field, in Gauss freq : int or float The freq frequency in GHz reptime : _type_ @@ -862,7 +920,7 @@ def __init__(self, *, B, freq, Bwidth, reptime, averages, shots, **kwargs) -> No Parameters ---------- B : int or float - The B0 field, in Guass + The B0 field, in Gauss Bwidth: int or float The width of the field sweep, in Gauss freq : int or float @@ -934,7 +992,7 @@ def __init__(self, *, B, freq, reptime, reptime_max, averages, shots, start=20, Parameters ---------- B : int or float - The B0 field, in Guass + The B0 field, in Gauss freq : int or float The freq frequency in GHz reptime: float @@ -1012,7 +1070,7 @@ def __init__(self, *, B, freq, reptime, averages, shots, Parameters ---------- B : int or float - The B0 field, in Guass + The B0 field, in Gauss freq : int or float The freq frequency in GHz reptime : _type_ @@ -1146,7 +1204,7 @@ def __init__(self, *, B, freq, reptime, averages, shots, fwidth=0.3,dtp=2, **kwa Parameters ---------- B : int or float - The B0 field, in Guass + The B0 field, in Gauss Bwidth: int or float The width of the field sweep, in Gauss freq : int or float @@ -1216,7 +1274,7 @@ def _build_sequence(self): self.freq = Parameter("freq", center_freq, start=-fwidth, step=fstep, dim=dim, unit="GHz", description="frequency") self.B = Parameter( "B",((center_freq)/self.gyro), start=-fwidth/self.gyro, step=fstep/self.gyro, dim=dim, - unit="Guass",link=self.freq,description="B0 Field" ) + unit="Gauss",link=self.freq,description="B0 Field" ) self.addPulse(RectPulse( # Hard pulse t=0, tp=tp, freq=0, flipangle="Hard" diff --git a/pyepr/tools.py b/pyepr/tools.py index 0e19fcf..01ccea3 100644 --- a/pyepr/tools.py +++ b/pyepr/tools.py @@ -2,8 +2,8 @@ import deerlab as dl import numpy as np import logging -from pyepr.dataset import create_dataset_from_bruker -from pyepr.hardware.ETH_awg_load import uwb_load, uwb_eval_match +from pyepr.dataset import create_dataset_from_bruker, downconvert_dataset +from pyepr.hardware.ETH_awg_load import uwb_load, uwb_eval_match, ETHUWB_xarray_load from scipy.io import loadmat from scipy.io.matlab import MatReadError import xarray as xr @@ -12,7 +12,7 @@ def eprload( - path: str, experiment: str = None, type: str = None, + path: str, experiment: str = None, type: str = None,downconvert=True, **kwargs): """ A general versions of eprload @@ -54,7 +54,7 @@ def eprload( type = 'TXT' elif file_extension == '.mat': - log.debug('File detecetd as Matlab') + log.debug('File detected as Matlab') type = 'MAT' else: @@ -64,10 +64,10 @@ def eprload( " set type manually \n Valid file types: '.DSC','.DTA','.h5'," "'.hdf5','.csv','.txt','.mat'") - if type == 'BRUKER': + if type.upper() == 'BRUKER': return create_dataset_from_bruker(path) - elif type == 'TXT': + elif type.upper() == 'TXT': if 'full_output' in kwargs: full_output = kwargs['full_output'] del kwargs['full_output'] @@ -76,7 +76,22 @@ def eprload( data = np.loadtxt(path, *kwargs) return data - elif type == 'MAT': + elif type.upper() == 'MAT': + try: + Matfile = loadmat(path, simplify_cells=True, squeeze_me=True) + except Exception as e: + raise MatReadError("Error opening MatFile") + + dataset = ETHUWB_xarray_load(Matfile,kwargs.get('sum_scans',True)) + + if downconvert and 'tx' in dataset.dims: + datasetDC = downconvert_dataset(dataset,**kwargs) + return datasetDC + else: + return dataset + + + elif type.upper() == 'MAT_OLD': try: Matfile = loadmat(path, simplify_cells=True, squeeze_me=True) except Exception as e: @@ -97,8 +112,14 @@ def eprload( return uwb_output - elif type == 'HDF5': - return xr.load_dataarray(path,engine='h5netcdf',invalid_netcdf=True) + elif type.upper() == 'HDF5': + dataset= xr.load_dataarray(path,engine='h5netcdf',invalid_netcdf=True) + + if downconvert and 'tx' in dataset.dims: + datasetDC = downconvert_dataset(dataset,**kwargs) + return datasetDC + else: + return dataset def progress_bar(progress, post=""): diff --git a/pyepr/utils.py b/pyepr/utils.py index 7189809..98e8d68 100644 --- a/pyepr/utils.py +++ b/pyepr/utils.py @@ -157,7 +157,7 @@ def autoEPRDecoder(dct): def gcd(values:list): - """Generates the greatest common dividor on a list of floats + """Generates the greatest common divisor on a list of floats Parameters ---------- diff --git a/pyproject.toml b/pyproject.toml index 64a0735..04aa1fd 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [tool.poetry] name = "pyEPR-ESR" -version = "1.0.2" +version = "1.1" description = "" authors = ["Hugo Karas ", "Gunnar Jeschke ", "Stefan Stoll "] readme = "README.md" @@ -9,7 +9,7 @@ packages = [ ] [tool.poetry.dependencies] -python = ">=3.11,<3.13" +python = ">=3.11" numpy = ">2.1" scipy = "^1.14.1" matplotlib = "^3.9.2" @@ -19,7 +19,6 @@ h5py = ">3.15" h5netcdf = ">1.4.0" toml = "^0.10.2" deerlab = "^1.1.4" -numba = ">=0.60.0" psutil = "^7.1.3" requests = ">=2.32" @@ -46,3 +45,4 @@ sphinx-design = "^0.6.1" [build-system] requires = ["poetry-core"] build-backend = "poetry.core.masonry.api" + diff --git a/tests/test_pulses.py b/tests/test_pulses.py new file mode 100644 index 0000000..555d196 --- /dev/null +++ b/tests/test_pulses.py @@ -0,0 +1,72 @@ +from autodeer.pulses import * +import pytest + +def test_pulse_init(): + pulse = Pulse(tp=10, scale=0.5) + assert pulse.tp.value == 10 + assert pulse.scale.value == 0.5 + +def test_pulse_add_phase_cycle(): + pulse = Pulse(tp=10, scale=0.5) + pulse._addPhaseCycle([0, 90, 180, 270]) + assert pulse.pcyc["Phases"] == [0, 90, 180, 270] + assert pulse.pcyc["DetSigns"] == [1, 1, 1, 1] + + +def test_pulse_is_static(): + pulse = Pulse(tp=10, scale=0.5) + assert pulse.is_static() + pulse = Pulse(tp=10, scale=0.5, t=0) + assert pulse.is_static() + pulse = Pulse(tp=10, scale=0.5, t=0, pcyc=None) + assert pulse.is_static() + tp = Parameter( + name="tp", value=10, unit="us", description="The pulse length", + axis=np.arange(0,10,1), axis_id=0) + pulse = Pulse(tp=tp, scale=0.5, t=0, pcyc=None) + assert pulse.is_static() + +def test_pulse_plot(): + pulse = Pulse(tp=10, scale=0.5) + pulse._buildFMAM(lambda x: (np.ones_like(x), np.zeros_like(x))) + pulse.plot() + +def test_pulse_exciteprofile(): + pulse = Pulse(tp=10, scale=0.5, flipangle=np.pi/2) + pulse.func = lambda x: (np.ones_like(x), np.zeros_like(x)) + freqs = np.linspace(-.25, .25, 1001) + Mag= pulse.exciteprofile(freqs=freqs) + assert len(Mag[:,0]) == 1001 + assert len(Mag[:,1]) == 1001 + assert len(Mag[:,2]) == 1001 + +def test_rectpulse_init(): + pulse = RectPulse(tp=10, freq=1, t=0, flipangle=np.pi/2) + assert pulse.tp.value == 10 + assert pulse.freq.value == 1 + assert pulse.t.value == 0 + assert pulse.flipangle.value == np.pi/2 + +def test_rectpulse_func(): + pulse = RectPulse(tp=10, freq=1, t=0, flipangle=np.pi/2) + AM, FM = pulse.func(np.arange(10)) + assert np.allclose(AM, np.ones(10)) + assert np.allclose(FM, np.ones(10) ) + +def test_hspulse_init(): + pulse = HSPulse(tp=10, order1=1, order2=6, beta=20, BW=1, init_freq=0) + assert pulse.tp.value == 10 + assert pulse.order1.value == 1 + assert pulse.order2.value == 6 + assert pulse.beta.value == 20 + assert pulse.BW.value == 1 + assert pulse.init_freq.value == 0 + assert pulse.final_freq.value == 1 + +def test_hspulse_func(): + pulse = HSPulse(tp=128, order1=1, order2=6, beta=20, BW=0.1, init_freq=0) + AM, FM = pulse.func(np.arange(10)) + # assert np.allclose(AM, np.ones(10)) + assert np.allclose(FM.min(), 0) + assert np.allclose(FM.max(), 0.1) + diff --git a/tests/test_respro.py b/tests/test_respro.py new file mode 100644 index 0000000..3885568 --- /dev/null +++ b/tests/test_respro.py @@ -0,0 +1,134 @@ +from autodeer.ResPro import * +from autodeer.hardware.dummy import _similate_respro +from autodeer.sequences import ResonatorProfileSequence +from autodeer.dataset import create_dataset_from_sequence, create_dataset_from_axes +from autodeer.FieldSweep import create_Nmodel, FieldSweepAnalysis +import pytest + +def test_ResonatorProfileAnalysis_from_sim(): + def lorenz_fcn(x, centre, sigma): + y = (0.5*sigma)/((x-centre)**2 + (0.5*sigma)**2) + return y + + mode = lambda x: lorenz_fcn(x, 34.0, 34.0/60) + x = np.linspace(33,35) + scale = 75/mode(x).max() + mode_fun = lambda x: lorenz_fcn(x, 34.0, 34.0/60) * scale + seq = ResonatorProfileSequence(B=12220,LO=34,reptime=3e3,averages=1,shots=50,fwidth=0.3) + + + [tp_x, LO_axis], data = _similate_respro(seq,mode_fun) + + dset = create_dataset_from_sequence(data,seq) + + respro = ResonatorProfileAnalysis(dset + ) + # respro.process_nutations(threshold=4) + respro.fit() + assert hasattr(respro,'results') + assert hasattr(respro,'fc') + assert hasattr(respro,'q') + + print(respro.fc) + assert respro.fc == pytest.approx(34,abs=0.1) + assert respro.q == pytest.approx(60,abs=2) + + fig = respro.plot() + assert fig is not None + + + +def test_ceil(): + assert ceil(3.5) == 4 + assert ceil(3.4) == 4 + assert ceil(3.0) == 3 + assert ceil(3.1) == 4 + assert ceil(3.9999999) == 4 + + assert ceil(45,decimals=1) == 45 + assert ceil(45,decimals=-1) == 50 + +def test_floor(): + assert floor(3.5) == 3 + assert floor(3.4) == 3 + assert floor(3.0) == 3 + assert floor(3.1) == 3 + assert floor(3.9999999) == 3 + + assert floor(45,decimals=1) == 45 + assert floor(45,decimals=-1) == 40 + +def test_calc_overlap(): + + def gauss(x,centre,sigma): + return np.exp(-((x-centre)/sigma)**2) + + gauss1 = lambda x: gauss(x,0,1) + gauss2 = lambda x: gauss(x,0.5,1) + + x = np.linspace(-5,5,1000) + overlap = calc_overlap(x,gauss1,gauss2) + + assert overlap == pytest.approx(0.352065) + +def test_BSpline_extra(): + + def gauss(x,centre,sigma): + return np.exp(-((x-centre)/sigma)**2) + + x = np.linspace(-5,5,1000) + y = gauss(x,0,1) + + spl = BSpline_extra((x,y,3)) + x_test = np.linspace(-10,10,100) + y_test = spl(x_test) + + assert y_test[0] == pytest.approx(0,abs=1e-3) + assert y_test[-1] == pytest.approx(0,abs=1e-3) + assert y_test[50] == pytest.approx(1,abs=1e-1) + +@pytest.fixture +def create_fake_respro(): + def lorenz_fcn(x, centre, sigma): + y = (0.5*sigma)/((x-centre)**2 + (0.5*sigma)**2) + return y + + mode = lambda x: lorenz_fcn(x, 34.0, 34.0/60) + x = np.linspace(33,35) + scale = 75/mode(x).max() + mode_fun = lambda x: lorenz_fcn(x, 34.0, 34.0/60) * scale + seq = ResonatorProfileSequence(B=12220,LO=34,reptime=3e3,averages=1,shots=50,fwidth=0.3) + + + [tp_x, LO_axis], data = _similate_respro(seq,mode_fun) + + dset = create_dataset_from_sequence(data,seq) + + respro = ResonatorProfileAnalysis( + nuts = dset.data.T, + freqs = dset.LO.data, + dt=2 + ) + respro.process_nutations(threshold=4) + respro.fit() + return respro + +@pytest.fixture +def create_fake_fieldsweep(): + B_axis = np.linspace(12000, 12400, 100) + Nmodel = create_Nmodel(34.0*1e3) + params = {"B":B_axis/1e1,"az":3.66,"axy":0.488,"gy":2.01,"gz":2.0,"GB":0.45,"scale":1, "Boffset":0.7} + V = Nmodel(**params) + dset = create_dataset_from_axes(V, B_axis,params={"LO":34.0},axes_labels=['B']) + fsweep = FieldSweepAnalysis(dset) + fsweep.calc_gyro() + fsweep.fit() + return fsweep + +def test_optimise_spectra_position(create_fake_fieldsweep,create_fake_respro): + fsweep = create_fake_fieldsweep + respro = create_fake_respro + + new_LO = optimise_spectra_position(respro,fsweep) + + assert new_LO == pytest.approx(-0.47,abs=0.1) #TODO: check this value \ No newline at end of file diff --git a/tests/test_utils.py b/tests/test_utils.py new file mode 100644 index 0000000..0f8ea99 --- /dev/null +++ b/tests/test_utils.py @@ -0,0 +1,93 @@ +import numpy as np +from pyepr import Parameter +import pytest +from pyepr.utils import * + +def test_gcd(): + assert gcd([2.0, 4.0, 6.0, 8.0]) == 2 + assert gcd([1.5, 3.0]) == 1.5 + assert gcd([3, 6, 9, 12]) == 3 + assert gcd([5, 10, 15, 20]) == 5 + assert gcd([7, 14, 21, 28]) == 7 + assert gcd([8, 12, 16, 20]) == 4 + assert gcd([10, 20, 30, 40]) == 10 + assert gcd([15, 25, 35, 45]) == 5 + assert gcd([18, 24, 30, 36]) == 6 + assert gcd([21, 28, 35, 42]) == 7 + assert gcd([27, 36, 45, 54]) == 9 + +def test_transpose_dict_of_list(): + d = {'a': [1, 2, 3], 'b': [4, 5, 6], 'c': [7, 8, 9]} + expected = [{'a': 1, 'b': 4, 'c': 7}, {'a': 2, 'b': 5, 'c': 8}, {'a': 3, 'b': 6, 'c': 9}] + assert transpose_dict_of_list(d) == expected + + d = {'a': [1, 2], 'b': [3, 4], 'c': [5, 6]} + expected = [{'a': 1, 'b': 3, 'c': 5}, {'a': 2, 'b': 4, 'c': 6}] + assert transpose_dict_of_list(d) == expected + + d = {'a': [1], 'b': [2], 'c': [3]} + expected = [{'a': 1, 'b': 2, 'c': 3}] + assert transpose_dict_of_list(d) == expected + + d = {'a': [], 'b': [], 'c': []} + expected = [] + assert transpose_dict_of_list(d) == expected + +def test_transpose_list_of_dicts(): + d = [{'a': 1, 'b': 4, 'c': 7}, {'a': 2, 'b': 5, 'c': 8}, {'a': 3, 'b': 6, 'c': 9}] + expected = {'a': [1, 2, 3], 'b': [4, 5, 6], 'c': [7, 8, 9]} + assert transpose_list_of_dicts(d) == expected + + d = [{'a': 1, 'b': 3, 'c': 5}, {'a': 2, 'b': 4, 'c': 6}] + expected = {'a': [1, 2], 'b': [3, 4], 'c': [5, 6]} + assert transpose_list_of_dicts(d) == expected + + d = [{'a': 1, 'b': 2, 'c': 3}] + expected = {'a': [1], 'b': [2], 'c': [3]} + assert transpose_list_of_dicts(d) == expected + + d = [] + expected = {} + assert transpose_list_of_dicts(d) == expected + +def test_val_in_ns(): + # Test with no axis + p = Parameter(name='p', value=10, unit="ns") + assert val_in_ns(p) == 10 + p = Parameter(name='p', value=10, unit="us") + assert val_in_ns(p) == 10000 + + # Test with one axis + p = Parameter(name='p', value=10, unit="ns", step=5, dim=1) + assert np.all(val_in_ns(p) == np.array([10])) + + p = Parameter(name='p', value=10, unit="ns", step=5, dim=3) + assert np.all(val_in_ns(p) == np.array([10,15,20])) + + # Test with two axis + p = Parameter(name='p', value=10, unit="ns", step=5, dim=2) + p.add_axis(2,axis=np.array([1,2])) + + with pytest.raises(ValueError): + val_in_ns(p) + +def test_val_in_us(): + # Test with no axis + p = Parameter(name='p', value=10, unit="ns") + assert val_in_us(p) == 0.01 + p = Parameter(name='p', value=10, unit="us") + assert val_in_us(p) == 10 + + # Test with one axis + p = Parameter(name='p', value=10, unit="us", step=5, dim=1) + assert np.all(val_in_us(p) == np.array([10])) + + p = Parameter(name='p', value=10, unit="us", step=5, dim=3) + assert np.all(val_in_us(p) == np.array([10,15,20])) + + # Test with two axis + p = Parameter(name='p', value=10, unit="us", step=5, dim=2) + p.add_axis(2,axis=np.array([1,2])) + + with pytest.raises(ValueError): + val_in_us(p) From b9688adf9ae9f58ff2427b8c6a18da52a1deb0b9 Mon Sep 17 00:00:00 2001 From: Hugo Karas Date: Wed, 27 May 2026 17:43:31 +0200 Subject: [PATCH 17/55] Update doc dependecies --- pyproject.toml | 24 ++++++++++++------------ 1 file changed, 12 insertions(+), 12 deletions(-) diff --git a/pyproject.toml b/pyproject.toml index 04aa1fd..263d133 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -29,18 +29,18 @@ pytest = "^8.3.3" [tool.poetry.group.doc.dependencies] -furo = {version = "^2024.8.6"} -autoapi = {version = "^2.0.1"} -sphinx = {version = "^8.1.3"} -sphinx-autoapi = "^3.3.3" -sphinx-toolbox = "^3.8.1" -sphinx-copybutton = "^0.5.2" -numpydoc = "^1.8.0" -sphinx-favicon = "^1.0.1" -sphinx-autobuild = "^2025.8.25" -sphinx-gallery = "^0.19.0" -myst-parser = "^4.0.1" -sphinx-design = "^0.6.1" +furo = {version = ">=2024.8.6"} +autoapi = {version = ">=2.0.1"} +sphinx = {version = ">=8.1.3"} +sphinx-autoapi = ">=3.3.3" +sphinx-toolbox = ">=3.8.1" +sphinx-copybutton = ">=0.5.2" +numpydoc = ">=1.8.0" +sphinx-favicon = ">=1.0.1" +sphinx-autobuild = ">=2025.8.25" +sphinx-gallery = ">=0.19.0" +myst-parser = ">=4.0.1" +sphinx-design = ">=0.6.1" [build-system] requires = ["poetry-core"] From ad1fc18440113c0039043bf2dbafd1fdf5511f20 Mon Sep 17 00:00:00 2001 From: Hugo Karas Date: Wed, 27 May 2026 17:47:39 +0200 Subject: [PATCH 18/55] Updated main deps --- pyproject.toml | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/pyproject.toml b/pyproject.toml index 263d133..5495370 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -9,17 +9,17 @@ packages = [ ] [tool.poetry.dependencies] -python = ">=3.11" -numpy = ">2.1" -scipy = "^1.14.1" -matplotlib = "^3.9.2" +python = ">=3.11,<4.0" +numpy = ">=2.1,<3.0" +scipy = ">=1.14.1" +matplotlib = ">=3.9.2" pyyaml = "^6.0.2" xarray = ">=2025" h5py = ">3.15" h5netcdf = ">1.4.0" -toml = "^0.10.2" -deerlab = "^1.1.4" -psutil = "^7.1.3" +toml = ">=0.10.2" +deerlab = ">=1.1.4,<2.0" +psutil = ">=7.1.3" requests = ">=2.32" From 3ec6e46bc21f6a0cc954564852e023dd2dd745d4 Mon Sep 17 00:00:00 2001 From: hkaras Date: Mon, 22 Jun 2026 10:31:42 +0200 Subject: [PATCH 19/55] PyEPR_Control docstring update --- pyepr/hardware/PyEPR_control.py | 110 ++++++++++++++++++++++++++++---- 1 file changed, 96 insertions(+), 14 deletions(-) diff --git a/pyepr/hardware/PyEPR_control.py b/pyepr/hardware/PyEPR_control.py index f7c66bc..84da6ef 100644 --- a/pyepr/hardware/PyEPR_control.py +++ b/pyepr/hardware/PyEPR_control.py @@ -53,6 +53,8 @@ def savefolder(self, folder): raise RuntimeError(response.json()['error']) def connect(self,ip='localhost',port=5000): + """Connects to the spectrometer server and configures the spectrometer if it is not already configured.""" + ## Connect to the server self.ip = ip @@ -83,13 +85,39 @@ def connect(self,ip='localhost',port=5000): self.savefolder = self.savefolder def disconnect(self): + """Disconnets the spectrometer from the components and stops the server.""" response = requests.post(self.server + '/disconnect') log.info(response.json()['message']) self.server = None return True - def acquire_dataset(self,verbosity=0,sum_scans=True, **kwargs): + def acquire_dataset(self,verbosity=0,sum_scans=True,**kwargs): + """ + Acquires the dataset from the spectrometer. + If no full scan has been completed, this will return the current buffer. Otherwise, the inclusion of the current buffer is determined by the `live` argument. + + Parameters + ---------- + verbosity : int, optional + The level of verbosity for logging, by default 0. Higher values will log more information. + sum_scans : bool, optional + Whether to sum the scans together, by default True. If False, the returned dataset will include a 'Scan' dimension with each individual scan. If True, the returned dataset will be summed over the 'Scan' dimension, returning a single averaged scan. + live : bool, optional + Whether to include the current buffer in the returned dataset, by default False. + downconvert : bool, optional + Whether to downconvert the data, by default True. + filter_type : str, optional + The type of filter to apply to the data, by default 'cheby'. Possible values are 'cheby' for a Chebyshev filter and 'boxcar' for a boxcar filter. + filter_width : int, optional + The width of the filter to apply to the data, by default 100 MHz for cheby and 250 ns for boxcar. For a Chebyshev filter, this is the width of the stopband in MHz. For a boxcar filter, this is the width of the filter in ns. + IFfreq : float, optional + The intermediate frequency to use. If None the IFfreq is extracted from the dataset, by default 0.15 + Returns + ------- + dataset : xarray.DataArray + The acquired dataset, following the standard PyEPR format. + """ if isinstance(self.cur_exp, FieldSweepSequence): kwargs['filter_type'] = kwargs.pop('filter_type', 'boxcar') kwargs['filter_width'] = kwargs.pop('filter_width', 250) @@ -127,6 +155,29 @@ def acquire_dataset(self,verbosity=0,sum_scans=True, **kwargs): raise RuntimeError("No data returned from server") def get_buffer(self,verbosity=0,sum_scans=True, **kwargs): + """ + Returns the current scan from the spectrometer buffer. + Parameters + ---------- + verbosity : int, optional + The level of verbosity for logging, by default 0. Higher values will log more information. + sum_scans : bool, optional + Whether to sum the scans together, by default True. If False, the returned dataset will include a 'Scan' dimension with each individual scan. If True, the returned dataset will be summed over the 'Scan' dimension, returning a single averaged scan. + downconvert : bool, optional + Whether to downconvert the data, by default True. + filter_type : str, optional + The type of filter to apply to the data, by default 'cheby'. Possible values are 'cheby' for a Chebyshev filter and 'boxcar' for a boxcar filter. + filter_width : int, optional + The width of the filter to apply to the data, by default 100 MHz for cheby and 250 ns for boxcar. For a Chebyshev filter, this is the width of the stopband in MHz. For a boxcar filter, this is the width of the filter in ns. + IFfreq : float, optional + The intermediate frequency to use. If None the IFfreq is extracted from the dataset, by default 0.15 + + Returns + ------- + dataset : xarray.DataArray + The acquired dataset, following the standard PyEPR format. + """ + for i in range(60): args = kwargs.copy() if 'downconvert' not in args: @@ -151,13 +202,19 @@ def get_buffer(self,verbosity=0,sum_scans=True, **kwargs): else: raise RuntimeError("No data returned from server") - def status(self): - """Returns the status of the spectrometer. + def status(self, get_errors=True): + """ + Returns the status of the spectrometer, including any errors. + + Parameters + ---------- + get_errors : bool, optional + Whether to include errors in the status, by default True Returns ------- dict - A dictionary containing the status of the spectrometer. + A dictionary containing the status of the spectrometer, including any errors if get_errors is True. """ response = requests.get(self.server + '/status') if 'error' in response.json(): @@ -188,18 +245,40 @@ def set_param(self, param: str, value: float): return True def terminate(self): + """ + Terminates the current sequence immediately and stops the AWG and digitiser processes + """ response = requests.post(self.server + '/terminate') log.debug(response.json()['message']) return True - - def status(self): - try: - response = requests.get(self.server + "/status", timeout=10) - except Exception as e: - print(f"Error updating status: {e}") - return pickle.loads(response.json()['status'].encode('latin1')) - def launch(self, sequence: Sequence , savename: str, IFgain=None, *args,**kwargs): + def stop(self): + """ + Stops the current sequence after the current scan is finished. The AWG and digitiser processes will be stopped after the current scan is finished. + """ + response = requests.post(self.server + '/stop') + log.debug(response.json()['message']) + return True + + def launch(self, sequence: Sequence , savename: str, IFgain=None, + save_scans=False, *args, **kwargs): + """ + sequence : Sequence + The sequence object to be launched. + savename : str + The name of the file to save the dataset to. The full path will be determined by the savefolder attribute of the interface and the savename argument. + mode : str, optional + The operating mode of the bridge. By default the mode is "normal". Other options are ["tune","amp_view","ampbypass","ampinput"]. + IFgain : int, float, or None, optional + If None the IFgain will be automatically determined by the interface. If an int or float, the IF gain will be set to this value. + IFfreq : float, optional + The IF frequency to be set on the AWG, by default None. If None, the IF frequency will be either automatically calculated or set to the default value in the config file. + save_scans : bool, optional + Whether to save individual scans, by default False. If True, individual scans will be saved to a temporary file and can be accessed by setting `sum_scans` to False when acquiring the dataset. If False, individual scans will not be saved and only the averaged dataset will be returned. + overwrite : bool, optional + If True, subsequent scans will overwrite the previous scans, by default False + + """ self.savefolder = self.savefolder # increase the detection length to a minimum 1024ns for pulse in sequence.pulses: @@ -255,7 +334,8 @@ def launch(self, sequence: Sequence , savename: str, IFgain=None, *args,**kwargs else: raise ValueError(f"IFgain must be of type [None, bool, int, float]. Type {type(IFgain)}_{IFgain} is not valid.") - def _launch(self, sequence: Sequence , savename: str, IFgain=0,reset_cur_exp=True,*args,**kwargs): + def _launch(self, sequence: Sequence , savename: str, + IFgain=0,reset_cur_exp=True, save_scans=False,*args,**kwargs): timestamp = datetime.datetime.now().strftime(r'%Y%m%d_%H%M_') self.savename = timestamp + savename + '.h5' @@ -272,7 +352,8 @@ def _launch(self, sequence: Sequence , savename: str, IFgain=0,reset_cur_exp=Tru launch_arg = { 'seq': sequence, 'savefile': self.savename, - 'IFgain': new_IFgain + 'IFgain': new_IFgain, + 'save_scans': save_scans } launch_arg.update(kwargs) response = requests.post(self.server + '/launch', data= pickle.dumps(launch_arg)) @@ -284,6 +365,7 @@ def _launch(self, sequence: Sequence , savename: str, IFgain=0,reset_cur_exp=Tru pass def isrunning(self) -> bool: + """Checks if the spectrometer is currently running a sequence.""" response = requests.get(self.server + '/isrunning') return response.json()['isrunning'] From d0da52ecf9c05f4aa12987dd6b7cd83cbf40151d Mon Sep 17 00:00:00 2001 From: Hugo Karas Date: Tue, 14 Jul 2026 12:01:33 +0200 Subject: [PATCH 20/55] Resonator fit moved to sqrt-lorentzian -Removed support for multiple modes --- pyepr/resonator_profile_analysis.py | 175 +++++----------------------- tests/test_respro.py | 12 +- 2 files changed, 34 insertions(+), 153 deletions(-) diff --git a/pyepr/resonator_profile_analysis.py b/pyepr/resonator_profile_analysis.py index 734f868..084d128 100644 --- a/pyepr/resonator_profile_analysis.py +++ b/pyepr/resonator_profile_analysis.py @@ -268,7 +268,7 @@ def _process_fit(self,R_limit=0.5,mask=None,debug=False,**kwargs): - def fit(self,f_diff_threshold=2,cores=1,multi_mode=False,fc_guess=None): + def fit(self,model='lorenz_sqrt',f_diff_threshold=2,cores=1,fc_guess=None,**kwargs): """Fit the resonator profile with a sum of lorentzians. Parameters @@ -288,32 +288,13 @@ def fit_gauss1(): result_gauss1 = dl.fit(gauss_model, self.profile, self.freqs,reg=False) return result_gauss1 - - def fit_gauss2(): - gauss_model = dl.dd_gauss2 - gauss_model.mean1.set(par0=34.05, **frq_limits) - gauss_model.std1.set(par0=0.2, lb=0.01, ub=10) - gauss_model.mean2.set(par0=34.05, **frq_limits) - gauss_model.std2.set(par0=0.3, lb=0.01, ub=10) - - result_gauss2 = dl.fit(gauss_model, self.profile, self.freqs,reg=False) - return result_gauss2 - - def fit_gauss3(): - gauss_model = dl.dd_gauss3 - gauss_model.mean1.set(par0=34.05, **frq_limits) - gauss_model.std1.set(par0=0.2, lb=0.01, ub=10) - gauss_model.mean2.set(par0=34.05, **frq_limits) - gauss_model.std2.set(par0=0.3, lb=0.01, ub=10) - gauss_model.mean3.set(par0=34.05, **frq_limits) - gauss_model.std3.set(par0=0.3, lb=0.01, ub=10) - - result_gauss3 = dl.fit(gauss_model, self.profile, self.freqs,reg=False) - return result_gauss3 - + def lorenz_fcn(x, fc, q): y = (0.5*fc)/(q*(x-fc)**2 + q*(0.5*(fc/q))**2) return y + def lorenz_fcn_sqrt(x, fc, q): + y = np.sqrt((0.5*fc)/(q*(x-fc)**2 + q*(0.5*(fc/q))**2)) + return y def fit_lorenz1(uni_means,uni_stds,fit_kwargs): lorenz = dl.Model(lorenz_fcn, constants='x') @@ -324,141 +305,39 @@ def fit_lorenz1(uni_means,uni_stds,fit_kwargs): lorenz.fc.set(par0=uni_means[0],lb=uni_means[0]-0.1,ub=uni_means[0]+0.1) result_lorenz1 = dl.fit(lorenz, self.profile, self.freqs,reg=False, **fit_kwargs) return result_lorenz1, lorenz_fcn, lorenz - - def fit_lorenz2(uni_means,uni_stds,uni_amps,fit_kwargs): - def lorenz2_fcn(x, fc1, q1, fc2, q2, amp1, amp2): - return lorenz_fcn(x, fc1, q1)*amp1 + lorenz_fcn(x, fc2, q2)*amp2 - - lorenz2 = dl.Model(lorenz2_fcn,constants='x') - lorenz2.fc1.par0 = uni_means[0] - lorenz2.fc1.set(**frq_limits) - lorenz2.q1.set(lb=0, ub=np.inf) - lorenz2.q1.par0 = uni_means[0]/uni_stds[0] - lorenz2.fc2.par0 = uni_means[1] - lorenz2.fc2.set(**frq_limits) - lorenz2.q2.set(lb=0, ub=np.inf) - lorenz2.q2.par0 = uni_means[1]/uni_stds[1] - lorenz2.amp1.set(lb=0, ub=np.inf, par0=uni_amps[0]) - lorenz2.amp2.set(lb=0, ub=np.inf, par0=uni_amps[1]) - result_lorenz2 = dl.fit(lorenz2, self.profile, self.freqs,reg=False, **fit_kwargs) - return result_lorenz2, lorenz2_fcn, lorenz2 - - def fit_lorenz3(uni_means,uni_stds,uni_amps,fit_kwargs): - def lorenz3_fcn(x, fc1, q1, fc2, q2, fc3, q3, amp1, amp2, amp3): - return lorenz_fcn(x, fc1, q1)*amp1 + lorenz_fcn(x, fc2, q2)*amp2 + lorenz_fcn(x, fc3, q3)*amp3 - lorenz3 = dl.Model(lorenz3_fcn,constants='x') - lorenz3.fc1.par0 = uni_means[0] - lorenz3.fc1.set(**frq_limits) - lorenz3.q1.set(lb=0, ub=np.inf) - lorenz3.q1.par0 = uni_means[0]/uni_stds[0] - lorenz3.fc2.par0 = uni_means[1] - lorenz3.fc2.set(**frq_limits) - lorenz3.q2.set(lb=0, ub=np.inf) - lorenz3.q2.par0 = uni_means[1]/uni_stds[1] - lorenz3.fc3.par0 = uni_means[2] - lorenz3.fc3.set(**frq_limits) - lorenz3.q3.set(lb=0, ub=np.inf) - lorenz3.q3.par0 = uni_means[2]/uni_stds[2] - lorenz3.amp1.set(lb=0, ub=np.inf, par0= uni_amps[0]) - lorenz3.amp2.set(lb=0, ub=np.inf, par0=uni_amps[1]) - lorenz3.amp3.set(lb=0, ub=np.inf, par0=uni_amps[2]) - - result_lorenz3 = dl.fit(lorenz3, self.profile, self.freqs,reg=False, **fit_kwargs) - return result_lorenz3, lorenz3_fcn, lorenz3 - - if multi_mode: - gs = [fit_gauss1(),fit_gauss2(),fit_gauss3()] - n_modes = np.argmin([g.stats['chi2red'] for g in gs]) + 1 - print(f"chi: {[g.stats['chi2red'] for g in gs]}") - print(f"aic: {[g.stats['aicc'] for g in gs]}") - n_modes=1 - best_fit = gs[n_modes-1] - best_fit = gs[n_modes-1] - # Find mean values which have an amplitude above 0.1 and are at least 0.1 apart - # This is to avoid double counting - if n_modes > 1: - amps = np.array([getattr(best_fit,'amp'+str(i+1)) for i in range(n_modes)]) - means = np.array([getattr(best_fit,'mean'+str(i+1)) for i in range(n_modes)]) - stds = np.array([getattr(best_fit,'std'+str(i+1)) for i in range(n_modes)]) - else: - amps = np.array([1]) - means = np.array([best_fit.mean]) - stds = np.array([best_fit.std]) - - def find_unique(means,amps,stds, threshold=0.05): - f1,f2 = np.meshgrid(means,means) - gap = f1-f2 - gap[np.tril_indices(gap.shape[0],-1)] =np.nan - connected = gap 0: - i=idx[0] - new_means.append(np.mean(means[connected[i,:]])) - new_amps.append(np.sum(amps[connected[i,:]])) - new_stds.append(np.mean(stds[connected[i,:]])) - connected[connected[i,:],:] = False - connected[:,connected[i,:]] = False - idx = calc_conn(connected) - connections = sum_con(connected) - - return np.array(new_means),np.array(new_amps),np.array(new_stds) - - - # uni_means, uni_means_idx, uni_means_inverse = np.unique(np.around(means,decimals=f_diff_threshold),return_index=True,return_inverse=True) - # uni_amps = np.array([np.sum(amps[uni_means_inverse == i]) for i in np.unique(uni_means_inverse)]) - # uni_stds = np.array([np.mean(stds[uni_means_inverse == i]) for i in np.unique(uni_means_inverse)]) - uni_means,uni_amps,uni_stds = find_unique(means,amps,stds,0.1) - - amp_threshold = 0.01 - uni_means = uni_means[uni_amps > amp_threshold] - uni_stds = uni_stds[uni_amps > amp_threshold] - uni_amps = uni_amps[uni_amps > amp_threshold] - - # Remove modes which are outside the frequency range +- 0.5GHz - uni_means = uni_means[(uni_means > self.f_lims[0]-0.5) & (uni_means < self.f_lims[1]+0.5)] - uni_stds = uni_stds[(uni_means > self.f_lims[0]-0.5) & (uni_means < self.f_lims[1]+0.5)] - uni_amps = uni_amps[(uni_means > self.f_lims[0]-0.5) & (uni_means < self.f_lims[1]+0.5)] - - n_modes = uni_means.shape[0] - - print("Number of modes detected: ", n_modes) - - else: - gs = fit_gauss1() - uni_means = [gs.mean] - uni_stds = [gs.std] - n_modes = 1 + + def fit_lorenz1_sqrt(uni_means,uni_stds,fit_kwargs): + lorenz_sqrt = dl.Model(lorenz_fcn_sqrt, constants='x') + lorenz_sqrt.fc.par0 = uni_means[0] + lorenz_sqrt.fc.set(**frq_limits) + lorenz_sqrt.q.set(lb=30, ub=np.inf) + lorenz_sqrt.q.par0 = uni_means[0]/uni_stds[0] + result_lorenz1_sqrt = dl.fit(lorenz_sqrt, self.profile, self.freqs,reg=False, **fit_kwargs) + return result_lorenz1_sqrt, lorenz_fcn_sqrt, lorenz_sqrt + + # First fit with a gaussian to get starting values + gs = fit_gauss1() + uni_means = [gs.mean] + uni_stds = [gs.std] + n_modes = 1 self.model_x = np.linspace(self.f_lims[0], self.f_lims[1], 200) fit_kwargs = {'bootstrap': 30, 'bootcores':cores} + fit_kwargs.update(kwargs) # fit_kwargs={} - if n_modes == 1: + if model=='lorenz': lorenz_fit,fun,mod = fit_lorenz1(uni_means,uni_stds,fit_kwargs) self.model_func = lambda x: lorenz_fit.scale * lorenz_fcn(x, lorenz_fit.fc, lorenz_fit.q) self.fc = lorenz_fit.fc self.q = lorenz_fit.q + elif model=='lorenz_sqrt': + lorenz_fit,fun,mod = fit_lorenz1_sqrt(uni_means,uni_stds,fit_kwargs) + self.model_func = lambda x: lorenz_fit.scale * lorenz_fcn_sqrt(x, lorenz_fit.fc, lorenz_fit.q) + self.fc = lorenz_fit.fc + self.q = lorenz_fit.q - elif n_modes == 2: - lorenz_fit,fun,mod = fit_lorenz2(uni_means,uni_stds,uni_amps,fit_kwargs) - self.model_func = lambda x: lorenz_fit.scale * fun(x, lorenz_fit.fc1, lorenz_fit.q1, lorenz_fit.fc2, lorenz_fit.q2, lorenz_fit.amp1, lorenz_fit.amp2) - self.fc = np.array([lorenz_fit.fc1,lorenz_fit.fc2]) - self.q = np.array([lorenz_fit.q1,lorenz_fit.q2]) - - elif n_modes == 3: - lorenz_fit,fun,mod = fit_lorenz3(uni_means,uni_stds,uni_amps,fit_kwargs) - self.model_func = lambda x: lorenz_fit.scale * fun(x, lorenz_fit.fc1, lorenz_fit.q1, lorenz_fit.fc2, lorenz_fit.q2, lorenz_fit.fc3, lorenz_fit.q3, lorenz_fit.amp1, lorenz_fit.amp2, lorenz_fit.amp3) - self.fc = np.array([lorenz_fit.fc1,lorenz_fit.fc2,lorenz_fit.fc3]) - self.q = np.array([lorenz_fit.q1,lorenz_fit.q2,lorenz_fit.q3]) - else: - raise RuntimeError('Between 1 and 3 mode must be deteceted') self.model = self.model_func(self.model_x) self.lorenz_model = mod diff --git a/tests/test_respro.py b/tests/test_respro.py index 3885568..2fe0992 100644 --- a/tests/test_respro.py +++ b/tests/test_respro.py @@ -1,9 +1,11 @@ -from autodeer.ResPro import * -from autodeer.hardware.dummy import _similate_respro -from autodeer.sequences import ResonatorProfileSequence -from autodeer.dataset import create_dataset_from_sequence, create_dataset_from_axes -from autodeer.FieldSweep import create_Nmodel, FieldSweepAnalysis +from pyepr.ResPro import * +from pyepr.hardware.dummy import _similate_respro +from pyepr.sequences import ResonatorProfileSequence +from pyepr.dataset import create_dataset_from_sequence, create_dataset_from_axes +from pyepr.FieldSweep import create_Nmodel, FieldSweepAnalysis import pytest +import numpy as np +from pyepr import ResonatorProfileAnalysis def test_ResonatorProfileAnalysis_from_sim(): def lorenz_fcn(x, centre, sigma): From f2d48350dc2f0d5c07755057fb0f0ac195f2a323 Mon Sep 17 00:00:00 2001 From: Hugo Karas Date: Tue, 14 Jul 2026 15:42:21 +0200 Subject: [PATCH 21/55] Lots of doc updates --- docsrc/API_docs.rst | 5 +- docsrc/conf.py | 7 +- pyepr/pulses.py | 490 ++++++++++++++++++++++++-------------------- pyepr/sequences.py | 41 ++-- 4 files changed, 302 insertions(+), 241 deletions(-) diff --git a/docsrc/API_docs.rst b/docsrc/API_docs.rst index c6c4340..5e13ce5 100644 --- a/docsrc/API_docs.rst +++ b/docsrc/API_docs.rst @@ -35,8 +35,8 @@ Sequences pyepr.sequences.ReptimeScan pyepr.sequences.CarrPurcellSequence pyepr.sequences.ResonatorProfileSequence - pyepr.sequences.TWTProfileSequence pyepr.sequences.T1InversionRecoverySequence + pyepr.sequences.TWTProfileSequence Pulses ~~~~~~ @@ -48,9 +48,10 @@ Pulses pyepr.pulses.Detection pyepr.pulses.RectPulse pyepr.pulses.GaussianPulse - pyepr.pulses.HSPulse pyepr.pulses.ChirpPulse + pyepr.pulses.HSPulse pyepr.pulses.SincPulse + pyepr.pulses.WURSTPulse Termination Criteria ~~~~~~~~~~~~~~~~~~~~ diff --git a/docsrc/conf.py b/docsrc/conf.py index 5524a89..71708b5 100644 --- a/docsrc/conf.py +++ b/docsrc/conf.py @@ -55,7 +55,12 @@ autoapi_python_class_content= "both" autoapi_python_use_implicit_namespaces = True autoapi_own_page_level = 'class' - +autoapi_options = ['members', + 'undoc-members', + 'show-inheritance', + 'show-module-summary', + 'imported-members', + 'inherited-members'] sphinx_gallery_conf = { 'examples_dirs': 'examples', # path to your example scripts 'gallery_dirs': 'auto_examples', # path to where to save gallery generated output diff --git a/pyepr/pulses.py b/pyepr/pulses.py index e9148e5..bfb9f63 100644 --- a/pyepr/pulses.py +++ b/pyepr/pulses.py @@ -89,7 +89,7 @@ class Pulse: Represents a general experimental pulse. """ - def __init__(self, *, tp, t=None, scale=None, flipangle=None, pcyc=[0], + def __init__(self, *, tp, t=None, scale=None, flipangle=None, pcyc=None, name=None, **kwargs) -> None: """The class for a general pulse. @@ -101,6 +101,12 @@ def __init__(self, *, tp, t=None, scale=None, flipangle=None, pcyc=[0], The arbitary experimental pulse amplitude, 0-1. t : float, optional The pulse start time in ns. + flipangle : float, optional + The target flip angle of the pulse in radians, defaults to None. + name : str, optional + The name of the pulse, defaults to None. + pcyc : list, optional + The phase cycle of the pulse given as a diction with keys "Phases" and "DetSigns", defaults to None. """ if t is not None: @@ -125,7 +131,6 @@ def __init__(self, *, tp, t=None, scale=None, flipangle=None, pcyc=[0], self.name = name - self.Progression = False if flipangle is not None: self.flipangle = Parameter( @@ -133,8 +138,10 @@ def __init__(self, *, tp, t=None, scale=None, flipangle=None, pcyc=[0], "The target flip angle of the spins") if pcyc is None: self.pcyc = None - elif type(pcyc) is dict: + elif type(pcyc) is dict and ("phases" in pcyc) and ("dets" in pcyc): self._addPhaseCycle(pcyc["phases"], detections=pcyc["dets"]) + elif type(pcyc) is dict and ("Phases" in pcyc) and ("DetSigns" in pcyc): + self._addPhaseCycle(pcyc["Phases"], detections=pcyc["DetSigns"]) else: self._addPhaseCycle(pcyc, detections=None) pass @@ -165,6 +172,13 @@ def _addPhaseCycle(self, phases, detections=None): detections = np.ones(len(phases)) self.pcyc = {"Phases": list(phases), "DetSigns": list(detections)} pass + + def removePhaseCycle(self): + """ + Clears the attached phase cycle. + """ + self.pcyc = None + pass def _buildFMAM(self, func, ax=None): """ @@ -247,65 +261,64 @@ def build_table(self): def is_static(self): - """ - Check if all parameters in the pulse object are static. - - Returns: - bool: True if all parameters are static, False otherwise. - """ - for arg in vars(self): - attr = getattr(self,arg) - if type(attr) is Parameter and not attr.is_static(): - return False - return True - - def isDelayFocused(self): - """ - Does the pulse contain a specified time, `t`? - - If so then it is not delay focused. - """ - if self.t is None: - return True - else: - return False - - def isPulseFocused(self): """ - Does the pulse contain a specified time, `t`? + Check if all parameters in the pulse object are static. - If so then it is delay focused. + Returns: + bool: True if all parameters are static, False otherwise. """ - if self.t is not None: - return True - else: - return False + for arg in vars(self): + attr = getattr(self,arg) + if type(attr) is Parameter and not attr.is_static(): + return False + return True - def plot(self, pad=1000): - """Plots the time domain representation of this pulse. + def plot(self, pad=1000, freqs=None): + """Plots the time domain representation of this pulse alongside its + Mz inversion profile. Parameters ---------- pad : int, optional The number of zeros to pad the data with, by default 1000 + freqs : np.ndarray, optional + The frequency axis to calculate the Mz inversion profile over. + If not given, a default range is calculated by `exciteprofile`. """ dt = self.ax[1] - self.ax[0] - if self.isPulseFocused(): - tax = self.t.value + self.ax - else: - tax = self.ax + tax = self.ax fwd_ex = np.linspace(tax[0] - dt * pad, tax[0], pad) rev_ex = np.linspace( tax[-1] + dt, tax[-1] + dt * pad, pad, endpoint=True) tax = np.concatenate((fwd_ex, tax, rev_ex)) data = np.pad(self.complex, pad) - plt.plot(tax, np.real(data), label="Re") - plt.plot(tax, np.imag(data), label="Im") - plt.legend() - plt.xlabel("Time (ns)") - plt.ylabel("Amplitude (A.U.)") - pass + fig, axs = plt.subplots(1, 2, figsize=(10, 4), layout='constrained') + + axs[0].plot(tax, np.real(data), label="Re") + axs[0].plot(tax, np.imag(data), label="Im") + axs[0].legend() + axs[0].set_xlabel("Time (ns)") + axs[0].set_ylabel("Amplitude (A.U.)") + + if freqs is None: + + if hasattr(self, "init_freq") and hasattr(self, "final_freq"): + freqs = np.linspace(self.init_freq.value - 0.2, self.final_freq.value + 0.2, 150) + else: + fxs, fs = self._calc_fft() + fs = np.abs(fs) + points = np.argwhere(fs > (fs.max() * 0.5))[:, 0] + BW = fxs[points[-1]] - fxs[points[0]] + c_freq = np.mean([fxs[points[-1]], fxs[points[0]]]) + freqs = np.linspace(-2 * BW, 2 * BW, 100) + c_freq + + Mag = self.exciteprofile(freqs=freqs) + axs[1].plot(freqs, Mag[:, 2]) + axs[1].set_xlabel("Frequency (GHz)") + axs[1].set_ylabel("Mz magnetisation") + + return fig def _calc_fft(self, pad=10000): self._buildFMAM(self.func) @@ -326,127 +339,17 @@ def amp_factor(self): """ The B1 amplitude factor (nutation frequency) for the pulse in GHz""" amp_factor_value= self.flipangle.value / (2 * np.pi * np.trapezoid(self.AM,self.ax)) return Parameter("amp_factor", amp_factor_value, "GHz", "Amplitude factor for the pulse") - - - # @cached(thread_safe=False) - def exciteprofile_old(self, freqs=None, resonator = None): - """Excitation profile - - Generates the exciatation profiles for this pulse. - - This function is ported from EasySpin - (https://easyspin.org/easyspin/documentation/sop.html) [1-2], - and based upon the method from Gunnar Jeschke, Stefan Pribitzer and Andrin Doll[3]. - - References: - +++++++++++ - [1] Stefan Stoll, Arthur Schweiger - EasySpin, a comprehensive software package for spectral simulation and analysis in EPR - J. Magn. Reson. 178(1), 42-55 (2006) - - [2] Stefan Stoll, R. David Britt - General and efficient simulation of pulse EPR spectra - Phys. Chem. Chem. Phys. 11, 6614-6625 (2009) - - [3] Jeschke, G., Pribitzer, S. & DollA. - Coherence Transfer by Passage Pulses in Electron Paramagnetic - Resonance Spectroscopy. - J. Phys. Chem. B 119, 13570-13582 (2015) - - - Parameters - ---------- - - freqs: np.ndarray, optional - The frequency axis. Caution: A larger number of points will linearly - increase computation time. - resonator: ad.ResonatorProfile, optional - - - Returns - ------- - - Mx: np.ndarray - The magentisation in the X direction. - My: np.ndarray - The magentisation in the Y direction. - Mz: np.ndarray - The magentisation in the Z direction. - """ - eye = np.identity(2) - # offsets = np.arange(-2*BW,2*BW,0.002) - - self._buildFMAM(self.func) - - if freqs is None: - fxs, fs = self._calc_fft() - fs = np.abs(fs) - points = np.argwhere(fs>(fs.max()*0.5))[:,0] - BW = fxs[points[-1]] - fxs[points[0]] - c_freq = np.mean([fxs[points[-1]], fxs[points[0]]]) - offsets = np.linspace(-2*BW, 2*BW, 100) + c_freq - else: - offsets = freqs - - offsets - t = self.ax - nOffsets = offsets.shape[0] - - ISignal = np.real(self.complex) * self.amp_factor.value - QSignal = np.imag(self.complex) * self.amp_factor.value - - if resonator is not None: - FM = self.FM - amp_factor = np.interp(FM, resonator.freqs-resonator.freq_c, resonator.profile) - amp_factor = np.min([amp_factor,np.ones_like(amp_factor)*self.amp_factor.value],axis=0) - ISignal = np.real(self.complex) * amp_factor - QSignal = np.imag(self.complex) * amp_factor - - npoints = ISignal.shape[0] - Sx = sop([1/2],"x") - Sy = sop([1/2],"y") - Sz = sop([1/2],"z") - Density0 = -Sz - Mag = np.zeros((3,nOffsets), dtype=np.complex128) - for iOffset in range(0,nOffsets): - UPulse = eye - Ham0 = offsets[iOffset]*Sz - - for it in range(0,npoints): - Ham = ISignal[it] * Sx + QSignal[it] * Sy + Ham0 - M = -2j * np.pi * (t[1]-t[0]) * Ham - q = np.sqrt(M[0,0] ** 2 - np.abs(M[0,1]) ** 2) - if np.abs(q) < 1e-10: - dU = eye + M - else: - dU = np.cosh(q)*eye + (np.sinh(q)/q)*M - UPulse = dU @ UPulse - - Density = UPulse @ Density0 @ UPulse.conjugate().T - Mag[0, iOffset] = -2 * (Sx @ Density.T).sum().real - Mag[1, iOffset] = -2 * (Sy @ Density.T).sum().real - Mag[2, iOffset] = -2 * (Sz * Density.T).sum().real - - return Mag[0,:], Mag[1,:], Mag[2,:] - + # @cached(thread_safe=False) def exciteprofile(self, freqs=None, resonator=None, trajectory=False): """Excitation profile Generates the exciatation profiles for this pulse, using the two-level system model developed by Jeschke et al. [1]. - And then optimised in the PulseShape software package by Maxx Tessmer [2], reproduced under the GNU GPL v3 license. - - References: - +++++++++++ - [1] Jeschke, G., Pribitzer, S. & Doll, A. - Coherence Transfer by Passage Pulses in Electron Paramagnetic - Resonance Spectroscopy. - J. Phys. Chem. B 119, 13570-13582 (2015) - [2] https://github.com/mtessmer/PulseShape + And then optimised in the PulseShape software package by Maxx Tessmer, reproduced under the GNU GPL v3 license [2]. Parameters ---------- - + freqs: np.ndarray, optional The frequency axis. Caution: A larger number of points will linearly increase computation time. @@ -454,12 +357,20 @@ def exciteprofile(self, freqs=None, resonator=None, trajectory=False): The resonator profile to apply resonator compensation. trajectory: bool, optional If True, the function will return the magnetisation at each time point. Default is False. - + Returns ------- Mag: np.ndarray The magnetisation in the X, Y, and Z directions. - + + References + ---------- + [1] Jeschke, G., Pribitzer, S. & Doll, A. + Coherence Transfer by Passage Pulses in Electron Paramagnetic + Resonance Spectroscopy. + J. Phys. Chem. B 119, 13570-13582 (2015) + + [2] https://github.com/mtessmer/PulseShape """ self._buildFMAM(self.func) @@ -575,18 +486,6 @@ def exciteprofile(self, freqs=None, resonator=None, trajectory=False): return Mag - - def plot_fft(self): - - ax, ft = self._calc_fft(1e4) - plt.plot(ax, np.real(ft), label="Re") - plt.plot(ax, np.imag(ft), label="Im") - plt.plot(ax, np.abs(ft), label="Im") - plt.legend() - plt.xlabel("Frequency (GHz)") - plt.ylabel("Amplitude (A.U.)") - pass - def _pcyc_str(self): if self.pcyc is not None: @@ -627,30 +526,16 @@ def __str__(self): header = "#" * 79 + "\n" + "PyEPR Pulse Definition" + \ "\n" + "#" * 79 + "\n" - # Build Overviews - if self.isPulseFocused(): - overview_params = "Time Pos (ns) \tLength (ns) \tScale (0-1)" +\ - "\t Static \n" - - if type(self) is Detection: - overview_params += f"{self.t.value}" + "\t\t" + \ - f"{self.tp.value}" + "\t\t" + "\t\t" +\ - f"{self.is_static()}" + "\n" + "#" * 79 + "\n" - else: - overview_params += f"{self.t.value}" + "\t\t" + \ - f"{self.tp.value}" + "\t\t" + f"{self.scale.value}" + \ - "\t\t" + f"{self.is_static()}" + "\n" + "#" * 79 + "\n" - elif self.isDelayFocused(): - overview_params = "Length (ns) \tScale (0-1)" +\ - "\t Static \n" - - if type(self) is Detection: - overview_params += f"{self.tp.value}" + "\t\t" + "\t\t" +\ - f"{self.is_static()}" + "\n" + "#" * 79 + "\n" - else: - overview_params += f"{self.tp.value}" + "\t\t" +\ - f"{self.scale.value}" + "\t\t" + f"{self.is_static()}" +\ - "\n" + "#" * 79 + "\n" + overview_params = "Length (ns) \t Scale (0-1)" +\ + "\t Static \n" + + if type(self) is Detection: + overview_params += f"{self.tp.value}" + "\t\t" + "\t\t" +\ + f"{self.is_static()}" + "\n" + "#" * 79 + "\n" + else: + overview_params += f"{self.tp.value}" + "\t\t" +\ + f"{self.scale.value}" + "\t\t" + f"{self.is_static()}" +\ + "\n" + "#" * 79 + "\n" # Build Pulse Parameter Table param_table = f"{'Name':^12} \t {'Value':^12} \t {'Unit':^7} \t Description\n" @@ -679,15 +564,7 @@ def __str__(self): param_table += f"{attr.name:>12} \t {value:>12} \t" +\ f"{attr.unit:>7} \t {attr.description} \n" - # Build Pulse Progression Table - if self.Progression is True: - prog_table = "#" * 79 + "\n" + "Progressive Variables:" + "\n" - prog_table += "Variable \t Axis \t Length \n" - prog_table += "-------- \t ---- \t ------ \n" - prog_table += f"{self.Prog_var} \t\t {self.Prog_axis} \t" +\ - f"{self.Prog_n} \n" - else: - prog_table = "" + prog_table = "" # Build Pulse Phase Cycle Table if self.pcyc is not None: @@ -960,6 +837,19 @@ def __init__( Time position in ns, by default None flipangle : _type_, optional The flip angle in radians, by default None + + Examples + -------- + + .. plot:: + :include-source: + + import pyepr as epr + import matplotlib.pyplot as plt + + pulse = epr.RectPulse(tp=32, flipangle=np.pi) + pulse.plot(pad=50) + """ Pulse.__init__( self, tp=tp, t=t, flipangle=flipangle,name='RectPulse', **kwargs) @@ -1002,10 +892,11 @@ def __init__(self, *, tp=32,FWHM=None, freq=0, **kwargs) -> None: import pyepr as epr import matplotlib.pyplot as plt - GuassPulse = epr.GaussianPulse(tp=32) - GuassPulse.plot(pad=0) - plt.annotate('', xy=(-GuassPulse.FWHM.value/2, 0.5), xytext=(GuassPulse.FWHM.value/2, 0.5), color='C1',arrowprops=dict(arrowstyle='<|-|>', color='C1',lw=2)) - plt.annotate('FWHM', xy=(0, 0.51), xytext=(0, 0.51), color='C1', ha='center', fontsize=12) + GuassPulse = epr.GaussianPulse(tp=32, flipangle=np.pi) + fig = GuassPulse.plot(pad=50) + axs = fig.get_axes() + axs[0].annotate('', xy=(-GuassPulse.FWHM.value/2, 0.5), xytext=(GuassPulse.FWHM.value/2, 0.5), color='C1',arrowprops=dict(arrowstyle='<|-|>', color='C1',lw=2)) + axs[0].annotate('FWHM', xy=(0, 0.51), xytext=(0, 0.51), color='C1', ha='center', fontsize=12) """ Pulse.__init__(self, tp=tp,name='GaussianPulse', **kwargs) self.freq = Parameter("Freq", freq, "GHz", "Frequency of the Pulse") @@ -1027,12 +918,29 @@ def func(self, ax): def plot(self, pad=1000): return super().plot(pad) # ============================================================================= -class FrequencySweptPulse(Pulse): - """ - A general parent class for Frequency Swept Pulses. - """ - +class FrequencySweptPulse(Pulse): def __init__(self, *, tp, t=None, scale=None, flipangle=None, pcyc=[0], name=None, **kwargs) -> None: + + """ + Parameters + ---------- + tp : float + Pulse length in ns + t : float, optional + The time position of the pulse, by default None + init_freq : float, optional + The initial frequency of the pulse in GHz, by default None. Either the initial and final frequency or the bandwidth and central frequency must be specified. + final_freq : float, optional + The final frequency of the pulse in GHz, by default None. Either the initial and final frequency or the bandwidth and central frequency must be specified. + BW : float, optional + The bandwidth of the pulse in GHz, by default None. Either the initial and final frequency or the bandwidth and central frequency must be specified. + freq : float, optional + The central frequency of the pulse in GHz, by default None. Either the initial and final frequency or the bandwidth and central frequency must be specified. + scale : float, optional + The scale of the pulse, by default None + flipangle : float, optional + The flip angle of the pulse in radians, by default None + """ super().__init__(tp=tp, t=t, scale=scale, flipangle=flipangle, pcyc=pcyc, name=name, **kwargs) @@ -1087,10 +995,67 @@ def flip(self): class HSPulse(FrequencySweptPulse): - """ - Represents a hyperboilc secant frequency-swept pulse. - """ def __init__(self, *, tp=128, order1=1, order2=6, beta=20, **kwargs) -> None: + r""" + Represents a hyperboilc secant frequency-swept pulse. + + The amplitude and frequency modulation functions are defined as: + + .. math:: + :nowrap: + + \begin{align} + \mathrm{AM} & = \begin{cases} + \mathrm{sech}\left(\frac{\beta}{2}\left(\frac{2t}{t_p}\right)^{\alpha_1}\right) & t < t_p/2 \\ + \mathrm{sech}\left(\frac{\beta}{2}\left(\frac{2t}{t_p}\right)^{\alpha_2}\right) & t \geq t_p/2 + \end{cases} \\ + \mathrm{FM} & = \frac{\mathrm{BW}}{2 \mathrm{tanh}( \beta/2)}\mathrm{tanh}\left(\frac{\beta t}{t_p} \right) + \omega_0 + \end{align} + + where :math:`\alpha_1` and :math:`\alpha_2` are the orders of the hyperbolic secant function + for the amplitude and frequency modulation respectively, :math:`\beta` is the + truncation parameter, and :math:`BW` is the sweep bandwidth. + + Parameters + ---------- + tp : float + Pulse length in ns + t : float, optional + The time position of the pulse, by default None + init_freq : float, optional + The initial frequency of the pulse in GHz, by default None. Either the initial and final frequency or the bandwidth and central frequency must be specified. + final_freq : float, optional + The final frequency of the pulse in GHz, by default None. Either the initial and final frequency or the bandwidth and central frequency must be specified. + BW : float, optional + The bandwidth of the pulse in GHz, by default None. Either the initial and final frequency or the bandwidth and central frequency must be specified. + freq : float, optional + The central frequency of the pulse in GHz, by default None. Either the initial and final frequency or the bandwidth and central frequency must be specified. + scale : float, optional + The scale of the pulse, by default None + flipangle : float, optional + The flip angle of the pulse in radians, by default None + order1 : float, optional + The order of the hyperbolic secant function for the first half of the pulse, by default 1 + order2 : float, optional + The order of the hyperbolic secant function for the second half of the pulse, by default 6 + beta : float, optional + The beta parameter of the hyperbolic secant function, by default 20 + + Examples + -------- + + + .. plot:: + :include-source: + + import pyepr as epr + import matplotlib.pyplot as plt + + pulse = epr.HSPulse(tp=128, flipangle=np.pi, init_freq=-0.2, final_freq=0.1, order1=1, order2=6, beta=20) + pulse.plot(pad=100) + + """ + FrequencySweptPulse.__init__(self, tp=tp, name='HSPulse', **kwargs) self.order1 = Parameter( "order1", order1, None, "Order 1 of the HS Pulse") @@ -1153,6 +1118,40 @@ class ChirpPulse(FrequencySweptPulse): """ def __init__(self, *, tp=128,rise_time=10, **kwargs) -> None: + """ + Parameters + ---------- + tp : float + Pulse length in ns + init_freq : float, optional + The initial frequency of the pulse in GHz, by default None. Either the initial and final frequency or the bandwidth and central frequency must be specified. + final_freq : float, optional + The final frequency of the pulse in GHz, by default None. Either the initial and final frequency or the bandwidth and central frequency must be specified. + BW : float, optional + The bandwidth of the pulse in GHz, by default None. Either the initial and final frequency or the bandwidth and central frequency must be specified. + freq : float, optional + The central frequency of the pulse in GHz, by default None. Either the initial and final frequency or the bandwidth and central frequency must be specified. + scale : float, optional + The scale of the pulse, by default None + rise_time : float, optional + The quarter sine wave rise time of the pulse in ns, by default 10 + t : float, optional + The time position of the pulse, by default None + flipangle : float, optional + The flip angle of the pulse in radians, by default None + + Examples + -------- + + .. plot:: + :include-source: + + import pyepr as epr + import matplotlib.pyplot as plt + + pulse = epr.ChirpPulse(tp=128, flipangle=np.pi, init_freq=-0.2, final_freq=0.1) + pulse.plot(pad=100) + """ FrequencySweptPulse.__init__(self, tp=tp,name='ChirpPulse', **kwargs) self.rise_time = Parameter("rise_time", rise_time, "ns", "The rise time of the pulse") @@ -1183,28 +1182,57 @@ def sweeprate(self): # ============================================================================= class WURSTPulse(FrequencySweptPulse): - """ + r""" Represents a WURST frequency-swept pulse. Equations: The amplitude :math:`AM` and frequency modulation :math:`FM` of the WURST pulse are defined as follows: + .. math:: - AM(t) = 1 - \left|\sin\left(\frac{\pi}{tp} \cdot t\right)\right|^{order} + + AM(t) = 1 - \left|\sin\left(\frac{\pi}{tp} \cdot t\right)\right|^{n} .. math:: - FM(t) = \frac{BW t}{tp} + init\_freq - where :math:`t` is the time axis, :math:`tp` is the pulse length, :math:`BW` is the bandwidth, :math:`init_freq` is the initial frequency of the pulse, and :math:`order` is the order of the WURST pulse. + + FM(t) = \frac{BW \cdot t}{tp} + \nu_0 + + where :math:`t` is the time axis, :math:`tp` is the pulse length, :math:`BW` is the bandwidth, :math:`\nu_0` is the initial frequency of the pulse, and :math:`n` is the order of the WURST pulse. + Parameters ---------- - tp : int, optional - Pulse length in ns, by default 128 + tp : float + Pulse length in ns + t : float, optional + The time position of the pulse, by default None + init_freq : float, optional + The initial frequency of the pulse in GHz, by default None. Either the initial and final frequency or the bandwidth and central frequency must be specified. + final_freq : float, optional + The final frequency of the pulse in GHz, by default None. Either the initial and final frequency or the bandwidth and central frequency must be specified. + BW : float, optional + The bandwidth of the pulse in GHz, by default None. Either the initial and final frequency or the bandwidth and central frequency must be specified. + freq : float, optional + The central frequency of the pulse in GHz, by default None. Either the initial and final frequency or the bandwidth and central frequency must be specified. + scale : float, optional + The scale of the pulse, by default None + flipangle : float, optional + The flip angle of the pulse in radians, by default None order : int, optional The order of the WURST pulse, by default 32 - **kwargs : dict, optional - Additional keyword arguments to pass to the default pulse class. + + Examples + -------- + + .. plot:: + :include-source: + + import pyepr as epr + import matplotlib.pyplot as plt + + pulse = epr.WURSTPulse(tp=128, flipangle=np.pi, init_freq=-0.2, final_freq=0.1,order=32) + pulse.plot(pad=100) """ def __init__(self, *, tp=128, order=32, **kwargs) -> None: @@ -1248,6 +1276,18 @@ def __init__(self, *, tp=128, freq=0, order=6, window=None, **kwargs) -> None: The order of this sinc function, by default 6 window : _type_, optional The window function, by default None + + Examples + -------- + + .. plot:: + :include-source: + + import pyepr as epr + import matplotlib.pyplot as plt + + pulse = epr.SincPulse(tp=128, flipangle=np.pi, freq=0, order=6) + pulse.plot(pad=100) """ Pulse.__init__(self, tp=tp,name='SincPulse', **kwargs) diff --git a/pyepr/sequences.py b/pyepr/sequences.py index 6899f7e..a2eb02f 100644 --- a/pyepr/sequences.py +++ b/pyepr/sequences.py @@ -46,10 +46,8 @@ def __init__( self.pulses = [] self.num_pulses = len(self.pulses) - self.axes_uuid = [] - self.reduce_uuid = [] - - + self._axes_uuid = [] + self._reduce_uuid = [] if isinstance(B, Parameter): self.B = B.copy() @@ -294,8 +292,8 @@ def evolution(self, params, reduce=[]): """ self.evo_params = params - self.axes_uuid = [param.uuid for param in params] - self.reduce_uuid = [param.uuid for param in reduce] + self._axes_uuid = [param.uuid for param in params] + self._reduce_uuid = [param.uuid for param in reduce] self._buildProgTable() @@ -308,13 +306,13 @@ def _buildProgTable(self): for n, pulse in enumerate(self.pulses): table = pulse.build_table() for i in range(len(table["uuid"])): - if table["uuid"][i] in self.axes_uuid: - progTable["axID"].append(self.axes_uuid.index(table["uuid"][i])) + if table["uuid"][i] in self._axes_uuid: + progTable["axID"].append(self._axes_uuid.index(table["uuid"][i])) progTable["uuid"].append(table["uuid"][i]) progTable["EventID"].append(n) progTable["Variable"].append(table["Variable"][i]) progTable["axis"].append(table["axis"][i]) - if table["uuid"][i] in self.reduce_uuid: + if table["uuid"][i] in self._reduce_uuid: progTable["reduce"].append(True) else: progTable["reduce"].append(False) @@ -324,13 +322,13 @@ def _buildProgTable(self): if type(var) is Parameter: if not var.is_static() and not var.virtual: for i in range(len(var.axis)): - if var.axis[i]["uuid"] in self.axes_uuid: - progTable["axID"].append(self.axes_uuid.index(var.axis[i]["uuid"])) + if var.axis[i]["uuid"] in self._axes_uuid: + progTable["axID"].append(self._axes_uuid.index(var.axis[i]["uuid"])) progTable["EventID"].append(None) progTable["Variable"].append(var_name) progTable["axis" ].append(var.axis[i]["axis"]) progTable["uuid"].append(var.axis[i]["uuid"]) - if var.axis[i]["uuid"] in self.reduce_uuid: + if var.axis[i]["uuid"] in self._reduce_uuid: progTable["reduce"].append(True) else: progTable["reduce"].append(False) @@ -1168,7 +1166,23 @@ def simulate(self,T_CP=2.5e3, e=1.8): Simulates the Carr-Purcell sequence as a single component stretched exponential decay. .. math:: - V(t) = e^(-(t/T_{CP})^e) + V(t) = e^{(-(t/T_{CP})^e)} + + Examples + -------- + + .. plot:: + :include-source: + + import matplotlib.pyplot as plt + import pyepr as epr + + seq = epr.CarrPurcellSequence(B=12000, freq=34, reptime=1000, averages=1, shots=10, n=4) + x,data = seq.simulate(T_CP=2.5e3, e=1.8) + plt.plot(x,data) + plt.xlabel("Interpulse Delay (ns)") + plt.ylabel("Signal Intensity (a.u.)") + Parameters ---------- @@ -1182,6 +1196,7 @@ def simulate(self,T_CP=2.5e3, e=1.8): xaxis : np.ndarray The x-axis of the simulation data : np.ndarray + """ From 29ad866406112b0e494eec8bc8bbfb5033f251a7 Mon Sep 17 00:00:00 2001 From: Hugo Karas Date: Tue, 14 Jul 2026 15:42:39 +0200 Subject: [PATCH 22/55] Removed poetry --- .gitignore | 2 ++ pyproject.toml | 81 ++++++++++++++++++++++++++------------------------ 2 files changed, 44 insertions(+), 39 deletions(-) diff --git a/.gitignore b/.gitignore index 50aa696..3538047 100644 --- a/.gitignore +++ b/.gitignore @@ -70,6 +70,7 @@ instance/ # Sphinx documentation docsrc/_build/ docsrc/autoapi/ +_build/ # PyBuilder target/ @@ -128,5 +129,6 @@ dmypy.json .DS_Store poetry.lock +*.lock docsrc/auto_examples/ diff --git a/pyproject.toml b/pyproject.toml index 5495370..c1dcabc 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,48 +1,51 @@ -[tool.poetry] +[project] name = "pyEPR-ESR" version = "1.1" description = "" -authors = ["Hugo Karas ", "Gunnar Jeschke ", "Stefan Stoll "] readme = "README.md" -packages = [ - { include = "pyepr" } +requires-python = ">=3.11,<4.0" +authors = [ + { name = "Hugo Karas", email = "hkaras@ethz.ch" }, + { name = "Gunnar Jeschke", email = "gjeschke@eth.ch" }, + { name = "Stefan Stoll", email = "stst@uw.edu" }, +] +dependencies = [ + "numpy>=2.1,<3.0", + "scipy>=1.14.1", + "matplotlib>=3.9.2", + "pyyaml>=6.0.2,<7.0.0", + "xarray>=2025", + "h5py>3.15", + "h5netcdf>1.4.0", + "toml>=0.10.2", + "deerlab>=1.1.4,<2.0", + "psutil>=7.1.3", + "requests>=2.32", ] -[tool.poetry.dependencies] -python = ">=3.11,<4.0" -numpy = ">=2.1,<3.0" -scipy = ">=1.14.1" -matplotlib = ">=3.9.2" -pyyaml = "^6.0.2" -xarray = ">=2025" -h5py = ">3.15" -h5netcdf = ">1.4.0" -toml = ">=0.10.2" -deerlab = ">=1.1.4,<2.0" -psutil = ">=7.1.3" -requests = ">=2.32" - - -[tool.poetry.group.dev.dependencies] -gitpython = "^3.1.43" -pytest = "^8.3.3" - - -[tool.poetry.group.doc.dependencies] -furo = {version = ">=2024.8.6"} -autoapi = {version = ">=2.0.1"} -sphinx = {version = ">=8.1.3"} -sphinx-autoapi = ">=3.3.3" -sphinx-toolbox = ">=3.8.1" -sphinx-copybutton = ">=0.5.2" -numpydoc = ">=1.8.0" -sphinx-favicon = ">=1.0.1" -sphinx-autobuild = ">=2025.8.25" -sphinx-gallery = ">=0.19.0" -myst-parser = ">=4.0.1" -sphinx-design = ">=0.6.1" +[project.optional-dependencies] +dev = [ + "gitpython>=3.1.43,<4.0.0", + "pytest>=8.3.3,<9.0.0", +] +doc = [ + "furo>=2024.8.6", + "autoapi>=2.0.1", + "sphinx>=8.1.3", + "sphinx-autoapi>=3.3.3", + "sphinx-toolbox>=3.8.1", + "sphinx-copybutton>=0.5.2", + "numpydoc>=1.8.0", + "sphinx-favicon>=1.0.1", + "sphinx-autobuild>=2025.8.25", + "sphinx-gallery>=0.19.0", + "myst-parser>=4.0.1", + "sphinx-design>=0.6.1", +] [build-system] -requires = ["poetry-core"] -build-backend = "poetry.core.masonry.api" +requires = ["hatchling"] +build-backend = "hatchling.build" +[tool.hatch.build.targets.wheel] +packages = ["pyepr"] From 5e687c288a6d1b61f20e428622ccd3ac0d1df9d5 Mon Sep 17 00:00:00 2001 From: Hugo Karas Date: Tue, 14 Jul 2026 17:31:27 +0200 Subject: [PATCH 23/55] Added support for linked/parallel phase cycles --- docsrc/conf.py | 1 + docsrc/examples/linking_sequence_parameter.py | 46 +++++++++ pyepr/pulses.py | 14 ++- pyepr/sequences.py | 97 ++++++++++--------- pyepr/utils.py | 8 +- tests/test_sequences.py | 32 +++++- 6 files changed, 145 insertions(+), 53 deletions(-) create mode 100644 docsrc/examples/linking_sequence_parameter.py diff --git a/docsrc/conf.py b/docsrc/conf.py index 71708b5..42c8edf 100644 --- a/docsrc/conf.py +++ b/docsrc/conf.py @@ -64,6 +64,7 @@ sphinx_gallery_conf = { 'examples_dirs': 'examples', # path to your example scripts 'gallery_dirs': 'auto_examples', # path to where to save gallery generated output + 'filename_pattern': r'.*\.py', } # -- Options for HTML output ------------------------------------------------- diff --git a/docsrc/examples/linking_sequence_parameter.py b/docsrc/examples/linking_sequence_parameter.py new file mode 100644 index 0000000..ce3ce73 --- /dev/null +++ b/docsrc/examples/linking_sequence_parameter.py @@ -0,0 +1,46 @@ +""" +Linking a pulse's phase cycle to another pulse +=============================================== + +When several pulses in a sequence are phase cycled, PyEPR combines them +multiplicatively by default: each pulse's phase cycle is stepped through +independently, giving the full outer product of every combination. + +Sometimes two pulses should instead be stepped *in phase* with one +another, rather than being combined with all other phase-cycled pulses. +This example shows how to link one pulse's phase cycle to another's so +that they are stepped through together. +""" +# %% +import numpy as np +import pyepr as epr + +# %% +# Create a pulse with its own two-step phase cycle. +exc_pulse = epr.RectPulse( + tp=16, freq=0, flipangle=np.pi / 2, t=0, + pcyc={"phases": [0, np.pi], "dets": [1, -1]}) + +# %% +# Link a second pulse's phase cycle to the first by passing the pulse +# itself as the ``pcyc`` argument. This copies ``exc_pulse``'s phases and +# detection signs, and links the two pulses together. +ref_pulse = epr.RectPulse( + tp=32, freq=0, flipangle=np.pi, t=100, pcyc=exc_pulse) + +det_event = epr.Detection(tp=32, t=200) + +# %% +# Build a sequence and add the pulses. +seq = epr.Sequence( + name="example", B=12127, freq=34, reptime=3e3, averages=1, shots=10) +seq.addPulse([exc_pulse, ref_pulse, det_event]) + +print(seq) + +# %% +# Because ``ref_pulse`` is linked to ``exc_pulse``, the two pulses step +# through their phases together, giving only 2 phase-cycle shots instead +# of the 2 x 2 = 4 that would result from two independent 2-step phase +# cycles. +print(f"Number of phase cycle shots: {seq.pcyc_dets.shape[0]}") diff --git a/pyepr/pulses.py b/pyepr/pulses.py index bfb9f63..ecd78ed 100644 --- a/pyepr/pulses.py +++ b/pyepr/pulses.py @@ -131,6 +131,7 @@ def __init__(self, *, tp, t=None, scale=None, flipangle=None, pcyc=None, self.name = name + self.uuid = uuid.uuid1() if flipangle is not None: self.flipangle = Parameter( @@ -142,6 +143,8 @@ def __init__(self, *, tp, t=None, scale=None, flipangle=None, pcyc=None, self._addPhaseCycle(pcyc["phases"], detections=pcyc["dets"]) elif type(pcyc) is dict and ("Phases" in pcyc) and ("DetSigns" in pcyc): self._addPhaseCycle(pcyc["Phases"], detections=pcyc["DetSigns"]) + elif issubclass(type(pcyc), Pulse): + self._addPhaseCycle(pcyc.pcyc["Phases"], detections=pcyc.pcyc["DetSigns"],link=pcyc.uuid) else: self._addPhaseCycle(pcyc, detections=None) pass @@ -157,7 +160,7 @@ def bandwidth(self): raise ValueError() return BW - def _addPhaseCycle(self, phases, detections=None): + def _addPhaseCycle(self, phases, detections=None, link=None): """ Adds a phase cycle to the pulse sequence. @@ -170,7 +173,7 @@ def _addPhaseCycle(self, phases, detections=None): """ if detections is None: detections = np.ones(len(phases)) - self.pcyc = {"Phases": list(phases), "DetSigns": list(detections)} + self.pcyc = {"Phases": list(phases), "DetSigns": list(detections), "link": link} pass def removePhaseCycle(self): @@ -589,7 +592,7 @@ def copy(self, clear=False, **kwargs): re-created at another memory space. Parameter can be chaged at this stage by adding them as keyword- - arguments (kwargs). + arguments (kwargs). If the phase cycle is changed, the UUID of the pulse will be reset. Returns ------- @@ -621,9 +624,10 @@ def copy(self, clear=False, **kwargs): if attr is None: new_pulse.pcyc = None elif type(new_pcyc) is dict: - new_pulse._addPhaseCycle(new_pcyc["phases"], detections=new_pcyc["dets"]) + new_pulse._addPhaseCycle(new_pcyc["phases"], detections=new_pcyc["dets"], link=new_pcyc.get("link", None)) else: - new_pulse._addPhaseCycle(new_pcyc, detections=None) + new_pulse._addPhaseCycle(new_pcyc, detections=None) + new_pulse.uuid = uuid.uuid1() # UUID reset when phase cycle is changed else: attr = kwargs[arg] elif arg == "t": diff --git a/pyepr/sequences.py b/pyepr/sequences.py index a2eb02f..7177108 100644 --- a/pyepr/sequences.py +++ b/pyepr/sequences.py @@ -227,43 +227,29 @@ def _estimate_time(self) -> float: return time def _buildPhaseCycle(self): - # Identify pulses which are phase cycled - - pcyc_pulses = [] - pulse_cycles = [] - det_cycles = [] - for ix, pulse in enumerate(self.pulses): - if pulse.pcyc is not None: - pcyc_pulses.append(ix) - # pulse_cycles.append(np.array(pulse.pcyc[0])) - # det_cycles.append(np.array(pulse.pcyc[1])) - pulse_cycles.append(pulse.pcyc["Phases"]) - det_cycles.append(pulse.pcyc["DetSigns"]) - - self.pcyc_cycles = np.array(list(product(*pulse_cycles))) - self.pcyc_dets = np.array(list(product(*det_cycles))).prod(axis=1) - self.pcyc_vars = pcyc_pulses - - # # Build expanded phase cycle - # func = lambda x: np.arange(0, len(x)) - # map(func, pulse_cycles) - # n_pulses = len(pulse_cycles) - - # m = list(map(func, pulse_cycles)) - # grids = np.meshgrid(*m, indexing='ij') - # expanded_cycles = [] - # expanded_dets = [] - - # for i in range(0, n_pulses): - # expanded_cycles.append( - # pulse_cycles[i][grids[i].flatten(order='F')]) - # expanded_dets.append(det_cycles[i][grids[i].flatten(order='F')]) - - # self.pcyc_vars = pcyc_pulses - # self.pcyc_cycles = np.stack(expanded_cycles) - # self.pcyc_dets = np.prod(np.stack(expanded_dets), axis=0) - # self.pcyc_n = self.pcyc_cycles.shape[1] - + # Group phase-cycled pulses by link target, so linked pulses step + # through their phase cycle in phase (zipped) instead of being + # combined via a full outer product with the rest of the sequence. + groups = {} + for pulse in self.pulses: + if pulse.pcyc is None: + continue + link = pulse.pcyc.get("link") + key = pulse.uuid if link is None else link + groups.setdefault(key, []).append(pulse) + groups = list(groups.values()) + + phase_axes = [list(zip(*(p.pcyc["Phases"] for p in g))) for g in groups] + det_axes = [list(zip(*(p.pcyc["DetSigns"] for p in g))) for g in groups] + + self.pcyc_vars = [self.pulses.index(p) for g in groups for p in g] + self.pcyc_cycles = np.array([ + [phase for phases in row for phase in phases] + for row in product(*phase_axes)]) + self.pcyc_dets = np.array([ + np.prod([det for dets in row for det in dets]) + for row in product(*det_axes)]) + return self.pcyc_vars, self.pcyc_cycles, self.pcyc_dets def evolution(self, params, reduce=[]): @@ -646,9 +632,12 @@ class HahnEchoSequence(Sequence): Represents a Hahn-Echo sequence. """ def __init__(self, *, B, freq, reptime, averages, shots, **kwargs) -> None: - """Build a Hahn-Echo sequence using either rectangular pulses or + r"""Build a Hahn-Echo sequence using either rectangular pulses or specified pulses. By default no progression is added to this sequence. + Sequence: + [\pi/2 - \tau - \pi - \tau - echo] + Parameters ---------- B : int or float @@ -725,7 +714,7 @@ def __init__(self, *, B, freq, reptime, averages, shots, **kwargs) -> None: # ============================================================================= class T1InversionRecoverySequence(Sequence): - """ + r""" Represents a T1 Inversion Recovery Sequence. Sequence: @@ -821,9 +810,12 @@ def simulate(self, T1=1e4): class HahnEchoRelaxationSequence(HahnEchoSequence): - """ + r""" Represents a Hahn Echo relaxation sequence for measureing Tm. A Hahn Echo where the interpulse delay increases + Sequence: + [\pi/2 - \tau - \pi - \tau - echo] + Parameters ---------- B : int or float @@ -871,9 +863,12 @@ def simulate(self,ESEEM_depth=0.1, Tm=1e3): return xaxis, data class T2RelaxationSequence(HahnEchoRelaxationSequence): - """ + r""" Represents a T2 relaxation sequence. This is an alias for HahnEchoRelaxationSequence. A Hahn Echo where the interpulse delay increases. + + Sequence: + [\pi/2 - \tau - \pi - \tau - echo] Parameters ---------- @@ -910,11 +905,17 @@ class T2RelaxationSequence(HahnEchoRelaxationSequence): class FieldSweepSequence(HahnEchoSequence): """ Represents a Field Sweep (EDFS) sequence. + + + """ def __init__(self, *, B, freq, Bwidth, reptime, averages, shots, **kwargs) -> None: - """Build a Field Sweep (EDFS) sequence using either rectangular pulses or + r"""Build a Field Sweep (EDFS) sequence using either rectangular pulses or specified pulses. + Sequence: + [\pi/2 - \tau - \pi - \tau - echo] + Parameters ---------- B : int or float @@ -985,7 +986,10 @@ class ReptimeScan(HahnEchoSequence): Represents a reptime scan of a Hahn Echo Sequence. """ def __init__(self, *, B, freq, reptime, reptime_max, averages, shots, start=20, dim=100, **kwargs) -> None: - """A Hahn echo sequence is perfomed with the shot repetition time increasing.1 + r"""A Hahn echo sequence is perfomed with the shot repetition time increasing.1 + + Sequence: + [\pi/2 - \tau - \pi - \tau - echo] Parameters ---------- @@ -1062,9 +1066,12 @@ class CarrPurcellSequence(Sequence): """ def __init__(self, *, B, freq, reptime, averages, shots, n,start=300,step=50, dim=100,**kwargs) -> None: - """Build a Carr-Purcell dynamical decoupling sequence using either + r"""Build a Carr-Purcell dynamical decoupling sequence using either rectangular pulses or specified pulses. + Sequence: + [\pi/2 [- \tau - \pi - \tau]^n - echo] + Parameters ---------- B : int or float @@ -1213,7 +1220,7 @@ class ResonatorProfileSequence(Sequence): """ def __init__(self, *, B, freq, reptime, averages, shots, fwidth=0.3,dtp=2, **kwargs) -> None: - """Build a resonator profile nutation sequence using either + r"""Build a resonator profile nutation sequence using either rectangular pulses or specified pulses. Parameters diff --git a/pyepr/utils.py b/pyepr/utils.py index 98e8d68..9922f19 100644 --- a/pyepr/utils.py +++ b/pyepr/utils.py @@ -43,7 +43,13 @@ def build_table(source, params, params_widths): elif param == "iD": elements.append(i) elif param == 'Phase Cycle': - elements.append(pulse._pcyc_str()) + link = pulse.pcyc.get("link") if pulse.pcyc is not None else None + if link is not None: + link_id = next( + (j for j, p in enumerate(source) if p.uuid == link), None) + elements.append(f"linked to pulse {link_id}") + else: + elements.append(pulse._pcyc_str()) elif hasattr(pulse, param): if getattr(pulse, param) is None: elements.append("N/A") diff --git a/tests/test_sequences.py b/tests/test_sequences.py index aff2bf8..c44ceb2 100644 --- a/tests/test_sequences.py +++ b/tests/test_sequences.py @@ -1,4 +1,6 @@ -from pyepr.sequences import FieldSweepSequence, CarrPurcellSequence, T2RelaxationSequence +from pyepr.sequences import FieldSweepSequence, CarrPurcellSequence, T2RelaxationSequence, Sequence +from pyepr.pulses import RectPulse, Detection +from pyepr.utils import build_table import pytest import numpy as np @@ -54,4 +56,30 @@ def test_T2RelaxationSequence(): axes, data = seq.simulate() assert np.allclose(axes,np.arange(500,5100,step=500)) - assert np.allclose(data.real,[6.39143954e-01, 2.90680188e-01, 1.31219296e-01, 3.81219609e-02,1.16796898e-02, 2.39331041e-03, 5.31640969e-04, 8.06720436e-05,1.34965908e-05, 1.56414588e-06]) \ No newline at end of file + assert np.allclose(data.real,[6.39143954e-01, 2.90680188e-01, 1.31219296e-01, 3.81219609e-02,1.16796898e-02, 2.39331041e-03, 5.31640969e-04, 8.06720436e-05,1.34965908e-05, 1.56414588e-06]) + +def test_linked_phase_cycle(): + N_gyro = 0.002803632236095 + freq = 34 + + exc = RectPulse( + tp=16, freq=0, flipangle=np.pi/2, t=0, + pcyc={"phases": [0, np.pi], "dets": [1, -1]}) + # `pcyc=exc` copies exc's phase cycle and links to it, so both pulses + # step through their phases in phase rather than being combined via a + # full outer product. + ref = RectPulse(tp=32, freq=0, flipangle=np.pi, t=100, pcyc=exc) + det = Detection(tp=32, t=200) + + seq = Sequence( + name="test", B=freq/N_gyro, freq=freq, reptime=3e3, averages=1, + shots=10) + seq.addPulse([exc, ref, det]) + + # Two linked 2-step phase cycles produce 2 shots, not 2x2=4 + assert seq.pcyc_cycles.shape == (2, 2) + assert np.allclose(seq.pcyc_cycles[:, 0], seq.pcyc_cycles[:, 1]) + assert np.allclose(seq.pcyc_dets, [1, 1]) + + table = build_table([exc, ref, det], ['iD', 'Phase Cycle'], ['4', '40']) + assert "linked to pulse 0" in table \ No newline at end of file From 3236532a7d044221deae25d42e6ed7bbac8e831d Mon Sep 17 00:00:00 2001 From: Hugo Karas Date: Thu, 30 Jul 2026 14:07:27 +0200 Subject: [PATCH 24/55] Bug Fixes with _axes_uuid and pcyc --- pyepr/dataset.py | 10 +++++----- pyepr/pulses.py | 20 ++++++++++---------- 2 files changed, 15 insertions(+), 15 deletions(-) diff --git a/pyepr/dataset.py b/pyepr/dataset.py index 1bf4c2f..fd88e81 100644 --- a/pyepr/dataset.py +++ b/pyepr/dataset.py @@ -25,8 +25,8 @@ def get_all_axes(sequence): continue for axis in param.axis: - if axis['uuid'] in sequence.axes_uuid and not axis['uuid'] in sequence.reduce_uuid: - ax_id = sequence.axes_uuid.index(axis['uuid']) + if axis['uuid'] in sequence._axes_uuid and not axis['uuid'] in sequence._reduce_uuid: + ax_id = sequence._axes_uuid.index(axis['uuid']) if param.unit == 'ns': convert = 1e-3 elif param.unit == 'us': @@ -45,8 +45,8 @@ def get_all_axes(sequence): if param.axis == []: continue for axis in param.axis: - if axis['uuid'] in sequence.axes_uuid and not axis['uuid'] in sequence.reduce_uuid: - ax_id = sequence.axes_uuid.index(axis['uuid']) + if axis['uuid'] in sequence._axes_uuid and not axis['uuid'] in sequence._reduce_uuid: + ax_id = sequence._axes_uuid.index(axis['uuid']) axes[f"pulse{i}_{param_name}"] = {'axis': axis['axis'] + param.value, 'ax_id':ax_id} return axes @@ -65,7 +65,7 @@ def get_all_fixed_param(sequence): else: if (param.axis == []) and (param.value is not None): fixed_param[param_name] = param.value - elif param.axis[0]['uuid'] in sequence.reduce_uuid: + elif param.axis[0]['uuid'] in sequence._reduce_uuid: fixed_param[param_name] = param.value diff --git a/pyepr/pulses.py b/pyepr/pulses.py index ecd78ed..4c68c14 100644 --- a/pyepr/pulses.py +++ b/pyepr/pulses.py @@ -618,18 +618,18 @@ def copy(self, clear=False, **kwargs): elif isinstance(kwargs[arg], Parameter): attr.value = kwargs[arg].value attr.axis = kwargs[arg].axis - - elif arg == "pcyc": - new_pcyc = kwargs[arg] - if attr is None: - new_pulse.pcyc = None - elif type(new_pcyc) is dict: - new_pulse._addPhaseCycle(new_pcyc["phases"], detections=new_pcyc["dets"], link=new_pcyc.get("link", None)) - else: - new_pulse._addPhaseCycle(new_pcyc, detections=None) - new_pulse.uuid = uuid.uuid1() # UUID reset when phase cycle is changed else: attr = kwargs[arg] + elif arg == "pcyc": + new_pcyc = kwargs[arg] + if new_pcyc is None: + new_pulse.pcyc = None + elif isinstance(new_pcyc, dict) and ("phases" in new_pcyc) and ("dets" in new_pcyc): + new_pulse._addPhaseCycle(new_pcyc["phases"], detections=new_pcyc["dets"], link=new_pcyc.get("link", None)) + else: + new_pulse._addPhaseCycle(new_pcyc, detections=None) + new_pulse.uuid = uuid.uuid1() # UUID reset when phase cycle is changed + elif arg == "t": if type(kwargs[arg]) is Parameter: kwargs[arg].name = "t" From 1894bc1930559f02b7f41636614c9ce1af389349 Mon Sep 17 00:00:00 2001 From: Hugo Karas Date: Thu, 30 Jul 2026 18:15:53 +0200 Subject: [PATCH 25/55] pulse UUID resets when being copied --- pyepr/pulses.py | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/pyepr/pulses.py b/pyepr/pulses.py index 4c68c14..e1eab16 100644 --- a/pyepr/pulses.py +++ b/pyepr/pulses.py @@ -587,13 +587,19 @@ def __str__(self): return string - def copy(self, clear=False, **kwargs): + def copy(self, clear=False, reset_uuid=True, **kwargs): """Creates a deep-copy of the pulse. I.e. Every parameter object is re-created at another memory space. Parameter can be chaged at this stage by adding them as keyword- arguments (kwargs). If the phase cycle is changed, the UUID of the pulse will be reset. + Parameters + ---------- + reset_uuid : bool, optional + If True, the UUID of the copied pulse will be reset to a new value. Default is True. + **kwargs : dict + Keyword arguments representing the parameters to be changed in the copied pulse. Includes 't', 'tp', 'scale', 'flipangle', and 'pcyc', and any other attributes of the pulse. Returns ------- Pulse @@ -602,6 +608,9 @@ def copy(self, clear=False, **kwargs): new_pulse = copy.deepcopy(self) + if reset_uuid: + new_pulse.uuid = uuid.uuid1() + if clear: for arg in vars(new_pulse): attr = getattr(new_pulse,arg) From a8b79c96118d8f7770fe6967f2b15a0b01dd33de Mon Sep 17 00:00:00 2001 From: hkaras Date: Thu, 30 Jul 2026 13:52:57 +0200 Subject: [PATCH 26/55] Minor improvements --- pyepr/dataset.py | 17 ++++++++++++++--- pyepr/hardware/PyEPR_control.py | 6 +++++- pyepr/tools.py | 7 +++++++ 3 files changed, 26 insertions(+), 4 deletions(-) diff --git a/pyepr/dataset.py b/pyepr/dataset.py index fd88e81..d037ac1 100644 --- a/pyepr/dataset.py +++ b/pyepr/dataset.py @@ -63,8 +63,9 @@ def get_all_fixed_param(sequence): elif not isinstance(param, Parameter): continue else: - if (param.axis == []) and (param.value is not None): - fixed_param[param_name] = param.value + if param.axis == []: + if (param.value is not None): + fixed_param[param_name] = param.value elif param.axis[0]['uuid'] in sequence._reduce_uuid: fixed_param[param_name] = param.value @@ -412,12 +413,19 @@ def downconvert_dataset(dataset, filter_type='boxcar',IF=None,reduce=True,sampli IF = dataset.attrs.get('IFfreq') # GHz else: raise ValueError('IFfreq not found in dataset attributes, please provide IF value') + + det_freqs = [v for k,v in dataset.attrs.items() if 'det' in k and 'freq' in k] + if len(det_freqs) > 0: + IF += det_freqs[0] if sampling_rate is None: if 'det_rate' in dataset.attrs: sampling_rate = dataset.attrs.get('det_rate') # GHz elif 'sampling_rate' in dataset.attrs: sampling_rate = dataset.attrs.get('sampling_rate') # GHz + elif 'SamplingRate' in dataset.attrs: + sampling_rate = dataset.attrs.get('SamplingRate') # GHz + else: raise ValueError('sampling_rate not found in dataset attributes, please provide sampling_rate value') if filter_type is None: @@ -459,7 +467,9 @@ def downconvert_dataset(dataset, filter_type='boxcar',IF=None,reduce=True,sampli else: data_array_dc = xr.apply_ufunc(funct,dataset) data_array_dc = data_array_dc*np.exp(-1j*2*np.pi*IF*data_array_dc.tx/sampling_rate) - + data_array_dc.attrs['filter_type'] = filter_type + data_array_dc.attrs['filter_width'] = filter_width + # if data_array_dc.ndim == 3: # max_echo_pos = np.unravel_index(np.argmax(np.abs(data_array_dc.data[0,0,20:-20])),data_array_dc.shape[-1])[0] + 20 # else: @@ -469,6 +479,7 @@ def downconvert_dataset(dataset, filter_type='boxcar',IF=None,reduce=True,sampli max_echo_pos = kwargs['max_echo_pos'] else: max_echo_pos = np.unravel_index(np.abs(data_array_dc).argmax(),data_array_dc.shape)[-1] + data_array_dc.attrs['max_echo_pos'] = max_echo_pos return data_array_dc[...,max_echo_pos] else: return data_array_dc diff --git a/pyepr/hardware/PyEPR_control.py b/pyepr/hardware/PyEPR_control.py index 84da6ef..85b21bb 100644 --- a/pyepr/hardware/PyEPR_control.py +++ b/pyepr/hardware/PyEPR_control.py @@ -668,7 +668,11 @@ def tune(self,*, sequence=None, mode="amp_hahn", freq=None, gyro=None): pulse.scale.value = scale return sequence - + + def tune_resonator(self,*,freq,sweep, reptime=1e3, shots=100, step=0.05, dim=25): + + pass + def get_config(self): """Returns the current configuration of the spectrometer.""" try: diff --git a/pyepr/tools.py b/pyepr/tools.py index 01ccea3..67ecdaf 100644 --- a/pyepr/tools.py +++ b/pyepr/tools.py @@ -7,6 +7,7 @@ from scipy.io import loadmat from scipy.io.matlab import MatReadError import xarray as xr +import warnings log = logging.getLogger('autoDEER.Tools') @@ -87,6 +88,9 @@ def eprload( if downconvert and 'tx' in dataset.dims: datasetDC = downconvert_dataset(dataset,**kwargs) return datasetDC + elif downconvert and 'tx' not in dataset.dims: + warnings.warn("Downconversion requested but no 'tx' dimension found in dataset. Returning original dataset.") + return dataset else: return dataset @@ -118,6 +122,9 @@ def eprload( if downconvert and 'tx' in dataset.dims: datasetDC = downconvert_dataset(dataset,**kwargs) return datasetDC + elif downconvert and 'tx' not in dataset.dims: + warnings.warn("Downconversion requested but no 'tx' dimension found in dataset. Returning original dataset.") + return dataset else: return dataset From e3cd5634616d126cf5f1576516e9faf561f5ccdf Mon Sep 17 00:00:00 2001 From: hkaras Date: Fri, 31 Jul 2026 14:38:16 +0200 Subject: [PATCH 27/55] Minor Changes --- pyepr/dataset.py | 2 +- pyepr/sequences.py | 11 ++++++++--- 2 files changed, 9 insertions(+), 4 deletions(-) diff --git a/pyepr/dataset.py b/pyepr/dataset.py index d037ac1..43b8c48 100644 --- a/pyepr/dataset.py +++ b/pyepr/dataset.py @@ -436,7 +436,7 @@ def downconvert_dataset(dataset, filter_type='boxcar',IF=None,reduce=True,sampli if filter_type == 'boxcar': - filter_width = kwargs.get('filter_width',20) + filter_width = int(round(kwargs.get('filter_width',20))) funct = lambda data: np.convolve(data,np.ones(filter_width),mode='same') dc_first=True elif isinstance(filter_type, ad_pulses.Pulse): # match filter to a epr Pulse diff --git a/pyepr/sequences.py b/pyepr/sequences.py index 7177108..3ade8e6 100644 --- a/pyepr/sequences.py +++ b/pyepr/sequences.py @@ -218,9 +218,11 @@ def _estimate_time(self) -> float: """ self._buildPhaseCycle() acqs = self.averages.value * self.shots.value * self.pcyc_dets.shape[0] + + reptime = np.mean(val_in_us(self.reptime)) if hasattr(self,'evo_params'): acqs *= np.prod([np.prod(param.dim) for param in self.evo_params]) - time = acqs * self.reptime.value * 1e-6 + time = acqs * reptime * 1e-6 self.time = Parameter(name="time", value=f"{(time // 3600):.0f}:{(time % 3600) // 60:.0f}:{(time % 60):.0f}", unit="HH:MM:SS", description="Estimated sequence run time") @@ -428,6 +430,9 @@ def __str__(self): if type(param.value) is str: seq_param_string += "{:<10} {:<12} {:<10} {:<30} \n".format( param.name, param.value, unit, param.description) + elif param.value is None: + seq_param_string += "{:<10} {:<12} {:<10} {:<30} \n".format( + param.name, "None", unit, param.description) else: seq_param_string += "{:<10} {:<12.5g} {:<10} {:<30} \n".format( param.name, param.value, unit, param.description) @@ -945,9 +950,9 @@ def __init__(self, *, B, freq, Bwidth, reptime, averages, shots, **kwargs) -> No shots=shots, **kwargs) self.name = "FieldSweepSequence" - + dim = Bwidth // kwargs.get('step',1) self.B = Parameter( - "B", value=B, start = -Bwidth/2, step=1, dim=Bwidth, unit="Gauss", description="Field sweep width" + "B", value=B, start = -Bwidth/2, step=kwargs.get('step',1), dim=dim, unit="Gauss", description="Field sweep width" ) self.evolution([self.B]) From 241a78956d237e5e5a566da959b2a906c5aa4ffe Mon Sep 17 00:00:00 2001 From: Hugo Karas Date: Tue, 18 Aug 2026 11:07:15 +0200 Subject: [PATCH 28/55] Improved pulse tuning --- pyepr/classes.py | 307 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 307 insertions(+) diff --git a/pyepr/classes.py b/pyepr/classes.py index b0df3bf..f8da96d 100644 --- a/pyepr/classes.py +++ b/pyepr/classes.py @@ -12,7 +12,10 @@ from pathlib import Path import logging from pyepr.config import get_waveform_precision +import pyepr.pulses as pulses import yaml +import warnings +from pyepr.sequences import HahnEchoSequence # ============================================================================= @@ -49,6 +52,8 @@ def __init__(self,config_file:dict=None,log=None) -> None: self.amp_nonlinearity = self.config["Spectrometer"]["Bridge"].get('Amplifier Non-Linearity',None) else: self.amp_nonlinearity = None + + self.AWG=True pass def connect(self) -> None: @@ -213,6 +218,308 @@ def terminate_at(self, criterion, test_interval=2, keep_running=True, verbosity= self.terminate() pass + def tune_RectPulse(self,freq, B, reptime, tp, offset_freq, shots=200, verbosity=0,**kwargs): + """ + Tunes a pair of equal power pi/2, pi rectangular pulses though an amplitude sweep. + + Parameters + ---------- + freq : float + The central frequency of the experiment in GHz. + B : float + The magnetic field in Gauss. + reptime : float + The repetition time in us. + tp : float + The length of the pi/2 pulse in ns. The pi pulse will be half this length. + This will be rounded to the nearest 2*waveform_precision to ensure that the pi pulse is of the correct length. + offset_freq : float + The offset frequency of the rectangular pulse in GHz. This is used to shift the pulse away from the central frequency of the experiment. + shots : int, optional + The number of shots to be used for the frequency sweep, by default 200. + verbosity : int, optional + The verbosity level, by default 0. If > 0, the scale values will be printed. + **kwargs : dict + - step : float, optional + The step size for the amplitude parameter, by default 0.01. + - dim : int, optional + The dimension of the amplitude parameter, by default 50. + - tau : float, optional + The delay between the pi/2 and pi pulses in ns, by default 500. + ** Interface specific launch commands + + Returns + ------- + p90 : pulses.RectPulse + The tuned pi/2 pulse. + p180 : pulses.RectPulse + The tuned pi pulse. + """ + step = kwargs.pop('step', 0.01) + dim = kwargs.pop('dim', 50) + start = kwargs.pop('start', 0.0) + tau = kwargs.pop('tau', 500) + + amp = Parameter(name="scale", value=start, step=step, dim=dim) + p90 = pulses.RectPulse(tp=tp,freq=offset_freq,flipangle=np.pi/2,scale=amp) + p180 = pulses.RectPulse(tp=tp,freq=offset_freq,flipangle=np.pi,scale=amp) + RectEchoTuneSeq =HahnEchoSequence( + B=B, freq=freq, reptime=reptime, averages=1, shots=shots, tau=tau, + pi2_pulse=p90, pi_pulse=p180, + name='RectPulse Echo Tune Sequence') + + RectEchoTuneSeq.evolution([amp]) + + self.launch(RectEchoTuneSeq, + savename=f"RectEchoTune", + **kwargs) + time.sleep(5) + while self.isrunning(): + time.sleep(1) + + dataset = self.acquire_dataset(filter_type='cheby',filter_width=p90.bandwidth.value*1e3) + + if np.any(dataset.data == 0): + warnings.warn("Zero values found in dataset. This may indicate an error in acquisition.") + time.sleep(5) + while self.isrunning(): + time.sleep(2) + dataset = self.acquire_dataset(downconvert=True,reduce=True,filter_type='boxcar',filter_width=250) + + dataset = dataset.epr.correctphase + data = np.abs(dataset.data) + scale = np.around(dataset.pulse0_scale[data.argmax()].data,2) + if verbosity > 0: + print(f"Scale Value: {scale}") + if scale > 0.95: + raise RuntimeError("Not enough power avaliable.") + + if scale == 0: + warnings.warn("Pulse tuned with a scale of zero!") + print("Pulse tuned with a scale of zero!") + p90 = p90.copy(scale=scale) + p180 = p180.copy(scale=scale) + + return p90, p180 + + + + def tune_GaussianPulse(self,freq, B, reptime, tp, offset_freq, shots=200, verbosity=0,**kwargs): + """ + Tunes a pair of equal power pi/2, pi Gaussian pulses though an amplitude sweep. + + Parameters + ---------- + freq : float + The central frequency of the experiment in GHz. + B : float + The magnetic field in Gauss. + reptime : float + The repetition time in us. + tp : float + The length of the pi/2 pulse in ns. The pi pulse will be half this length. + This will be rounded to the nearest 2*waveform_precision to ensure that the pi pulse is of the correct length. + offset_freq : float + The offset frequency of the Gaussian pulse in GHz. This is used to shift the pulse away from the central frequency of the experiment. + shots : int, optional + The number of shots to be used for the frequency sweep, by default 200. + verbosity : int, optional + The verbosity level, by default 0. If > 0, the scale values will be printed. + **kwargs : dict + - step : float, optional + The step size for the amplitude parameter, by default 0.01. + - dim : int, optional + The dimension of the amplitude parameter, by default 50. + - tau : float, optional + The delay between the pi/2 and pi pulses in ns, by default 500. + ** Interface specific launch commands + + Returns + ------- + p90 : pulses.GaussianPulse + The tuned pi/2 pulse. + p180 : pulses.GaussianPulse + The tuned pi pulse. + + """ + + if not self.AWG: + raise RuntimeError("Only AWG based spectrometers can tune Gaussian pulses.") + + step = kwargs.pop('step', 0.01) + dim = kwargs.pop('dim', 50) + start = kwargs.pop('start', 0.0) + tau = kwargs.pop('tau', 500) + + amp = Parameter(name="scale", value=start, step=step, dim=dim) + p90 = pulses.GaussianPulse(tp=tp,freq=offset_freq,flipangle=np.pi/2,scale=amp) + p180 = pulses.GaussianPulse(tp=tp,freq=offset_freq,flipangle=np.pi,scale=amp) + GaussianEchoTuneSeq =HahnEchoSequence( + B=B, freq=freq, reptime=reptime, averages=1, shots=shots, tau=tau, + pi2_pulse=p90, pi_pulse=p180, + name='GaussianPulse Echo Tune Sequence') + + GaussianEchoTuneSeq.evolution([amp]) + + self.launch(GaussianEchoTuneSeq, + savename=f"GaussEchoTune", + **kwargs) + time.sleep(5) + while self.isrunning(): + time.sleep(1) + + dataset = self.acquire_dataset(filter_type='cheby',filter_width=p90.bandwidth.value*1e3) + + if np.any(dataset.data == 0): + warnings.warn("Zero values found in dataset. This may indicate an error in acquisition.") + time.sleep(5) + while self.isrunning(): + time.sleep(2) + dataset = self.acquire_dataset(downconvert=True,reduce=True,filter_type='boxcar',filter_width=250) + + dataset = dataset.epr.correctphase + data = np.abs(dataset.data) + scale = np.around(dataset.pulse0_scale[data.argmax()].data,2) + if verbosity > 0: + print(f"Scale Value: {scale}") + if scale > 0.95: + raise RuntimeError("Not enough power avaliable.") + + if scale == 0: + warnings.warn("Pulse tuned with a scale of zero!") + print("Pulse tuned with a scale of zero!") + p90 = p90.copy(scale=scale) + p180 = p180.copy(scale=scale) + + return p90, p180 + + + def tune_KBBPulse(self,*, freq, B, reptime, tp, init_freq, final_freq, shots=200, verbosity=0,**kwargs): + """ + Tunes a Kutz-Boehlen-Bodenhausen linear chirp echo. This is a three step optimisation: + + 1. Both pulses amplitudes are swept with a 1:2 ratio. + 2. Pulse 0 is fixed using the optimal amplitude from step 1 and pulse 1 is swept. + 3. Pulse 1 is fixed using the optimal amplitude from step 2 and pulse 0 is swept. + + Parameters + ---------- + freq : float + The central frequency of the experiment in GHz. + B : float + The magnetic field in Gauss. + reptime : float + The repetition time in us. + tp : float + The length of the pi/2 pulse in ns. The pi pulse will be half this length. + This will be rounded to the nearest 2*waveform_precision to ensure that the pi pulse is of the correct length. + init_freq : float + The initial frequency of the frequency sweep in GHz. + final_freq : float + The final frequency of the frequency sweep in GHz. + shots : int, optional + The number of shots to be used for the frequency sweep, by default 200. + verbosity : int, optional + The verbosity level, by default 0. If > 0, the scale values will be printed. + **kwargs : dict + - step : float, optional + The step size for the amplitude parameter, by default 0.01. + - dim : int, optional + The dimension of the amplitude parameter, by default 50. + - tau : float, optional + The delay between the pi/2 and pi pulses in ns, by default 500. + ** Interface specific launch commands + + Returns + ------- + p90 : pulses.ChirpPulse + The tuned pi/2 pulse. + p180 : pulses.ChirpPulse + The tuned pi pulse. + """ + if not self.AWG: + raise RuntimeError("Only AWG based spectrometers can tune KBB pulses.") + + waveform_precision = get_waveform_precision() + tp = round_step(tp,waveform_precision*2) # Round to nearest 2*waveform_precision to ensure that the pi pulse is an integer multiple of waveform_precision + + step = kwargs.pop('step', 0.01) + dim = kwargs.pop('dim', 50) + start = kwargs.pop('start', 0.0) + amp = Parameter(name="Amp", value=start, step=step, dim=dim) + + p90 = pulses.ChirpPulse( + tp=tp,init_freq=init_freq,final_freq=final_freq,flipangle=np.pi/2) + p180 = pulses.ChirpPulse( + tp=tp*0.5,init_freq=init_freq,final_freq=final_freq,flipangle=np.pi) + + + tau = kwargs.pop('tau', 500) + + ChirpEchoTuneSeq = HahnEchoSequence( + freq=freq,B=B, reptime=reptime, shots=shots, averages=1, pi2_pulse=p90, + pi_pulse=p180, tau=tau) + ChirpEchoTuneSeq.evolution([amp]) + + + self.launch(ChirpEchoTuneSeq, + savename=f"chirpechotune_step1", + **kwargs) + time.sleep(5) + while self.isrunning(): + time.sleep(1) + + dataset = self.acquire_dataset(filter_type='cheby',filter_width=p90.bandwidth.value*1e3) + + scale = np.around(dataset.pulse0_scale[np.abs(dataset.epr.correctphase).argmax()].data,2) + + if verbosity > 0: + print(f"Initial Scale Value: {scale}") + + ChirpEchoTuneSeq.pulses[0].scale = Parameter('scale',value=scale) + ChirpEchoTuneSeq.pulses[1].scale = amp*2 + ChirpEchoTuneSeq.evolution([amp]) + + self.launch(ChirpEchoTuneSeq, + savename=f"chirpechotune_step2", + **kwargs) + + while self.isrunning(): + time.sleep(1) + + dataset = self.acquire_dataset(filter_type='cheby',filter_width=p90.bandwidth.value*1e3) + + scale1 = np.around(dataset.pulse1_scale[np.abs(dataset.epr.correctphase).argmax()].data,2) + + if verbosity > 0: + print(f"Improved pulse1 scale: {scale1}") + + ChirpEchoTuneSeq.pulses[0].scale = amp + ChirpEchoTuneSeq.pulses[1].scale = Parameter('scale',value=scale) + ChirpEchoTuneSeq.evolution([amp]) + + self.launch(ChirpEchoTuneSeq, + savename=f"chirpechotune_step3", + **kwargs) + + while self.isrunning(): + time.sleep(1) + + dataset = self.acquire_dataset(filter_type='cheby',filter_width=p90.bandwidth.value*1e3) + + scale0 = np.around(dataset.pulse0_scale[np.abs(dataset.epr.correctphase).argmax()].data,2) + + if verbosity > 0: + print(f"Improved pulse0 scale: {scale0}") + + p90 = pulses.ChirpPulse( + tp=tp,init_freq=init_freq,final_freq=final_freq,flipangle=np.pi/2,scale=scale0) + p180 = pulses.ChirpPulse( + tp=tp*0.5,init_freq=init_freq,final_freq=final_freq,flipangle=np.pi,scale=scale1) + + return p90, p180 + + # ============================================================================= class Parameter: From c1b4c9472d8808bedf7aafad7e62230e18470d4a Mon Sep 17 00:00:00 2001 From: Hugo Karas Date: Tue, 18 Aug 2026 11:07:27 +0200 Subject: [PATCH 29/55] More colors --- pyepr/__init__.py | 2 +- pyepr/colors.py | 4 +++- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/pyepr/__init__.py b/pyepr/__init__.py index 8cf921f..444af18 100644 --- a/pyepr/__init__.py +++ b/pyepr/__init__.py @@ -10,4 +10,4 @@ from .fieldsweep_analysis import * from .relaxation_analysis import * from .resonator_profile_analysis import * -from .colors import primary_colors \ No newline at end of file +from .colors import primary_colors, primary_colors_light, secondary_colors \ No newline at end of file diff --git a/pyepr/colors.py b/pyepr/colors.py index f3c3b3e..0b9a72c 100644 --- a/pyepr/colors.py +++ b/pyepr/colors.py @@ -1,3 +1,5 @@ -primary_colors=['#D95B6F','#42A399','#E1AE38'] +primary_colors=['#7C37DB','#DB7C17','#166122'] +primary_colors_light=['#A787D6','#D68B3B','#67B875'] +secondary_colors=['#D95B6F','#42A399','#E1AE38'] ReIm_colors = ['#D61B00','#00BBD6'] shade_colors=[] From 2ce6df228a4c045108158a341874942be6eefd01 Mon Sep 17 00:00:00 2001 From: Hugo Karas Date: Tue, 18 Aug 2026 11:08:29 +0200 Subject: [PATCH 30/55] More plotting --- pyepr/__init__.py | 3 +- pyepr/plotting.py | 93 ++++++++++++++++++++++++++++++++++++ pyepr/relaxation_analysis.py | 7 ++- pyepr/sequences.py | 56 +++++++++++++++++++++- 4 files changed, 155 insertions(+), 4 deletions(-) create mode 100644 pyepr/plotting.py diff --git a/pyepr/__init__.py b/pyepr/__init__.py index 444af18..921be17 100644 --- a/pyepr/__init__.py +++ b/pyepr/__init__.py @@ -10,4 +10,5 @@ from .fieldsweep_analysis import * from .relaxation_analysis import * from .resonator_profile_analysis import * -from .colors import primary_colors, primary_colors_light, secondary_colors \ No newline at end of file +from .colors import primary_colors, primary_colors_light, secondary_colors +from .plotting import plot_sequence_freq \ No newline at end of file diff --git a/pyepr/plotting.py b/pyepr/plotting.py new file mode 100644 index 0000000..d56f505 --- /dev/null +++ b/pyepr/plotting.py @@ -0,0 +1,93 @@ +import matplotlib.pyplot as plt +import numpy as np +import pyepr as epr + +def plot_sequence_freq(sequence, resonator=None, spectrum=None, title=None, fig=None, axs=None, **kwargs): + """ + Plots the relative pulses in the frequency domain. If a resonator or spectrum is provided, these are plotted as well. + + Parameters + ---------- + sequence : epr.Sequence + The pulse sequence to be plotted. + resonator : epr.ResonatorProfile, optional + The resonator profile to be plotted. If provided, the resonator profile will be plotted on a secondary y-axis. + spectrum : epr.FieldSweepAnalysis, optional + The field sweep spectrum to be plotted. If provided, the spectrum will be plotted on the same axis as the pulse sequence. + title : str, optional + The title of the plot. If not provided, no title will be set. + fig : matplotlib.figure.Figure, optional + The figure to plot on. If not provided, a new figure will be created. + axs : matplotlib.axes.Axes, optional + The axes to plot on. If not provided, new axes will be created. + + Returns + ------- + fig : matplotlib.figure.Figure + The figure containing the plot. + """ + + if fig is None or axs is None: + figsize = kwargs.get('figsize', (6,4)) + fig, axs = plt.subplots(figsize=figsize, layout='constrained') + elif fig is None and isinstance(axs,plt.Axes): + fig = axs.figure + + fc = sequence.freq.value + B = sequence.B.value + if resonator is not None: + axs_res = axs.twinx() + axs_res.plot(resonator.freqs, resonator.profile*1e3,'.-', label='Resonator Profile', color=epr.primary_colors[0]) + axs_res.set_ylabel(r'Resonator Profile $\nu_1$ / MHz', color=epr.primary_colors[0]) + BW = resonator.fc/resonator.q + freqs = np.linspace(-BW*3, BW*3, 100) + else: + axs_res = None + freqs = np.linspace(-0.5, 0.5, 100) + + if spectrum is not None and hasattr(spectrum, 'gyro'): + gyro = spectrum.gyro + freq_peak = B*gyro + axs.plot(spectrum.fs_x+freq_peak,spectrum.data, color=epr.primary_colors[1], label='Field Sweep Spectrum') + + for i,pulse in enumerate(sequence.pulses): + if isinstance(pulse,epr.Detection): + continue + pulse:epr.Pulse + + profile = pulse.exciteprofile(freqs=freqs)[:,2] + rescaled_profile = (profile *-0.5 + 0.5) / (pulse.flipangle.value/np.pi) + label = f"Pulse {i}" + + axs.fill_between(freqs+fc, rescaled_profile, label=label,alpha=0.3,color=epr.secondary_colors[i%len(epr.secondary_colors)]) + + # Cretate parallel x axis offset by seq.freq.value + secax = axs.secondary_xaxis('top', functions=(lambda x: x - fc, lambda x: x + fc)) + secax.set_xlabel('Pulse Frequency / GHz') # adjust label/units as needed + axs.set_xlabel('Lab Frequency / GHz') + axs.set_ylabel('Normalized Pulse Efficiency ') + axs.set_xlim(freqs[0]+fc, freqs[-1]+fc) + + lines1, labels1 = axs.get_legend_handles_labels() + if axs_res is not None: + lines2, labels2 = axs_res.get_legend_handles_labels() + lines = lines2+ lines1 + labels = labels2+ labels1 + else: + lines = lines1 + labels = labels1 + fig.legend(lines, labels, ncol=3, loc='outside lower left', fontsize=8) + + if title is not None: + fig.suptitle(title) + + return fig + +def plot_sequence_time(sequence, title=None, fig=None, axs=None): + """ + Creates a graphical summary of a pulse sequence over time. + Showing the pulses at their respective times and durations, as well as the sequence of events in the experiment. + + """ + + pass \ No newline at end of file diff --git a/pyepr/relaxation_analysis.py b/pyepr/relaxation_analysis.py index fd3a2b0..826492b 100644 --- a/pyepr/relaxation_analysis.py +++ b/pyepr/relaxation_analysis.py @@ -636,7 +636,7 @@ def find_pnl(freq): cmap = ['#D95B6F','#42A399'] -def plot_1Drelax(*args,fig=None, axs=None,cmap=cmap, labels =None): +def plot_1Drelax(*args,fig=None, axs=None,cmap=None, labels =None): """ Create a superimposed plot of relaxation data and fits. @@ -650,7 +650,7 @@ def plot_1Drelax(*args,fig=None, axs=None,cmap=cmap, labels =None): axs : Axes, optional The axes to plot to, by default None cmap : list, optional - The color map to use, by default ad.cmap + The color map to use, by default None which uses the primary_colors from pyepr.colors """ @@ -659,6 +659,9 @@ def plot_1Drelax(*args,fig=None, axs=None,cmap=cmap, labels =None): elif axs is None: axs = fig.subplots(1,1) + if cmap is None: + cmap = primary_colors + for i,arg in enumerate(args): if arg.dataset.seq_name == 'T2RelaxationSequence': xscale = 2 diff --git a/pyepr/sequences.py b/pyepr/sequences.py index 3ade8e6..cee13dd 100644 --- a/pyepr/sequences.py +++ b/pyepr/sequences.py @@ -1252,6 +1252,8 @@ def __init__(self, *, B, freq, reptime, averages, shots, fwidth=0.3,dtp=2, **kwa The time step for the test pulse in ns, by default 2 ns step: The frequency step parameter in GHz, by default 0.02GHz + dim: int + The number of points in the tp axis, by default set to 120/dtp, which is 60 points for dtp=2ns. Optional Parameters ------------------- @@ -1292,7 +1294,7 @@ def _build_sequence(self): tau1 = self.kwargs.get("tau1",2000) #2000 tau2 = self.kwargs.get("tau2",500) #500 fstep = self.kwargs.get("step",0.02) - dim = np.floor(120/self.dtp.value).astype(int) + dim = self.kwargs.get("dim",np.floor(120/self.dtp.value).astype(int)) tp = Parameter("tp", 0, step=self.dtp.value, dim=dim, unit="ns", description="Test Pulse length") fwidth= self.fwidth.value fstep = self.fstep.value @@ -1436,3 +1438,55 @@ def _build_sequence(self,): self.evolution([tp, scale]) # ============================================================================= + +class KBBSequence(Sequence): + """ + Builds a Kutnz-Boehlen-Bodenhausen echo sequence. + + """ + + def __init__(self,*,B,freq,reptime,averages=1,shots=100,**kwargs) -> None: + """ + Parameters + ---------- + B : _type_ + _description_ + freq : _type_ + _description_ + reptime : _type_ + _description_ + averages : int, optional + _description_, by default 1 + shots : int, optional + _description_, by default 100 + dtp : int, optional + _description_, by default 2 + """ + name = "KBBSequence" + super().__init__( + name=name, B=B, freq=freq, reptime=reptime, averages=averages, + shots=shots, **kwargs) + + self.kwargs = kwargs + + self._build_sequence() + + def _build_sequence(self,): + pass + + +class KBBPulseProfileSequence(KBBSequence): + """ + Builds a KBB based Resonator Profile sequence. + """ + + def __init__(self,*,B,freq,reptime,averages=1,shots=100,dtp=2,**kwargs) -> None: + + name = "KBB_PulseProfileSequence" + super().__init__( + name=name, B=B, freq=freq, reptime=reptime, averages=averages, + shots=shots, **kwargs) + self._build_sequence() + + def _build_sequence(self,): + pass \ No newline at end of file From 6ef538f9753aaa73f847e9d901dad41c9a65a34b Mon Sep 17 00:00:00 2001 From: hkaras Date: Tue, 18 Aug 2026 11:16:27 +0200 Subject: [PATCH 31/55] Added ResonatorTuneSequences --- pyepr/__init__.py | 3 +- pyepr/resonator_tune.py | 65 +++++++++++++++++++++++++++++++++++++++++ 2 files changed, 67 insertions(+), 1 deletion(-) create mode 100644 pyepr/resonator_tune.py diff --git a/pyepr/__init__.py b/pyepr/__init__.py index 921be17..04da9b0 100644 --- a/pyepr/__init__.py +++ b/pyepr/__init__.py @@ -11,4 +11,5 @@ from .relaxation_analysis import * from .resonator_profile_analysis import * from .colors import primary_colors, primary_colors_light, secondary_colors -from .plotting import plot_sequence_freq \ No newline at end of file +from .plotting import plot_sequence_freq +from .resonator_tune import LoSweepTuneSequence diff --git a/pyepr/resonator_tune.py b/pyepr/resonator_tune.py new file mode 100644 index 0000000..22b5302 --- /dev/null +++ b/pyepr/resonator_tune.py @@ -0,0 +1,65 @@ +from pyepr import Sequence, Parameter, Detection, ChirpPulse, RectPulse + +class LoSweepTuneSequence(Sequence): + + def __init__(self,*,freq, **kwargs): + """ + LO Sweep Tune Sequence + + This is formed of a single monochromatic rectangular pulse which is detected, at different LO frequencies. + The resonator dip is charecterised by the absorption of the pulse, and less reflected power. + + Parameters + ---------- + freq : float + The center frequency in GHz. + + B: float + The magnetic field in gAUSS, default is 0. + reptime : float + The repetition time in us, default is 1e3. + shots : int + The number of shots per point, default is 100. + sweep : float + The full sweep (span) width in GHz, default is 1 GHz. + Note that the sweep is centered around the freq frequency, so the sweep goes from freq-sweep/2 to freq+sweep/2. + step: float + The frequency step in GHz, default 0.05 + dim: int + The number of points in the sweep, default 25. + + + + """ + + name = 'LO Sweep Tune Sequence' + B = kwargs.pop('B', None) + reptime = kwargs.pop('reptime', 1e3) # 0.1ms + shots=kwargs.pop('shots', 100) + averages=kwargs.pop('averages', 1) + + if all(key in kwargs for key in ('sweep', 'step', 'dim')): + raise ValueError("Cannot specify sweep, step and dim together. Specify only two of them.") + elif 'sweep' not in kwargs: + step = kwargs.pop('step', 0.05) + dim = int(kwargs.pop('dim', 25)) + sweep = step*(dim-1) + elif 'step' not in kwargs: + sweep = kwargs.pop('sweep', 1) + dim = int(kwargs.pop('dim', 25)) + step = sweep/(dim-1) + elif 'dim' not in kwargs: + sweep = kwargs.pop('sweep', 1) + step = kwargs.pop('step', 0.05) + dim = int(sweep/step)+1 + + + super().__init__(name=name, B=B, freq=freq, reptime=reptime,shots=shots,averages=averages, **kwargs) + + self.freq = Parameter(name='freq', value=freq-sweep/2, step=step, dim=dim, unit='GHz', virtual=False) + self._build() + self.evolution([self.freq]) + + def _build(self): + self.addPulse(RectPulse(t=350,tp=300, freq=0, scale=1, flipangle='hard')) + self.addPulse(Detection(t=512,tp=1024)) From 2cc2190315128421d6d26a04bcc24ed4ae38c846 Mon Sep 17 00:00:00 2001 From: hkaras Date: Tue, 18 Aug 2026 11:37:39 +0200 Subject: [PATCH 32/55] Moved Base Interface Class to prenvet circular imports --- pyepr/__init__.py | 3 +- pyepr/classes.py | 513 +------------------------- pyepr/hardware/BaseInterfaceClass.py | 519 +++++++++++++++++++++++++++ pyepr/hardware/Bruker_AWG.py | 2 +- pyepr/hardware/Bruker_MPFU.py | 3 +- pyepr/hardware/ETH_awg.py | 3 +- pyepr/hardware/PyEPR_control.py | 3 +- pyepr/hardware/dummy.py | 3 +- pyepr/pulses.py | 13 + pyepr/sequences.py | 2 +- 10 files changed, 545 insertions(+), 519 deletions(-) create mode 100644 pyepr/hardware/BaseInterfaceClass.py diff --git a/pyepr/__init__.py b/pyepr/__init__.py index 04da9b0..160da9d 100644 --- a/pyepr/__init__.py +++ b/pyepr/__init__.py @@ -1,7 +1,7 @@ from ._version import __version__, __copyright__ from .tools import eprload from .utils import * -from .classes import Parameter, Interface +from .classes import Parameter from .sequences import * from .pulses import * from .criteria import * @@ -13,3 +13,4 @@ from .colors import primary_colors, primary_colors_light, secondary_colors from .plotting import plot_sequence_freq from .resonator_tune import LoSweepTuneSequence +from .hardware.BaseInterfaceClass import Interface \ No newline at end of file diff --git a/pyepr/classes.py b/pyepr/classes.py index f8da96d..3a2ea3e 100644 --- a/pyepr/classes.py +++ b/pyepr/classes.py @@ -1,524 +1,13 @@ import numpy as np -import os from pyepr import __version__ import copy -import time -import datetime import numbers import uuid import json import base64 from pyepr.utils import autoEPRDecoder, round_step -from pathlib import Path -import logging -from pyepr.config import get_waveform_precision -import pyepr.pulses as pulses -import yaml -import warnings -from pyepr.sequences import HahnEchoSequence - - -# ============================================================================= - - -class Interface: - """Represents the interface connection from autoEPR to the spectrometer. - """ - - def __init__(self,config_file:dict=None,log=None) -> None: - """ - Parameters - ---------- - config_file : dict or str or Path, optional - The configuration file or dict for the spectrometer interface, by default None. If None, a default configuration will be used. - log : logging.Logger, optional - The logger to be used, by default None. If None, a default logger will be created. - """ - if isinstance(config_file, (str,Path)): - with open(config_file, 'r') as f: - config_file = yaml.safe_load(f) - - self.config = config_file if isinstance(config_file, dict) else {"Spectrometer":{"Bridge":{}}} - - self.pulses = {} - self.savefolder = str(Path.home()) - self.savename = "" - if log is None: - self.log = logging.getLogger('interface') - else: - self.log = log - self.resonator = None - if self.config != {}: - self.amp_nonlinearity = self.config["Spectrometer"]["Bridge"].get('Amplifier Non-Linearity',None) - else: - self.amp_nonlinearity = None - - self.AWG=True - pass - - def connect(self) -> None: - pass - - def acquire_dataset(self, data): - """ - Acquires the dataset. - """ - - # data.sequence = self.cur_exp - data.attrs['time'] = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S') - return data - - - def launch(self, sequence, savename: str): - """Launches the experiment and initialises autosaving. - - Parameters - ---------- - sequence : Sequence - The sequence to be launched - savename : str - The savename for this measurement. A timestamp will be added to the value. - """ - timestamp = datetime.datetime.now().strftime(r'%Y%m%d_%H%M_') - self.savename=timestamp + savename + '.h5' - pass - - def isrunning(self) -> bool: - return False - - def rescale(self,scale: float) -> float: - """Rescales the scale factor to account for applifier non-linearity. - - Parameters - ---------- - scale : float - The scale factor to be rescaled. - - Returns - ------- - float - The rescaled value. - """ - - if self.amp_nonlinearity is None: - print("WARNING: No amplifier non-linearity defined. Using linear scaling.") - return scale - if isinstance(self.amp_nonlinearity, list): # Assume polyniomial coefficients - coeff = copy.copy(self.amp_nonlinearity) - coeff[-1] -= scale # Set the last coefficient to the negative of the scale factor - roots = np.roots(coeff) # Check if the coefficients are valid - real_roots = roots[np.isreal(roots)].real - - if np.all(real_roots < 0): - new_scale = scale - print("Warning: All roots are negative, setting scale to orginal") - elif len(real_roots[(real_roots >= 0) & (real_roots <= 1)]) == 0: - new_scale = 1.0 - else: - valid = real_roots[(real_roots >= 0) & (real_roots <= 1)] - new_scale = valid[0] - - new_scale = np.clip(new_scale, 0, 1) - return new_scale - - def terminate(self) -> None: - """ - Terminates the experiment immediately. - """ - pass - - def terminate_at(self, criterion, test_interval=2, keep_running=True, verbosity=0,autosave=True): - """Terminates the experiment upon a specific condition being - satisified. - - Parameters - ---------- - criterion : _type_ - The criteria to be tested. - test_interval : int, optional - How often should the criteria be tested in minutes, by default 10. - keep_running : bool, optional - If True, an error will not be raised if the experiment finishes before the criteria is met, by default True. - verbosity : int, optional - The verbosity level, by default 0. - autosave : bool, optional - If True, the data will be autosaved, by default True. - - """ - - - - test_interval_seconds = test_interval * 60 - condition = False - last_scan = 0 - - - while not condition: - - time.sleep(10) # TODO: Replace with half sequence time - - if not self.isrunning(): - if keep_running: - self.terminate() - return None - else: - msg = "Experiments has finished before criteria met." - raise RuntimeError(msg) - - start_time = time.time() - data = self.acquire_dataset() - if autosave: - self.log.debug(f"Autosaving to {os.path.join(self.savefolder,self.savename)}") - # data.to_netcdf(os.path.join(self.savefolder,self.savename),engine='h5netcdf',invalid_netcdf=True) - data.epr.save(os.path.join(self.savefolder,self.savename)) - - try: - # nAvgs = data.num_scans.value - nAvgs = data.attrs['nAvgs'] - - except AttributeError or KeyError: - self.log.warning("WARNING: Dataset missing number of averages(nAvgs)!") - nAvgs = 1 - finally: - if nAvgs < 1: - time.sleep(30) # TODO: Replace with single scan time - continue - elif nAvgs <= last_scan: - time.sleep(30) - continue - last_scan = nAvgs - if verbosity > 0: - print("Testing") - - if isinstance(criterion,list): - conditions = [crit.test(data, verbosity) for crit in criterion] - condition = any(conditions) - - else: - condition = criterion.test(data, verbosity) - - if not condition: - end_time = time.time() - if (end_time - start_time) < test_interval_seconds: - if verbosity > 0: - print("Sleeping") - time.sleep(test_interval_seconds - (end_time - start_time)) - - if isinstance(criterion,list): - for i,crit in enumerate(criterion): - if conditions[i]: - if callable(crit.end_signal): - crit.end_signal() - - else: - if callable(criterion.end_signal): - criterion.end_signal() - - - self.terminate() - pass - - def tune_RectPulse(self,freq, B, reptime, tp, offset_freq, shots=200, verbosity=0,**kwargs): - """ - Tunes a pair of equal power pi/2, pi rectangular pulses though an amplitude sweep. - - Parameters - ---------- - freq : float - The central frequency of the experiment in GHz. - B : float - The magnetic field in Gauss. - reptime : float - The repetition time in us. - tp : float - The length of the pi/2 pulse in ns. The pi pulse will be half this length. - This will be rounded to the nearest 2*waveform_precision to ensure that the pi pulse is of the correct length. - offset_freq : float - The offset frequency of the rectangular pulse in GHz. This is used to shift the pulse away from the central frequency of the experiment. - shots : int, optional - The number of shots to be used for the frequency sweep, by default 200. - verbosity : int, optional - The verbosity level, by default 0. If > 0, the scale values will be printed. - **kwargs : dict - - step : float, optional - The step size for the amplitude parameter, by default 0.01. - - dim : int, optional - The dimension of the amplitude parameter, by default 50. - - tau : float, optional - The delay between the pi/2 and pi pulses in ns, by default 500. - ** Interface specific launch commands - - Returns - ------- - p90 : pulses.RectPulse - The tuned pi/2 pulse. - p180 : pulses.RectPulse - The tuned pi pulse. - """ - step = kwargs.pop('step', 0.01) - dim = kwargs.pop('dim', 50) - start = kwargs.pop('start', 0.0) - tau = kwargs.pop('tau', 500) - - amp = Parameter(name="scale", value=start, step=step, dim=dim) - p90 = pulses.RectPulse(tp=tp,freq=offset_freq,flipangle=np.pi/2,scale=amp) - p180 = pulses.RectPulse(tp=tp,freq=offset_freq,flipangle=np.pi,scale=amp) - RectEchoTuneSeq =HahnEchoSequence( - B=B, freq=freq, reptime=reptime, averages=1, shots=shots, tau=tau, - pi2_pulse=p90, pi_pulse=p180, - name='RectPulse Echo Tune Sequence') - - RectEchoTuneSeq.evolution([amp]) - - self.launch(RectEchoTuneSeq, - savename=f"RectEchoTune", - **kwargs) - time.sleep(5) - while self.isrunning(): - time.sleep(1) - - dataset = self.acquire_dataset(filter_type='cheby',filter_width=p90.bandwidth.value*1e3) - - if np.any(dataset.data == 0): - warnings.warn("Zero values found in dataset. This may indicate an error in acquisition.") - time.sleep(5) - while self.isrunning(): - time.sleep(2) - dataset = self.acquire_dataset(downconvert=True,reduce=True,filter_type='boxcar',filter_width=250) - - dataset = dataset.epr.correctphase - data = np.abs(dataset.data) - scale = np.around(dataset.pulse0_scale[data.argmax()].data,2) - if verbosity > 0: - print(f"Scale Value: {scale}") - if scale > 0.95: - raise RuntimeError("Not enough power avaliable.") - - if scale == 0: - warnings.warn("Pulse tuned with a scale of zero!") - print("Pulse tuned with a scale of zero!") - p90 = p90.copy(scale=scale) - p180 = p180.copy(scale=scale) - - return p90, p180 - - - - def tune_GaussianPulse(self,freq, B, reptime, tp, offset_freq, shots=200, verbosity=0,**kwargs): - """ - Tunes a pair of equal power pi/2, pi Gaussian pulses though an amplitude sweep. - - Parameters - ---------- - freq : float - The central frequency of the experiment in GHz. - B : float - The magnetic field in Gauss. - reptime : float - The repetition time in us. - tp : float - The length of the pi/2 pulse in ns. The pi pulse will be half this length. - This will be rounded to the nearest 2*waveform_precision to ensure that the pi pulse is of the correct length. - offset_freq : float - The offset frequency of the Gaussian pulse in GHz. This is used to shift the pulse away from the central frequency of the experiment. - shots : int, optional - The number of shots to be used for the frequency sweep, by default 200. - verbosity : int, optional - The verbosity level, by default 0. If > 0, the scale values will be printed. - **kwargs : dict - - step : float, optional - The step size for the amplitude parameter, by default 0.01. - - dim : int, optional - The dimension of the amplitude parameter, by default 50. - - tau : float, optional - The delay between the pi/2 and pi pulses in ns, by default 500. - ** Interface specific launch commands - - Returns - ------- - p90 : pulses.GaussianPulse - The tuned pi/2 pulse. - p180 : pulses.GaussianPulse - The tuned pi pulse. - - """ - - if not self.AWG: - raise RuntimeError("Only AWG based spectrometers can tune Gaussian pulses.") - - step = kwargs.pop('step', 0.01) - dim = kwargs.pop('dim', 50) - start = kwargs.pop('start', 0.0) - tau = kwargs.pop('tau', 500) - - amp = Parameter(name="scale", value=start, step=step, dim=dim) - p90 = pulses.GaussianPulse(tp=tp,freq=offset_freq,flipangle=np.pi/2,scale=amp) - p180 = pulses.GaussianPulse(tp=tp,freq=offset_freq,flipangle=np.pi,scale=amp) - GaussianEchoTuneSeq =HahnEchoSequence( - B=B, freq=freq, reptime=reptime, averages=1, shots=shots, tau=tau, - pi2_pulse=p90, pi_pulse=p180, - name='GaussianPulse Echo Tune Sequence') - - GaussianEchoTuneSeq.evolution([amp]) - - self.launch(GaussianEchoTuneSeq, - savename=f"GaussEchoTune", - **kwargs) - time.sleep(5) - while self.isrunning(): - time.sleep(1) - - dataset = self.acquire_dataset(filter_type='cheby',filter_width=p90.bandwidth.value*1e3) - - if np.any(dataset.data == 0): - warnings.warn("Zero values found in dataset. This may indicate an error in acquisition.") - time.sleep(5) - while self.isrunning(): - time.sleep(2) - dataset = self.acquire_dataset(downconvert=True,reduce=True,filter_type='boxcar',filter_width=250) - - dataset = dataset.epr.correctphase - data = np.abs(dataset.data) - scale = np.around(dataset.pulse0_scale[data.argmax()].data,2) - if verbosity > 0: - print(f"Scale Value: {scale}") - if scale > 0.95: - raise RuntimeError("Not enough power avaliable.") - - if scale == 0: - warnings.warn("Pulse tuned with a scale of zero!") - print("Pulse tuned with a scale of zero!") - p90 = p90.copy(scale=scale) - p180 = p180.copy(scale=scale) - - return p90, p180 - - - def tune_KBBPulse(self,*, freq, B, reptime, tp, init_freq, final_freq, shots=200, verbosity=0,**kwargs): - """ - Tunes a Kutz-Boehlen-Bodenhausen linear chirp echo. This is a three step optimisation: - - 1. Both pulses amplitudes are swept with a 1:2 ratio. - 2. Pulse 0 is fixed using the optimal amplitude from step 1 and pulse 1 is swept. - 3. Pulse 1 is fixed using the optimal amplitude from step 2 and pulse 0 is swept. - - Parameters - ---------- - freq : float - The central frequency of the experiment in GHz. - B : float - The magnetic field in Gauss. - reptime : float - The repetition time in us. - tp : float - The length of the pi/2 pulse in ns. The pi pulse will be half this length. - This will be rounded to the nearest 2*waveform_precision to ensure that the pi pulse is of the correct length. - init_freq : float - The initial frequency of the frequency sweep in GHz. - final_freq : float - The final frequency of the frequency sweep in GHz. - shots : int, optional - The number of shots to be used for the frequency sweep, by default 200. - verbosity : int, optional - The verbosity level, by default 0. If > 0, the scale values will be printed. - **kwargs : dict - - step : float, optional - The step size for the amplitude parameter, by default 0.01. - - dim : int, optional - The dimension of the amplitude parameter, by default 50. - - tau : float, optional - The delay between the pi/2 and pi pulses in ns, by default 500. - ** Interface specific launch commands - - Returns - ------- - p90 : pulses.ChirpPulse - The tuned pi/2 pulse. - p180 : pulses.ChirpPulse - The tuned pi pulse. - """ - if not self.AWG: - raise RuntimeError("Only AWG based spectrometers can tune KBB pulses.") - - waveform_precision = get_waveform_precision() - tp = round_step(tp,waveform_precision*2) # Round to nearest 2*waveform_precision to ensure that the pi pulse is an integer multiple of waveform_precision - - step = kwargs.pop('step', 0.01) - dim = kwargs.pop('dim', 50) - start = kwargs.pop('start', 0.0) - amp = Parameter(name="Amp", value=start, step=step, dim=dim) - - p90 = pulses.ChirpPulse( - tp=tp,init_freq=init_freq,final_freq=final_freq,flipangle=np.pi/2) - p180 = pulses.ChirpPulse( - tp=tp*0.5,init_freq=init_freq,final_freq=final_freq,flipangle=np.pi) - - - tau = kwargs.pop('tau', 500) - - ChirpEchoTuneSeq = HahnEchoSequence( - freq=freq,B=B, reptime=reptime, shots=shots, averages=1, pi2_pulse=p90, - pi_pulse=p180, tau=tau) - ChirpEchoTuneSeq.evolution([amp]) - - - self.launch(ChirpEchoTuneSeq, - savename=f"chirpechotune_step1", - **kwargs) - time.sleep(5) - while self.isrunning(): - time.sleep(1) - - dataset = self.acquire_dataset(filter_type='cheby',filter_width=p90.bandwidth.value*1e3) - - scale = np.around(dataset.pulse0_scale[np.abs(dataset.epr.correctphase).argmax()].data,2) - - if verbosity > 0: - print(f"Initial Scale Value: {scale}") - - ChirpEchoTuneSeq.pulses[0].scale = Parameter('scale',value=scale) - ChirpEchoTuneSeq.pulses[1].scale = amp*2 - ChirpEchoTuneSeq.evolution([amp]) - - self.launch(ChirpEchoTuneSeq, - savename=f"chirpechotune_step2", - **kwargs) - - while self.isrunning(): - time.sleep(1) - - dataset = self.acquire_dataset(filter_type='cheby',filter_width=p90.bandwidth.value*1e3) - - scale1 = np.around(dataset.pulse1_scale[np.abs(dataset.epr.correctphase).argmax()].data,2) - - if verbosity > 0: - print(f"Improved pulse1 scale: {scale1}") - - ChirpEchoTuneSeq.pulses[0].scale = amp - ChirpEchoTuneSeq.pulses[1].scale = Parameter('scale',value=scale) - ChirpEchoTuneSeq.evolution([amp]) - - self.launch(ChirpEchoTuneSeq, - savename=f"chirpechotune_step3", - **kwargs) - - while self.isrunning(): - time.sleep(1) - - dataset = self.acquire_dataset(filter_type='cheby',filter_width=p90.bandwidth.value*1e3) - - scale0 = np.around(dataset.pulse0_scale[np.abs(dataset.epr.correctphase).argmax()].data,2) - - if verbosity > 0: - print(f"Improved pulse0 scale: {scale0}") - - p90 = pulses.ChirpPulse( - tp=tp,init_freq=init_freq,final_freq=final_freq,flipangle=np.pi/2,scale=scale0) - p180 = pulses.ChirpPulse( - tp=tp*0.5,init_freq=init_freq,final_freq=final_freq,flipangle=np.pi,scale=scale1) - - return p90, p180 +from pyepr.config import get_waveform_precision # ============================================================================= diff --git a/pyepr/hardware/BaseInterfaceClass.py b/pyepr/hardware/BaseInterfaceClass.py new file mode 100644 index 0000000..7c7e296 --- /dev/null +++ b/pyepr/hardware/BaseInterfaceClass.py @@ -0,0 +1,519 @@ +import numpy as np +import os +import copy +import time +import datetime +from pathlib import Path +import logging +import yaml +import warnings + +from pyepr.utils import round_step +from pyepr.config import get_waveform_precision +import pyepr.pulses as pulses +from pyepr.classes import Parameter +from pyepr.sequences import HahnEchoSequence + + + +# ============================================================================= + + +class Interface: + """Represents the interface connection from autoEPR to the spectrometer. + """ + + def __init__(self,config_file:dict=None,log=None) -> None: + """ + Parameters + ---------- + config_file : dict or str or Path, optional + The configuration file or dict for the spectrometer interface, by default None. If None, a default configuration will be used. + log : logging.Logger, optional + The logger to be used, by default None. If None, a default logger will be created. + """ + if isinstance(config_file, (str,Path)): + with open(config_file, 'r') as f: + config_file = yaml.safe_load(f) + + self.config = config_file if isinstance(config_file, dict) else {"Spectrometer":{"Bridge":{}}} + + self.pulses = {} + self.savefolder = str(Path.home()) + self.savename = "" + if log is None: + self.log = logging.getLogger('interface') + else: + self.log = log + self.resonator = None + if self.config != {}: + self.amp_nonlinearity = self.config["Spectrometer"]["Bridge"].get('Amplifier Non-Linearity',None) + else: + self.amp_nonlinearity = None + + self.AWG=True + pass + + def connect(self) -> None: + pass + + def acquire_dataset(self, data): + """ + Acquires the dataset. + """ + + # data.sequence = self.cur_exp + data.attrs['time'] = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S') + return data + + + def launch(self, sequence, savename: str): + """Launches the experiment and initialises autosaving. + + Parameters + ---------- + sequence : Sequence + The sequence to be launched + savename : str + The savename for this measurement. A timestamp will be added to the value. + """ + timestamp = datetime.datetime.now().strftime(r'%Y%m%d_%H%M_') + self.savename=timestamp + savename + '.h5' + pass + + def isrunning(self) -> bool: + return False + + def rescale(self,scale: float) -> float: + """Rescales the scale factor to account for applifier non-linearity. + + Parameters + ---------- + scale : float + The scale factor to be rescaled. + + Returns + ------- + float + The rescaled value. + """ + + if self.amp_nonlinearity is None: + print("WARNING: No amplifier non-linearity defined. Using linear scaling.") + return scale + if isinstance(self.amp_nonlinearity, list): # Assume polyniomial coefficients + coeff = copy.copy(self.amp_nonlinearity) + coeff[-1] -= scale # Set the last coefficient to the negative of the scale factor + roots = np.roots(coeff) # Check if the coefficients are valid + real_roots = roots[np.isreal(roots)].real + + if np.all(real_roots < 0): + new_scale = scale + print("Warning: All roots are negative, setting scale to orginal") + elif len(real_roots[(real_roots >= 0) & (real_roots <= 1)]) == 0: + new_scale = 1.0 + else: + valid = real_roots[(real_roots >= 0) & (real_roots <= 1)] + new_scale = valid[0] + + new_scale = np.clip(new_scale, 0, 1) + return new_scale + + def terminate(self) -> None: + """ + Terminates the experiment immediately. + """ + pass + + def terminate_at(self, criterion, test_interval=2, keep_running=True, verbosity=0,autosave=True): + """Terminates the experiment upon a specific condition being + satisified. + + Parameters + ---------- + criterion : _type_ + The criteria to be tested. + test_interval : int, optional + How often should the criteria be tested in minutes, by default 10. + keep_running : bool, optional + If True, an error will not be raised if the experiment finishes before the criteria is met, by default True. + verbosity : int, optional + The verbosity level, by default 0. + autosave : bool, optional + If True, the data will be autosaved, by default True. + + """ + + + + test_interval_seconds = test_interval * 60 + condition = False + last_scan = 0 + + + while not condition: + + time.sleep(10) # TODO: Replace with half sequence time + + if not self.isrunning(): + if keep_running: + self.terminate() + return None + else: + msg = "Experiments has finished before criteria met." + raise RuntimeError(msg) + + start_time = time.time() + data = self.acquire_dataset() + if autosave: + self.log.debug(f"Autosaving to {os.path.join(self.savefolder,self.savename)}") + # data.to_netcdf(os.path.join(self.savefolder,self.savename),engine='h5netcdf',invalid_netcdf=True) + data.epr.save(os.path.join(self.savefolder,self.savename)) + + try: + # nAvgs = data.num_scans.value + nAvgs = data.attrs['nAvgs'] + + except AttributeError or KeyError: + self.log.warning("WARNING: Dataset missing number of averages(nAvgs)!") + nAvgs = 1 + finally: + if nAvgs < 1: + time.sleep(30) # TODO: Replace with single scan time + continue + elif nAvgs <= last_scan: + time.sleep(30) + continue + last_scan = nAvgs + if verbosity > 0: + print("Testing") + + if isinstance(criterion,list): + conditions = [crit.test(data, verbosity) for crit in criterion] + condition = any(conditions) + + else: + condition = criterion.test(data, verbosity) + + if not condition: + end_time = time.time() + if (end_time - start_time) < test_interval_seconds: + if verbosity > 0: + print("Sleeping") + time.sleep(test_interval_seconds - (end_time - start_time)) + + if isinstance(criterion,list): + for i,crit in enumerate(criterion): + if conditions[i]: + if callable(crit.end_signal): + crit.end_signal() + + else: + if callable(criterion.end_signal): + criterion.end_signal() + + + self.terminate() + pass + + def tune_RectPulse(self,freq, B, reptime, tp, offset_freq=0, shots=200, verbosity=0,**kwargs): + """ + Tunes a pair of equal power pi/2, pi rectangular pulses though an amplitude sweep. + + Parameters + ---------- + freq : float + The central frequency of the experiment in GHz. + B : float + The magnetic field in Gauss. + reptime : float + The repetition time in us. + tp : float + The length of the pi/2 pulse in ns. The pi pulse will be half this length. + This will be rounded to the nearest 2*waveform_precision to ensure that the pi pulse is of the correct length. + offset_freq : float, optional + The offset frequency of the rectangular pulse in GHz. This is used to shift the pulse away from the central frequency of the experiment. Default is 0. + shots : int, optional + The number of shots to be used for the frequency sweep, by default 200. + verbosity : int, optional + The verbosity level, by default 0. If > 0, the scale values will be printed. + **kwargs : dict + - step : float, optional + The step size for the amplitude parameter, by default 0.02. + - dim : int, optional + The dimension of the amplitude parameter, by default 50. + - tau : float, optional + The delay between the pi/2 and pi pulses in ns, by default 500. + ** Interface specific launch commands + + Returns + ------- + p90 : pulses.RectPulse + The tuned pi/2 pulse. + p180 : pulses.RectPulse + The tuned pi pulse. + """ + step = kwargs.pop('step', 0.02) + dim = kwargs.pop('dim', 50) + start = kwargs.pop('start', 0.0) + tau = kwargs.pop('tau', 500) + + amp = Parameter(name="scale", value=start, step=step, dim=dim) + p90 = pulses.RectPulse(tp=tp,freq=offset_freq,flipangle=np.pi/2,scale=amp) + p180 = pulses.RectPulse(tp=tp*2,freq=offset_freq,flipangle=np.pi,scale=amp) + RectEchoTuneSeq =HahnEchoSequence( + B=B, freq=freq, reptime=reptime, averages=1, shots=shots, tau=tau, + pi2_pulse=p90, pi_pulse=p180, + name='RectPulse Echo Tune Sequence') + + RectEchoTuneSeq.evolution([amp]) + + self.launch(RectEchoTuneSeq, + savename=f"RectEchoTune", + **kwargs) + time.sleep(5) + while self.isrunning(): + time.sleep(1) + + dataset = self.acquire_dataset(filter_type='cheby',filter_width=p90.bandwidth.value*1e3) + + if np.any(dataset.data == 0): + warnings.warn("Zero values found in dataset. This may indicate an error in acquisition.") + time.sleep(5) + while self.isrunning(): + time.sleep(2) + dataset = self.acquire_dataset(downconvert=True,reduce=True,filter_type='boxcar',filter_width=250) + + dataset = dataset.epr.correctphase + data = np.abs(dataset.data) + scale = np.around(dataset.pulse0_scale[data.argmax()].data,2) + if verbosity > 0: + print(f"Scale Value: {scale}") + if scale > 0.95: + raise RuntimeError("Not enough power avaliable.") + + if scale == 0: + warnings.warn("Pulse tuned with a scale of zero!") + print("Pulse tuned with a scale of zero!") + p90 = p90.copy(scale=scale) + p180 = p180.copy(scale=scale) + + return p90, p180 + + + + def tune_GaussianPulse(self,freq, B, reptime, tp, offset_freq=0, shots=200, verbosity=0,**kwargs): + """ + Tunes a pair of equal power pi/2, pi Gaussian pulses though an amplitude sweep. + + Parameters + ---------- + freq : float + The central frequency of the experiment in GHz. + B : float + The magnetic field in Gauss. + reptime : float + The repetition time in us. + tp : float + The length of the pi/2 pulse in ns. The pi pulse will be half this length. + This will be rounded to the nearest 2*waveform_precision to ensure that the pi pulse is of the correct length. + offset_freq : float, optional + The offset frequency of the Gaussian pulse in GHz. This is used to shift the pulse away from the central frequency of the experiment. Default is 0. + shots : int, optional + The number of shots to be used for the frequency sweep, by default 200. + verbosity : int, optional + The verbosity level, by default 0. If > 0, the scale values will be printed. + **kwargs : dict + - step : float, optional + The step size for the amplitude parameter, by default 0.02. + - dim : int, optional + The dimension of the amplitude parameter, by default 50. + - tau : float, optional + The delay between the pi/2 and pi pulses in ns, by default 500. + ** Interface specific launch commands + + Returns + ------- + p90 : pulses.GaussianPulse + The tuned pi/2 pulse. + p180 : pulses.GaussianPulse + The tuned pi pulse. + + """ + + if not self.AWG: + raise RuntimeError("Only AWG based spectrometers can tune Gaussian pulses.") + + step = kwargs.pop('step', 0.02) + dim = kwargs.pop('dim', 50) + start = kwargs.pop('start', 0.0) + tau = kwargs.pop('tau', 500) + + amp = Parameter(name="scale", value=start, step=step, dim=dim) + p90 = pulses.GaussianPulse(tp=tp,freq=offset_freq,flipangle=np.pi/2,scale=amp) + p180 = pulses.GaussianPulse(tp=tp*2,freq=offset_freq,flipangle=np.pi,scale=amp) + GaussianEchoTuneSeq =HahnEchoSequence( + B=B, freq=freq, reptime=reptime, averages=1, shots=shots, tau=tau, + pi2_pulse=p90, pi_pulse=p180, + name='GaussianPulse Echo Tune Sequence') + + GaussianEchoTuneSeq.evolution([amp]) + + self.launch(GaussianEchoTuneSeq, + savename=f"GaussEchoTune", + **kwargs) + time.sleep(5) + while self.isrunning(): + time.sleep(1) + + dataset = self.acquire_dataset(filter_type='cheby',filter_width=p90.bandwidth.value*1e3) + + if np.any(dataset.data == 0): + warnings.warn("Zero values found in dataset. This may indicate an error in acquisition.") + time.sleep(5) + while self.isrunning(): + time.sleep(2) + dataset = self.acquire_dataset(downconvert=True,reduce=True,filter_type='boxcar',filter_width=250) + + dataset = dataset.epr.correctphase + data = np.abs(dataset.data) + scale = np.around(dataset.pulse0_scale[data.argmax()].data,2) + if verbosity > 0: + print(f"Scale Value: {scale}") + if scale > 0.95: + raise RuntimeError("Not enough power avaliable.") + + if scale == 0: + warnings.warn("Pulse tuned with a scale of zero!") + print("Pulse tuned with a scale of zero!") + p90 = p90.copy(scale=scale) + p180 = p180.copy(scale=scale) + + return p90, p180 + + + def tune_KBBPulse(self,*, freq, B, reptime, tp, init_freq, final_freq, shots=200, verbosity=0,**kwargs): + """ + Tunes a Kutz-Boehlen-Bodenhausen linear chirp echo. This is a three step optimisation: + + 1. Both pulses amplitudes are swept with a 1:2 ratio. + 2. Pulse 0 is fixed using the optimal amplitude from step 1 and pulse 1 is swept. + 3. Pulse 1 is fixed using the optimal amplitude from step 2 and pulse 0 is swept. + + Parameters + ---------- + freq : float + The central frequency of the experiment in GHz. + B : float + The magnetic field in Gauss. + reptime : float + The repetition time in us. + tp : float + The length of the pi/2 pulse in ns. The pi pulse will be half this length. + This will be rounded to the nearest 2*waveform_precision to ensure that the pi pulse is of the correct length. + init_freq : float + The initial frequency of the frequency sweep in GHz. + final_freq : float + The final frequency of the frequency sweep in GHz. + shots : int, optional + The number of shots to be used for the frequency sweep, by default 200. + verbosity : int, optional + The verbosity level, by default 0. If > 0, the scale values will be printed. + **kwargs : dict + - step : float, optional + The step size for the amplitude parameter, by default 0.01. + - dim : int, optional + The dimension of the amplitude parameter, by default 50. + - tau : float, optional + The delay between the pi/2 and pi pulses in ns, by default 500. + ** Interface specific launch commands + + Returns + ------- + p90 : pulses.ChirpPulse + The tuned pi/2 pulse. + p180 : pulses.ChirpPulse + The tuned pi pulse. + """ + if not self.AWG: + raise RuntimeError("Only AWG based spectrometers can tune KBB pulses.") + + waveform_precision = get_waveform_precision() + tp = round_step(tp,waveform_precision*2) # Round to nearest 2*waveform_precision to ensure that the pi pulse is an integer multiple of waveform_precision + + step = kwargs.pop('step', 0.01) + dim = kwargs.pop('dim', 50) + start = kwargs.pop('start', 0.0) + amp = Parameter(name="Scale", value=start, step=step, dim=dim) + + p90 = pulses.ChirpPulse( + tp=tp,init_freq=init_freq,final_freq=final_freq,flipangle=np.pi/2,scale=amp) + p180 = pulses.ChirpPulse( + tp=tp*0.5,init_freq=init_freq,final_freq=final_freq,flipangle=np.pi,scale=amp) + + + tau = kwargs.pop('tau', 500) + + ChirpEchoTuneSeq = HahnEchoSequence( + freq=freq,B=B, reptime=reptime, shots=shots, averages=1, pi2_pulse=p90, + pi_pulse=p180, tau=tau) + ChirpEchoTuneSeq.evolution([amp]) + + + self.launch(ChirpEchoTuneSeq, + savename=f"chirpechotune_step1", + **kwargs) + time.sleep(5) + while self.isrunning(): + time.sleep(1) + + dataset = self.acquire_dataset(filter_type='cheby',filter_width=p90.bandwidth.value*1e3) + + scale = np.around(dataset.pulse0_scale[np.abs(dataset.epr.correctphase).argmax()].data,2) + + if verbosity > 0: + print(f"Initial Scale Value: {scale}") + + ChirpEchoTuneSeq.pulses[0].scale = Parameter('scale',value=scale) + ChirpEchoTuneSeq.pulses[1].scale = amp*2 + ChirpEchoTuneSeq.evolution([amp]) + + self.launch(ChirpEchoTuneSeq, + savename=f"chirpechotune_step2", + **kwargs) + + while self.isrunning(): + time.sleep(1) + + dataset = self.acquire_dataset(filter_type='cheby',filter_width=p90.bandwidth.value*1e3) + + scale1 = np.around(dataset.pulse1_scale[np.abs(dataset.epr.correctphase).argmax()].data,2) + + if verbosity > 0: + print(f"Improved pulse1 scale: {scale1}") + + ChirpEchoTuneSeq.pulses[0].scale = amp + ChirpEchoTuneSeq.pulses[1].scale = Parameter('scale',value=scale) + ChirpEchoTuneSeq.evolution([amp]) + + self.launch(ChirpEchoTuneSeq, + savename=f"chirpechotune_step3", + **kwargs) + + while self.isrunning(): + time.sleep(1) + + dataset = self.acquire_dataset(filter_type='cheby',filter_width=p90.bandwidth.value*1e3) + + scale0 = np.around(dataset.pulse0_scale[np.abs(dataset.epr.correctphase).argmax()].data,2) + + if verbosity > 0: + print(f"Improved pulse0 scale: {scale0}") + + p90 = pulses.ChirpPulse( + tp=tp,init_freq=init_freq,final_freq=final_freq,flipangle=np.pi/2,scale=scale0) + p180 = pulses.ChirpPulse( + tp=tp*0.5,init_freq=init_freq,final_freq=final_freq,flipangle=np.pi,scale=scale1) + + return p90, p180 + diff --git a/pyepr/hardware/Bruker_AWG.py b/pyepr/hardware/Bruker_AWG.py index e900e06..5c48970 100644 --- a/pyepr/hardware/Bruker_AWG.py +++ b/pyepr/hardware/Bruker_AWG.py @@ -1,4 +1,4 @@ -from pyepr.classes import Interface +from pyepr.hardware.BaseInterfaceClass import Interface from pyepr.hardware.XeprAPI_link import XeprAPILink from pyepr.hardware.Bruker_tools import PulseSpel, run_general, build_unique_progtable,write_pulsespel_file,step_parameters, get_specjet_data from pyepr.dataset import * diff --git a/pyepr/hardware/Bruker_MPFU.py b/pyepr/hardware/Bruker_MPFU.py index 2f50c48..033d683 100644 --- a/pyepr/hardware/Bruker_MPFU.py +++ b/pyepr/hardware/Bruker_MPFU.py @@ -1,4 +1,5 @@ -from pyepr.classes import Interface, Parameter +from pyepr.classes import Parameter +from pyepr.hardware.BaseInterfaceClass import Interface from pyepr.pulses import Delay, Detection, RectPulse from pyepr.hardware.XeprAPI_link import XeprAPILink from pyepr.hardware.Bruker_tools import PulseSpel, run_general,build_unique_progtable,PSPhaseCycle, write_pulsespel_file diff --git a/pyepr/hardware/ETH_awg.py b/pyepr/hardware/ETH_awg.py index ad1b653..66998d6 100644 --- a/pyepr/hardware/ETH_awg.py +++ b/pyepr/hardware/ETH_awg.py @@ -1,5 +1,6 @@ import matlab.engine -from pyepr.classes import Interface, Parameter +from pyepr.classes import Parameter +from pyepr.hardware.BaseInterfaceClass import Interface from pyepr.pulses import Pulse, RectPulse, ChirpPulse, HSPulse, Delay, Detection from pyepr.sequences import Sequence, HahnEchoSequence, FieldSweepSequence import numpy as np diff --git a/pyepr/hardware/PyEPR_control.py b/pyepr/hardware/PyEPR_control.py index 85b21bb..e2b759f 100644 --- a/pyepr/hardware/PyEPR_control.py +++ b/pyepr/hardware/PyEPR_control.py @@ -9,9 +9,10 @@ import logging # PyEPR imports -from pyepr.classes import Interface, Parameter +from pyepr.classes import Parameter from pyepr.pulses import Delay, Detection from pyepr.sequences import Sequence, HahnEchoSequence, FieldSweepSequence +from pyepr.hardware.BaseInterfaceClass import Interface log = logging.getLogger("interface") diff --git a/pyepr/hardware/dummy.py b/pyepr/hardware/dummy.py index e5cf50f..5bfdf41 100644 --- a/pyepr/hardware/dummy.py +++ b/pyepr/hardware/dummy.py @@ -1,4 +1,5 @@ -from pyepr.classes import Interface, Parameter +from pyepr.classes import Parameter +from pyepr.hardware.BaseInterfaceClass import Interface from pyepr.dataset import create_dataset_from_sequence from pyepr.pulses import Pulse, RectPulse, ChirpPulse, HSPulse, Delay, Detection from pyepr.sequences import * diff --git a/pyepr/pulses.py b/pyepr/pulses.py index e1eab16..09d56d0 100644 --- a/pyepr/pulses.py +++ b/pyepr/pulses.py @@ -875,6 +875,12 @@ def func(self, ax): AM = np.ones(nx) FM = np.zeros(nx) + self.freq.value return AM, FM + + @property + def bandwidth(self): + bandwidth = 1 / self.tp.value + BW = Parameter("Bandwidth", bandwidth, "GHz", "Bandwidth of pulse") + return BW class GaussianPulse(Pulse): """ @@ -930,6 +936,13 @@ def func(self, ax): def plot(self, pad=1000): return super().plot(pad) + + @property + def bandwidth(self): + bandwidth = 1 / self.FWHM.value + BW = Parameter("Bandwidth", bandwidth, "GHz", "Bandwidth of pulse") + return BW + # ============================================================================= class FrequencySweptPulse(Pulse): def __init__(self, *, tp, t=None, scale=None, flipangle=None, pcyc=[0], name=None, **kwargs) -> None: diff --git a/pyepr/sequences.py b/pyepr/sequences.py index cee13dd..a30fd64 100644 --- a/pyepr/sequences.py +++ b/pyepr/sequences.py @@ -671,7 +671,7 @@ def __init__(self, *, B, freq, reptime, averages, shots, **kwargs) -> None: """ - name = "HahnEchoSequence" + name = kwargs.pop('name',"HahnEchoSequence") if "pi_pulse" in kwargs: self.pi_pulse = kwargs["pi_pulse"] From 81eae023cd42ec0616d1e706fff0eac7cfad7717 Mon Sep 17 00:00:00 2001 From: Hugo Karas Date: Fri, 18 Sep 2026 15:01:52 +0200 Subject: [PATCH 33/55] Bug Fix: copying with pcyc --- pyepr/pulses.py | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/pyepr/pulses.py b/pyepr/pulses.py index 09d56d0..2091bae 100644 --- a/pyepr/pulses.py +++ b/pyepr/pulses.py @@ -627,6 +627,15 @@ def copy(self, clear=False, reset_uuid=True, **kwargs): elif isinstance(kwargs[arg], Parameter): attr.value = kwargs[arg].value attr.axis = kwargs[arg].axis + elif arg == "pcyc": + new_pcyc = kwargs[arg] + if new_pcyc is None: + new_pulse.pcyc = None + elif isinstance(new_pcyc, dict) and ("phases" in new_pcyc) and ("dets" in new_pcyc): + new_pulse._addPhaseCycle(new_pcyc["phases"], detections=new_pcyc["dets"], link=new_pcyc.get("link", None)) + else: + new_pulse._addPhaseCycle(new_pcyc, detections=None) + new_pulse.uuid = uuid.uuid1() # UUID reset when phase cycle is changed else: attr = kwargs[arg] elif arg == "pcyc": From bb8b15ce6ea57c70d98469336db8a4e5e4888efe Mon Sep 17 00:00:00 2001 From: Hugo Karas Date: Thu, 8 Oct 2026 11:20:53 +0200 Subject: [PATCH 34/55] Add set field command and hilbert transform --- pyepr/dataset.py | 8 ++ pyepr/hardware/PyEPR_control.py | 21 +++++ tests/test_downconvert_dataset.py | 138 ++++++++++++++++++++++++++++++ 3 files changed, 167 insertions(+) create mode 100644 tests/test_downconvert_dataset.py diff --git a/pyepr/dataset.py b/pyepr/dataset.py index 43b8c48..0ad5340 100644 --- a/pyepr/dataset.py +++ b/pyepr/dataset.py @@ -431,8 +431,16 @@ def downconvert_dataset(dataset, filter_type='boxcar',IF=None,reduce=True,sampli if filter_type is None: dc_first=True elif filter_type not in ['boxcar','cheby']: + Warning('Filter type not recognised, using cheby filter') filter_type = 'cheby' filter_width = 50 + + if not np.iscomplexobj(dataset): + # Apply a Hilbert transform to the dataset to make it complex + from scipy.signal import hilbert + from scipy.fft import set_workers + with set_workers(-1): + dataset = xr.apply_ufunc(hilbert,dataset) if filter_type == 'boxcar': diff --git a/pyepr/hardware/PyEPR_control.py b/pyepr/hardware/PyEPR_control.py index e2b759f..8594589 100644 --- a/pyepr/hardware/PyEPR_control.py +++ b/pyepr/hardware/PyEPR_control.py @@ -245,6 +245,27 @@ def set_param(self, param: str, value: float): log.info(response.json()['message']) return True + def set_field(self,field,ramp_rate=None,wait=False): + """ + Sets the magnetic field + + Parameters + ---------- + field : float + The target magnetic field in Gauss. + ramp_rate : float, optional + The ramp rate in Gauss per second. If not specified, the current ramp rate is used. + wait : bool, optional + If True, the method will block until the field is reached. Default is False. + + """ + response = requests.post(self.server + '/set_field', json={'value': field, 'ramp_rate': ramp_rate, 'wait': wait}) + if 'error' in response.json(): + raise RuntimeError(response.json()['error']) + elif 'message' in response.json(): + log.info(response.json()['message']) + return True + def terminate(self): """ Terminates the current sequence immediately and stops the AWG and digitiser processes diff --git a/tests/test_downconvert_dataset.py b/tests/test_downconvert_dataset.py new file mode 100644 index 0000000..9a72ee4 --- /dev/null +++ b/tests/test_downconvert_dataset.py @@ -0,0 +1,138 @@ +from pyepr.dataset import create_dataset_from_axes, downconvert_dataset +import numpy as np +import pytest + +DC_IF = 0.15 # GHz +DC_FS = 1.0 # GHz, detector sampling rate +DC_N_TX = 256 +DC_ECHO_POS = 128 # samples +DC_ECHO_WIDTH = 10 # samples +DC_PHASE = 0.3 # rad +DC_T_AMP = np.exp(-np.linspace(0, 1, 8)) +DC_SCAN_AMP = np.array([1.0, 0.5, 2.0]) + + +def build_echo_dataset(complex_data, with_scan): + """Gaussian echo on an IF carrier, with dims ('t','tx') or ('scan','t','tx'). + + Returns the dataset and the expected echo amplitude for every non-tx point. + """ + tx = np.arange(DC_N_TX) + t = np.linspace(0, 1, DC_T_AMP.shape[0]) + envelope = np.exp(-0.5 * ((tx - DC_ECHO_POS) / DC_ECHO_WIDTH)**2) + carrier_phase = 2*np.pi*DC_IF*tx/DC_FS + DC_PHASE + if complex_data: + carrier = np.exp(1j*carrier_phase) + else: + carrier = np.cos(carrier_phase) + + amp = DC_T_AMP + axes = [t, tx] + labels = ['t', 'tx'] + if with_scan: + amp = DC_SCAN_AMP[:, None] * amp[None, :] + axes = [np.arange(DC_SCAN_AMP.shape[0])] + axes + labels = ['scan'] + labels + + data = amp[..., None] * envelope * carrier + params = {'IF_freq': DC_IF, 'det_rate': DC_FS} + dset = create_dataset_from_axes(data, axes, params=params, axes_labels=labels) + return dset, amp + + +complex_param = pytest.mark.parametrize( + 'complex_data', [True, False], ids=['complex', 'real']) +scan_param = pytest.mark.parametrize( + 'with_scan', [False, True], ids=['t_tx', 'scan_t_tx']) +filter_param = pytest.mark.parametrize('filter_type', ['boxcar', 'cheby']) + + +@complex_param +@scan_param +def test_downconvert_dataset_mixing_only(complex_data, with_scan): + dset, amp = build_echo_dataset(complex_data, with_scan) + dc = downconvert_dataset(dset, filter_type=None) + + assert dc.dims == dset.dims + assert dc.shape == dset.shape + assert np.iscomplexobj(dc) + + envelope = np.exp(-0.5 * ((dset.tx.values - DC_ECHO_POS) / DC_ECHO_WIDTH)**2) + expected = amp[..., None] * envelope * np.exp(1j*DC_PHASE) + np.testing.assert_allclose(dc.values, expected, atol=1e-6) + + +@complex_param +@scan_param +@filter_param +def test_downconvert_dataset_reduced(complex_data, with_scan, filter_type): + dset, amp = build_echo_dataset(complex_data, with_scan) + dc = downconvert_dataset(dset, filter_type=filter_type, reduce=True) + + assert dc.dims == tuple(d for d in dset.dims if d != 'tx') + assert dc.shape == amp.shape + assert np.iscomplexobj(dc) + for dim in dc.dims: + np.testing.assert_array_equal(dc[dim].values, dset[dim].values) + + assert dc.attrs['filter_type'] == filter_type + assert abs(dc.attrs['max_echo_pos'] - DC_ECHO_POS) <= 1 + + # Every trace is the same echo scaled, so relative amplitudes are kept + # and the downconverted signal has the same constant phase everywhere. + mag = np.abs(dc.values) + np.testing.assert_allclose(mag / mag.max(), amp / amp.max(), rtol=1e-6) + np.testing.assert_allclose(np.angle(dc.values), DC_PHASE, atol=1e-2) + + +@complex_param +@scan_param +@filter_param +def test_downconvert_dataset_unreduced(complex_data, with_scan, filter_type): + dset, amp = build_echo_dataset(complex_data, with_scan) + dc_full = downconvert_dataset(dset, filter_type=filter_type, reduce=False) + + assert dc_full.dims == dset.dims + assert dc_full.shape == dset.shape + assert np.iscomplexobj(dc_full) + + peak_pos = np.abs(dc_full.values).argmax(axis=-1) + assert np.all(np.abs(peak_pos - DC_ECHO_POS) <= 1) + + dc = downconvert_dataset(dset, filter_type=filter_type, reduce=True) + np.testing.assert_allclose( + dc.values, dc_full.values[..., dc.attrs['max_echo_pos']]) + + +@scan_param +@filter_param +def test_downconvert_dataset_real_matches_complex(with_scan, filter_type): + dset_complex, _ = build_echo_dataset(True, with_scan) + dset_real, _ = build_echo_dataset(False, with_scan) + + dc_complex = downconvert_dataset(dset_complex, filter_type=filter_type, reduce=False) + dc_real = downconvert_dataset(dset_real, filter_type=filter_type, reduce=False) + + scale = np.abs(dc_complex.values).max() + np.testing.assert_allclose(dc_real.values, dc_complex.values, atol=1e-6*scale) + + +@complex_param +@filter_param +def test_downconvert_dataset_scans_match_summed(complex_data, filter_type): + dset, _ = build_echo_dataset(complex_data, with_scan=True) + dset_summed = dset.sum('scan', keep_attrs=True) + + dc = downconvert_dataset(dset, filter_type=filter_type) + dc_summed = downconvert_dataset(dset_summed, filter_type=filter_type) + + assert dc.attrs['max_echo_pos'] == dc_summed.attrs['max_echo_pos'] + np.testing.assert_allclose(dc.sum('scan').values, dc_summed.values) + + # Each scan is downconverted independently of the others + for i in range(dset.sizes['scan']): + dc_scan = downconvert_dataset( + dset.isel(scan=i), filter_type=filter_type, + max_echo_pos=dc.attrs['max_echo_pos']) + np.testing.assert_allclose(dc.isel(scan=i).values, dc_scan.values) + From cd163e5f8231d47c7271dc8f5b3b8bd3bb753d91 Mon Sep 17 00:00:00 2001 From: hkaras Date: Tue, 13 Oct 2026 11:33:58 +0200 Subject: [PATCH 35/55] Three Pulse ESEEM --- pyepr/sequences.py | 113 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 113 insertions(+) diff --git a/pyepr/sequences.py b/pyepr/sequences.py index a30fd64..26c1471 100644 --- a/pyepr/sequences.py +++ b/pyepr/sequences.py @@ -1381,6 +1381,118 @@ def lorenz_fcn(x, centre, sigma): # ============================================================================= +class ThreePulseESEEMSequence(Sequence): + + def __init__(self, *, B, freq, reptime, averages, shots, tau=300, start=500, step=40, dim=200, **kwargs) -> None: + + self.tau = Parameter(name="tau", value=start,step=step,dim=dim, unit="ns", description="1st Inter Pulse Delay",virtual=True) + self.T = Parameter( + name='T', + description = 'Mixing Time', + unit = 'ns', + value=start, + step = step, + dim = dim, + virtual=True) + + super().__init__(name="ThreePulseESEEMSequence", + B=B, freq=freq, reptime=reptime, averages=averages, shots=shots, **kwargs) + + self._build_sequence() + + def _build_sequence(self): + if hasattr(self, "pi2_pulse"): + self.addPulse(self.pi2_pulse.copy( + t=0, pcyc={"phases":[0, np.pi], "dets": [1, -1]})) + else: + self.addPulse(RectPulse( # pi/2 + t=0, tp=16, freq=0, flipangle=np.pi/2, + pcyc={"phases":[0, np.pi], "dets": [1, -1]} + )) + + if hasattr(self, "pi2_pulse"): + self.addPulse(self.pi2_pulse.copy( + t=self.tau)) + else: + self.addPulse(RectPulse( # pi/2 + t=self.tau, tp=32, freq=0, flipangle=np.pi + )) + + if hasattr(self, "pi2_pulse"): + self.addPulse(self.pi2_pulse.copy( + t=self.tau+self.T)) + else: + self.addPulse(RectPulse( # pi/2 + t=self.tau+self.T, tp=32, freq=0, flipangle=np.pi + )) + + self.addPulse(Detection(t=self.tau+self.T+self.tau, tp=512)) + + self.evolution([self.T]) + + def _simulate(self): + raise NotImplementedError("Simulation for Three Pulse ESEEM is not implemented yet.") + + +class HYSCORESequence(Sequence): + def __init__(self, *, B, freq, reptime, averages, shots, tau=300, start=300, step=16, dim=128, **kwargs) -> None: + + self.tau = Parameter(name="tau", value=start,step=step,dim=dim, unit="ns", description="1st Inter Pulse Delay",virtual=True) + self.T1 = Parameter( + name='T1', + description = '1st Mixing Time', + unit = 'ns', + value=start, + step = step, + dim = dim, + virtual=True) + self.T2 = Parameter( + name='T2', + description = '2nd Mixing Time', + unit = 'ns', + value=start, + step = step, + dim = dim, + virtual=True) + + super().__init__( + name = "HYSCORESequence", + B=B, freq=freq, reptime=reptime, averages=averages, shots=shots, **kwargs) + + self._build_sequence() + + def _build_sequence(self): + + if hasattr(self, "pi2_pulse"): + p90 = self.pi2_pulse.copy(t=0, pcyc={'phases':[0], 'dets':[1]}) + else: + p90 = RectPulse( # pi/2 + t=0, tp=16, freq=0, flipangle=np.pi/2, + pcyc={"phases":[0], "dets": [1]} + ) + + if hasattr(self, "pi_pulse"): + p180 = self.pi_pulse.copy(t=0, pcyc={'phases':[0], 'dets':[1]}) + else: + p180 = RectPulse( # pi + t=0, tp=32, freq=0, flipangle=np.pi, + pcyc={"phases":[0], "dets": [1]} + ) + + det_event = Detection(t=0, tp=512) + + + self.addPulse(p90.copy(t=0, pcyc={'phases':[0], 'dets':[1]})) + self.addPulse(p90.copy(t=self.tau, pcyc={'phases':[0], 'dets':[1]})) + self.addPulse(p180.copy(t=self.tau+self.T1,pcyc={'phases':[0,np.pi/2,np.pi,3*np.pi/2,], 'dets':[1,-1,1,-1]})) + self.addPulse(p90.copy(t=self.tau+self.T1+self.T2,pcyc={'phases':[0], 'dets':[1]})) + + self.addPulse(det_event.copy(t=2*self.tau+self.T1+self.T2)) + self._buildPhaseCycle() + self.evolution([self.T1,self.T2]) + +# ============================================================================= + class TWTProfileSequence(Sequence): """ Builds TWT based Resonator Profile sequence. @@ -1474,6 +1586,7 @@ def __init__(self,*,B,freq,reptime,averages=1,shots=100,**kwargs) -> None: def _build_sequence(self,): pass +# ============================================================================= class KBBPulseProfileSequence(KBBSequence): """ From fc078f424657c40cb32f727b82dcfff82cfe98db Mon Sep 17 00:00:00 2001 From: hkaras Date: Tue, 13 Oct 2026 11:34:07 +0200 Subject: [PATCH 36/55] Extended IO --- docsrc/examples/loading_cw.py | 18 +++ docsrc/examples/uhrig_decoupling_sequence.py | 4 + docsrc/releasenotes.rst | 10 ++ docsrc/tutorial_loading.md | 5 + pyepr/dataset.py | 151 ++++++++++++++++++- tests/test_dataset.py | 42 ++++++ 6 files changed, 229 insertions(+), 1 deletion(-) create mode 100644 docsrc/examples/loading_cw.py create mode 100644 docsrc/examples/uhrig_decoupling_sequence.py diff --git a/docsrc/examples/loading_cw.py b/docsrc/examples/loading_cw.py new file mode 100644 index 0000000..a110f43 --- /dev/null +++ b/docsrc/examples/loading_cw.py @@ -0,0 +1,18 @@ +""" +Loading a CW EPR file +=============================================== + +PyEPR can also be used to load CW EPR data files, for plotting and analysis in python. + +At the moment, PyEPR is focused on providing analysis for pulse EPR data, and the CW EPR functionality is limited to loading and plotting data. + +Supported file formats include: +- Bruker .DTA/.DSC files +- Magnetech (binary) .dat files +- PyEPR .h5 files (saved using the ``dataset.epr.save()`` method) + +""" + +import pyepr as epr +import matplotlib.pyplot as plt + diff --git a/docsrc/examples/uhrig_decoupling_sequence.py b/docsrc/examples/uhrig_decoupling_sequence.py new file mode 100644 index 0000000..4a42278 --- /dev/null +++ b/docsrc/examples/uhrig_decoupling_sequence.py @@ -0,0 +1,4 @@ +""" +Uhrig Decoupling Sequence +=============================================== +""" diff --git a/docsrc/releasenotes.rst b/docsrc/releasenotes.rst index 9070159..4e2d4f5 100644 --- a/docsrc/releasenotes.rst +++ b/docsrc/releasenotes.rst @@ -1,6 +1,16 @@ Release Notes ============= + +Version 1.2 (2026-10-01): +++++++++++++++++++++++++++++ +- Added `ThreePulseESEEMSequence` and `HYSCORESequence` sequences. +- Added `ESEEMAnalysis` and `HYSCOREAnalysis` classes for analyzing ESEEM and HYSCORE data. +- Expanded `dataset.epr.save` method to support saving in Bruker format. +- Expanded `eprload` function to support loading from MS400 dataformat. +- Improved Documentation +- Increase test coverage + Version 1.1 (2026-05-27): ++++++++++++++++++++++++++++ - Added `AmplifierLinearityAnalysis` class for characterizing amplifier non-linearity. diff --git a/docsrc/tutorial_loading.md b/docsrc/tutorial_loading.md index 1d9f42d..462622c 100644 --- a/docsrc/tutorial_loading.md +++ b/docsrc/tutorial_loading.md @@ -12,6 +12,11 @@ import pyepr as epr data = epr.eprload('path/to/datafile.h5') # Load data from a text file data_txt = epr.eprload('path/to/datafile.txt') +# Load data from a Bruker .DSC/.DTA file +data_bruker = epr.eprload('path/to/datafile.DTA') +# Load data from a MS400 file +data_ms400 = epr.eprload('path/to/datafile_ms400.dat') + ``` ## Viewing Data diff --git a/pyepr/dataset.py b/pyepr/dataset.py index 0ad5340..f20701b 100644 --- a/pyepr/dataset.py +++ b/pyepr/dataset.py @@ -11,6 +11,7 @@ from deerlab import correctphase from deerlab import deerload import copy +import datetime # ============================================================================= @@ -201,7 +202,11 @@ def save(self, filename, type='netCDF',overwrite=True): mode = "a" #if filename doesn't have the extension .h5, add it - if isinstance(filename,str) and not filename.endswith('.h5'): + if not isinstance(filename,str): + raise ValueError("filename must be a string") + elif filename.endswith('.DSC'): + type = 'bruker' + elif not filename.endswith('.h5'): filename = filename + '.h5' if 'Scan' in self._obj.dims: @@ -213,6 +218,10 @@ def save(self, filename, type='netCDF',overwrite=True): if type == 'netCDF': self._obj.to_netcdf(filename,engine='h5netcdf',invalid_netcdf=True,mode=mode,unlimited_dims=unlimited_dims) + elif type == 'bruker': + save_bruker(self._obj, filename, overwrite=overwrite) + + @property def correctphase(self): new_obj = copy.deepcopy(self._obj) @@ -503,3 +512,143 @@ def find_peak(dataset, freq,freq_axis=None,search_range=4): loc = loc-search_range + dataset.values[loc-search_range:loc+search_range].argmax() peak = dataset[loc].values return loc,peak + + +def save_bruker(dataset, filename, overwrite=True): + """ + Save a dataset to a Bruker .DSC/ .DTA file + + Parameters + ---------- + dataset : xr.DataArray + The dataset to save + filename : str + The name of the file to save + overwrite : bool, optional + If True, overwrite the file if it exists, by default True + """ + if not filename.endswith('.DSC'): + filename = filename + '.DSC' + + if overwrite: + mode = 'w' + else: + mode = 'a' + + data = dataset.values + if data.ndim > 2: + raise ValueError("Cannot save data with more than 2 dimensions.") + + two_dim = data.ndim == 2 and min(data.shape) > 1 + + if two_dim: + if not (isinstance(x, (list, tuple)) and len(x) == 2): + raise ValueError("For 2D data, x must be a list/tuple of two axes.") + x_axis = np.asarray(x[0], dtype=np.float64).ravel() + y_axis = np.asarray(x[1], dtype=np.float64).ravel() + else: + if isinstance(x, (list, tuple)): + x_axis = np.asarray(x[0], dtype=np.float64).ravel() + else: + x_axis = np.asarray(x, dtype=np.float64).ravel() + y_axis = None + + complex_data = not np.isrealobj(data) + byteorder = 'big' # BES3T default (XEPR/Linux) + bes3t_version = '1.2' + + dta_path = filename + '.DTA' + # Flatten column-major (Fortran order) to match MATLAB data(:) + flat = data.flatten('F') + if complex_data: + interleaved = np.empty(2 * len(flat), dtype=np.float64) + interleaved[0::2] = flat.real + interleaved[1::2] = flat.imag + raw = interleaved + else: + raw = flat.real.astype(np.float64) + + with open(dta_path, 'wb') as f: + f.write(raw.astype('>f8').tobytes()) + + # --- Write .DSC descriptor file --- + dsc_path = filename + '.DSC' + now = datetime.now() + + def _is_linear(axis): + diffs = np.diff(axis) + if len(diffs) == 0: + return True + mn, mx = diffs.min(), diffs.max() + if mn == 0: + return False + return abs(mx / mn - 1) < 1e-5 + + x_linear = _is_linear(x_axis) + x_type = 'IDX' if x_linear else 'IGD' + if two_dim: + y_linear = _is_linear(y_axis) + y_type = 'IDX' if y_linear else 'IGD' + else: + y_type = 'NODATA' + + with open(dsc_path, 'w') as f: + def kv(key, val): + f.write(f'{key}\t{val}\n') + + def line(val=''): + f.write(f'{val}\n') + + f.write(f'* Exported from PyEPR Version {__version__}, {now.strftime("%Y-%m-%d %H:%M:%S")}\n') + kv('#DESC', f'{bes3t_version} * DESCRIPTOR INFORMATION ***********************') + kv('DSRC', 'MAN') + kv('BSEQ', 'BIG' if byteorder == 'big' else 'LIT') + kv('IKKF', 'CPLX' if complex_data else 'REAL') + kv('IRFMT', 'D') + if complex_data: + kv('IIFMT', 'D') + + # Write XGF gauge file if X axis is non-linear + if not x_linear: + xgf_path = filename + '.XGF' + with open(xgf_path, 'wb') as gf: + gf.write(x_axis.astype('>f8').tobytes()) + kv('XFMT', 'D') + + # Write YGF gauge file if Y axis is non-linear + if two_dim and not y_linear: + ygf_path = filename + '.YGF' + with open(ygf_path, 'wb') as gf: + gf.write(y_axis.astype('>f8').tobytes()) + kv('YFMT', 'D') + + kv('XTYP', x_type) + kv('YTYP', y_type) + kv('ZTYP', 'NODATA') + + kv('XPTS', str(len(x_axis))) + kv('XMIN', f'{x_axis[0]:g}') + kv('XWID', f'{x_axis[-1] - x_axis[0]:g}') + if two_dim: + kv('YPTS', str(len(y_axis))) + kv('YMIN', f'{y_axis[0]:g}') + kv('YWID', f'{y_axis[-1] - y_axis[0]:g}') + + if 'title' in dataset.attrs: + kv('TITL', f"'{dataset.attrs['title']}'") + + line('*') + line('************************************************************') + line('*') + kv('#SPL', f'{bes3t_version} * STANDARD PARAMETER LAYER') + kv('OPER', '') + kv('DATE', now.strftime('%d/%m/%y')) + kv('TIME', now.strftime('%H:%M:%S')) + kv('CMNT', '') + kv('SAMP', '') + kv('SFOR', '') + if 'freq' in dataset.attrs: + kv('MWFQ', f'{dataset.attrs.get('freq') * 1e9:.9g}') + + if 'B' in dataset.attrs: + kv('B0VL', f'{dataset.attrs.get('B') * 1e-4:.9g}') # G -> T diff --git a/tests/test_dataset.py b/tests/test_dataset.py index c1f2cd8..ef44ad7 100644 --- a/tests/test_dataset.py +++ b/tests/test_dataset.py @@ -5,6 +5,7 @@ import numpy as np from scipy.signal import hilbert import pytest +import os def test_create_dataset_from_sequence(): seq = FieldSweepSequence(B=12200, Bwidth=500, LO=34.4, reptime=3e3, averages=1, shots=100) @@ -105,3 +106,44 @@ def build_dataset(tmin): dset = dset1.epr.merge(dset2) assert dset.data.shape[0] == dset1.data.shape[0] + dset2.data.shape[0] + +@pytest.mark.parametrize('format', ['hdf5', 'bruker']) +def test_save_dataset(format, dataset_from_sequence): + dataset = dataset_from_sequence + if format == 'hdf5': + file_path = "test/test_data/test_dataset.h5" + dataset.epr.save(file_path) + + os.path.exists(file_path) + os.remove(file_path) + + elif format == 'bruker': + file_path = "test/test_data/test_dataset.DTA" + dataset.epr.save(file_path, format='bruker') + + # check both .DTA and .DSC files exist + os.path.exists(file_path) + os.path.exists(file_path.replace('.DTA','.DSC')) + + + os.remove(file_path) + os.remove(file_path.replace('.DTA','.DSC')) + +@pytest.mark.parametrize('format', ['hdf5', 'bruker','bruker_cw','ms400']) + +def test_load(format): + + if format == 'hdf5': + file_path = "test/test_data/test_dataset.h5" + + elif format == 'bruker': + file_path = "test/test_data/test_dataset.DTA" + + elif format == 'bruker_cw': + file_path = "test/test_data/test_CW.DTA" + + elif format == 'ms400': + file_path = "test/test_data/test_MS400.dat" + + + \ No newline at end of file From a3bf9cc1866182192ef35ac53dc1407b6ef05262 Mon Sep 17 00:00:00 2001 From: Hugo Karas Date: Wed, 14 Oct 2026 11:48:27 +0200 Subject: [PATCH 37/55] Better ResonatorProfile plot and Filtering --- pyepr/dataset.py | 33 +++++++++-- pyepr/resonator_profile_analysis.py | 87 +++++++++++++++-------------- 2 files changed, 74 insertions(+), 46 deletions(-) diff --git a/pyepr/dataset.py b/pyepr/dataset.py index f20701b..097c2b2 100644 --- a/pyepr/dataset.py +++ b/pyepr/dataset.py @@ -3,10 +3,10 @@ import re import scipy.fft as fft from pyepr import __version__ -from pyepr.pulses import Detection +from pyepr.pulses import Detection, Pulse from pyepr.classes import Parameter from pyepr.sequences import Sequence -import pyepr.pulses as ad_pulses +import pyepr.pulses as epr_pulses import xarray as xr from deerlab import correctphase from deerlab import deerload @@ -319,7 +319,7 @@ def sequence(self): params[param_type] = Parameter(name = param_type, value = min_value, dim=dim, step=step) try: - pulse_build = getattr(ad_pulses,pulse_type) + pulse_build = getattr(epr_pulses,pulse_type) pulses_obj.append(pulse_build(**params)) except: continue @@ -437,6 +437,7 @@ def downconvert_dataset(dataset, filter_type='boxcar',IF=None,reduce=True,sampli else: raise ValueError('sampling_rate not found in dataset attributes, please provide sampling_rate value') + if filter_type is None: dc_first=True elif filter_type not in ['boxcar','cheby']: @@ -456,8 +457,6 @@ def downconvert_dataset(dataset, filter_type='boxcar',IF=None,reduce=True,sampli filter_width = int(round(kwargs.get('filter_width',20))) funct = lambda data: np.convolve(data,np.ones(filter_width),mode='same') dc_first=True - elif isinstance(filter_type, ad_pulses.Pulse): # match filter to a epr Pulse - raise NotImplementedError('Match filter to a pulse not implemented yet') elif filter_type == 'cheby': from scipy.signal import cheby1,sosfiltfilt filter_width = kwargs.get('filter_width',50) # MHz @@ -470,8 +469,32 @@ def downconvert_dataset(dataset, filter_type='boxcar',IF=None,reduce=True,sampli a = cheby1(order,0.5,Wn,'bandpass',analog=False,fs=sampling_rate,output='sos') funct = lambda data: sosfiltfilt(a,data) dc_first=False + elif filter_type in ['gaussian','gauss']: + from scipy.signal import gaussian,convolve + filter_width = kwargs.get('filter_width',50) # MHz + filter_width /= 1e3 + std = filter_width/2.355 + gauss_filter = gaussian(6*std,std) + gauss_filter /= np.sum(gauss_filter) + funct = lambda data: convolve(data,gauss_filter,mode='same') + dc_first=False + elif filter_type == 'butter': + from scipy.signal import butter,sosfiltfilt + filter_width = kwargs.get('filter_width',50) # MHz + filter_width /= 1e3 + + Wn = np.array([IF-filter_width,IF+filter_width]) + Wn[Wn<=0] = 0.001 + order = 5 + + a = butter(order,Wn,'bandpass',analog=False,fs=sampling_rate,output='sos') + funct = lambda data: sosfiltfilt(a,data) + dc_first=False elif filter_type is None: dc_first=True + elif issubclass(filter_type, Pulse): # match filter to a epr Pulse + raise NotImplementedError('Match filter to a pulse not implemented yet') + else: raise ValueError('Filter not recognised') diff --git a/pyepr/resonator_profile_analysis.py b/pyepr/resonator_profile_analysis.py index 084d128..603da4c 100644 --- a/pyepr/resonator_profile_analysis.py +++ b/pyepr/resonator_profile_analysis.py @@ -80,13 +80,13 @@ def __init__( self.dataset = dataset if "LO" in self.dataset.coords: - self.freqs = self.dataset.LO + self.freqs = self.dataset.LO.values self.freq_c = np.mean(self.dataset.LO) elif "freq" in self.dataset.coords: - self.freqs = self.dataset.freq + self.freqs = self.dataset.freq.values self.freq_c = np.mean(self.dataset.freq) elif "freq_axis" in self.dataset.coords: - self.freqs = self.dataset.freq_axis + self.freqs = self.dataset.freq_axis.values self.freq_c = self.dataset.freq if isinstance(self.freq_c,xr.DataArray): @@ -347,15 +347,13 @@ def fit_lorenz1_sqrt(uni_means,uni_stds,fit_kwargs): return lorenz_fit - def plot(self, fieldsweep=None, axs= None, fig=None): + def plot(self, axs= None, fig=None, **kwargs): """plot. Parameters ---------- - fieldsweep : FieldSweepAnalysis, optional - Overlays the FieldSweep if provided, by default None axs : matplotlib.Axes, optional - Axes to plot on, by default None + Axes to plot on, by default None. Needs to be a flat array with two axes fig : matplotlib.Figure, optional Figure to plot on, by default None @@ -365,32 +363,27 @@ def plot(self, fieldsweep=None, axs= None, fig=None): matplotlib figure object """ if axs is None and fig is None: - fig, axs = plt.subplots(2,1,constrained_layout=True,height_ratios=[0.8,0.2],sharex=True) - - if isinstance(axs, list) or isinstance(axs, np.ndarray): - axs1 = axs[0] - axs2 = axs[1] - else: - axs1 = axs - axs2 = None - prof_data = self.profile * 1e3 # GHz -MHz - - axs1.errorbar(self.freqs, prof_data, yerr=self.profile_ci*1e3, fmt='o', label='Data') - - if hasattr(self, 'model'): - axs1.plot(self.model_x, self.model*1e3, label='Model') - # CI= self.results.propagate(self.lorenz_model,self.model_x).ci(50) - # axs1.fill_between(self.model_x, (CI[:,0])*1e3, (CI[:,1])*1e3, alpha=0.5) - - if axs2 is not None: - axs2.plot(self.model_x, self.pha, label='Phase') - axs2.set_xlabel("Frequency / GHz") - axs2.set_ylabel("Phase / rad") - - - if axs2 is None: - axs1.set_xlabel("Frequency / GHz") - axs1.set_ylabel("Nutation Frequency / MHz") + figsize = kwargs.get('figsize', (6,4)) + fig, axs = plt.subplots(2,1,figsize=figsize,sharex=True) + fig.subplots_adjust(hspace=0.05) + elif fig is None and isinstance(axs,plt.Axes): + fig = axs.figure + + self.dataset.real.plot(y='pulse0_tp',x='freq', ax=axs[0],add_colorbar=False,cmap='PuOr') + axs[0].set_xlabel('',fontsize=15) + axs[1].plot(self.freqs,self.profile *1e3,ls='',ms=10,marker='.',alpha=0.8,color=primary_colors[0]) + if hasattr(self,'results'): + model_x = np.linspace(self.freqs.min(), self.freqs.max(), 200) + model_y = self.model_func(model_x) + axs[1].plot(model_x,model_y *1e3,color=primary_colors[1],lw=3) + axs[1].set_ylabel('Nutation Frequency / MHz',fontsize=11) + axs[1].set_xlabel('Freq / GHz',fontsize=11) + + axs[1].yaxis.set_visible(True) + axs[0].tick_params(axis='both', which='major', labelsize=10) + axs[0].set_ylabel('tp / ns',fontsize=11) + axs[1].grid() + axs[1].tick_params(axis='both', which='major', labelsize=10) def Hz2length(x): return 1 / ((x/1000)*2) @@ -398,15 +391,27 @@ def Hz2length(x): def length2Hz(x): return 1 / ((x*1000)*2) - secax = axs1.secondary_yaxis('right', functions=(Hz2length, length2Hz)) - secax.set_ylabel(r'$\pi/2$ pulse length / ns') - # secax.yaxis.set_locator(AutoLocator) + secax = axs[1].secondary_yaxis('right', functions=(Hz2length, length2Hz)) + secax.set_ylabel(r'$\pi$ pulse length / ns',fontsize=11) + secax.set_ticks([8,10,12,14,16,24,32,64]) + secax.tick_params(axis='both', which='major', labelsize=10) + + if hasattr(self,'results'): + props = dict(boxstyle='round', facecolor='wheat', alpha=0.5) + textstr = f"Q = {self.q:.2f}\n$f_c$ = {self.fc:.2f} GHz\n$\\nu_{{max}}$ = {self.model.max()*1e3:.2f} MHz" + axs[1].text(0.02, 0.95, textstr, transform=axs[1].transAxes, fontsize=11, + verticalalignment='top', bbox=props) + + axs[0].set_ylim(*axs[1].get_ylim()) + axs[0].vlines(self.fc,*axs[0].get_ylim(),ls='--',color='0.7',lw=2) + + axs[1].set_ylim(*axs[1].get_ylim()) + axs[1].vlines(self.fc,*axs[1].get_ylim(),ls='--',color='0.7',lw=2) + + secax.tick_params(axis='both', which='major', labelsize=10) + secax2 = axs[1].secondary_xaxis(-0.22, functions=(lambda x: x - self.fc, lambda x: x + self.fc)) - if fieldsweep: - fsweep_data = np.abs(fieldsweep.data) - fsweep_data /= fsweep_data.max() - fsweep_data = fsweep_data * prof_data.max() - axs1.plot(fieldsweep.fs_x + fieldsweep.freq, fsweep_data) + secax2.set_xlabel('Relative Freq / GHz',fontsize=11) return fig From 3386241fc023fd96959b9801cce4d0475b883574 Mon Sep 17 00:00:00 2001 From: Hugo Karas Date: Tue, 27 Oct 2026 10:05:55 +0100 Subject: [PATCH 38/55] Some more fixes --- pyepr/hardware/PyEPR_control.py | 4 +-- pyepr/resonator_profile_analysis.py | 5 ++- pyepr/sequences.py | 50 ++++++++++++++++++++++++++--- 3 files changed, 52 insertions(+), 7 deletions(-) diff --git a/pyepr/hardware/PyEPR_control.py b/pyepr/hardware/PyEPR_control.py index 8594589..1e68509 100644 --- a/pyepr/hardware/PyEPR_control.py +++ b/pyepr/hardware/PyEPR_control.py @@ -312,7 +312,7 @@ def launch(self, sequence: Sequence , savename: str, IFgain=None, test_IF = True while test_IF: self.terminate() - self._launch(sequence,savename,self.IFgain, *args,**kwargs) + self._launch(sequence,savename,self.IFgain, *args,save_scans=save_scans,**kwargs) scan_time = sequence._estimate_time() / sequence.averages.value check_1stScan = True while check_1stScan: @@ -351,7 +351,7 @@ def launch(self, sequence: Sequence , savename: str, IFgain=None, test_IF = False elif (IFgain is not None) and isinstance(IFgain, (int, float)): - self._launch(sequence,savename,IFgain, *args,**kwargs) + self._launch(sequence,savename,IFgain, *args,save_scans=save_scans,**kwargs) else: raise ValueError(f"IFgain must be of type [None, bool, int, float]. Type {type(IFgain)}_{IFgain} is not valid.") diff --git a/pyepr/resonator_profile_analysis.py b/pyepr/resonator_profile_analysis.py index 603da4c..cb33827 100644 --- a/pyepr/resonator_profile_analysis.py +++ b/pyepr/resonator_profile_analysis.py @@ -564,7 +564,10 @@ def _process_fit(self,R_limit=0.5,mask=None): x = self.tp if np.iscomplexobj(nutation): nutation = nutation.epr.correctphase - nutation = nutation/np.max(nutation) + + nutation = nutation/np.max(np.abs(nutation)) + if np.abs(np.min(nutation)) > np.max(nutation): + nutation *= -1 try: results = curve_fit(fun, x, nutation, bounds=bounds,xtol=1e-4,ftol=1e-4,p0=p0) diff --git a/pyepr/sequences.py b/pyepr/sequences.py index 26c1471..fa1c5ac 100644 --- a/pyepr/sequences.py +++ b/pyepr/sequences.py @@ -1500,6 +1500,40 @@ class TWTProfileSequence(Sequence): def __init__(self,*,B,freq,reptime,averages=1,shots=100,dtp=2,**kwargs) -> None: + """ + + + Parameters + ---------- + B: float + The B0 field, in Gauss + freq: float + The freq frequency in GHz + reptime: float + The shot repetition time in us + averages: int + The number of scans. + shots: int + The number of shots per point + dtp: float + The time step for the test pulse in ns, by default 2 ns + tp_dim: int + The number of points in the tp axis, by default set to 120/dtp, which is 60 points for dtp=2ns. + step: float + The scale step parameter, by default 0.02 + dim: int + The number of points in the scale axis, by default 50 + tau1: float + The delay between the nutating pulse and the Hahn Echo, by default 2000 ns + tau2: float + The interpulse delay in the Hahn Echo, by default 500 ns + pi2_pulse : Pulse + A PyEPR `Pulse` object describing the excitation pi/2 pulse. + pi_pulse : Pulse + A PyEPR `Pulse` object describing the refocusing pi pulses. + + """ + name = "TWTProfileSequence" super().__init__( name=name, B=B, freq=freq, reptime=reptime, averages=averages, @@ -1520,12 +1554,20 @@ def _build_sequence(self,): tau1 = self.kwargs.get("tau1",2000) #2000 tau2 = self.kwargs.get("tau2",500) #500 - dim = np.floor(120/self.dtp.value).astype(int) - tp = Parameter("tp", 0, step=self.dtp.value, dim=dim, unit="ns", description="Test Pulse length") - scale = Parameter("scale", 0, step=0.01, dim=100, unit="None", description="Amplitude scale factor") + tp_dim = self.kwargs.get("tp_dim",np.floor(120/self.dtp.value).astype(int)) + tp = Parameter("tp", 0, step=self.dtp.value, dim=tp_dim, unit="ns", description="Test Pulse length") + + step = self.kwargs.get("step",0.02) + dim = self.kwargs.get("dim",50) + # limit the scale to a max of 1.0 + if step * dim > 1.0: + dim = int(1.0 / step) + warnings.warn(f"Scale axis limited to a maximum of 1.0, dim set to {dim}.") + + scale = Parameter("scale", 0, step=step, dim=dim, unit="None", description="Amplitude scale factor") self.addPulse(RectPulse( # Hard pulse - t=0, tp=tp, freq=0, flipangle="Hard",scale=scale + t=0, tp=tp, freq=0, flipangle="hard",scale=scale )) if hasattr(self, "pi2_pulse"): From 1f66a776f1a4ece4610e9672512b795e51e8c120 Mon Sep 17 00:00:00 2001 From: Hugo Karas Date: Mon, 2 Nov 2026 15:38:54 +0100 Subject: [PATCH 39/55] Minor Bug Fixes --- pyepr/hardware/ETH_awg.py | 22 ++++++++++++++++------ pyepr/hardware/dummy.py | 2 +- 2 files changed, 17 insertions(+), 7 deletions(-) diff --git a/pyepr/hardware/ETH_awg.py b/pyepr/hardware/ETH_awg.py index 66998d6..3e322aa 100644 --- a/pyepr/hardware/ETH_awg.py +++ b/pyepr/hardware/ETH_awg.py @@ -1,7 +1,7 @@ import matlab.engine from pyepr.classes import Parameter from pyepr.hardware.BaseInterfaceClass import Interface -from pyepr.pulses import Pulse, RectPulse, ChirpPulse, HSPulse, Delay, Detection +from pyepr.pulses import Pulse, RectPulse, ChirpPulse, HSPulse, GaussianPulse, Delay, Detection from pyepr.sequences import Sequence, HahnEchoSequence, FieldSweepSequence import numpy as np import re @@ -474,7 +474,7 @@ def isrunning(self) -> bool: state= self.bg_thread.is_alive() return state - def tune_rectpulse(self,*,tp, freq, B, reptime, shots=400,step=0.02, dim=45): + def tune_rectpulse(self,*,tp, freq, B, reptime, shots=400,step=0.02, dim=45,**kwargs): """Generates a rectangular pi and pi/2 pulse of the given length at the given field position. This value is stored in the pulse cache. @@ -517,7 +517,7 @@ def tune_rectpulse(self,*,tp, freq, B, reptime, shots=400,step=0.02, dim=45): amp_tune.evolution([scale]) - self.launch(amp_tune, "autoDEER_amptune", IFgain=0) + self.launch(amp_tune, "autoDEER_amptune", IFgain=kwargs.get("IFgain",0)) while self.isrunning(): time.sleep(10) @@ -540,7 +540,7 @@ def tune_rectpulse(self,*,tp, freq, B, reptime, shots=400,step=0.02, dim=45): return p90, p180 - def tune_pulse(self, pulse, mode, freq, B , reptime, shots=400,step=0.02, dim=45): + def tune_pulse(self, pulse, mode, freq, B , reptime, shots=400,step=0.02, dim=45,**kwargs): """Tunes a single pulse a range of methods. Parameters @@ -606,7 +606,7 @@ def tune_pulse(self, pulse, mode, freq, B , reptime, shots=400,step=0.02, dim=45 amp_tune.evolution([scale]) - self.launch(amp_tune, "autoDEER_amptune", IFgain=0) + self.launch(amp_tune, "autoDEER_amptune", IFgain=kwargs.get("IFgain",0)) while self.isrunning(): time.sleep(10) @@ -675,6 +675,8 @@ def tune_pulse(self, pulse, mode, freq, B , reptime, shots=400,step=0.02, dim=45 pulse.scale = Parameter('scale',new_amp,unit=None,description='The amplitude of the pulse 0-1') return pulse + else: + raise ValueError("Mode must be either amp_hahn or amp_nut") def tune(self,*, sequence=None, mode="amp_hahn", freq=None, gyro=None): @@ -801,8 +803,9 @@ def _build_pulse(self, pulse) -> dict: event["t"] = float(pulse.t.value) if type(pulse) is Detection: - # event["det_len"] = float(pulse.tp.value * self.dig_rate) event["det_len"] = float(1024*2) + # event["det_len"] = float(pulse.tp.value * self.dig_rate) + event["det_frq"] = float(pulse.freq.value) + self.IF_freq event["name"] = "det" return event @@ -854,9 +857,16 @@ def _build_pulse(self, pulse) -> dict: event["pulsedef"]["HSorder2"] = float(pulse.order2.value) event["pulsedef"]["HSbeta"] = float(pulse.beta.value) + elif type(pulse) is GaussianPulse: + + event["pulsedef"]["type"] = 'gauss' + + elif type(pulse) is Pulse: event["pulsedef"]["type"] = 'FMAM' raise RuntimeError("Not yet implemented") + else: + raise ValueError(f"Pulse type not recognised, got {type(pulse)}") if self.resonator is not None: resonator = {} diff --git a/pyepr/hardware/dummy.py b/pyepr/hardware/dummy.py index 5bfdf41..a5d5a7d 100644 --- a/pyepr/hardware/dummy.py +++ b/pyepr/hardware/dummy.py @@ -163,7 +163,7 @@ def __init__(self,config_file) -> None: self.mode = self.dummyResonator.mode - super().__init__(self.config,log=hw_log) + super().__init__(self.config, log=hw_log) def launch(self, sequence, savename: str, **kwargs): hw_log.info(f"Launching {sequence.name} sequence") From fa358c85689c84f8312e985e3fbf4e656dcdf281 Mon Sep 17 00:00:00 2001 From: Hugo Karas Date: Wed, 4 Nov 2026 15:04:04 +0100 Subject: [PATCH 40/55] Gaussian Pulse Definition Fix --- pyepr/pulses.py | 1 + 1 file changed, 1 insertion(+) diff --git a/pyepr/pulses.py b/pyepr/pulses.py index 2091bae..7781f30 100644 --- a/pyepr/pulses.py +++ b/pyepr/pulses.py @@ -937,6 +937,7 @@ def __init__(self, *, tp=32,FWHM=None, freq=0, **kwargs) -> None: pass def func(self, ax): + ax -= self.tp.value / 2 # Shift the axis to center the Gaussian pulse nx = ax.shape[0] sigma = self.FWHM.value / (2 * np.sqrt(2 * np.log(2))) AM = np.exp(-ax**2 / (2 * sigma**2)) From adf44c4ecfdeae8c5f7e9c1c87fe95496ebdcc91 Mon Sep 17 00:00:00 2001 From: Hugo Karas Date: Mon, 16 Nov 2026 11:02:13 +0100 Subject: [PATCH 41/55] Moved Sequences + drawing function --- pyepr/__init__.py | 6 +- pyepr/plotting.py | 318 ++++- pyepr/resonator_tune.py | 4 +- pyepr/sequences/DEER.py | 190 +++ pyepr/sequences/ESEEM.py | 211 +++ pyepr/sequences/__init__.py | 3 + pyepr/sequences/base_sequences.py | 1633 ++++++++++++++++++++++ pyepr/sequences/calibration_sequences.py | 0 8 files changed, 2354 insertions(+), 11 deletions(-) create mode 100644 pyepr/sequences/DEER.py create mode 100644 pyepr/sequences/ESEEM.py create mode 100644 pyepr/sequences/__init__.py create mode 100644 pyepr/sequences/base_sequences.py create mode 100644 pyepr/sequences/calibration_sequences.py diff --git a/pyepr/__init__.py b/pyepr/__init__.py index 160da9d..66bc61e 100644 --- a/pyepr/__init__.py +++ b/pyepr/__init__.py @@ -2,7 +2,6 @@ from .tools import eprload from .utils import * from .classes import Parameter -from .sequences import * from .pulses import * from .criteria import * from .dataset import * @@ -11,6 +10,7 @@ from .relaxation_analysis import * from .resonator_profile_analysis import * from .colors import primary_colors, primary_colors_light, secondary_colors -from .plotting import plot_sequence_freq +from .plotting import plot_sequence_freq, draw_sequence from .resonator_tune import LoSweepTuneSequence -from .hardware.BaseInterfaceClass import Interface \ No newline at end of file +from .hardware.BaseInterfaceClass import Interface +from .sequences import * \ No newline at end of file diff --git a/pyepr/plotting.py b/pyepr/plotting.py index d56f505..0111b31 100644 --- a/pyepr/plotting.py +++ b/pyepr/plotting.py @@ -1,6 +1,7 @@ import matplotlib.pyplot as plt import numpy as np import pyepr as epr +import numbers def plot_sequence_freq(sequence, resonator=None, spectrum=None, title=None, fig=None, axs=None, **kwargs): """ @@ -83,11 +84,314 @@ def plot_sequence_freq(sequence, resonator=None, spectrum=None, title=None, fig= return fig -def plot_sequence_time(sequence, title=None, fig=None, axs=None): - """ - Creates a graphical summary of a pulse sequence over time. - Showing the pulses at their respective times and durations, as well as the sequence of events in the experiment. - - """ +def draw_sequence(sequence, ax=None,**kwargs): + """ + Draws the sequence as an anotated matplotlib figure, showing + pictorial representations of the pulses and delays in the sequence. It + does not show the phase cycle and nothing is to scale. + + Pulses are drawn with their amplitude envelope and labelled with their + flip angle. Frequency swept pulses are additionally shown with a chirp + of increasing (or decreasing) frequency. Pulses at a frequency other + than the detection frequency are drawn on a separate channel below. + The delay between each consecutive event is annotated beneath the + sequence. + + Evolution axes are colour coded and listed beneath the sequence. + Delays and pulse parameters that change along an evolution axis are + drawn in that axis colour, and labelled with the range they cover. + + Parameters + ---------- + ax : matplotlib.axes.Axes, optional + The axes to draw onto. If None, a new figure is created. + + Returns + ------- + fig : matplotlib.figure.Figure + The figure containing the drawing. + """ + from pyepr.colors import primary_colors, secondary_colors + + time_scales = {"ns": 1, "us": 1e3, "ms": 1e6, "s": 1e9} + + def to_ns(param): + return param.value * time_scales.get(param.unit, 1) + + evo_params = getattr(sequence, "evo_params", None) + if evo_params is None: + raise ValueError("The sequence has no evolution parameters to draw. Please call Sequence.evolution first.") + evo_uuids = [param.uuid for param in evo_params] + evo_colors = {uid: secondary_colors[i % len(secondary_colors)] + for i, uid in enumerate(evo_uuids)} + + def evo_axes(param): + # Offsets from the initial value, for each evolution axis the + # parameter follows + axes = {} + for axis in getattr(param, "axis", []): + if axis["uuid"] in evo_uuids: + axes[axis["uuid"]] = np.asarray(axis["axis"], dtype=float) + return axes + + def fmt_value(value, unit): + if unit in time_scales: + return fmt_delay(value * time_scales[unit]) + if unit in (None, "", "None"): + return f"{value:.4g}" + return f"{value:.5g} {unit}" + + def fmt_range(start, end, unit): + return f"{fmt_value(start, unit)} → {fmt_value(end, unit)}" + + def pulse_evolution(pulse): + # Evolving pulse parameters, other than the start time + lines = [] + for name, param in vars(pulse).items(): + if name == "t" or not isinstance(param, epr.Parameter) or param.value is None: + continue + axes = evo_axes(param) + if len(axes) == 0: + continue + start = param.value + sum(axis[0] for axis in axes.values()) + end = param.value + sum(axis[-1] for axis in axes.values()) + lines.append((f"{name}: {fmt_range(start, end, param.unit)}", + evo_colors[next(iter(axes))])) + return lines + + def centre_freq(pulse): + if hasattr(pulse, "freq"): + return pulse.freq.value + elif hasattr(pulse, "init_freq") and hasattr(pulse, "final_freq"): + return (pulse.init_freq.value + pulse.final_freq.value) / 2 + return 0 + + def is_swept(pulse): + return hasattr(pulse, "init_freq") and hasattr(pulse, "final_freq") + + def flip_label(pulse): + flipangle = getattr(pulse, "flipangle", None) + if flipangle is None or flipangle.value is None: + return "" + if isinstance(flipangle.value, str): + return flipangle.value + frac = flipangle.value / np.pi + for den in range(1, 9): + num = int(np.round(frac * den)) + if num != 0 and np.isclose(num / den, frac): + num_str = {1: "", -1: "-"}.get(num, str(num)) + den_str = "" if den == 1 else f"/{den}" + return rf"${num_str}\pi{den_str}$" + return f"{np.degrees(flipangle.value):.0f}°" + + def pulse_width(pulse): + # Pictorial widths, a pi pulse is twice as wide as a pi/2 pulse + if isinstance(pulse, epr.Detection) or is_swept(pulse): + return 1.2 + flipangle = getattr(pulse, "flipangle", None) + if flipangle is None or not isinstance(flipangle.value, numbers.Number): + width = 0.5 + else: + width = float(np.clip(0.7 * abs(flipangle.value) / np.pi, 0.25, 1.0)) + if isinstance(pulse, (epr.GaussianPulse, epr.SincPulse)): + width = max(width, 0.8) # Shaped pulses need room to show their envelope + return width + + def envelope(pulse): + # Idealised amplitude envelope over x in [-1, 1] + x = np.linspace(-1, 1, 400) + if isinstance(pulse, epr.GaussianPulse): + AM = np.exp(-(x / 0.45)**2) + elif isinstance(pulse, epr.SincPulse): + AM = np.sinc(3 * x) + elif isinstance(pulse, epr.HSPulse): + AM = 1 / np.cosh(4 * np.abs(x)**pulse.order1.value) + elif isinstance(pulse, epr.WURSTPulse): + AM = 1 - np.abs(np.sin(np.pi * x / 2))**pulse.order.value + elif isinstance(pulse, epr.ChirpPulse): + AM = np.clip((1 - np.abs(x)) / 0.15, 0, 1) + AM = np.sin(np.pi / 2 * AM)**2 + else: + return np.array([-1, -1, 1, 1]), np.array([0, 1, 1, 0]) + AM[[0, -1]] = 0 + return x, AM + + def fmt_delay(dt): + if abs(dt) >= 1e3: + return f"{dt/1e3:.4g} µs" + return f"{dt:.4g} ns" + + # Collect the events in time order + events = [pulse for pulse in sequence.pulses + if pulse.t is not None and pulse.t.value is not None] + if len(events) == 0: + raise ValueError("The sequence contains no pulses to draw.") + events.sort(key=lambda pulse: to_ns(pulse.t)) + + # Assign each event to a frequency channel, the observer channel is + # the detection frequency + dets = [pulse for pulse in events if isinstance(pulse, epr.Detection)] + obs_freq = centre_freq(dets[0] if len(dets) > 0 else events[0]) + channel_freqs = [obs_freq] + channels = [] + for pulse in events: + freq = centre_freq(pulse) + match = [i for i, f in enumerate(channel_freqs) if np.isclose(f, freq, atol=1e-4)] + if len(match) == 0: + channel_freqs.append(freq) + match = [len(channel_freqs) - 1] + channels.append(match[0]) + + # Group simultaneous events into slots, evenly spaced along the x-axis + slot_times = [] + slot_axes = [] + slot_of_event = [] + for pulse in events: + t = to_ns(pulse.t) + if len(slot_times) == 0 or not np.isclose(t, slot_times[-1], atol=1e-3): + slot_times.append(t) + scale = time_scales.get(pulse.t.unit, 1) + slot_axes.append({uid: axis * scale for uid, axis in evo_axes(pulse.t).items()}) + slot_of_event.append(len(slot_times) - 1) + + def delay_evolution(i): + # Change of the delay between slot i and i+1 along each evolution axis + diffs = {} + for uid in evo_uuids: + diff = slot_axes[i+1].get(uid, 0) - slot_axes[i].get(uid, 0) + if np.ndim(diff) > 0 and not np.allclose(diff, 0): + diffs[uid] = diff + return diffs + + slot_widths = np.zeros(len(slot_times)) + for pulse, slot in zip(events, slot_of_event): + slot_widths[slot] = max(slot_widths[slot], pulse_width(pulse)) + + slot_x = np.zeros(len(slot_times)) + for i in range(1, len(slot_times)): + slot_x[i] = slot_x[i-1] + slot_widths[i-1]/2 + slot_widths[i]/2 + 1.8 + + # Layout + height = 1.0 + channel_spacing = 2.2 + baselines = [-i * channel_spacing for i in range(len(channel_freqs))] + # Leave room under the bottom channel for evolving pulse parameters + n_bottom_lines = max([len(pulse_evolution(pulse)) for pulse, channel + in zip(events, channels) if channel == len(channel_freqs) - 1]) + arrow_y = baselines[-1] - 0.6 - 0.3 * n_bottom_lines + legend_y = arrow_y - 0.75 + y_min = legend_y - 0.35 * len(evo_params) + (0.2 if len(evo_params) else 0.15) + x_min = slot_x[0] - slot_widths[0]/2 - 1.0 + x_max = slot_x[-1] + slot_widths[-1]/2 + 1.0 + + if ax is None: + fig_width = float(np.clip(0.75 * (x_max - x_min) + 1.5, 6, 18)) + fig_height = 0.7 * (baselines[0] + height + 0.6 - y_min) + 0.6 + fig, ax = plt.subplots(figsize=(fig_width, fig_height)) + else: + fig = ax.figure + + colors = [primary_colors[i % len(primary_colors)] for i in range(len(channel_freqs))] + + # Channel baselines and labels + for i, (y0, freq) in enumerate(zip(baselines, channel_freqs)): + ax.plot([x_min, x_max], [y0, y0], color='k', lw=1.2, zorder=1) + if len(channel_freqs) == 1: + label = "mw" + elif i == 0: + label = r"$\nu_{obs}$" + elif len(channel_freqs) == 2: + label = r"$\nu_{pump}$" + else: + label = rf"$\nu_{{{i+1}}}$" + ax.text(x_min - 0.2, y0 + 0.3*height, label, ha='right', va='center', fontsize=12) + if i > 0: + offset = (freq - obs_freq) * 1e3 + ax.text(x_min - 0.2, y0 - 0.15*height, rf"$\Delta\nu$ = {offset:+.0f} MHz", + ha='right', va='center', fontsize=8, color='0.35') + + # Vertical guides from each event down to the delay arrows + for x in slot_x: + ax.plot([x, x], [arrow_y, baselines[0]], color='0.75', lw=0.8, ls=':', zorder=0) + + # Pulses and detection events + for pulse, slot, channel in zip(events, slot_of_event, channels): + x0 = slot_x[slot] + y0 = baselines[channel] + w = pulse_width(pulse) + color = colors[channel] + + for j, (text, evo_color) in enumerate(pulse_evolution(pulse)): + ax.text(x0, y0 - 0.12 - 0.3*j, text, ha='center', va='top', + fontsize=8, color=evo_color) + + if isinstance(pulse, epr.Detection): + ax.add_patch(plt.Rectangle( + (x0 - w/2, y0), w, height, facecolor=color, alpha=0.1, + edgecolor=color, ls='--', lw=0.8, zorder=1)) + xs = np.linspace(-1, 1, 400) + env = np.exp(-(xs / 0.35)**2) + ax.fill_between(x0 + xs*w/2, y0, y0 + 0.8*height*env, + color=color, alpha=0.25, lw=0, zorder=2) + ax.plot(x0 + xs*w/2, y0 + 0.8*height*env*np.cos(2*np.pi*2.5*xs), + color=color, lw=1.2, zorder=3) + label = "echo" + if hasattr(pulse, "n_echoes"): + label += rf" $\times${pulse.n_echoes.value}" + ax.text(x0, y0 + height + 0.1, label, ha='center', va='bottom', fontsize=10) + continue + + xs, AM = envelope(pulse) + px = x0 + xs*w/2 + ax.fill_between(px, y0, y0 + height*AM, color=color, alpha=0.85 if not is_swept(pulse) else 0.35, + lw=0, zorder=2) + ax.plot(px, y0 + height*AM, color=color, lw=1.0, zorder=3) + + if is_swept(pulse): + # Draw a chirp inside the envelope to show the frequency sweep + xs_fine = np.linspace(-1, 1, 600) + AM_fine = np.interp(xs_fine, xs, AM) + f0, f1 = (2, 9) if pulse.final_freq.value >= pulse.init_freq.value else (9, 2) + u = (xs_fine + 1) / 2 + phase = 2*np.pi*(f0*u + (f1 - f0)*u**2/2) + ax.plot(x0 + xs_fine*w/2, + y0 + 0.5*height*AM_fine*(1 + 0.85*np.sin(phase)), + color=color, lw=0.8, zorder=3) + + ax.text(x0, y0 + height*max(AM.max(), 0) + 0.1, flip_label(pulse), + ha='center', va='bottom', fontsize=12) + + # Delays between consecutive events, evolving delays are coloured by + # their evolution axis and given as a range + for i in range(len(slot_times) - 1): + dt = slot_times[i+1] - slot_times[i] + diffs = delay_evolution(i) + if len(diffs) > 0: + color = evo_colors[next(iter(diffs))] + label = fmt_range(dt + sum(diff[0] for diff in diffs.values()), + dt + sum(diff[-1] for diff in diffs.values()), "ns") + lw = 1.6 + else: + color, label, lw = '0.3', fmt_delay(dt), 0.9 + ax.annotate("", xy=(slot_x[i+1], arrow_y), xytext=(slot_x[i], arrow_y), + arrowprops=dict(arrowstyle='<->', color=color, lw=lw, + shrinkA=0, shrinkB=0)) + ax.text((slot_x[i] + slot_x[i+1]) / 2, arrow_y - 0.12, label, + ha='center', va='top', fontsize=9, + color='k' if len(diffs) == 0 else color) + + # Legend of the evolution axes + for i, param in enumerate(evo_params): + axis = evo_axes(param).get(param.uuid, param.axis[0]["axis"]) + ax.text(x_min, legend_y - 0.35*i, + f"■ Axis {i+1}: {param.name}, " + f"{fmt_range(param.value + axis[0], param.value + axis[-1], param.unit)}" + f" ({len(axis)} pts)", + ha='left', va='top', fontsize=9, color=evo_colors[param.uuid]) + + ax.set_xlim(x_min - 0.2, x_max) + ax.set_ylim(y_min, baselines[0] + height + 0.6) + ax.set_title(kwargs.get("title", sequence.name)) + ax.axis('off') - pass \ No newline at end of file + return fig \ No newline at end of file diff --git a/pyepr/resonator_tune.py b/pyepr/resonator_tune.py index 22b5302..727a9e9 100644 --- a/pyepr/resonator_tune.py +++ b/pyepr/resonator_tune.py @@ -1,4 +1,6 @@ -from pyepr import Sequence, Parameter, Detection, ChirpPulse, RectPulse +from pyepr.sequences import Sequence +from pyepr.classes import Parameter +from pyepr.pulses import Detection, ChirpPulse, RectPulse class LoSweepTuneSequence(Sequence): diff --git a/pyepr/sequences/DEER.py b/pyepr/sequences/DEER.py new file mode 100644 index 0000000..c50ce74 --- /dev/null +++ b/pyepr/sequences/DEER.py @@ -0,0 +1,190 @@ +# This file contains the object definitions for DEER Sequences +# + +import pyepr.pulses as p +from pyepr.sequences import Sequence +from warnings import warn +import numpy as np +import deerlab as dl +from pyepr.utils import val_in_us, add_phaseshift +from pyepr.classes import Parameter + +class FourPulseDEERSequence(Sequence): + """ + Class for the 4-pulse DEER sequence. + """ + + def __init__(self, *, B, freq,reptime,averages, shots, + tau1, tau2, step=8, start=None, dim=None, + phase_cycle='16-step', + **kwargs): + r""" + Initialize the 4-pulse DEER sequence. + + Sequence: + [\pi/2 - \tau_1 - \pi - t \pi_{pump} - (\tau_2+\tau_1-t) - \pi - echo] + + Parameters + ---------- + B : int or float + The B0 field, in Gauss + freq : int or float + The freq frequency in GHz + reptime : _type_ + The shot repetition time in us + averages : int + The number of scans. + shots : int + The number of shots per point + tau1 : int or float + The first interpulse delay in us + tau2 : int or float + The second interpulse delay in us + step : int or float + The step size for the DEER time in ns, by default it is 8 ns + start : int or float + The starting DEER time in us, also known as tmin. If it is None then it is 180ns before tau2. By default it is None. + dim : int + The number of points in the DEER time, by default it is calculated from the step and start values, and stops at tau2 + phase_cycle : str|list, optional + The phase cycling scheme to use. Either a pre-defined option + ('16-step' or 'DC'), can be supplied or a list of the phase cycles + for each pulse. Default is '16-step'. + + Examples + -------- + + .. plot:: + :include-source: + + import pyepr as epr + import numpy as np + from pyepr.sequences.DEER import FourPulseDEERSequence + N_gyro = 0.002803632236095 + freq = 34 + + exc_pulse = epr.GaussianPulse(tp=32,freq=0,flipangle=np.pi/2) + ref_pulse = epr.GaussianPulse(tp=32,freq=0,flipangle=np.pi) + pump_pulse = epr.ChirpPulse(tp=200,init_freq=-0.10,final_freq=-0.05,flipangle=np.pi) + seq = FourPulseDEERSequence( + B=freq/N_gyro, + freq=freq, + reptime=3e3, + averages=1, + shots=10, + tau1=0.4, + tau2=4, + step=8, + start=0.28, + phase_cycle='16-step', + exc_pulse=exc_pulse, + ref_pulse=ref_pulse, + pump_pulse=pump_pulse + ) + + seq.draw() + print(seq) + """ + name = kwargs.pop('name',"FourPulseDEER") + + self._base_pulses = {} + self._base_pulses['exc'] = kwargs.pop('exc_pulse', p.RectPulse(tp=16, freq=0, flipangle=np.pi/2)) + self._base_pulses['pump'] = kwargs.pop('pump_pulse', p.RectPulse(tp=32, freq=-0.1, flipangle=np.pi)) + self._base_pulses['ref'] = kwargs.pop('ref_pulse', p.RectPulse(tp=32, freq=0, flipangle=np.pi)) + self._base_pulses['det'] = kwargs.pop('det_pulse', p.Detection(tp=256,freq=self._base_pulses['exc'].freq.value)) + + if self._base_pulses['det'].freq.value != self._base_pulses['exc'].freq.value: + warn("The detection pulse frequency is not equal to the excitation pulse frequency. This may lead to unexpected results.") + + + self.tau1: Parameter = Parameter(name="tau1", value=tau1*1e3, unit="ns", description="Interpulse Delay 1", virtual=True) + """The first interpulse delay parameter in ns.""" + self.tau2: Parameter = Parameter(name="tau2", value=tau2*1e3, unit="ns", description="Interpulse Delay 2", virtual=True) + """The second interpulse delay parameter in ns.""" + if start is None: + start = tau1*1e3 - 180 # Start 180ns before tau2 + else: + start *= 1e3 # Convert to ns + if dim is None: + dim = int(tau2*1e3 / step) + 1 + + self.t: Parameter = Parameter(name="t", value=start, step=step, dim=dim, unit="ns", description="DEER Time", virtual=True) + """The pump pulse position parameter in ns.""" + super().__init__(name=name, B=B, freq=freq, reptime=reptime, averages=averages, shots=shots) + + self._build_sequence() + self._build_pcyc(phase_cycle) + + self.evolution([self.t]) + + def _build_sequence(self): + + self.addPulse(self._base_pulses['exc'].copy(t=0, pcyc={'phases':[0], 'dets':[1]})) + self.addPulse(self._base_pulses['ref'].copy(t=self.tau1, pcyc={'phases':[0], 'dets':[1]})) + self.addPulse(self._base_pulses['pump'].copy(t=self.tau1+self.t, pcyc={'phases':[0], 'dets':[1]})) + self.addPulse(self._base_pulses['ref'].copy(t=2*self.tau1+self.tau2, pcyc={'phases':[0], 'dets':[1]})) + self.addPulse(self._base_pulses['det'].copy(t=2*(self.tau1+self.tau2)+self._base_pulses['ref'].tp.value, pcyc={'phases':[0], 'dets':[1]})) + + + def _build_pcyc(self, phase_cycle): + + if isinstance(phase_cycle,list): + if len(phase_cycle) != 4: + raise ValueError("Phase cycle list must have 4 elements, one for each pulse.") + self._pcyc = phase_cycle + self.pcyc_name = "Custom Phase Cycle" + + elif phase_cycle == '16-step': + self._pcyc = [ + [[0],[1]], # No phase cycling for the excitation pulse + [[0, np.pi/2, np.pi, -np.pi/2], [1, -1, 1, -1]], + [[0, np.pi/2, np.pi, -np.pi/2], [1, 1, 1, 1]], + [[0],[1]], + ] + self.pcyc_name = "16-step" + elif phase_cycle == '2-step': # Used only when the pump pulse is + self._pcyc = [ + [[0,np.pi],[1,-1]], # No phase cycling for the excitation pulse + [[0],[1]], + [[0],[1]], + [[0],[1]], + ] + self.pcyc_name = "2-step" + else: + raise ValueError("Invalid phase cycle option. Choose from '16-step', '2-step', or provide a list of 4 phase cycles.") + + for i in range(len(self.pulses)-1): + self.pulses[i]._addPhaseCycle(*self._pcyc[i]) + + self._buildPhaseCycle() + + + def simulate(self,**kwargs): + tau1 = val_in_us(self.tau1) + tau2 = val_in_us(self.tau2) + t = val_in_us(self.t) + + experimentInfo = dl.ex_4pdeer(tau1=tau1,tau2=tau2,pathways=[1,2,3]) + reftimes = dict(zip(["reftime1","reftime2","reftime3"],experimentInfo.reftimes(tau1,tau2))) + mod_depths = {"lam1":0.4, "lam2":0.1, "lam3":0.2} + + r = np.linspace(0.5,10,100) + rmean = kwargs.pop('rmean', 4.0) + rstd = kwargs.pop('rstd', 0.75) + conc = kwargs.pop('conc', 100) + + Vmodel = dl.dipolarmodel(t,r,Pmodel=dl.dd_gauss, experiment=experimentInfo) + Vsim = Vmodel(mean=rmean, std=rstd, conc=conc, scale=1, **reftimes, **mod_depths) + + Vsim = add_phaseshift(Vsim, 0.05) + return t, Vsim + + +class FivePulseDEERSequence(Sequence): + + pass + + +class ThreePulseDEERSequence(Sequence): + + pass \ No newline at end of file diff --git a/pyepr/sequences/ESEEM.py b/pyepr/sequences/ESEEM.py new file mode 100644 index 0000000..d622176 --- /dev/null +++ b/pyepr/sequences/ESEEM.py @@ -0,0 +1,211 @@ +import pyepr.pulses as p +from pyepr.sequences import Sequence +from pyepr.classes import Parameter +from warnings import warn +import numpy as np + + +class ThreePulseESEEMSequence(Sequence): + + def __init__(self, *, B, freq, reptime, averages, shots, tau=300, start=500, step=40, dim=200, **kwargs) -> None: + """ + Creates a Three Pulse ESEEM sequence object. + In the form of [\pi/2 - \tau - \pi/2 - T - \pi/2 - echo] + + Parameters + ---------- + B : float + The B0 field in Gauss. + freq : float + The frequency in GHz. + reptime : float + The shot repetition time in us. + averages : int + The number of scans. + shots : int + The number of shots per point. + tau : float, optional + The first interpulse delay in us, by default 300. + start : float, optional + The starting mixing time in ns, by default 500. + step : float, optional + The step size for the mixing time in ns, by default 40. + dim : int, optional + The number of points in the mixing time, by default 200. + pi2_pulse : Pulse, optional + The pi/2 pulse to use, by default None. If None, a RectPulse will be used. + pi_pulse : Pulse, optional + The pi pulse to use, by default None. If None, a RectPulse will be used. + + + Examples + -------- + .. plot:: + :include-source: + + import pyepr as epr + epr.set_waveform_precision(1) + seq = epr.ThreePulseESEEMSequence( + B=12000, freq=34, reptime=1000, averages=1, shots=10, + tau=300, start=500, step=40, dim=200) + seq.draw() + + """ + + self.tau: Parameter = Parameter(name="tau", value=start,step=step,dim=dim, unit="ns", description="1st Inter Pulse Delay",virtual=True) + """First Interpulse Delay parameter in ns.""" + + self.T: Parameter = Parameter( + name='T', + description = 'Mixing Time', + unit = 'ns', + value=start, + step = step, + dim = dim, + virtual=True) + """1st Mixing Time parameter in ns.""" + + super().__init__(name="ThreePulseESEEMSequence", + B=B, freq=freq, reptime=reptime, averages=averages, shots=shots, **kwargs) + + self._build_sequence() + + def _build_sequence(self): + if hasattr(self, "pi2_pulse"): + self.addPulse(self.pi2_pulse.copy( + t=0, pcyc={"phases":[0, np.pi], "dets": [1, -1]})) + else: + self.addPulse(p.RectPulse( # pi/2 + t=0, tp=16, freq=0, flipangle=np.pi/2, + pcyc={"phases":[0, np.pi], "dets": [1, -1]} + )) + + if hasattr(self, "pi2_pulse"): + self.addPulse(self.pi2_pulse.copy( + t=self.tau)) + else: + self.addPulse(p.RectPulse( # pi/2 + t=self.tau, tp=32, freq=0, flipangle=np.pi + )) + + if hasattr(self, "pi2_pulse"): + self.addPulse(self.pi2_pulse.copy( + t=self.tau+self.T)) + else: + self.addPulse(p.RectPulse( # pi/2 + t=self.tau+self.T, tp=32, freq=0, flipangle=np.pi + )) + + self.addPulse(p.Detection(t=self.tau+self.T+self.tau, tp=512)) + + self.evolution([self.T]) + + def _simulate(self): + raise NotImplementedError("Simulation for Three Pulse ESEEM is not implemented yet.") + + +class HYSCORESequence(Sequence): + def __init__(self, *, B, freq, reptime, averages, shots, tau=300, start=300, step=16, dim=128, **kwargs) -> None: + """ + Creates a HYSCORE sequence object. + In the form of [\pi/2 - \tau - \pi/2 - T1 - \pi - T2 - \pi/2 - echo] + + Parameters + ---------- + B : float + The B0 field in Gauss. + freq : float + The frequency in GHz. + reptime : float + The shot repetition time in us. + averages : int + The number of scans. + shots : int + The number of shots per point. + tau : float, optional + The first interpulse delay in us, by default 300. + start : float, optional + The starting mixing time in ns, by default 300. + step : float, optional + The step size for the mixing time in ns, by default 16. + dim : int, optional + The number of points in the mixing time, by default 128. + + Examples + -------- + .. plot:: + :include-source: + + import pyepr as epr + epr.set_waveform_precision(1) + + seq = epr.HYSCORESequence( + B=12000, freq=34, reptime=1000, averages=1, shots=10, + tau=300, start=300, step=16, dim=128) + seq.draw() + + """ + + self.tau: Parameter = Parameter( + name="tau", value=start,step=step, dim=dim, unit="ns", + description="1st Inter Pulse Delay",virtual=True) + """First Interpulse Delay parameter in ns.""" + + self.T1: Parameter = Parameter( + name='T1', + description = '1st Mixing Time', + unit = 'ns', + value=start, + step = step, + dim = dim, + virtual=True) + """1st Mixing Time parameter in ns.""" + + self.T2: Parameter = Parameter( + name='T2', + description = '2nd Mixing Time', + unit = 'ns', + value=start, + step = step, + dim = dim, + virtual=True) + """2nd Mixing Time parameter in ns.""" + + super().__init__( + name = "HYSCORESequence", + B=B, freq=freq, reptime=reptime, averages=averages, shots=shots, **kwargs) + + self._build_sequence() + + def _build_sequence(self): + + if hasattr(self, "pi2_pulse"): + p90 = self.pi2_pulse.copy(t=0, pcyc={'phases':[0], 'dets':[1]}) + else: + p90 = p.RectPulse( # pi/2 + t=0, tp=16, freq=0, flipangle=np.pi/2, + pcyc={"phases":[0], "dets": [1]} + ) + + if hasattr(self, "pi_pulse"): + p180 = self.pi_pulse.copy(t=0, pcyc={'phases':[0], 'dets':[1]}) + else: + p180 = p.RectPulse( # pi + t=0, tp=32, freq=0, flipangle=np.pi, + pcyc={"phases":[0], "dets": [1]} + ) + + det_event = p.Detection(t=0, tp=512) + + + self.addPulse(p90.copy(t=0, pcyc={'phases':[0], 'dets':[1]})) + self.addPulse(p90.copy(t=self.tau, pcyc={'phases':[0], 'dets':[1]})) + self.addPulse(p180.copy(t=self.tau+self.T1,pcyc={'phases':[0,np.pi/2,np.pi,3*np.pi/2,], 'dets':[1,-1,1,-1]})) + self.addPulse(p90.copy(t=self.tau+self.T1+self.T2,pcyc={'phases':[0], 'dets':[1]})) + + self.addPulse(det_event.copy(t=2*self.tau+self.T1+self.T2)) + self._buildPhaseCycle() + self.evolution([self.T1,self.T2]) + + def simulate(self): + raise NotImplementedError("Simulation for HYSCORE is not implemented yet.") \ No newline at end of file diff --git a/pyepr/sequences/__init__.py b/pyepr/sequences/__init__.py new file mode 100644 index 0000000..933a8a4 --- /dev/null +++ b/pyepr/sequences/__init__.py @@ -0,0 +1,3 @@ +from .base_sequences import * +from .DEER import * +from .ESEEM import * \ No newline at end of file diff --git a/pyepr/sequences/base_sequences.py b/pyepr/sequences/base_sequences.py new file mode 100644 index 0000000..b92383c --- /dev/null +++ b/pyepr/sequences/base_sequences.py @@ -0,0 +1,1633 @@ +from pyepr.classes import Parameter +from pyepr.pulses import Pulse, Detection, Delay, RectPulse +from pyepr.utils import val_in_ns, val_in_us, add_phaseshift, _gen_ESEEM +from pyepr.fieldsweep_analysis import create_Nmodel +from pyepr.plotting import draw_sequence +import pyepr.pulses as ad_pulses +import numpy as np +import matplotlib.pyplot as plt +import json +from itertools import product +import copy +from pyepr.utils import build_table, autoEPRDecoder +import json +from pyepr._version import __version__ +import uuid +import base64 +import numbers +import warnings + +__all__ = [ + 'Sequence', 'HahnEchoSequence', 'T1InversionRecoverySequence', + 'HahnEchoRelaxationSequence', 'T2RelaxationSequence', 'FieldSweepSequence', + 'ReptimeScan', 'CarrPurcellSequence', 'ResonatorProfileSequence', + 'TWTProfileSequence', 'KBBSequence', 'KBBPulseProfileSequence', +] + +class Sequence: + """ + Represents an experimental pulse sequence. + """ + + def __init__( + self, *, name, B, reptime, averages, shots,LO=None, freq=None, **kwargs) -> None: + """Represents an experimental pulse sequence. + + Parameters + ---------- + name : str + The name of this pulse sequence + B : float + The magnetic field for this sequence in Gauss. + freq : float + The central frequency of this sequence. I.e. The frequnecy at which + a zero offset pulse is at. + reptime : float + The shot repetition time in us. + averages : int + The number of scans to be accumulated. + shots : itn + The number of shots per point. + LO : float + The now deprecated local oscillator frequency. freq should be used. + """ + + self.pulses:list = [] + """"The list of pulses in this sequence.""" + + self._axes_uuid = [] + self._reduce_uuid = [] + + if isinstance(B, Parameter): + self.B = B.copy() + else: + self.B = Parameter( + "B", B, "Gauss", + "The static B0 field for the experiment") + + if freq is not None: + self.freq = Parameter( + "freq", freq, "GHz", + "The central frequency of the sequence") + elif LO is not None: + self.freq = Parameter( + "freq", LO, "GHz", + "The central frequency of the sequence") + warnings.warn("LO is deprecated, please use freq instead", DeprecationWarning, stacklevel=2) + else: + raise ValueError("Either freq or LO must be specified") + + if isinstance(reptime, Parameter): + self.reptime = reptime.copy() + else: + self.reptime = Parameter( + "reptime", reptime, "us", + "The shot repetition time") + + self.averages = Parameter("averages", int(averages), "None", + "The number of averages to perform.") + + self.shots = Parameter( + "shots", int(shots), "None", + "The number of shots per scan.") + + if "det_window" in kwargs: + self.det_window = Parameter( + "det_window", kwargs["det_window"], "None", + "The length of the default detection gate" + ) + else: + self.det_window = Parameter( + "det_window", 128, "None", + "The length of the default detection gate" + ) + + + self.name: str = name + """The name of this pulse sequence.""" + self.progTable: dict = {"EventID": [], "Variable": [], "axis": [], + "axID": [], "uuid": [], "reduce": []} + """The program table for this sequence, which is used to generate the pulse program. Has columns for EventID, Variable, axis, axID, uuid, and reduce.""" + self.evo_params: list[Parameter] = [] + """The list of evolution parameters for this sequence, which are used to define the evolution axes of the sequence.""" + + pass + + + @property + def num_pulses(self) -> int: + """The number of pulses in this sequence.""" + return len(self.pulses) + + def plot(self) -> None: + + pass + + def plot_pulse_exc(self, FieldSweep=None, ResonatorProfile=None): + + if FieldSweep is not None: + data = FieldSweep.data + data /= np.max(np.abs(data)) + ax = FieldSweep.fs_x + plt.plot(ax, data, label="Field Sweep", color='r') + + if ResonatorProfile is not None: + data = ResonatorProfile.prof_data / ResonatorProfile.prof_data.max() + plt.plot(ResonatorProfile.prof_frqs-self.LO.value, data, label="Resonator Profile", color='k') + + + def check_array_new(list,array, return_pos=False): + test = True + for i, ele in enumerate(list): + if np.allclose( + ele,array,rtol=1e-03, atol=1e-03, equal_nan=True): + test = False + if return_pos: + return i + return test + + axs = [] + fts = [] + labels = [] + for i, pulse in enumerate(self.pulses): + if type(pulse) == Delay: + continue + elif type(pulse) == Detection: + continue + ax, ft = pulse._calc_fft(1e4) + + if check_array_new(fts, ft): + axs.append(ax) + fts.append(ft) + labels.append([i]) + else: + j = check_array_new(fts, ft, return_pos=True) + labels[j].append(i) + + hatches = ['/', '\\', '|', '-', 'o', '.'] + + + for i in range(0,len(axs)): + ft = np.abs(fts[i]) + ft /= np.max(ft) + plt.fill(axs[i],ft, + label=f"Pulse id={str(labels[i])[1:-1]}", + hatch=hatches.pop(), alpha=0.3) + + plt.xlabel("Frequency (GHz)") + plt.legend() + + # Set correct axis, find mim and max freq + + for i, pulse in enumerate(self.pulses): + if hasattr(pulse, "freq"): + p_min = pulse.freq.value + p_max = pulse.freq.value + elif hasattr(pulse, "init_freq") & hasattr(pulse, "final_freq"): + p_min = pulse.init_freq.value + p_max = pulse.final_freq.value + elif hasattr(pulse, "init_freq") & hasattr(pulse, "BW"): + p_min = pulse.init_freq.value + p_max = p_min + pulse.BW.value + elif hasattr(pulse, "final_freq") & hasattr(pulse, "BW"): + p_max = pulse.init_freq.value + p_min = p_max - pulse.BW.value + # Check p_min < p_max + if p_min > p_max: + p_temp = p_min + p_min = p_max + p_max = p_temp + if i == 0: + min_frq = p_min + max_frq = p_max + else: + if min_frq > p_min: + min_frq = p_min + if max_frq < p_max: + max_frq = p_max + + min_frq = np.floor(min_frq*100)/100 - 0.2 + max_frq = np.ceil(max_frq*100)/100 + 0.2 + plt.xlim(min_frq, max_frq) + + + pass + + def draw(self, **kwargs): + """ + Draws the sequence as an annotated matplotlib figure, showing pictorial representations of the pulses and delays in the sequence. + Calls the `draw_sequence` function from the `pyepr.plotting` module. + """ + return draw_sequence(self, **kwargs) + + def addPulse(self, pulse): + """Adds a pulse to the next position in the sequence. + + Parameters + ---------- + pulse : Pulse + The object describing the pulse. + """ + if type(pulse) == Pulse or issubclass(type(pulse), Pulse): + self.pulses.append(pulse) + + elif type(pulse) == list: + for el in pulse: + self.pulses.append(el) + self._buildPhaseCycle() + self._estimate_time() + + def _estimate_time(self) -> float: + """ + Calculates the estimated experiment time in seconds. + """ + self._buildPhaseCycle() + acqs = self.averages.value * self.shots.value * self.pcyc_dets.shape[0] + + reptime = np.mean(val_in_us(self.reptime)) + if hasattr(self,'evo_params'): + acqs *= np.prod([np.prod(param.dim) for param in self.evo_params]) + time = acqs * reptime * 1e-6 + + self.time = Parameter(name="time", value=f"{(time // 3600):.0f}:{(time % 3600) // 60:.0f}:{(time % 60):.0f}", unit="HH:MM:SS", + description="Estimated sequence run time") + return time + + def _buildPhaseCycle(self): + # Group phase-cycled pulses by link target, so linked pulses step + # through their phase cycle in phase (zipped) instead of being + # combined via a full outer product with the rest of the sequence. + groups = {} + for pulse in self.pulses: + if pulse.pcyc is None: + continue + link = pulse.pcyc.get("link") + key = pulse.uuid if link is None else link + groups.setdefault(key, []).append(pulse) + groups = list(groups.values()) + + phase_axes = [list(zip(*(p.pcyc["Phases"] for p in g))) for g in groups] + det_axes = [list(zip(*(p.pcyc["DetSigns"] for p in g))) for g in groups] + + self.pcyc_vars = [self.pulses.index(p) for g in groups for p in g] + self.pcyc_cycles = np.array([ + [phase for phases in row for phase in phases] + for row in product(*phase_axes)]) + self.pcyc_dets = np.array([ + np.prod([det for dets in row for det in dets]) + for row in product(*det_axes)]) + + return self.pcyc_vars, self.pcyc_cycles, self.pcyc_dets + + def evolution(self, params, reduce=[]): + """ + Sets what parameters are being evolved in the sequence, and which are + being automatically. + + `self.evo_params = params` + + Parameters + ---------- + params : list + A list of Parameter objects which are being evolved. Each every + entry in the list will be a new axis in the sequence. Only one parameter + per axis should be specified. + reduce : list + A list of Parameter objects which are being reduced. These are the + parameters which are being averaged over. These parameters should + also be in the params list. + + Returns + ------- + progTable : dict + A dictionary containing the progression of the sequence. + + + """ + self.evo_params = params + self._axes_uuid = [param.uuid for param in params] + self._reduce_uuid = [param.uuid for param in reduce] + + self._buildProgTable() + + + def _buildProgTable(self): + + progTable = {"EventID": [], "Variable": [], "axis": [], + "axID": [], "uuid": [], "reduce": []} + + for n, pulse in enumerate(self.pulses): + table = pulse.build_table() + for i in range(len(table["uuid"])): + if table["uuid"][i] in self._axes_uuid: + progTable["axID"].append(self._axes_uuid.index(table["uuid"][i])) + progTable["uuid"].append(table["uuid"][i]) + progTable["EventID"].append(n) + progTable["Variable"].append(table["Variable"][i]) + progTable["axis"].append(table["axis"][i]) + if table["uuid"][i] in self._reduce_uuid: + progTable["reduce"].append(True) + else: + progTable["reduce"].append(False) + + for var_name in vars(self): + var = getattr(self, var_name) + if type(var) is Parameter: + if not var.is_static() and not var.virtual: + for i in range(len(var.axis)): + if var.axis[i]["uuid"] in self._axes_uuid: + progTable["axID"].append(self._axes_uuid.index(var.axis[i]["uuid"])) + progTable["EventID"].append(None) + progTable["Variable"].append(var_name) + progTable["axis" ].append(var.axis[i]["axis"]) + progTable["uuid"].append(var.axis[i]["uuid"]) + if var.axis[i]["uuid"] in self._reduce_uuid: + progTable["reduce"].append(True) + else: + progTable["reduce"].append(False) + self.progTable = progTable + self._estimate_time() + return self.progTable + + @property + def seqtable_steps(self) -> int: + """The number of steps in the sequence table, which is the product of the number of phase cycle detections, the number of phase cycle variables, and the product of the dimensions of the evolution parameters.""" + if len(self.evo_params) > 0: + return self.pcyc_dets.shape[0] * (len(self.pcyc_vars)+1) * np.prod([np.prod(param.dim) for param in self.evo_params]) + + @property + def shape(self) -> list[int]: + """ + Gives the shape of the sequence,excluding the number of shots. + + Returns + ------- + list + [nAvgs, axes_dims, nPcyc] + + """ + nAvgs = self.averages.value + nPcyc = self.pcyc_dets.shape[0] + nAxes = len(self.evo_params) + if nAxes > 0: + axes_dim = [] + for i in range(nAxes): + axes_dim.append(self.evo_params[i].dim[0]) + else: + axes_dim = [1] + + # Flip the axes dim so it is Z,Y,X... + axes_dim = axes_dim[::-1] + + shape = [nAvgs]+ axes_dim +[nPcyc] + + # Force list output to all be int + shape = np.array(shape).astype(int).tolist() + + return shape + + + + def adjust_step(self,waveform_precision): + """ + Adjust the step size of all axes and pulses to be an integer multiple of the waveform precision + This is to ensure that the waveform is generated correctly by the specific AWG + + Parameters + ---------- + waveform_precision : float + The precision of the waveform in ns + + """ + + for param in self.evo_params: + param.adjust_step(waveform_precision) + for pulse in self.pulses: + pulse.t.adjust_step(waveform_precision) + pulse.tp.adjust_step(waveform_precision) + + self._buildProgTable() + return self + + def shift_detfreq_to_zero(self): + """Shifts the detection frequency of all pulses to zero, by subtracting the detection frequency from all pulses and the sequence frequency.""" + det_pulse = None + for pulse in self.pulses: + if isinstance(pulse,Detection): + det_pulse = pulse + + det_freq = det_pulse.freq.value + self.freq.value -= det_freq + for pulse in self.pulses: + if hasattr(pulse,'freq'): + pulse.freq.value -= det_freq + if hasattr(pulse,'init_freq'): + pulse.init_freq.value -= det_freq + if hasattr(pulse,'final_freq'): + pulse.final_freq.value -= det_freq + return self + + def _checkRect(self) -> bool: + """Checks if all the pulses in the sequence are rectangular. + """ + test = True + + for pulse in self.pulses: + if type(pulse) is not RectPulse: + test = False + + return test + + def __str__(self): + + header = "#" * 79 + "\n" + "PyEPR Sequence Definition" + \ + "\n" + "#" * 79 + "\n" + + # Sequence Parameters + seq_param_string = "Sequence Parameters: \n" + seq_param_string += "{:<10} {:<12} {:<10} {:<30} \n".format( + 'Name', 'Value', 'Unit', 'Description') + + for param_key in vars(self): + param = getattr(self, param_key) + if type(param) is Parameter: + if param.unit is None: + unit = "" + else: + unit = param.unit + if type(param.value) is str: + seq_param_string += "{:<10} {:<12} {:<10} {:<30} \n".format( + param.name, param.value, unit, param.description) + elif param.value is None: + seq_param_string += "{:<10} {:<12} {:<10} {:<30} \n".format( + param.name, "None", unit, param.description) + else: + seq_param_string += "{:<10} {:<12.5g} {:<10} {:<30} \n".format( + param.name, param.value, unit, param.description) + + # Pulses + pulses_string = "\nEvents (Pulses, Delays, etc...): \n" + + params = ['iD', 't', 'tp', 'scale', 'type', 'Phase Cycle'] + params_widths = ["4", "8", "8", "8", "14", "40"] + + pulses_string += build_table(self.pulses, params, params_widths) + + def print_event_id(i): + if prog_table["EventID"][i] is None: + return "Seq" + else: + return str(prog_table["EventID"][i]) + + def get_unit(i): + pulse_num = prog_table["EventID"][i] + if pulse_num is None: + param = getattr(self, prog_table["Variable"][i]) + else: + param = getattr( + self.pulses[pulse_num], prog_table["Variable"][i]) + + if param.unit is None: + return "None" + else: + return param.unit + + + def test_unique_step(array): + diffs = np.diff(array)-np.diff(array)[0] + return np.isclose(diffs,np.zeros(diffs.shape)).all() + + # Progressive elements + prog_string = "\nProgression: \n" + if len(self.progTable["axID"]) >= 1: + prog_string += "{:<10} {:<10} {:<10} {:<10} {:<10} {:<10} \n".format( + 'Pulse', 'Prog. Axis', 'Parameter', 'Step', 'Dim', 'Unit') + for i in range(0, len(self.progTable["axID"])): + prog_table = self.progTable + axis = prog_table["axis"][i] + if test_unique_step(axis): + step = np.unique(np.diff(axis))[0] + fstring = "{:<10} {:<10} {:<10} {:<10.5g} {:<10} {:<10} \n" + else: + step = "Var" + fstring = "{:<10} {:<10} {:<10} {:<10} {:<10} {:<10} \n" + + prog_string += fstring.format( + print_event_id(i), prog_table["axID"][i], + prog_table["Variable"][i], step, + prog_table["axis"][i].shape[0], get_unit(i)) + + footer = "#" * 79 + "\n" +\ + f"Built by PyEPR Version: {__version__}" + "\n" + "#" * 79 + + return header + seq_param_string + pulses_string + prog_string + footer + + def copy(self): + """Deep copy the sequence object, including all pulses and parameters.""" + return copy.deepcopy(self) + + def _to_dict(self): + to_return = {"version": __version__, "type": "Sequence", "subclass": str(type(self))} + + for key, var in vars(self).items(): + if isinstance(var, Parameter): + to_return[key] = var._to_dict() + if key == "pulses": + new_list = [] + for pulse in var: + new_list.append(pulse._to_dict()) + to_return[key] = new_list + else: + to_return[key] = var + + return to_return + + def _to_json(self): + class autoEPREncoder(json.JSONEncoder): + def default(self, obj): + if isinstance(obj, np.ndarray): + if (len(obj) > 0 ) and isinstance(obj[0], str): + return list(obj) + data = np.ascontiguousarray(obj.data) + data_b64 = base64.b64encode(data) + return dict(__ndarray__=str(data_b64), + dtype=str(obj.dtype), + shape=obj.shape) + if isinstance(obj, complex): + return str(obj) + if isinstance(obj, numbers.Number): + return str(obj) + if isinstance(obj, uuid.UUID): + return_dict = {"__uuid__": str(obj)} + return return_dict + if isinstance(obj, Parameter): + return obj._to_dict() + if isinstance(obj, Pulse): + return obj._to_dict() + if isinstance(obj, Sequence): + return obj._to_dict() + else: + return json.JSONEncoder.default(self, obj) + + return json.dumps(self._to_dict(), cls=autoEPREncoder, indent=4) + + def save(self, filename): + """Save the sequence to a JSON file. + + Parameters + ---------- + filename : str + Path to the JSON file. + + Returns + ------- + None + + Raises + ------ + TypeError + If the object cannot be serialized to JSON. + + Example + ------- + >>> obj = Sequence() + >>> obj.save("my_sequence.json") + """ + + + with open(filename, "w") as f: + f.write(self._to_json()) + + @classmethod + def _from_dict(cls, dct): + name = dct["name"] + B = Parameter._from_dict(dct["B"]) + freq = Parameter._from_dict(dct["freq"]) + reptime = Parameter._from_dict(dct["reptime"]) + averages = Parameter._from_dict(dct["averages"]) + shots = Parameter._from_dict(dct["shots"]) + new_sequence = cls( + name=name, B=B, freq=freq, reptime=reptime, averages=averages, shots=shots + ) + for key, var in dct.items(): + if isinstance(var, dict) and ("type" in var): + setattr(new_sequence, key, Parameter._from_dict(var)) + elif key == "pulses": + for pulse in var: + if hasattr(ad_pulses,pulse['type']): + new_sequence.pulses.append( + getattr(ad_pulses,pulse['type'])._from_dict(pulse)) + else: + new_sequence.pulses.append( + Pulse._from_dict(pulse)) + else: + setattr(new_sequence, key, var) + + return new_sequence + + @classmethod + def _from_json(cls, JSONstring): + dct = json.loads(JSONstring, object_hook=autoEPRDecoder) + return cls._from_dict(dct) + + @classmethod + def load(cls, filename): + """Load an object from a JSON file. + + Parameters + ---------- + filename : str + Path to the JSON file. + + Returns + ------- + obj : Sequence + The Sequence loaded from the JSON file. + + Raises + ------ + FileNotFoundError + If the file does not exist. + + Example + ------- + >>> obj = Sequence.load("my_sequence.json") + """ + with open(filename, "r") as f: + file_buffer = f.read() + return cls._from_json(file_buffer) + +# ============================================================================= +# Subclasses +# ============================================================================= + +class HahnEchoSequence(Sequence): + """ + Represents a Hahn-Echo sequence. + """ + def __init__(self, *, B, freq, reptime, averages, shots, **kwargs) -> None: + r"""Build a Hahn-Echo sequence using either rectangular pulses or + specified pulses. By default no progression is added to this sequence. + + Sequence: + [\pi/2 - \tau - \pi - \tau - echo] + + Parameters + ---------- + B : int or float + The B0 field, in Gauss + freq : int or float + The freq frequency in GHz + reptime : _type_ + The shot repetition time in us + averages : int + The number of scans. + shots : int + The number of shots per point + + Optional Parameters + ------------------- + pi2_pulse : Pulse + An autoEPR Pulse object describing the excitation pi/2 pulse. If + not specified a RectPulse will be created instead. + pi_pulse : Pulse + An autoEPR Pulse object describing the refocusing pi pulses. If + not specified a RectPulse will be created instead. + det_event : Pulse + An autoEPR Pulse object describing the detection even. If + not specified a standard detection event will be created instead, + with an offset frequency of 0MHz. + + .. plot:: + :include-source: + + import pyepr as epr + import numpy as np + + epr.set_waveform_precision(1) + seq = epr.HahnEchoRelaxationSequence( + B=12000, freq=34, reptime=1e3, averages=1, shots=10, start=300, step=40, dim=200) + seq.draw() + + + """ + + name = kwargs.pop('name',"HahnEchoSequence") + + if "pi_pulse" in kwargs: + self.pi_pulse = kwargs["pi_pulse"] + if "pi2_pulse" in kwargs: + self.pi2_pulse = kwargs["pi2_pulse"] + if "det_event" in kwargs: + self.det_event = kwargs["det_event"] + + + super().__init__( + name=name, B=B, freq=freq, reptime=reptime, averages=averages, + shots=shots, **kwargs) + + if "tau" in kwargs: + tau = kwargs["tau"] + else: + tau = 500 + if "tp" in kwargs: + tp = kwargs["tp"] + else: + tp = 12 + + if hasattr(self, "pi2_pulse"): + self.addPulse(self.pi2_pulse.copy( + t=0, pcyc={"phases":[0, np.pi], "dets": [1, -1]})) + else: + self.addPulse(RectPulse( # Exc pulse + t=0, tp=tp, freq=0, flipangle=np.pi/2, + pcyc={"phases":[0, np.pi], "dets":[1, -1]} + )) + + if hasattr(self, "pi_pulse"): + pi_pulse = self.addPulse(self.pi_pulse.copy( + t=tau, pcyc={"phases":[0], "dets": [1]})) + else: + pi_pulse = self.addPulse(RectPulse( # Pump 1 pulse + t=tau, tp=tp, freq=0, flipangle=np.pi + )) + + if hasattr(self, "det_event"): + self.addPulse(self.det_event.copy(t=2*tau)) + else: + self.addPulse(Detection(t=2*tau, tp=512)) + +# ============================================================================= + +class T1InversionRecoverySequence(Sequence): + r""" + Represents a T1 Inversion Recovery Sequence. + + Sequence: + [\pi - t - \pi/2 - \tau - \pi - \tau - echo] + + Parameters + ---------- + B : int or float + The B0 field, in Gauss + LO : int or float + The LO frequency in GHz + reptime : _type_ + The shot repetition time in us + averages : int + The number of scans. + shots : int + The number of shots per point + start : float + The minimum interpulse delay in ns, by default 300 ns + step : float + The step size of the interpulse delay in ns, by default 50 ns + dim : int + The number of points in the X axis + tau: float + The Hahn echo interpulse delay in ns, by default 500 ns + + Optional Parameters + ------------------- + pi2_pulse : Pulse + An autoEPR Pulse object describing the excitation pi/2 pulse. If + not specified a RectPulse will be created instead. + pi_pulse : Pulse + An autoEPR Pulse object describing the refocusing pi pulses. If + not specified a RectPulse will be created instead. + + Examples + -------- + .. plot:: + :include-source: + + import pyepr as epr + epr.set_waveform_precision(1) + seq = epr.T1InversionRecoverySequence( + B=12000, freq=34, reptime=1e3, averages=1, shots=10, start=10000, step=2500, dim=500) + seq.draw() + + """ + + def __init__(self, *, B, freq, reptime, averages, shots,start=500, step=40, dim=200, **kwargs) -> None: + name = "T1InversionRecoverySequence" + tp = kwargs.get("tp", 12) + + self.tau = Parameter(name="tau", value=500, unit="ns", description="The hahn ehco interpulse delay",virtual=True) + self.t = Parameter(name="t", value=start, step=step, dim=dim, unit="ns", description="The inversion recovery delay",virtual=True) + super().__init__(name=name,B=B, freq=freq, reptime=reptime, averages=averages, shots=shots, **kwargs) + + if "pi_pulse" in kwargs: + self.pi_pulse = kwargs["pi_pulse"] + if "pi2_pulse" in kwargs: + self.pi2_pulse = kwargs["pi2_pulse"] + if "det_event" in kwargs: + self.det_event = kwargs["det_event"] + + if hasattr(self, "pi_pulse"): + pi_pulse = self.addPulse(self.pi_pulse.copy( + t=0, pcyc={"phases":[0], "dets": [1]})) + else: + pi_pulse = self.addPulse(RectPulse( # Pump 1 pulse + t=0, tp=tp, freq=0, flipangle=np.pi + )) + + if hasattr(self, "pi2_pulse"): + self.addPulse(self.pi2_pulse.copy( + t=self.t, pcyc={"phases":[0, np.pi], "dets": [1, -1]})) + else: + self.addPulse(RectPulse( # Exc pulse + t=self.t, tp=tp, freq=0, flipangle=np.pi/2, + pcyc={"phases":[0, np.pi], "dets":[1, -1]} + )) + + if hasattr(self, "pi_pulse"): + pi_pulse = self.addPulse(self.pi_pulse.copy( + t=self.t+self.tau, pcyc={"phases":[0], "dets": [1]})) + else: + pi_pulse = self.addPulse(RectPulse( # Pump 1 pulse + t=self.t+self.tau, tp=tp, freq=0, flipangle=np.pi + )) + if hasattr(self, "det_event"): + self.addPulse(self.det_event.copy(t=self.t+2*self.tau)) + else: + self.addPulse(Detection(t=self.t+2*self.tau, tp=self.det_window.value)) + + self.evolution([self.t]) + + def simulate(self, T1=1e4): + """ + Simulates the T1 recovery as a simple exponential recovery. + """ + func = lambda x, a, T1: a*(1 - 2*np.exp(-x/T1)) + xaxis = val_in_ns(self.t) + data = func(xaxis,1,T1) + data = add_phaseshift(data, 0.05) + return xaxis, data +# ============================================================================= + + +class HahnEchoRelaxationSequence(HahnEchoSequence): + r""" + Represents a Hahn Echo relaxation sequence for measureing Tm. A Hahn Echo where the interpulse delay increases + + Sequence: + [\pi/2 - \tau - \pi - \tau - echo] + + Parameters + ---------- + B : int or float + The B0 field, in Gauss + freq : int or float + The freq frequency in GHz + reptime : _type_ + The shot repetition time in us + averages : int + The number of scans. + shots : int + The number of shots per point + start : float + The minimum interpulse delay in ns, by default 300 ns + step : float + The step size of the interpulse delay in ns, by default 50 ns + dim : int + The number of points in the X axis + + Optional Parameters + ------------------- + pi2_pulse : Pulse + An autoEPR Pulse object describing the excitation pi/2 pulse. If + not specified a RectPulse will be created instead. + pi_pulse : Pulse + An autoEPR Pulse object describing the refocusing pi pulses. If + not specified a RectPulse will be created instead. + + Examples + -------- + .. plot:: + :include-source: + + import pyepr as epr + epr.set_waveform_precision(1) + seq = epr.HahnEchoRelaxationSequence( + B=12000, freq=34, reptime=1e3, averages=1, shots=10, start=300, step=40, dim=200) + seq.draw() + + + """ + + def __init__(self, *, B, freq, reptime, averages, shots,start=500, step=40, dim=200, **kwargs) -> None: + + self.tau = Parameter(name="tau", value=start,step=step,dim=dim, unit="ns", description="The interpulse delay",virtual=True) + super().__init__(B=B, freq=freq, reptime=reptime, averages=averages, shots=shots,tau=self.tau, **kwargs) + + self.name = "T2RelaxationSequence" + self.evolution([self.tau]) + + def simulate(self,ESEEM_depth=0.1, Tm=1e3): + func = lambda x, a, tau, e: a*np.exp(-(x/tau)**e) + xaxis = val_in_ns(self.tau) + data = func(xaxis,1,Tm,1.6) + data = add_phaseshift(data, 0.05) + if ESEEM_depth != 0: + data *= _gen_ESEEM(xaxis, 7.842, ESEEM_depth) + return xaxis, data + +class T2RelaxationSequence(HahnEchoRelaxationSequence): + r""" + Represents a T2 relaxation sequence. This is an alias for HahnEchoRelaxationSequence. + A Hahn Echo where the interpulse delay increases. + + Sequence: + [\pi/2 - \tau - \pi - \tau - echo] + + Parameters + ---------- + B : int or float + The B0 field, in Gauss + freq : int or float + The freq frequency in GHz + reptime : _type_ + The shot repetition time in us + averages : int + The number of scans. + shots : int + The number of shots per point + start : float + The minimum interpulse delay in ns, by default 500 ns + step : float + The step size of the interpulse delay in ns, by default 40 ns + dim : int + The number of points in the X axis + + Optional Parameters + ------------------- + pi2_pulse : Pulse + An autoEPR Pulse object describing the excitation pi/2 pulse. If + not specified a RectPulse will be created instead. + pi_pulse : Pulse + An autoEPR Pulse object describing the refocusing pi pulses. If + not specified a RectPulse will be created instead. + """ + pass + +# ============================================================================= + +class FieldSweepSequence(HahnEchoSequence): + """ + Represents a Field Sweep (EDFS) sequence. + + + + """ + def __init__(self, *, B, freq, Bwidth, reptime, averages, shots, **kwargs) -> None: + r"""Build a Field Sweep (EDFS) sequence using either rectangular pulses or + specified pulses. + + Sequence: + [\pi/2 - \tau - \pi - \tau - echo] + + Parameters + ---------- + B : int or float + The B0 field, in Gauss + Bwidth: int or float + The width of the field sweep, in Gauss + freq : int or float + The freq frequency in GHz + reptime : _type_ + The shot repetition time in us + averages : int + The number of scans. + shots : int + The number of shots per point + + Optional Parameters + ------------------- + pi2_pulse : Pulse + An autoEPR Pulse object describing the excitation pi/2 pulse. If + not specified a RectPulse will be created instead. + pi_pulse : Pulse + An autoEPR Pulse object describing the refocusing pi pulses. If + not specified a RectPulse will be created instead. + + Examples + -------- + .. plot:: + :include-source: + + import pyepr as epr + epr.set_waveform_precision(1) + + seq = epr.FieldSweepSequence( + B=12000, Bwidth=100, freq=34, reptime=1e3, averages=1, shots=10) + seq.draw() + + """ + super().__init__( + B=B, freq=freq, reptime=reptime, averages=averages, + shots=shots, **kwargs) + self.name = "FieldSweepSequence" + + dim = Bwidth // kwargs.get('step',1) + self.B = Parameter( + "B", value=B, start = -Bwidth/2, step=kwargs.get('step',1), dim=dim, unit="Gauss", description="Field sweep width" + ) + + self.evolution([self.B]) + + def simulate(self): + """ + Simulate the Field Sweep spectra as a Nitroxide radical. + + returns + ------- + axis : np.ndarray + The x-axis of the simulation + data : np.ndarray + The y-axis of the simulation + + """ + Vmodel = create_Nmodel(self.freq.value *1e3) + axis = self.B.value + self.B.axis[0]['axis'] + sim_axis = axis * 0.1 + Boffset=0 + gy = 2.0061 + gz = 2.0021 + axy = 0.488 + az = 3.66 + GB = 0.45 + scale=1 + + data = Vmodel(sim_axis,Boffset,gy,gz,axy,az,GB,scale) + data = add_phaseshift(data, 0.05) + return axis,data + +# ============================================================================= + +class ReptimeScan(HahnEchoSequence): + """ + Represents a reptime scan of a Hahn Echo Sequence. + """ + def __init__(self, *, B, freq, reptime, reptime_max, averages, shots, start=20, dim=100, **kwargs) -> None: + r"""A Hahn echo sequence is perfomed with the shot repetition time increasing.1 + + Sequence: + [\pi/2 - \tau - \pi - \tau - echo] + + Parameters + ---------- + B : int or float + The B0 field, in Gauss + freq : int or float + The freq frequency in GHz + reptime: float + The default reptime, this is used for tuning pulses etc... + averages : int + The number of scans. + shots : int + The number of shots per point + reptime_max : float + The maximum shot repetition time in us + start : float + The minimum shot repetition time in us, by default 20 us + dim : int + The number of points in the reptime axis + + + Optional Parameters + ------------------- + pi2_pulse : Pulse + An autoEPR Pulse object describing the excitation pi/2 pulse. If + not specified a RectPulse will be created instead. + pi_pulse : Pulse + An autoEPR Pulse object describing the refocusing pi pulses. If + not specified a RectPulse will be created instead. + + Examples + -------- + .. plot:: + :include-source: + + import pyepr as epr + epr.set_waveform_precision(1) + seq = epr.ReptimeScan( + B=12000, freq=34, reptime=1000, averages=1, + shots=10, reptime_max=10000, start=20, dim=100) + + seq.draw() + """ + min_reptime = start + step = (reptime_max-min_reptime)/dim + step = np.around(step,decimals=-1) + step = np.around(step,decimals=-1) + reptime = Parameter( + "reptime", reptime, start = min_reptime-reptime, step=step, dim=dim, unit="us", + description = "The shot repetition time") + + super().__init__( + B=B, freq=freq, reptime=reptime, averages=averages, + shots=shots, **kwargs) + self.name = "ReptimeScan" + + self.evolution([self.reptime]) + + def simulate(self): + """ + Simulates the reptime scan as an exponential recovery. + + .. math:: + V(t) = 1 - e^(-t/T1) + + Returns + ------- + t : np.ndarray + The x-axis of the simulation + data : np.ndarray + The y-axis of the simulation + """ + def func(x,T1): + return 1-np.exp(-x/T1) + t = self.reptime.value + self.reptime.axis[0]['axis'] + T1 = 2000 #us + + data = func(t,T1) + data = add_phaseshift(data, 0.05) + return t, data + +# ============================================================================= + +class CarrPurcellSequence(Sequence): + """ + Represents a Carr-Purcell sequence. + """ + def __init__(self, *, B, freq, reptime, averages, shots, + n,start=300,step=50, dim=100,**kwargs) -> None: + r"""Build a Carr-Purcell dynamical decoupling sequence using either + rectangular pulses or specified pulses. + + Sequence: + [\pi/2 [- \tau - \pi - \tau]^n - echo] + + Parameters + ---------- + B : int or float + The B0 field, in Gauss + freq : int or float + The freq frequency in GHz + reptime : _type_ + The shot repetition time in us + averages : int + The number of scans. + shots : int + The number of shots per point + n : int + The number refocusing pulses + start : float + The minimum interpulse delay in ns, by default 300 ns + step : float + The step size of the interpulse delay in ns, by default 50 ns + dim : int + The number of points in the X axis + + Optional Parameters + ------------------- + pi2_pulse : Pulse + An autoEPR Pulse object describing the excitation pi/2 pulse. If + not specified a RectPulse will be created instead. + pi_pulse : Pulse + An autoEPR Pulse object describing the refocusing pi pulses. If + not specified a RectPulse will be created instead. + + Examples + -------- + .. plot:: + :include-source: + + import pyepr as epr + epr.set_waveform_precision(1) + seq = epr.CarrPurcellSequence(B=12000, freq=34, reptime=1000, averages=1, shots=10, n=4) + + seq.draw() + """ + + name = "CarrPurcellSequence" + super().__init__( + name=name, B=B, freq=freq, reptime=reptime, averages=averages, + shots=shots, **kwargs) + self.t = Parameter(name="tau", value=start,step=step,dim=dim, unit="ns", + description="First interpulse delay", virtual=True) + self.n = Parameter(name="n", value=n, + description="The number of pi pulses", unit="None", virtual=True) + self.dim = Parameter(name="dim", value=dim, unit="None", + description="The number of points in the X axis", virtual=True) + + if "pi_pulse" in kwargs: + self.pi_pulse = kwargs["pi_pulse"] + if "pi2_pulse" in kwargs: + self.pi2_pulse = kwargs["pi2_pulse"] + if "det_event" in kwargs: + self.det_event = kwargs["det_event"] + + self._build_sequence() + + def _build_sequence(self): + + n = self.n.value + # dt = 20 + # dim = np.floor((self.tau.value/(2*self.n.value) -deadtime)/dt) + # # multipliers = [1] + # # multipliers += [1+2*i for i in range(1,n)] + # # multipliers += [2*n] + + # axis = np.arange(deadtime,tau/(2*n),10) + + if hasattr(self, "pi2_pulse"): + self.addPulse(self.pi2_pulse.copy( + t=0, pcyc={"phases":[0, np.pi], "dets": [1, -1]})) + else: + self.addPulse(RectPulse( # pi/2 + t=0, tp=16, freq=0, flipangle=np.pi/2, + pcyc={"phases":[0, np.pi], "dets": [1, -1]} + )) + + for i in range(n): + if i==(n-1): + phases = [0] + dets = [1] + elif i == (n-2): + phases = [0, np.pi] + dets = [1, 1] + else: + phases = [0, np.pi/2, np.pi, -np.pi/2] + dets = [1,-1,1,-1] + if hasattr(self, "pi_pulse"): + self.addPulse(self.pi_pulse.copy( + t=self.t*(2*i + 1), pcyc={"phases":phases, "dets": dets})) + else: + self.addPulse(RectPulse( # pi + t=self.t*(2*i + 1), tp=32, freq=0, flipangle=np.pi, + pcyc={"phases":phases, "dets": dets} + )) + if hasattr(self, "det_event"): + self.addPulse(self.det_event.copy(t=self.t*(2*n))) + else: + self.addPulse(Detection(t=self.t*(2*n), tp=512)) + + self.evolution([self.t]) + + def simulate(self,T_CP=2.5e3, e=1.8): + """ + Simulates the Carr-Purcell sequence as a single component stretched exponential decay. + + .. math:: + V(t) = e^{(-(t/T_{CP})^e)} + + Examples + -------- + + .. plot:: + :include-source: + + import matplotlib.pyplot as plt + import pyepr as epr + epr.set_waveform_precision(1) + + seq = epr.CarrPurcellSequence(B=12000, freq=34, reptime=1000, averages=1, shots=10, n=4) + x,data = seq.simulate(T_CP=2.5e3, e=1.8) + plt.plot(x,data) + plt.xlabel("Interpulse Delay (ns)") + plt.ylabel("Signal Intensity (a.u.)") + + + Parameters + ---------- + T_CP : float + The Carr-Purcell relaxation time, by default 2.5e3 ns + e : float + The stretching exponent, by default 1.8 + + Returns + ------- + xaxis : np.ndarray + The x-axis of the simulation + data : np.ndarray + + """ + + + xaxis = val_in_ns(self.t) + func = lambda x, a, tau, e: a*np.exp(-(x/tau)**e) + data = func(xaxis,1,T_CP,e) + data = add_phaseshift(data, 0.05) + return xaxis, data +# ============================================================================= + +class ResonatorProfileSequence(Sequence): + """ + Builds nutation based Resonator Profile sequence. + """ + + def __init__(self, *, B, freq, reptime, averages, shots, fwidth=0.3,dtp=2, **kwargs) -> None: + r"""Build a resonator profile nutation sequence using either + rectangular pulses or specified pulses. + + Parameters + ---------- + B : int or float + The B0 field, in Gauss + Bwidth: int or float + The width of the field sweep, in Gauss + freq : int or float + The freq frequency in GHz + reptime : _type_ + The shot repetition time in us + averages : int + The number of scans. + shots : int + The number of shots per point + fwidth: float + The frequency width of the resonator profile in GHz, + by default 0.3GHz + fstep: float + The frequency step for the profile in GHz, by default 0.02GHz + + dtp: float + The time step for the test pulse in ns, by default 2 ns + step: + The frequency step parameter in GHz, by default 0.02GHz + dim: int + The number of points in the tp axis, by default set to 120/dtp, which is 60 points for dtp=2ns. + + Optional Parameters + ------------------- + tau1: float + The delay between the nutating pulse and the Hahn Echo, + by default 2000 ns + tau2: float + The interpulse delay in the Hahn Echo, + by default 500 ns + pi2_pulse : Pulse + An autoEPR Pulse object describing the excitation pi/2 pulse. If + not specified a RectPulse will be created instead. + pi_pulse : Pulse + An autoEPR Pulse object describing the refocusing pi pulses. If + not specified a RectPulse will be created instead. + + Examples + -------- + + .. plot:: + :include-source: + + import pyepr as epr + import numpy as np + epr.set_waveform_precision(1) + + N_gyro = 0.002803 + freq = 34 + pi2_pulse = epr.RectPulse(tp=32,freq=0,flipangle=np.pi/2) + pi_pulse = epr.RectPulse(tp=32,freq=0,flipangle=np.pi) + + seq = epr.ResonatorProfileSequence( + B=freq/N_gyro, + freq=freq, + reptime=3e3, + averages=1, + shots=10, + pi2_pulse=pi2_pulse, + pi_pulse=pi_pulse, + fwidth=0.3, + fstep=0.02, + dtp=1, + dim=40) + + seq.draw() + + """ + + name = "ResonatorProfileSequence" + super().__init__( + name=name, B=B, freq=freq, reptime=reptime, averages=averages, + shots=shots, **kwargs) + self.gyro: float = freq/B + """Gyromagenetic ratio in GHz/Gauss""" + self.fwidth: Parameter = Parameter('fwidth',fwidth,'GHz','Half the frequency sw') + """Half the frequency sweep width for the profile""" + self.fstep: Parameter = Parameter('fstep',kwargs.get('fstep',0.02),'GHz','Frequency step for the profile') + """Frequency step for the profile""" + self.dtp: Parameter = Parameter('dtp',float(dtp),'ns','Time step for the pulse') + """Time step for the test pulse""" + self.kwargs: dict = kwargs + """Keyword arguments""" + + if "pi_pulse" in kwargs: + self.pi_pulse = kwargs["pi_pulse"] + if "pi2_pulse" in kwargs: + self.pi2_pulse = kwargs["pi2_pulse"] + + self._build_sequence() + + def _build_sequence(self): + + tau1 = self.kwargs.get("tau1",2000) #2000 + tau2 = self.kwargs.get("tau2",500) #500 + fstep = self.kwargs.get("step",0.02) + dim = self.kwargs.get("dim",np.floor(120/self.dtp.value).astype(int)) + tp = Parameter("tp", 0, step=self.dtp.value, dim=dim, unit="ns", description="Test Pulse length") + fwidth= self.fwidth.value + fstep = self.fstep.value + dim = np.floor(fwidth*2/fstep) + center_freq = self.freq.value + self.freq = Parameter("freq", center_freq, start=-fwidth, step=fstep, dim=dim, unit="GHz", description="frequency") + self.B = Parameter( + "B",((center_freq)/self.gyro), start=-fwidth/self.gyro, step=fstep/self.gyro, dim=dim, + unit="Gauss",link=self.freq,description="B0 Field" ) + + self.addPulse(RectPulse( # Hard pulse + t=0, tp=tp, freq=0, flipangle="Hard" + )) + + if hasattr(self, "pi2_pulse"): + self.addPulse(self.pi2_pulse.copy( + t=tau1, pcyc={"phases":[0, np.pi], "dets": [1, -1]})) + else: + self.addPulse(RectPulse( # pi/2 + t=tau1, tp=16, freq=0, flipangle=np.pi/2, + pcyc={"phases":[0, np.pi], "dets": [1, -1]} + )) + + if hasattr(self, "pi_pulse"): + self.addPulse(self.pi_pulse.copy( + t=tau1+tau2)) + else: + self.addPulse(RectPulse( # pi/2 + t=tau1+tau2, tp=32, freq=0, flipangle=np.pi + )) + + self.addPulse(Detection(t=tau1+2*tau2, tp=512)) + + + self.pulses[0].scale.value = 1 + + + self.evolution([tp, self.freq]) + + def simulate(self, Q=100, fc=None, nu1=75,damping=0.06): + """ + Simulates a resonator profile sequence as a damped oscillation. + + Parameters + ---------- + Q : int + The quality factor of the resonator, by default 100 + fc : float + The center frequency of the resonator, by default None. If None the freq frequency is used. + nu1 : float + The maximum amplitude of the resonator profile, by default 75 MHz. This is a linear frequency scale. + damping : float + The damping factor of the resonator, by default 0.06. + + """ + + if fc is None: + fc = self.freq.value + + xmin = self.freq.value - self.fwidth.value + xmax = self.freq.value + self.fwidth.value + + + def lorenz_fcn(x, centre, sigma): + y = (0.5*sigma)/((x-centre)**2 + (0.5*sigma)**2) + return y + + mode = lambda x: lorenz_fcn(x, fc, fc/Q) + axis = np.linspace(xmin,xmax) + scale = nu1/mode(axis).max() + self.mode = lambda x: lorenz_fcn(x, fc, fc/Q) * scale + + damped_oscilations = lambda x, f, c: np.cos(2*np.pi*f*x) * np.exp(-c*x) + damped_oscilations_vec = np.vectorize(damped_oscilations) + freq_axis = self.freq.value + self.freq.axis[0]['axis'] + freq_len = freq_axis.shape[0] + tp_x = val_in_ns(self.pulses[0].tp) + tp_len = tp_x.shape[0] + nut_freqs = self.mode(freq_axis) + + damped_oscilations_vec + data = damped_oscilations_vec(tp_x.reshape(tp_len,1),nut_freqs.reshape(1,freq_len)*1e-3,damping) + return [tp_x, freq_axis], data + + +# ============================================================================= + +class TWTProfileSequence(Sequence): + """ + Builds TWT based Resonator Profile sequence. + """ + + def __init__(self,*,B,freq,reptime,averages=1,shots=100,dtp=2,**kwargs) -> None: + + name = "TWTProfileSequence" + super().__init__( + name=name, B=B, freq=freq, reptime=reptime, averages=averages, + shots=shots, **kwargs) + + self.kwargs = kwargs + self.dtp = Parameter('dtp',dtp,'ns','Time step for the pulse') + + if "pi_pulse" in kwargs: + self.pi_pulse = kwargs["pi_pulse"] + if "pi2_pulse" in kwargs: + self.pi2_pulse = kwargs["pi2_pulse"] + + self._build_sequence() + + def _build_sequence(self,): + + tau1 = self.kwargs.get("tau1",2000) #2000 + tau2 = self.kwargs.get("tau2",500) #500 + + dim = np.floor(120/self.dtp.value).astype(int) + tp = Parameter("tp", 0, step=self.dtp.value, dim=dim, unit="ns", description="Test Pulse length") + scale = Parameter("scale", 0, step=0.01, dim=100, unit="None", description="Amplitude scale factor") + + self.addPulse(RectPulse( # Hard pulse + t=0, tp=tp, freq=0, flipangle="Hard",scale=scale + )) + + if hasattr(self, "pi2_pulse"): + self.addPulse(self.pi2_pulse.copy( + t=tau1, pcyc={"phases":[0, np.pi], "dets": [1, -1]})) + else: + self.addPulse(RectPulse( # pi/2 + t=tau1, tp=16, freq=0, flipangle=np.pi/2, + pcyc={"phases":[0, np.pi], "dets": [1, -1]} + )) + + if hasattr(self, "pi_pulse"): + self.addPulse(self.pi_pulse.copy( + t=tau1+tau2)) + else: + self.addPulse(RectPulse( # pi/2 + t=tau1+tau2, tp=32, freq=0, flipangle=np.pi + )) + + self.addPulse(Detection(t=tau1+2*tau2, tp=512)) + + self.evolution([tp, scale]) + +# ============================================================================= + +class KBBSequence(Sequence): + """ + Builds a Kutnz-Boehlen-Bodenhausen echo sequence. + + """ + + def __init__(self,*,B,freq,reptime,averages=1,shots=100,**kwargs) -> None: + """ + Parameters + ---------- + B : _type_ + _description_ + freq : _type_ + _description_ + reptime : _type_ + _description_ + averages : int, optional + _description_, by default 1 + shots : int, optional + _description_, by default 100 + dtp : int, optional + _description_, by default 2 + """ + name = "KBBSequence" + super().__init__( + name=name, B=B, freq=freq, reptime=reptime, averages=averages, + shots=shots, **kwargs) + + self.kwargs = kwargs + + self._build_sequence() + + def _build_sequence(self,): + pass + +# ============================================================================= + +class KBBPulseProfileSequence(KBBSequence): + """ + Builds a KBB based Resonator Profile sequence. + """ + + def __init__(self,*,B,freq,reptime,averages=1,shots=100,dtp=2,**kwargs) -> None: + + name = "KBB_PulseProfileSequence" + super().__init__( + name=name, B=B, freq=freq, reptime=reptime, averages=averages, + shots=shots, **kwargs) + self._build_sequence() + + def _build_sequence(self,): + pass \ No newline at end of file diff --git a/pyepr/sequences/calibration_sequences.py b/pyepr/sequences/calibration_sequences.py new file mode 100644 index 0000000..e69de29 From 587ba8831b1285688f13dc9a27d69abb5ed396bc Mon Sep 17 00:00:00 2001 From: Hugo Karas Date: Mon, 16 Nov 2026 11:03:37 +0100 Subject: [PATCH 42/55] Major refactor of import statements --- pyepr/classes.py | 2 +- pyepr/criteria.py | 2 ++ pyepr/dataset.py | 8 +++++++- pyepr/fieldsweep_analysis.py | 5 +++++ pyepr/hardware/Bruker_AWG.py | 7 ++++--- pyepr/hardware/Bruker_MPFU.py | 2 +- pyepr/hardware/Bruker_tools.py | 2 +- pyepr/hardware/ETH_awg.py | 2 +- pyepr/pulses.py | 10 +++++++++- pyepr/relaxation_analysis.py | 5 +++++ pyepr/resonator_profile_analysis.py | 6 ++++++ pyepr/tools.py | 8 -------- tests/test_dataset.py | 1 - tests/test_fieldsweep.py | 1 + 14 files changed, 43 insertions(+), 18 deletions(-) diff --git a/pyepr/classes.py b/pyepr/classes.py index 3a2ea3e..a3e0be8 100644 --- a/pyepr/classes.py +++ b/pyepr/classes.py @@ -1,5 +1,5 @@ import numpy as np -from pyepr import __version__ +from pyepr._version import __version__ import copy import numbers import uuid diff --git a/pyepr/criteria.py b/pyepr/criteria.py index 67729b0..92dee33 100644 --- a/pyepr/criteria.py +++ b/pyepr/criteria.py @@ -5,6 +5,8 @@ import logging import datetime +__all__ = ['Criteria', 'TimeCriteria', 'SNRCriteria'] + log = logging.getLogger('interface') class Criteria: diff --git a/pyepr/dataset.py b/pyepr/dataset.py index 097c2b2..3741f65 100644 --- a/pyepr/dataset.py +++ b/pyepr/dataset.py @@ -2,7 +2,7 @@ import matplotlib.pyplot as plt import re import scipy.fft as fft -from pyepr import __version__ +from pyepr._version import __version__ from pyepr.pulses import Detection, Pulse from pyepr.classes import Parameter from pyepr.sequences import Sequence @@ -13,6 +13,12 @@ import copy import datetime +__all__ = [ + 'get_all_axes', 'get_all_fixed_param', 'create_dataset_from_sequence', + 'create_dataset_from_axes', 'create_dataset_from_bruker', 'EPRAccessor', + 'downconvert_dataset', 'find_peak', 'save_bruker', +] + # ============================================================================= def get_all_axes(sequence): diff --git a/pyepr/fieldsweep_analysis.py b/pyepr/fieldsweep_analysis.py index 674a573..1e2d55b 100644 --- a/pyepr/fieldsweep_analysis.py +++ b/pyepr/fieldsweep_analysis.py @@ -11,6 +11,11 @@ from pyepr.colors import primary_colors, ReIm_colors from scipy.interpolate import UnivariateSpline +__all__ = [ + 'create_Nmodel', 'FieldSweepAnalysis', 'SpinSystem', 'erot', 'eyekron', + 'kroneye', 'ham', 'ham_ez', 'ham_nz', 'resfields', 'build_spectrum', +] + def create_Nmodel(mwFreq): """Create the field sweep model for a Nitroxide spin system. diff --git a/pyepr/hardware/Bruker_AWG.py b/pyepr/hardware/Bruker_AWG.py index 5c48970..dfbdaa6 100644 --- a/pyepr/hardware/Bruker_AWG.py +++ b/pyepr/hardware/Bruker_AWG.py @@ -1,10 +1,11 @@ from pyepr.hardware.BaseInterfaceClass import Interface from pyepr.hardware.XeprAPI_link import XeprAPILink from pyepr.hardware.Bruker_tools import PulseSpel, run_general, build_unique_progtable,write_pulsespel_file,step_parameters, get_specjet_data -from pyepr.dataset import * +from pyepr.dataset import create_dataset_from_sequence +from pyepr.classes import Parameter from pyepr.utils import transpose_list_of_dicts, transpose_dict_of_list,round_step -from pyepr.pulses import RectPulse, Delay -from pyepr.sequences import HahnEchoSequence +from pyepr.pulses import RectPulse, Delay, Detection +from pyepr.sequences import Sequence, HahnEchoSequence import tempfile import time from scipy.optimize import minimize_scalar, curve_fit diff --git a/pyepr/hardware/Bruker_MPFU.py b/pyepr/hardware/Bruker_MPFU.py index 033d683..cc756a4 100644 --- a/pyepr/hardware/Bruker_MPFU.py +++ b/pyepr/hardware/Bruker_MPFU.py @@ -5,7 +5,7 @@ from pyepr.hardware.Bruker_tools import PulseSpel, run_general,build_unique_progtable,PSPhaseCycle, write_pulsespel_file from pyepr.sequences import Sequence, HahnEchoSequence from pyepr.utils import save_file, transpose_list_of_dicts, transpose_dict_of_list, round_step -from pyepr import create_dataset_from_sequence, create_dataset_from_axes +from pyepr.dataset import create_dataset_from_sequence, create_dataset_from_axes import tempfile import time diff --git a/pyepr/hardware/Bruker_tools.py b/pyepr/hardware/Bruker_tools.py index cc945da..607d92b 100644 --- a/pyepr/hardware/Bruker_tools.py +++ b/pyepr/hardware/Bruker_tools.py @@ -5,7 +5,7 @@ import re import time import importlib -from pyepr import __version__ +from pyepr._version import __version__ import os import logging diff --git a/pyepr/hardware/ETH_awg.py b/pyepr/hardware/ETH_awg.py index 3e322aa..460bcbf 100644 --- a/pyepr/hardware/ETH_awg.py +++ b/pyepr/hardware/ETH_awg.py @@ -13,7 +13,7 @@ from pyepr.utils import transpose_list_of_dicts from pyepr.hardware.ETH_awg_load import uwb_eval_match from pyepr.utils import save_file, transpose_list_of_dicts, transpose_dict_of_list -from pyepr import create_dataset_from_sequence +from pyepr.dataset import create_dataset_from_sequence import datetime import copy import threading diff --git a/pyepr/pulses.py b/pyepr/pulses.py index 7781f30..39e3c56 100644 --- a/pyepr/pulses.py +++ b/pyepr/pulses.py @@ -9,11 +9,19 @@ import base64 import matplotlib.pyplot as plt import scipy.fft as fft -from pyepr import __version__ +from pyepr._version import __version__ import copy from functools import reduce from itertools import accumulate +__all__ = [ + 'compute_upulses_not_trajectory', 'compute_upulses_trajectory', + 'compute_magnetization_not_trajectory', 'compute_magnetization_trajectory', + 'Pulse', 'Detection', 'Delay', 'RectPulse', 'GaussianPulse', + 'FrequencySweptPulse', 'HSPulse', 'ChirpPulse', 'WURSTPulse', 'SincPulse', + 'CPMGDetection', 'build_default_pulses', +] + def compute_upulses_not_trajectory(dUs): n_offsets, n_steps, _, _ = dUs.shape Upulses = np.empty((n_offsets, 2, 2), dtype=np.complex128) diff --git a/pyepr/relaxation_analysis.py b/pyepr/relaxation_analysis.py index 826492b..aaefc1b 100644 --- a/pyepr/relaxation_analysis.py +++ b/pyepr/relaxation_analysis.py @@ -8,6 +8,11 @@ import deerlab as dl from scipy.linalg import svd from pyepr.colors import primary_colors + +__all__ = [ + 'CarrPurcellAnalysis', 'HahnEchoRelaxationAnalysis', 'ReptimeAnalysis', + 'detect_ESEEM', 'plot_1Drelax', +] # =========================================================================== # T2-type relaxation analysis classes diff --git a/pyepr/resonator_profile_analysis.py b/pyepr/resonator_profile_analysis.py index cb33827..4b17a67 100644 --- a/pyepr/resonator_profile_analysis.py +++ b/pyepr/resonator_profile_analysis.py @@ -11,6 +11,12 @@ import xarray as xr from pyepr.colors import primary_colors +__all__ = [ + 'phase_correct_respro', 'ResonatorProfileAnalysis', 'ceil', 'floor', + 'calc_overlap', 'BSpline_extra', 'optimise_spectra_position', + 'AmplifierLinearityAnalysis', +] + # def phase_correct_respro(data_array): # Vre, Vim, ph = dl.correctphase(data_array.values,full_output=True) # index = np.argmax(np.abs(Vre),axis=0) diff --git a/pyepr/tools.py b/pyepr/tools.py index 67ecdaf..3a7ac7b 100644 --- a/pyepr/tools.py +++ b/pyepr/tools.py @@ -1,7 +1,6 @@ import os import deerlab as dl import numpy as np -import logging from pyepr.dataset import create_dataset_from_bruker, downconvert_dataset from pyepr.hardware.ETH_awg_load import uwb_load, uwb_eval_match, ETHUWB_xarray_load from scipy.io import loadmat @@ -9,8 +8,6 @@ import xarray as xr import warnings -log = logging.getLogger('autoDEER.Tools') - def eprload( path: str, experiment: str = None, type: str = None,downconvert=True, @@ -43,23 +40,18 @@ def eprload( _, file_extension = os.path.splitext(path) if (file_extension == ".DSC") | (file_extension == ".DTA"): - log.debug('File detected as Bruker') type = 'BRUKER' elif (file_extension == ".h5") | (file_extension == ".hdf5"): - log.debug('File detected as HDF5') type = 'HDF5' elif (file_extension == ".csv") | (file_extension == ".txt"): - log.debug('File detected as csv or txt file') type = 'TXT' elif file_extension == '.mat': - log.debug('File detected as Matlab') type = 'MAT' else: - log.error("Can't detect file type") raise ValueError( "Can't detect file type. Please choose the correct file or" " set type manually \n Valid file types: '.DSC','.DTA','.h5'," diff --git a/tests/test_dataset.py b/tests/test_dataset.py index ef44ad7..acbbb9c 100644 --- a/tests/test_dataset.py +++ b/tests/test_dataset.py @@ -1,7 +1,6 @@ from pyepr.classes import * from pyepr.dataset import * from pyepr.sequences import * -from pyepr.hardware.dummy import _simulate_field_sweep, _simulate_T2 import numpy as np from scipy.signal import hilbert import pytest diff --git a/tests/test_fieldsweep.py b/tests/test_fieldsweep.py index 826c122..141a696 100644 --- a/tests/test_fieldsweep.py +++ b/tests/test_fieldsweep.py @@ -1,4 +1,5 @@ +import numpy as np from pyepr.fieldsweep_analysis import * from pyepr.dataset import * import pytest From db38078e2f0b0c0d8760d7dcfc22c185c926b881 Mon Sep 17 00:00:00 2001 From: Hugo Karas Date: Mon, 16 Nov 2026 11:04:38 +0100 Subject: [PATCH 43/55] Docstring update --- pyepr/classes.py | 37 +++++++++++++++++++-------------- pyepr/hardware/Bruker_tools.py | 20 ++++++------------ pyepr/hardware/ETH_awg_load.py | 2 +- pyepr/hardware/PyEPR_control.py | 3 ++- pyepr/hardware/XeprAPI_link.py | 7 ++++--- pyepr/pulses.py | 19 +++++++---------- pyepr/utils.py | 6 ++++++ 7 files changed, 48 insertions(+), 46 deletions(-) diff --git a/pyepr/classes.py b/pyepr/classes.py index a3e0be8..1d827ef 100644 --- a/pyepr/classes.py +++ b/pyepr/classes.py @@ -59,22 +59,27 @@ def __init__(self, name, value, unit="", description="", virtual=False, Examples -------- Creating a static parameter - ``` - Par1 = Parameter( - name="Par1", value=10, unit="us", description="The first parameter") - ``` + + .. code-block:: python + + Par1 = Parameter( + name="Par1", value=10, unit="us", description="The first parameter") + Creating a dynamic parameter - ``` - Par1 = Parameter( - name="Par1", value=10, unit="us", description="The first parameter", - axis=np.arange(0,10,1), axis_id=0) - ``` + + .. code-block:: python + + Par1 = Parameter( + name="Par1", value=10, unit="us", description="The first parameter", + axis=np.arange(0,10,1), axis_id=0) Adding a parameter and a number: - ``` - Par1 = Parameter( - name="Par1", value=10, unit="us", description="The first parameter") - Par2 = Par1 + 2 + + .. code-block:: python + + Par1 = Parameter( + name="Par1", value=10, unit="us", description="The first parameter") + Par2 = Par1 + 2 """ self.name = name @@ -330,7 +335,7 @@ def __sub__(self, __o:object): # a_ax_ids:list = self.ax_id a_ax_ids:list = [self.axis[i]["uuid"] for i in range(len(self.axis))] # b_ax_ids:list = __o.ax_id - b_ax_ids:list = [__o.axis[i]["uuid"] for i in range(len(self.__o))] + b_ax_ids:list = [__o.axis[i]["uuid"] for i in range(len(self.__o.axis))] ab_ax_ids = list(set(a_ax_ids + b_ax_ids)) for id in ab_ax_ids: if id not in b_ax_ids: # I.e. only in A @@ -408,7 +413,7 @@ def __mul__(self, __o:object): # a_ax_ids:list = self.ax_id a_ax_ids:list = [self.axis[i]["uuid"] for i in range(len(self.axis))] # b_ax_ids:list = __o.ax_id - b_ax_ids:list = [__o.axis[i]["uuid"] for i in range(len(self.__o))] + b_ax_ids:list = [__o.axis[i]["uuid"] for i in range(len(self.__o.axis))] ab_ax_ids = list(set(a_ax_ids + b_ax_ids)) for id in ab_ax_ids: if id not in b_ax_ids: # I.e. only in A @@ -444,7 +449,7 @@ def __mul__(self, __o:object): elif isinstance(__o, numbers.Number): new_value = self.value * __o - new_name = f"{self.name} + {__o}" + new_name = f"{self.name} * {__o}" new_parameter = Parameter( name=new_name, value=new_value, unit=self.unit) if self.axis is not []: diff --git a/pyepr/hardware/Bruker_tools.py b/pyepr/hardware/Bruker_tools.py index 607d92b..0eca1d0 100644 --- a/pyepr/hardware/Bruker_tools.py +++ b/pyepr/hardware/Bruker_tools.py @@ -15,19 +15,9 @@ header = "; " + "-" * 79 + "\n" header += "; " + \ - f"Auto-generated PulseSpel {{}} file by autoDEER {__version__}\n" + f"Auto-generated PulseSpel {{}} file by PyEPR {__version__}\n" header += "; " + "-" * 79 + "\n" - -def get_specjet_data(interface): - n_points = interface.api.hidden['specJet.Data'].aqGetParDimSize(0) - array = np.zeros(n_points,dtype=np.complex128) - for i in range(n_points): - array[i] = interface.api.hidden['specJet.Data'][i] + 1j* interface.api.hidden['specJet.Data1'][i] - - return array - - # ============================================================================= class PSPhaseCycle: @@ -220,10 +210,12 @@ def __init__(self, sequence: Sequence, id) -> None: pass def checkPulseSpel(self) -> bool: - """Checks if parvar can be run in PulseSpel.\\ + """Checks if parvar can be run in PulseSpel. + Criteria: - 1) Only pulse/delay lengths changing - 2) Constant integer step changes + + 1) Only pulse/delay lengths changing + 2) Constant integer step changes Returns ------- diff --git a/pyepr/hardware/ETH_awg_load.py b/pyepr/hardware/ETH_awg_load.py index ef52432..f6adcb0 100644 --- a/pyepr/hardware/ETH_awg_load.py +++ b/pyepr/hardware/ETH_awg_load.py @@ -12,7 +12,7 @@ def uwb_load(matfile: np.ndarray, options: dict = dict(), verbosity=0, compress: bool = True, mask=None, sequence=None): """uwb_load This function is based upon the uwb_eval matlab function developed by Andrin Doll. This is mostly a Python version of this software, - for loading data generated by Doll style spectrometers. + for loading data generated by Doll style spectrometers. Parameters ---------- diff --git a/pyepr/hardware/PyEPR_control.py b/pyepr/hardware/PyEPR_control.py index 1e68509..a984b06 100644 --- a/pyepr/hardware/PyEPR_control.py +++ b/pyepr/hardware/PyEPR_control.py @@ -157,7 +157,8 @@ def acquire_dataset(self,verbosity=0,sum_scans=True,**kwargs): def get_buffer(self,verbosity=0,sum_scans=True, **kwargs): """ - Returns the current scan from the spectrometer buffer. + Returns the current scan from the spectrometer buffer. + Parameters ---------- verbosity : int, optional diff --git a/pyepr/hardware/XeprAPI_link.py b/pyepr/hardware/XeprAPI_link.py index 546c023..2856124 100644 --- a/pyepr/hardware/XeprAPI_link.py +++ b/pyepr/hardware/XeprAPI_link.py @@ -26,15 +26,16 @@ class XeprAPILink: def __init__(self, config_file: str = None, **kwargs) -> None: """ This class links to the Bruker Xepr API to control the spectrometer. + Parameters ---------- config_file : str, optional Path to a PyEPR spectrometer configuration file, by default None kwargs : dict, optional Additional keyword arguments: - - retry_attempts : int - Number of times to retry getting a Xepr parameter before - raising an exception. Default is 50. + + - retry_attempts (int): Number of times to retry getting a Xepr + parameter before raising an exception. Default is 50. """ self.Xepr = None self.cur_exp = None diff --git a/pyepr/pulses.py b/pyepr/pulses.py index 39e3c56..92aaa49 100644 --- a/pyepr/pulses.py +++ b/pyepr/pulses.py @@ -93,10 +93,6 @@ def compute_magnetization_trajectory(Upulses, density0): return Mag class Pulse: - """ - Represents a general experimental pulse. - """ - def __init__(self, *, tp, t=None, scale=None, flipangle=None, pcyc=None, name=None, **kwargs) -> None: """The class for a general pulse. @@ -1041,7 +1037,7 @@ def flip(self): class HSPulse(FrequencySweptPulse): def __init__(self, *, tp=128, order1=1, order2=6, beta=20, **kwargs) -> None: r""" - Represents a hyperboilc secant frequency-swept pulse. + Represents a non-symetric hyperboilc secant frequency-swept pulse. The amplitude and frequency modulation functions are defined as: @@ -1101,11 +1097,14 @@ def __init__(self, *, tp=128, order1=1, order2=6, beta=20, **kwargs) -> None: """ FrequencySweptPulse.__init__(self, tp=tp, name='HSPulse', **kwargs) - self.order1 = Parameter( + self.order1: Parameter = Parameter( "order1", order1, None, "Order 1 of the HS Pulse") - self.order2 = Parameter( + """The order of the hyperbolic secant function for the first half of the pulse""" + self.order2: Parameter = Parameter( "order2", order2, None, "Order 2 of the HS Pulse") - self.beta = Parameter("beta", beta, None, "Beta of the HS Pulse") + """The order of the hyperbolic secant function for the first half of the pulse""" + self.beta: Parameter = Parameter("beta", beta, None, "Beta of the HS Pulse") + """The beta parameter of the hyperbolic secant function""" self._buildFMAM(self.func) pass @@ -1150,9 +1149,7 @@ def func(self, ax): def sweeprate(self): """ The sweep rate of the pulse in GHz/ns""" sweeprate_value = self.beta.value * self.bandwidth.value / (2*self.tp.value) - return Parameter("sweeprate", sweeprate_value, "GHz/ns", "Sweep rate of the pulse") - - + return Parameter("sweeprate", sweeprate_value, "GHz/ns", "Sweep rate of the pulse") # ============================================================================= diff --git a/pyepr/utils.py b/pyepr/utils.py index 9922f19..a462291 100644 --- a/pyepr/utils.py +++ b/pyepr/utils.py @@ -4,6 +4,12 @@ import uuid import base64 +__all__ = [ + 'build_table', 'sop', 'transpose_dict_of_list', 'transpose_list_of_dicts', + 'save_file', 'autoEPRDecoder', 'gcd', 'val_in_us', 'val_in_ns', + 'add_phaseshift', 'round_step', +] + def build_table(source, params, params_widths): string = "" From 59048a8b35a7f7cf5e2c654bd05c83cff125a23b Mon Sep 17 00:00:00 2001 From: Hugo Karas Date: Mon, 16 Nov 2026 11:04:55 +0100 Subject: [PATCH 44/55] Package file update --- .gitignore | 2 ++ .vscode/settings.json | 9 ++++++++- pyproject.toml | 3 +-- 3 files changed, 11 insertions(+), 3 deletions(-) diff --git a/.gitignore b/.gitignore index 3538047..73d4947 100644 --- a/.gitignore +++ b/.gitignore @@ -26,6 +26,8 @@ share/python-wheels/ .installed.cfg *.egg MANIFEST +sg_execution_times.rst + # PyInstaller # Usually these files are written by a python script from a template diff --git a/.vscode/settings.json b/.vscode/settings.json index 9b38853..f0005c5 100644 --- a/.vscode/settings.json +++ b/.vscode/settings.json @@ -3,5 +3,12 @@ "tests" ], "python.testing.unittestEnabled": false, - "python.testing.pytestEnabled": true + "python.testing.pytestEnabled": true, + "python-envs.pythonProjects": [ + { + "path": ".", + "envManager": "ms-python.python:venv", + "packageManager": "ms-python.python:pip" + } + ] } \ No newline at end of file diff --git a/pyproject.toml b/pyproject.toml index c1dcabc..b5626da 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "pyEPR-ESR" -version = "1.1" +version = "1.2" description = "" readme = "README.md" requires-python = ">=3.11,<4.0" @@ -30,7 +30,6 @@ dev = [ ] doc = [ "furo>=2024.8.6", - "autoapi>=2.0.1", "sphinx>=8.1.3", "sphinx-autoapi>=3.3.3", "sphinx-toolbox>=3.8.1", From 607c2d978cd1d06d031de3037f4fead1ce0b7cb5 Mon Sep 17 00:00:00 2001 From: Hugo Karas Date: Mon, 16 Nov 2026 11:05:03 +0100 Subject: [PATCH 45/55] Tests update --- tests/test_criteria.py | 1 + tests/test_dataset.py | 4 +-- tests/test_pulses.py | 76 ++++------------------------------------- tests/test_respro.py | 7 ++-- tests/test_sequences.py | 38 ++++++++++++++++++++- 5 files changed, 50 insertions(+), 76 deletions(-) diff --git a/tests/test_criteria.py b/tests/test_criteria.py index eb462e3..9dfbd88 100644 --- a/tests/test_criteria.py +++ b/tests/test_criteria.py @@ -1,3 +1,4 @@ +import numpy as np from pyepr.criteria import * import time import deerlab as dl diff --git a/tests/test_dataset.py b/tests/test_dataset.py index acbbb9c..f89c65a 100644 --- a/tests/test_dataset.py +++ b/tests/test_dataset.py @@ -55,7 +55,7 @@ def dataset_from_sequence(): seq = FieldSweepSequence(B=12200, Bwidth=500, LO=34.4, reptime=3e3, averages=1, shots=100) - t, data = _simulate_field_sweep(seq) + t, data = seq.simulate() data += rng.normal(0,0.04,data.shape) + 1j*rng.normal(0,0.04,data.shape) extra_params = {"nAvgs":1} dset = create_dataset_from_sequence(data,seq, extra_params) @@ -93,7 +93,7 @@ def test_merge_dataset(): def build_dataset(tmin): seq = T2RelaxationSequence( B=12200, LO=34.4, reptime=3e3, averages=1, shots=100, start=tmin) - t, data = _simulate_T2(seq,0.2) + t, data = seq.simulate() data += rng.normal(0,0.04,data.shape) + 1j*rng.normal(0,0.04,data.shape) extra_params = {"nAvgs":1} dset = create_dataset_from_sequence(data,seq, extra_params) diff --git a/tests/test_pulses.py b/tests/test_pulses.py index 555d196..1e48b3f 100644 --- a/tests/test_pulses.py +++ b/tests/test_pulses.py @@ -1,72 +1,10 @@ -from autodeer.pulses import * -import pytest +from pyepr.pulses import RectPulse, GaussianPulse, Detection +import pytest +import numpy as np +import pyepr as epr -def test_pulse_init(): - pulse = Pulse(tp=10, scale=0.5) - assert pulse.tp.value == 10 - assert pulse.scale.value == 0.5 -def test_pulse_add_phase_cycle(): - pulse = Pulse(tp=10, scale=0.5) - pulse._addPhaseCycle([0, 90, 180, 270]) - assert pulse.pcyc["Phases"] == [0, 90, 180, 270] - assert pulse.pcyc["DetSigns"] == [1, 1, 1, 1] - - -def test_pulse_is_static(): - pulse = Pulse(tp=10, scale=0.5) - assert pulse.is_static() - pulse = Pulse(tp=10, scale=0.5, t=0) - assert pulse.is_static() - pulse = Pulse(tp=10, scale=0.5, t=0, pcyc=None) - assert pulse.is_static() - tp = Parameter( - name="tp", value=10, unit="us", description="The pulse length", - axis=np.arange(0,10,1), axis_id=0) - pulse = Pulse(tp=tp, scale=0.5, t=0, pcyc=None) - assert pulse.is_static() - -def test_pulse_plot(): - pulse = Pulse(tp=10, scale=0.5) - pulse._buildFMAM(lambda x: (np.ones_like(x), np.zeros_like(x))) - pulse.plot() - -def test_pulse_exciteprofile(): - pulse = Pulse(tp=10, scale=0.5, flipangle=np.pi/2) - pulse.func = lambda x: (np.ones_like(x), np.zeros_like(x)) - freqs = np.linspace(-.25, .25, 1001) - Mag= pulse.exciteprofile(freqs=freqs) - assert len(Mag[:,0]) == 1001 - assert len(Mag[:,1]) == 1001 - assert len(Mag[:,2]) == 1001 - -def test_rectpulse_init(): - pulse = RectPulse(tp=10, freq=1, t=0, flipangle=np.pi/2) - assert pulse.tp.value == 10 - assert pulse.freq.value == 1 - assert pulse.t.value == 0 - assert pulse.flipangle.value == np.pi/2 - -def test_rectpulse_func(): - pulse = RectPulse(tp=10, freq=1, t=0, flipangle=np.pi/2) - AM, FM = pulse.func(np.arange(10)) - assert np.allclose(AM, np.ones(10)) - assert np.allclose(FM, np.ones(10) ) - -def test_hspulse_init(): - pulse = HSPulse(tp=10, order1=1, order2=6, beta=20, BW=1, init_freq=0) - assert pulse.tp.value == 10 - assert pulse.order1.value == 1 - assert pulse.order2.value == 6 - assert pulse.beta.value == 20 - assert pulse.BW.value == 1 - assert pulse.init_freq.value == 0 - assert pulse.final_freq.value == 1 - -def test_hspulse_func(): - pulse = HSPulse(tp=128, order1=1, order2=6, beta=20, BW=0.1, init_freq=0) - AM, FM = pulse.func(np.arange(10)) - # assert np.allclose(AM, np.ones(10)) - assert np.allclose(FM.min(), 0) - assert np.allclose(FM.max(), 0.1) +def test_gaussian_pulse(): + pulse = GaussianPulse(tp=100, freq=0, scale=0.5) + pulse.func() \ No newline at end of file diff --git a/tests/test_respro.py b/tests/test_respro.py index 2fe0992..b861163 100644 --- a/tests/test_respro.py +++ b/tests/test_respro.py @@ -1,8 +1,7 @@ -from pyepr.ResPro import * -from pyepr.hardware.dummy import _similate_respro +from pyepr.resonator_profile_analysis import * from pyepr.sequences import ResonatorProfileSequence from pyepr.dataset import create_dataset_from_sequence, create_dataset_from_axes -from pyepr.FieldSweep import create_Nmodel, FieldSweepAnalysis +from pyepr.fieldsweep_analysis import create_Nmodel, FieldSweepAnalysis import pytest import numpy as np from pyepr import ResonatorProfileAnalysis @@ -19,7 +18,7 @@ def lorenz_fcn(x, centre, sigma): seq = ResonatorProfileSequence(B=12220,LO=34,reptime=3e3,averages=1,shots=50,fwidth=0.3) - [tp_x, LO_axis], data = _similate_respro(seq,mode_fun) + [tp_x, LO_axis], data = seq.simulate(Q=60, fc=34.0) dset = create_dataset_from_sequence(data,seq) diff --git a/tests/test_sequences.py b/tests/test_sequences.py index c44ceb2..73801fb 100644 --- a/tests/test_sequences.py +++ b/tests/test_sequences.py @@ -4,6 +4,8 @@ import pytest import numpy as np +from pyepr.sequences.DEER import FourPulseDEERSequence, FivePulseDEERSequence, ThreePulseDEERSequence + def test_fieldsweep_simulate(): N_gyro = 0.002803632236095 @@ -82,4 +84,38 @@ def test_linked_phase_cycle(): assert np.allclose(seq.pcyc_dets, [1, 1]) table = build_table([exc, ref, det], ['iD', 'Phase Cycle'], ['4', '40']) - assert "linked to pulse 0" in table \ No newline at end of file + assert "linked to pulse 0" in table + + +def test_FourPulseDEERSequence(): + N_gyro = 0.002803632236095 + freq = 34 + + seq = FourPulseDEERSequence( + B=freq/N_gyro, + freq=freq, + reptime=3e3, + averages=1, + shots=10, + tau1=0.4, + tau2=4, + step=8, + start=0.28, + phase_cycle='16-step' + ) + + + + assert seq.tau1.value == 0.4 + assert seq.tau2.value == 4 + + assert seq.t.get_axis().shape[0] == 501 + assert seq.t.get_axis()[0] == 0.28 + assert seq.t.get_axis()[-1] == 4.28 + + assert seq.pulses[2].t.get_axis()[0] == 800 + 280 + + + axes, data = seq.simulate() + + From d10eacf95a4ef2c7ff0487d128d48adab779e58a Mon Sep 17 00:00:00 2001 From: Hugo Karas Date: Mon, 16 Nov 2026 11:05:26 +0100 Subject: [PATCH 46/55] Dataset doc-string updates --- pyepr/dataset.py | 32 ++++++++++++++++++++++++++------ 1 file changed, 26 insertions(+), 6 deletions(-) diff --git a/pyepr/dataset.py b/pyepr/dataset.py index 3741f65..9c6807b 100644 --- a/pyepr/dataset.py +++ b/pyepr/dataset.py @@ -185,7 +185,10 @@ def create_dataset_from_bruker(filepath): @xr.register_dataarray_accessor("epr") class EPRAccessor: - + """ + Xarray accessor for EPR datasets. Provides methods for saving, phase correction, normalization, FFT, and more. + These can be accessed via the `.epr` attribute of an xarray DataArray object. E.g. `dataset.epr.save('filename.h5')` + """ def __init__(self, xarray_obj): self._obj = xarray_obj @@ -229,7 +232,10 @@ def save(self, filename, type='netCDF',overwrite=True): @property - def correctphase(self): + def correctphase(self)->xr.DataArray: + """ + Correct the phase of the dataset using the DeerLab correctphase function. + """ new_obj = copy.deepcopy(self._obj) if np.iscomplexobj(self._obj.data): corr_data = correctphase(self._obj.data) @@ -240,11 +246,17 @@ def correctphase(self): @property def normalise(self): + """ + In-place normalisation of the dataset to the maximum absolute value of the data. + """ self._obj.data = self._obj.data / np.abs(self._obj.data).max() return self._obj @property - def correctphasefull(self): + def correctphasefull(self)->xr.DataArray: + """ + Correct the phase of the dataset using the DeerLab correctphase function and keeps the real and imaginary parts of the data. + """ new_obj = copy.deepcopy(self._obj) if np.iscomplexobj(self._obj.data): Re,Im,_ = correctphase(self._obj.data,full_output=True) @@ -254,13 +266,19 @@ def correctphasefull(self): return new_obj @property - def SNR(self): + def SNR(self)->float: + """ + Calculate the signal-to-noise ratio of the dataset using the DeerLab der_snr function. + """ from deerlab import der_snr norm_data = self._obj.data / np.abs(self._obj.data).max() return 1/der_snr(norm_data) @property def fft(self): + """ + Calculate the FFT of the dataset and returns a new dataset with the FFT applied. + """ new_obj = copy.deepcopy(self._obj) new_obj.data = fft.fftshift(fft.fft(self._obj.data)) new_coords = {} @@ -278,7 +296,8 @@ def MeasurementTime(self): @property - def sequence(self): + def sequence(self)->Sequence: + """Extracts the PyEPR Sequence object from the dataset attributes and coordinates.""" dataset_attrs = self._obj.attrs dataset_coords = self._obj.coords @@ -397,7 +416,8 @@ def merge(self,other,ignore_errors=True): def downconvert_dataset(dataset, filter_type='boxcar',IF=None,reduce=True,sampling_rate=None,**kwargs): """ - Downconvert a dataset to baseband using a filter + Downconvert a dataset to baseband using a filter + Parameters ---------- dataset : xr.DataArray From ff69ac5c22a9dee2854b2be35c35580d6d4f2721 Mon Sep 17 00:00:00 2001 From: Hugo Karas Date: Mon, 16 Nov 2026 11:05:44 +0100 Subject: [PATCH 47/55] Documentation update --- docsrc/API_docs.rst | 67 ++++++-- docsrc/README.md | 5 + docsrc/_static/autoapi.css | 23 +++ docsrc/_templates/autoapi/python/class.rst | 150 ++++++++++++++++++ docsrc/_templates/autoapi/python/function.rst | 26 +++ docsrc/conf.py | 28 +++- .../advanced_sequences/GALLERY_HEADER.rst | 4 + .../advanced_sequence_axes.py | 109 +++++++++++++ .../linking_sequence_parameter.py | 0 .../uhrig_decoupling_sequence.py | 95 +++++++++++ docsrc/examples/tools/GALLERY_HEADER.rst | 4 + docsrc/examples/{ => tools}/loading_cw.py | 3 +- docsrc/examples/uhrig_decoupling_sequence.py | 4 - docsrc/sg_execution_times.rst | 17 +- docsrc/tutorial_hardware.md | 10 +- docsrc/tutorial_loading.md | 2 +- docsrc/tutorial_sequencer.md | 48 ++++-- 17 files changed, 549 insertions(+), 46 deletions(-) create mode 100644 docsrc/_static/autoapi.css create mode 100644 docsrc/_templates/autoapi/python/class.rst create mode 100644 docsrc/_templates/autoapi/python/function.rst create mode 100644 docsrc/examples/advanced_sequences/GALLERY_HEADER.rst create mode 100644 docsrc/examples/advanced_sequences/advanced_sequence_axes.py rename docsrc/examples/{ => advanced_sequences}/linking_sequence_parameter.py (100%) create mode 100644 docsrc/examples/advanced_sequences/uhrig_decoupling_sequence.py create mode 100644 docsrc/examples/tools/GALLERY_HEADER.rst rename docsrc/examples/{ => tools}/loading_cw.py (82%) delete mode 100644 docsrc/examples/uhrig_decoupling_sequence.py diff --git a/docsrc/API_docs.rst b/docsrc/API_docs.rst index 5e13ce5..3fa8817 100644 --- a/docsrc/API_docs.rst +++ b/docsrc/API_docs.rst @@ -1,3 +1,5 @@ +.. rst-class:: api-docs + API doc ================= Classes @@ -26,18 +28,44 @@ Analysis Modules Sequences ~~~~~~~~~ -.. _Sequences: + +Setup and Calibration Sequences ++++++++++++++++++++++++++++++++ +.. _SetupSequences: .. autoapisummary:: pyepr.sequences.HahnEchoSequence - pyepr.sequences.HahnEchoRelaxationSequence - pyepr.sequences.FieldSweepSequence - pyepr.sequences.ReptimeScan - pyepr.sequences.CarrPurcellSequence + pyepr.sequences.FieldSweepSequence pyepr.sequences.ResonatorProfileSequence - pyepr.sequences.T1InversionRecoverySequence pyepr.sequences.TWTProfileSequence +Relxation Sequences ++++++++++++++++++++++ +.. _RelaxationSequences: +.. autoapisummary:: + + pyepr.sequences.HahnEchoRelaxationSequence + pyepr.sequences.CarrPurcellSequence + pyepr.sequences.T1InversionRecoverySequence + pyepr.sequences.ReptimeScan + +Dipolar EPR Sequences ++++++++++++++++++++++ +.. _DipolarSequences: + +.. autoapisummary:: + + pyepr.sequences.DEER.FourPulseDEERSequence + +Hyperfine Spectroscopy Sequences +++++++++++++++++++++++++++++++++ +.. _HyperfineSequences: + +.. autoapisummary:: + + pyepr.sequences.ESEEM.ThreePulseESEEMSequence + pyepr.sequences.ESEEM.HYSCORESequence + Pulses ~~~~~~ .. _Pulses: @@ -56,29 +84,36 @@ Pulses Termination Criteria ~~~~~~~~~~~~~~~~~~~~ +Termination criteria are used for stopping sequences under specific conditions, +such as when a certain signal-to-noise ratio is reached or when a specific time has elapsed. +They are used through the :py:meth:`interface.terminate_at ` method. + .. autoapisummary:: pyepr.criteria.Criteria pyepr.criteria.TimeCriteria pyepr.criteria.SNRCriteria -Utilities -~~~~~~~~~ - -.. autoapisummary:: - - pyepr.dataset.EPRAccessor Interfaces ~~~~~~~~~~ .. _Interfaces: .. autoapisummary:: - pyepr.classes.Interface + + pyepr.hardware.BaseInterfaceClass.Interface pyepr.hardware.Bruker_AWG.BrukerAWG pyepr.hardware.Bruker_MPFU.BrukerMPFU - pyepr.hardware.XeprAPI_link.XeprAPILink pyepr.hardware.ETH_awg.ETH_awg_interface + pyepr.hardware.PyEPR_control.PyEPRControlInterface + pyepr.hardware.XeprAPI_link.XeprAPILink + +Utilities +~~~~~~~~~ + +.. autoapisummary:: + + pyepr.dataset.EPRAccessor Functions ---------------- @@ -87,6 +122,8 @@ I/O ~~~ .. autoapisummary:: + :nosignatures: + pyepr.tools.eprload pyepr.utils.save_file pyepr.dataset.create_dataset_from_sequence @@ -98,6 +135,8 @@ Utilities ~~~~~~~~~ .. autoapisummary:: + :nosignatures: + pyepr.utils.transpose_dict_of_list pyepr.utils.transpose_list_of_dicts pyepr.utils.round_step diff --git a/docsrc/README.md b/docsrc/README.md index 0b040ec..337ed93 100644 --- a/docsrc/README.md +++ b/docsrc/README.md @@ -3,4 +3,9 @@ To build the documentation and serve it with live reloading, run: ``` sphinx-autobuild docsrc docsrc/_build/html +``` + +to build the documentation once without live reloading, run: +``` +sphinx-build -b html docsrc docsrc/_build/html ``` \ No newline at end of file diff --git a/docsrc/_static/autoapi.css b/docsrc/_static/autoapi.css new file mode 100644 index 0000000..5a1517d --- /dev/null +++ b/docsrc/_static/autoapi.css @@ -0,0 +1,23 @@ +/* "Attributes" / "Methods" headings on class pages (_templates/autoapi/python/class.rst). + Styled as section headings so they stand apart from docstring rubrics such as "Examples". */ +p.rubric.autoapi-member-heading { + font-size: 1.25em; + margin-top: 2rem; + padding-bottom: 0.25rem; + border-bottom: 1px solid var(--color-background-border); +} + +/* Summary tables on API_docs.rst (its top section has class "api-docs"): full width with + a fixed first column, so every table on the page lines up. */ +section.api-docs table.autosummary { + width: 100%; + table-layout: fixed; +} +section.api-docs table.autosummary td:first-child { + width: 40%; +} + +/* "Inherited from X: a, b, c" link lists under those headings. */ +div.autoapi-inherited { + margin-top: 1rem; +} diff --git a/docsrc/_templates/autoapi/python/class.rst b/docsrc/_templates/autoapi/python/class.rst new file mode 100644 index 0000000..9b750a5 --- /dev/null +++ b/docsrc/_templates/autoapi/python/class.rst @@ -0,0 +1,150 @@ +{# Class template: groups members under "Attributes" and "Methods" headings + instead of listing them in source order. Properties are treated as + attributes. Members stay nested in the py:class directive so their + signatures and cross-reference targets are unchanged; reST does not allow + section titles inside a directive, so the headings are rubrics. + Only members defined (or overridden) by this class are documented in full; + inherited members are listed as links to the class that defines them. #} +{% macro inherited_links(members, role) %} + {% for group in members|groupby("obj.inherited_from.full_name") %} + + .. container:: autoapi-inherited + + **Inherited from** :py:class:`~{{ group.grouper }}`: {% for member in group.list %}:py:{{ role }}:`~{{ group.grouper }}.{{ member.short_name }}`{% if not loop.last %}, {% endif %}{% endfor %} + + {% endfor %} +{% endmacro %} +{% if obj.display %} + {% if is_own_page %} +{{ obj.id }} +{{ "=" * obj.id | length }} + + {% endif %} + {% set visible_children = obj.children|selectattr("display")|list %} + {% set own_page_children = visible_children|selectattr("type", "in", own_page_types)|list %} + {% set inline_children = visible_children|rejectattr("type", "in", own_page_types)|list %} + {% set inline_attributes = inline_children|selectattr("type", "in", ["attribute", "property"])|list %} + {% set inline_methods = inline_children|selectattr("type", "equalto", "method")|list %} + {% set inline_other = inline_children|rejectattr("type", "in", ["attribute", "property", "method"])|list %} + {% if is_own_page and own_page_children %} +.. toctree:: + :hidden: + + {% for child in own_page_children %} + {{ child.include_path }} + {% endfor %} + + {% endif %} + {% if is_own_page %} +{# Declare the module so sphinx.ext.viewcode can add [source] links; + without it own-page classes have no module and get no links. #} +.. py:currentmodule:: {{ obj.id[:-(obj.qual_name|length + 1)] }} + + {% endif %} +.. py:{{ obj.type }}:: {% if is_own_page %}{{ obj.qual_name }}{% else %}{{ obj.short_name }}{% endif %}{% if obj.type_params %}[{{ obj.type_params }}]{% endif %}{% if obj.args %}({{ obj.args }}){% endif %} + + {% for (args, return_annotation) in obj.overloads %} + {{ " " * (obj.type | length) }} {{ obj.short_name }}{% if args %}({{ args }}){% endif %} + + {% endfor %} + {% if obj.bases %} + {% if "show-inheritance" in autoapi_options %} + + Bases: {% for base in obj.bases %}{{ base|link_objs }}{% if not loop.last %}, {% endif %}{% endfor %} + {% endif %} + + + {% if "show-inheritance-diagram" in autoapi_options and obj.bases != ["object"] %} + .. autoapi-inheritance-diagram:: {{ obj.obj["full_name"] }} + :parts: 1 + {% if "private-members" in autoapi_options %} + :private-bases: + {% endif %} + + {% endif %} + {% endif %} + {% if obj.docstring %} + + {{ obj.docstring|indent(3) }} + {% endif %} + {% if inline_attributes %} + + .. rubric:: Attributes + :class: autoapi-member-heading + + {% for obj_item in inline_attributes|rejectattr("inherited") %} + + {{ obj_item.render()|indent(3) }} + {% endfor %} +{{ inherited_links(inline_attributes|selectattr("inherited")|list, "attr") }} + {% endif %} + {% if inline_methods %} + + .. rubric:: Methods + :class: autoapi-member-heading + + {% for obj_item in inline_methods|rejectattr("inherited") %} + + {{ obj_item.render()|indent(3) }} + {% endfor %} +{{ inherited_links(inline_methods|selectattr("inherited")|list, "meth") }} + {% endif %} + {% for obj_item in inline_other %} + + {{ obj_item.render()|indent(3) }} + {% endfor %} + {% if is_own_page and own_page_children %} + {% set visible_attributes = own_page_children|selectattr("type", "in", ["attribute", "property"])|list %} + {% if visible_attributes %} +Attributes +---------- + +.. autoapisummary:: + + {% for attribute in visible_attributes %} + {{ attribute.id }} + {% endfor %} + + + {% endif %} + {% set visible_exceptions = own_page_children|selectattr("type", "equalto", "exception")|list %} + {% if visible_exceptions %} +Exceptions +---------- + +.. autoapisummary:: + + {% for exception in visible_exceptions %} + {{ exception.id }} + {% endfor %} + + + {% endif %} + {% set visible_classes = own_page_children|selectattr("type", "equalto", "class")|list %} + {% if visible_classes %} +Classes +------- + +.. autoapisummary:: + + {% for klass in visible_classes %} + {{ klass.id }} + {% endfor %} + + + {% endif %} + {% set visible_methods = own_page_children|selectattr("type", "equalto", "method")|list %} + {% if visible_methods %} +Methods +------- + +.. autoapisummary:: + + {% for method in visible_methods %} + {{ method.id }} + {% endfor %} + + + {% endif %} + {% endif %} +{% endif %} diff --git a/docsrc/_templates/autoapi/python/function.rst b/docsrc/_templates/autoapi/python/function.rst new file mode 100644 index 0000000..8e4c5fd --- /dev/null +++ b/docsrc/_templates/autoapi/python/function.rst @@ -0,0 +1,26 @@ +{# Function template: same as the autoapi default, except that on a function's + own page the module is declared with py:currentmodule so sphinx.ext.viewcode + can add a [source] link (see class.rst). #} +{% if obj.display %} + {% if is_own_page %} +{{ obj.id }} +{{ "=" * obj.id | length }} + +.. py:currentmodule:: {{ obj.id[:-(obj.qual_name|length + 1)] }} + + {% endif %} +.. py:function:: {% if is_own_page %}{{ obj.qual_name }}{% else %}{{ obj.short_name }}{% endif %}{% if obj.type_params %}[{{ obj.type_params }}]{% endif %}({{ obj.args }}){% if obj.return_annotation is not none %} -> {{ obj.return_annotation }}{% endif %} + {% for (args, return_annotation) in obj.overloads %} + + {%+ if is_own_page %}{{ obj.qual_name }}{% else %}{{ obj.short_name }}{% endif %}({{ args }}){% if return_annotation is not none %} -> {{ return_annotation }}{% endif %} + {% endfor %} + {% for property in obj.properties %} + + :{{ property }}: + {% endfor %} + + {% if obj.docstring %} + + {{ obj.docstring|indent(3) }} + {% endif %} +{% endif %} diff --git a/docsrc/conf.py b/docsrc/conf.py index 42c8edf..baef093 100644 --- a/docsrc/conf.py +++ b/docsrc/conf.py @@ -38,7 +38,8 @@ ] templates_path = ['_templates'] -exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store'] +exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store', + 'examples'] # gallery sources; sphinx-gallery renders them into auto_examples # -- Options for autoapi.extension ------------------------------------------- # https://sphinx-autoapi.readthedocs.io/en/latest/config.html @@ -54,7 +55,7 @@ autoapi_add_toctree_entry = False autoapi_python_class_content= "both" autoapi_python_use_implicit_namespaces = True -autoapi_own_page_level = 'class' +autoapi_own_page_level = 'function' autoapi_options = ['members', 'undoc-members', 'show-inheritance', @@ -65,6 +66,7 @@ 'examples_dirs': 'examples', # path to your example scripts 'gallery_dirs': 'auto_examples', # path to where to save gallery generated output 'filename_pattern': r'.*\.py', + 'subsection_order': ['examples/advanced_sequences', 'examples/tools', '*'], } # -- Options for HTML output ------------------------------------------------- @@ -72,14 +74,34 @@ html_theme = 'furo' html_static_path = ['_static'] +html_css_files = ['autoapi.css'] html_theme_options = { # "announcement": "Version 0.7 out now!", "light_logo": "pyepr_logo_light.svg", "dark_logo": "pyepr_logo_dark.svg", + "source_repository": "https://github.com/jeschkelab/PyEPR/", + "source_branch": "main", + "source_directory": "docsrc/", } favicons = [ "favicon_16x16.png", "favicon_32x32.png", "icon.svg", -] \ No newline at end of file +] + + +def setup(app): + # sphinx-autoapi 2.0.1 ignores autosummary's :nosignatures: option on Sphinx >= 9, + # which expects get_items() to return None as the signature when it is set. + from autoapi.directives import AutoapiSummary + + class AutoapiSummaryNoSig(AutoapiSummary): + def get_items(self, names): + items = super().get_items(names) + if 'nosignatures' in self.options or self.options.get('signatures') == 'none': + items = [(name, None, summary, real_name) + for name, _sig, summary, real_name in items] + return items + + app.add_directive('autoapisummary', AutoapiSummaryNoSig, override=True) \ No newline at end of file diff --git a/docsrc/examples/advanced_sequences/GALLERY_HEADER.rst b/docsrc/examples/advanced_sequences/GALLERY_HEADER.rst new file mode 100644 index 0000000..1495e0f --- /dev/null +++ b/docsrc/examples/advanced_sequences/GALLERY_HEADER.rst @@ -0,0 +1,4 @@ +Advanced Sequences +------------------ + +Examples of building more complex pulse sequences with PyEPR. diff --git a/docsrc/examples/advanced_sequences/advanced_sequence_axes.py b/docsrc/examples/advanced_sequences/advanced_sequence_axes.py new file mode 100644 index 0000000..717b38f --- /dev/null +++ b/docsrc/examples/advanced_sequences/advanced_sequence_axes.py @@ -0,0 +1,109 @@ +""" +Advanced Sequence Axes +=============================================== + + +""" +# %% +import pyepr as epr +import numpy as np + +# %% +# Parameter Arithmetic +# -------------------- +# +# Parameters can be added to, subtracted from and multiplied by numbers or +# other parameters. Any dynamic axes are carried through to the new parameter. + +tau1 = epr.Parameter("tau1", 400, unit="ns", description="Interpulse delay 1") +tau2 = epr.Parameter("tau2", 2000, unit="ns", description="Interpulse delay 2") +t = epr.Parameter( + "t", 200, step=8, dim=250, unit="ns", description="Pump pulse position") + +pump_t = tau1 + t +ref2_t = 2 * tau1 + tau2 + +print(f"Pump pulse position: {pump_t.get_axis()[:5]} ... ns") +print(f"Second refocusing pulse position: {ref2_t.value} ns") + +# %% +# Linked Axes +# ----------- +# +# In experiments such as the resonator profile sequence two parameters need to +# be stepped together, we can do this by linking the two parameters together. +# Parameter Arithmetic automatically creates a new parameter that is linked to +# the original parameter. + +fc = 34.0 # GHz +B = 12127.0 # Gauss +gyro = fc/B # GHz/Gauss + +freq = epr.Parameter( + "freq", fc, start=-0.3, step=0.02, dim=30, unit="GHz", + description="Frequency") +B_field = epr.Parameter( + "B", B, start=-0.3/gyro, step=0.02/gyro, dim=30, unit="Gauss", + link=freq, description="B0 Field") + +seq = epr.Sequence( + name="linked_axes", B=B_field, freq=fc, reptime=3e3, averages=1, shots=10) +seq.freq = freq +seq.addPulse([ + epr.RectPulse(t=0, tp=16, freq=0, flipangle=np.pi/2), + epr.RectPulse(t=500, tp=32, freq=0, flipangle=np.pi), + epr.Detection(t=1000, tp=512)]) +seq.evolution([freq]) + +# Both ``freq`` and ``B`` are now stepped along the same axis +print(f"Variables: {seq.progTable['Variable']}, axis IDs: {seq.progTable['axID']}") +print(seq) + +# %% +# Reduced Axes +# ------------ +# We can also tag one moving parameter to be automatically reduced to a single +# value, for example for tau1 averaging in 4p-DEER. + +tau1 = epr.Parameter( + "tau1", 400, step=16, dim=8, unit="ns", description="Interpulse delay 1") +tau2 = epr.Parameter("tau2", 2000, unit="ns", description="Interpulse delay 2") +t = epr.Parameter( + "t", 200, step=8, dim=250, unit="ns", description="Pump pulse position") + +seq = epr.Sequence( + name="4pDEER_tau_avg", B=B, freq=fc, reptime=3e3, averages=1, shots=10) +seq.addPulse([ + epr.RectPulse(t=0, tp=16, freq=0, flipangle=np.pi/2), + epr.RectPulse(t=tau1, tp=32, freq=0, flipangle=np.pi), + epr.RectPulse(t=tau1 + t, tp=32, freq=-0.1, flipangle=np.pi), + epr.RectPulse(t=2*tau1 + tau2, tp=32, freq=0, flipangle=np.pi), + epr.Detection(t=2*tau1 + 2*tau2, tp=256)]) +seq.evolution([t, tau1], reduce=[tau1]) + +print(f"Reduced: {seq.progTable['reduce']}") +print(seq) + +# %% +# Non-linear Axes +# ---------------- +# We can also define a parameter that is non-linear for non-uniform sampling +# for example. +# +# Non linear axes are not supported on all spectrometer interfaces, for example +# Bruker XeprAPI based systems. + +tau = epr.Parameter( + "tau", np.round(np.geomspace(200, 20000, 40)), unit="ns", + description="Interpulse delay") + +seq = epr.Sequence( + name="T2_NUS", B=B, freq=fc, reptime=3e3, averages=1, shots=10) +seq.addPulse([ + epr.RectPulse(t=0, tp=16, freq=0, flipangle=np.pi/2), + epr.RectPulse(t=tau, tp=32, freq=0, flipangle=np.pi), + epr.Detection(t=2*tau, tp=256)]) +seq.evolution([tau]) + +print(f"tau axis: {tau.get_axis()[:5]} ... ns") +print(seq) \ No newline at end of file diff --git a/docsrc/examples/linking_sequence_parameter.py b/docsrc/examples/advanced_sequences/linking_sequence_parameter.py similarity index 100% rename from docsrc/examples/linking_sequence_parameter.py rename to docsrc/examples/advanced_sequences/linking_sequence_parameter.py diff --git a/docsrc/examples/advanced_sequences/uhrig_decoupling_sequence.py b/docsrc/examples/advanced_sequences/uhrig_decoupling_sequence.py new file mode 100644 index 0000000..1b43db4 --- /dev/null +++ b/docsrc/examples/advanced_sequences/uhrig_decoupling_sequence.py @@ -0,0 +1,95 @@ +""" +Uhrig Decoupling Sequence +=============================================== + +The Uhrig dynamical decoupling (UDD) sequence uses ``n`` refocusing pulses +placed non-uniformly over the total evolution time ``T``. The j-th pulse is +placed at + +.. math:: + t_j = T \\sin^2\\left(\\frac{\\pi j}{2n + 2}\\right), \\quad j = 1, \\dots, n + +and the echo forms at ``T``. +""" +# %% +import pyepr as epr +import numpy as np +import matplotlib.pyplot as plt + +epr.set_waveform_precision(1) + +# %% +# Define the total evolution time ``T`` as a virtual parameter, this is +# stepped but never passed to the spectrometer itself. + +n = 5 # Number of refocusing pulses +T = epr.Parameter( + "T", 1000, step=200, dim=50, unit="ns", + description="Total evolution time", virtual=True) + +# %% +# Build the sequence. Each refocusing pulse position is a fixed fraction of +# ``T``, so its step is generally not a multiple of the waveform precision. +# Rounding the step would accumulate errors along the axis, so instead each +# position is given as an explicit (non-uniform) axis, rounded point by point, +# and linked to the ``T`` axis. +# +# The same phase cycle as the Carr-Purcell sequence is used. Shifting the +# phase of a refocusing pulse by :math:`\phi` shifts the echo phase by +# :math:`2\phi`, which sets the detection signs. +# +# ====================================== ============== =============== +# Pulse Phases Detection signs +# ====================================== ============== =============== +# :math:`\pi/2` +x, -x +, - +# :math:`\pi_1` to :math:`\pi_{n-2}` +x, +y, -x, -y +, -, +, - +# :math:`\pi_{n-1}` +x, -x +, + +# :math:`\pi_n` +x \+ +# ====================================== ============== =============== +# +# The phase cycles are combined multiplicatively, giving +# :math:`2 \times 4^{n-2} \times 2` steps in total. + +seq = epr.Sequence( + name="UhrigSequence", B=12127, freq=34, reptime=3e3, averages=1, shots=10) + +seq.addPulse(epr.RectPulse( + t=0, tp=16, freq=0, flipangle=np.pi/2, + pcyc={"phases": [0, np.pi], "dets": [1, -1]})) + +for j in range(1, n + 1): + if j == n: + pcyc = {"phases": [0], "dets": [1]} + elif j == n - 1: + pcyc = {"phases": [0, np.pi], "dets": [1, 1]} + else: + pcyc = {"phases": [0, np.pi/2, np.pi, -np.pi/2], "dets": [1, -1, 1, -1]} + + t_j = epr.Parameter( + f"t{j}", np.round(T.get_axis() * np.sin(np.pi * j / (2 * n + 2))**2), + unit="ns", link=T, description=f"Position of refocusing pulse {j}") + seq.addPulse(epr.RectPulse( + t=t_j, tp=32, freq=0, flipangle=np.pi, pcyc=pcyc)) + +seq.addPulse(epr.Detection(t=T, tp=512)) +seq.evolution([T]) + +print(seq) +print(f"Number of phase cycle steps: {seq.pcyc_dets.shape[0]}") + +# %% +# Plot the pulse positions as a fraction of ``T``, compared to a Carr-Purcell +# sequence with the same number of pulses. + +udd = [seq.pulses[j].t.value / T.value for j in range(1, n + 1)] +cp = [(2 * j - 1) / (2 * n) for j in range(1, n + 1)] + +plt.figure(figsize=(6, 2)) +plt.eventplot([cp, udd], lineoffsets=[0, 1], colors=["C0", "C1"]) +plt.yticks([0, 1], ["Carr-Purcell", "Uhrig"]) +plt.xlim(0, 1) +plt.xlabel("t / T") +plt.tight_layout() + +# %% +seq.draw() diff --git a/docsrc/examples/tools/GALLERY_HEADER.rst b/docsrc/examples/tools/GALLERY_HEADER.rst new file mode 100644 index 0000000..f1f0588 --- /dev/null +++ b/docsrc/examples/tools/GALLERY_HEADER.rst @@ -0,0 +1,4 @@ +Tools +----- + +Examples of PyEPR's utilities for loading, plotting and handling data. diff --git a/docsrc/examples/loading_cw.py b/docsrc/examples/tools/loading_cw.py similarity index 82% rename from docsrc/examples/loading_cw.py rename to docsrc/examples/tools/loading_cw.py index a110f43..9236e43 100644 --- a/docsrc/examples/loading_cw.py +++ b/docsrc/examples/tools/loading_cw.py @@ -4,7 +4,8 @@ PyEPR can also be used to load CW EPR data files, for plotting and analysis in python. -At the moment, PyEPR is focused on providing analysis for pulse EPR data, and the CW EPR functionality is limited to loading and plotting data. +At the moment, PyEPR is focused on providing analysis for pulse EPR data, +and the CW EPR functionality is limited to loading and plotting data. Nonetheless Supported file formats include: - Bruker .DTA/.DSC files diff --git a/docsrc/examples/uhrig_decoupling_sequence.py b/docsrc/examples/uhrig_decoupling_sequence.py deleted file mode 100644 index 4a42278..0000000 --- a/docsrc/examples/uhrig_decoupling_sequence.py +++ /dev/null @@ -1,4 +0,0 @@ -""" -Uhrig Decoupling Sequence -=============================================== -""" diff --git a/docsrc/sg_execution_times.rst b/docsrc/sg_execution_times.rst index 78433a9..530f76e 100644 --- a/docsrc/sg_execution_times.rst +++ b/docsrc/sg_execution_times.rst @@ -6,7 +6,7 @@ Computation times ================= -**00:00.000** total execution time for 0 files **from all galleries**: +**00:00.133** total execution time for 4 files **from all galleries**: .. container:: @@ -32,6 +32,15 @@ Computation times * - Example - Time - Mem (MB) - * - N/A - - N/A - - N/A + * - :ref:`sphx_glr_auto_examples_advanced_sequences_uhrig_decoupling_sequence.py` (``examples/advanced_sequences/uhrig_decoupling_sequence.py``) + - 00:00.133 + - 0.0 + * - :ref:`sphx_glr_auto_examples_advanced_sequences_advanced_sequence_axes.py` (``examples/advanced_sequences/advanced_sequence_axes.py``) + - 00:00.000 + - 0.0 + * - :ref:`sphx_glr_auto_examples_advanced_sequences_linking_sequence_parameter.py` (``examples/advanced_sequences/linking_sequence_parameter.py``) + - 00:00.000 + - 0.0 + * - :ref:`sphx_glr_auto_examples_tools_loading_cw.py` (``examples/tools/loading_cw.py``) + - 00:00.000 + - 0.0 diff --git a/docsrc/tutorial_hardware.md b/docsrc/tutorial_hardware.md index 90abf79..e9b0d05 100644 --- a/docsrc/tutorial_hardware.md +++ b/docsrc/tutorial_hardware.md @@ -1,8 +1,9 @@ # Interfacing with Hardware PyEPR has been designed to interface with a range of different EPR spectrometers, providing a hardware abstraction layer that allows users to write experiments in a hardware-agnostic manner. Currently, PyEPR supports the following hardware interfaces: - - Bruker ElexSys AWG based spectrometers - - ETH Zürich Matlab based homebuilt spectrometers + +- Bruker ElexSys AWG based spectrometers +- ETH Zürich Matlab based homebuilt spectrometers For homebuilt spectrometers, there can be additional packages required. Please refer to the respective hardware interface documentation for more details. @@ -82,8 +83,9 @@ This is done as an amplitude sweep, either as a Hahn Echo (`amp_hahn`) or more c When a hole-burning recovery experiment is used, a pair of on-resonance rectangular pulses are first created using the `tune_rectpulse` method. ```python -from pyepr.pulses import GaussPulse -pulse = GaussPulse(tp=32, freq=0, flipangle=np.pi) # Create a Gaussian pulse with length 32 ns +import numpy as np +from pyepr.pulses import GaussianPulse +pulse = GaussianPulse(tp=32, freq=0, flipangle=np.pi) # Create a Gaussian pulse with length 32 ns tuned_pulse = interface.tune_pulse( pulse, 'amp_nut', diff --git a/docsrc/tutorial_loading.md b/docsrc/tutorial_loading.md index 462622c..66587b5 100644 --- a/docsrc/tutorial_loading.md +++ b/docsrc/tutorial_loading.md @@ -87,7 +87,7 @@ fieldsweep.plot() .. code-block:: python tm_data = epr.eprload('path/to/tm_datafile.h5') - t2_analysis = epr.HahnEchoRelaxationAnalysis(t2_data) + t2_analysis = epr.HahnEchoRelaxationAnalysis(tm_data) # Calculate T2 relaxation time t2_result = t2_analysis.fit() # Plot the results diff --git a/docsrc/tutorial_sequencer.md b/docsrc/tutorial_sequencer.md index 784cbf3..a406d35 100644 --- a/docsrc/tutorial_sequencer.md +++ b/docsrc/tutorial_sequencer.md @@ -4,17 +4,19 @@ PyEPR provides an intuitive object-oriented pulse programmer allowing the user t PyEPR uses ns, GHz and G as the default time, frequency and field units. Very occasionally, other units such as µs or MHz are used, in which case it will be explicitly mentioned. -## Seqeunce Construction +## Sequence Construction First we must import the pyepr package, and set our waveform precision. This waveform precision determines the time resolution of the pulse length and positons. If values are given that are not multiples of the waveform precision, they will be rounded. ```python +import numpy as np import pyepr as epr epr.set_waveform_precision(2) # Set waveform precision to 2 ns ``` +### 1. Creating the base sequence object Next, we want to create a sequence object. Here we are aiming to create a simple Hahn Echo sequence. -It is normally recommened, to set the field `B` and frequency `freq` as external variables. +It is normally recommended, to set the field `B` and frequency `freq` as external variables. ```python B = 12200 # Magnetic field in Gauss freq = 34.0 # Microwave frequency in GHz @@ -26,40 +28,53 @@ seq = epr.Sequence(name='Hahn Echo Sequence', shots = 20, # Number of shots per point ) ``` +### 2. Defining the moving parmameter +We now need a time axis for our sequence and to add them to the sequence object. +This is necessary for parameter sweeps and for any parameter that we would ideally like to +be saved in the sequence object for later use. + +```python +t = epr.Parameter(name='Interpulse Delay', + value=400, # Initial interpulse delay in ns + step=8, # Step size in ns + dim=1024, # Number of points, + unit='ns', # Unit of the parameter + description='Interpulse delay between the pi/2 and pi pulse' + ) +``` + +### 3. Defining the pulses Now we need to define some pulses that can be used in our sequence. Here we create a 90 degree and a 180 degree rectangular pulse. +Standard phases cycles are added to each pulse using the pcyc argument and a dict listing the phases and detection sign for each step. PyEPR automatically multiplies the phase cycles up, i.e. a 4 step on two pulses will result in a 16 step phase cycle. + These pulses will eventually need a scale (amplitude), before the sequence can be run on hardware. A Detection window is also created ```python p90 = epr.RectPulse(tp=16, freq=0, # Frequency offset in GHz, w.r.t the sequence frequency, - flipangle=np.pi/2, # Flip angle in degrees + flipangle=np.pi/2, # Flip angle in radians pcyc = {"phases":[0, np.pi], "dets":[1,-1]} ) p180 = epr.RectPulse(tp=32, freq=0, # Frequency offset in GHz, w.r.t the sequence frequency, - flipangle=np.pi, # Flip angle in degrees + flipangle=np.pi, # Flip angle in radians ) det = epr.Detection(tp=32, freq=0, # Frequency offset in GHz, w.r.t the sequence frequency, ) ``` -We now need a time axis for our sequence and to add them to the sequence object. When a pulse is copied into the sequence using the `addPulse` method, parameters can be modified allowing the same pulse can be used multiple times with different timings or amplitudes. ```python -t = epr.Parameter(name='Interpulse Delay', - value=400, # Initial interpulse delay in ns - step=8, # Step size in ns - dim=1024, # Number of points, - unit='ns', # Unit of the parameter - description='Interpulse delay between the pi/2 and pi pulse' - ) - # Adding the pulses to the sequence seq.addPulse(p90.copy(t=0)) seq.addPulse(p180.copy(t=t)) seq.addPulse(det.copy(t=2*t)) +``` -# Defining the evolution +### 4. Defining the evolution +To define the evolution of the sequence, we need to specify which parameters are evolving. In this case, we want to evolve the interpulse delay `t`. + +```python seq.evolution([t]) ``` ### Advanced Sequences @@ -67,9 +82,12 @@ The sequence class is capable of more advanced features such as: - Linked axes - Reduced axes - Non-linear axes +- Linked phase cycles + +Which are covered in the [examples](auto_examples/index.rst). ## Default Experiments -For convienience, several common EPR experiments are pre-defined and can be easily instantiated and modified. +For convenience, several common EPR experiments are pre-defined and can be easily instantiated and modified. A list of currently implemented experiments can be found in the [API documentation](API_docs.rst). Here we show how to create a simple Hahn Echo Relaxation experiment. ```python From 703e9be247fae4a0b20bcd509a758f291db9b277 Mon Sep 17 00:00:00 2001 From: Hugo Karas Date: Mon, 16 Nov 2026 15:23:28 +0100 Subject: [PATCH 48/55] Updates to PyEPR_Control and other minor changes --- pyepr/hardware/BaseInterfaceClass.py | 4 ++-- pyepr/hardware/PyEPR_control.py | 27 ++++++++++++++++++++------- pyepr/resonator_profile_analysis.py | 2 +- pyepr/sequences.py | 24 +++++++++++++++++++++--- 4 files changed, 44 insertions(+), 13 deletions(-) diff --git a/pyepr/hardware/BaseInterfaceClass.py b/pyepr/hardware/BaseInterfaceClass.py index 7c7e296..4973e89 100644 --- a/pyepr/hardware/BaseInterfaceClass.py +++ b/pyepr/hardware/BaseInterfaceClass.py @@ -481,7 +481,7 @@ def tune_KBBPulse(self,*, freq, B, reptime, tp, init_freq, final_freq, shots=200 self.launch(ChirpEchoTuneSeq, savename=f"chirpechotune_step2", **kwargs) - + time.sleep(5) while self.isrunning(): time.sleep(1) @@ -499,7 +499,7 @@ def tune_KBBPulse(self,*, freq, B, reptime, tp, init_freq, final_freq, shots=200 self.launch(ChirpEchoTuneSeq, savename=f"chirpechotune_step3", **kwargs) - + time.sleep(5) while self.isrunning(): time.sleep(1) diff --git a/pyepr/hardware/PyEPR_control.py b/pyepr/hardware/PyEPR_control.py index 1e68509..8fbd5ee 100644 --- a/pyepr/hardware/PyEPR_control.py +++ b/pyepr/hardware/PyEPR_control.py @@ -245,7 +245,7 @@ def set_param(self, param: str, value: float): log.info(response.json()['message']) return True - def set_field(self,field,ramp_rate=None,wait=False): + def set_field(self,field,ramp_rate=None,wait=False,persistance=None): """ Sets the magnetic field @@ -257,9 +257,11 @@ def set_field(self,field,ramp_rate=None,wait=False): The ramp rate in Gauss per second. If not specified, the current ramp rate is used. wait : bool, optional If True, the method will block until the field is reached. Default is False. + persistance : bool, optional + If True, the magnet will be set to persistent mode after reaching the target field. If False, the magnet will be set to driven mode. If None, the current mode is maintained. Default is None. """ - response = requests.post(self.server + '/set_field', json={'value': field, 'ramp_rate': ramp_rate, 'wait': wait}) + response = requests.post(self.server + '/set_field', json={'value': field, 'ramp_rate': ramp_rate, 'wait': wait, 'persistance': persistance}) if 'error' in response.json(): raise RuntimeError(response.json()['error']) elif 'message' in response.json(): @@ -305,8 +307,9 @@ def launch(self, sequence: Sequence , savename: str, IFgain=None, # increase the detection length to a minimum 1024ns for pulse in sequence.pulses: if isinstance(pulse, Detection): - if pulse.tp.value < 256: - pulse.tp.value = 256 + if pulse.tp.value < 128: + pulse.tp.value = 128 + print(f"Warning: Detection pulse length increased to 128 ns for {pulse.name} to ensure sufficient data acquisition.") if (IFgain is None) or (IFgain is True): test_IF = True @@ -392,7 +395,7 @@ def isrunning(self) -> bool: return response.json()['isrunning'] - def tune_rectpulse(self,*,tp, freq, B, reptime, shots=400,tau=500,IFgain=None): + def tune_rectpulse(self,*,tp, freq, B, reptime, shots=400,tau=500,IFgain=None, offset=0): """Generates a rectangular pi and pi/2 pulse of the given length at the given field position. This value is stored in the pulse cache. @@ -408,6 +411,12 @@ def tune_rectpulse(self,*,tp, freq, B, reptime, shots=400,tau=500,IFgain=None): Shot repetion time in us. shots: int The number of shots + tau: float + The tau value for the Hahn echo sequence in ns, default is 500 ns + IFgain: float + The IF gain to be used for the tuning sequence. If None, the IF gain will be automatically determined by the interface. + offset: float + The frequency offset of the pulse in GHz. This is added to the central frequency of the pulse. Default is 0. Returns ------- @@ -429,6 +438,10 @@ def tune_rectpulse(self,*,tp, freq, B, reptime, shots=400,tau=500,IFgain=None): amp_tune.pulses[2].tp.value = 512 + amp_tune.pulses[0].freq.value = offset + amp_tune.pulses[1].freq.value = offset + amp_tune.pulses[2].freq.value = offset + amp_tune.evolution([scale]) self.launch(amp_tune, "autoDEER_amptune",IFgain=IFgain) @@ -455,10 +468,10 @@ def tune_rectpulse(self,*,tp, freq, B, reptime, shots=400,tau=500,IFgain=None): warnings.warn("Pulse tuned with a scale of zero!") print("Pulse tuned with a scale of zero!") p90 = amp_tune.pulses[0].copy( - scale=scale, freq=0) + scale=scale, freq=offset) p180 = amp_tune.pulses[1].copy( - scale=scale, freq=0) + scale=scale, freq=offset) return p90, p180 diff --git a/pyepr/resonator_profile_analysis.py b/pyepr/resonator_profile_analysis.py index cb33827..09acd71 100644 --- a/pyepr/resonator_profile_analysis.py +++ b/pyepr/resonator_profile_analysis.py @@ -402,7 +402,7 @@ def length2Hz(x): axs[1].text(0.02, 0.95, textstr, transform=axs[1].transAxes, fontsize=11, verticalalignment='top', bbox=props) - axs[0].set_ylim(*axs[1].get_ylim()) + axs[0].set_ylim(*axs[0].get_ylim()) axs[0].vlines(self.fc,*axs[0].get_ylim(),ls='--',color='0.7',lw=2) axs[1].set_ylim(*axs[1].get_ylim()) diff --git a/pyepr/sequences.py b/pyepr/sequences.py index fa1c5ac..98d5c7a 100644 --- a/pyepr/sequences.py +++ b/pyepr/sequences.py @@ -1,5 +1,5 @@ from pyepr.classes import Parameter -from pyepr.pulses import Pulse, Detection, Delay, RectPulse +from pyepr.pulses import Pulse, Detection, Delay, RectPulse, ChirpPulse from pyepr.utils import val_in_ns, val_in_us, add_phaseshift, _gen_ESEEM from pyepr.fieldsweep_analysis import create_Nmodel import pyepr.pulses as ad_pulses @@ -1613,8 +1613,16 @@ def __init__(self,*,B,freq,reptime,averages=1,shots=100,**kwargs) -> None: _description_, by default 1 shots : int, optional _description_, by default 100 - dtp : int, optional - _description_, by default 2 + pi2_pulse : Pulse, optional + A PyEPR Pulse object describing the excitation pi/2 pulse. + If missing a ChirpPulse without amplitude will be created instead, with frequency sweep of -50 to 50 MHz and duration of 200 ns. + pi_pulse : Pulse, optional + A PyEPR Pulse object describing the refocusing pi pulses. + If missing a ChirpPulse without amplitude will be created instead, with frequency sweep of -50 to 50 MHz and duration of 100 ns. + det_event : Detection, optional + A PyEPR Detection object describing the detection event. + tau : float, optional + The interpulse delay in ns, by default 500 ns """ name = "KBBSequence" super().__init__( @@ -1626,6 +1634,16 @@ def __init__(self,*,B,freq,reptime,averages=1,shots=100,**kwargs) -> None: self._build_sequence() def _build_sequence(self,): + + tau_value = self.kwargs.get("tau",500) #500 + pi2_pulse = self.kwargs.get("pi2_pulse",ChirpPulse(tp=200,freq=0,flipangle=np.pi/2, init_freq=-0.05, final_freq=0.05)) + pi_pulse = self.kwargs.get("pi_pulse",ChirpPulse(tp=100,freq=0,flipangle=np.pi, init_freq=-0.05, final_freq=0.05)) + + self.addPulse(pi2_pulse.copy(t=0, pcyc={"phases":[0, np.pi], "dets": [1,-1]})) + self.addPulse(pi_pulse.copy(t=tau_value, pcyc={"phases":[0], "dets": [1]})) + self.addPulse(Detection(t=2*tau_value, tp=512)) + + self.evolution([]) pass # ============================================================================= From 2135bb683bf6f23670eadca2b5a4016220506070 Mon Sep 17 00:00:00 2001 From: Hugo Karas Date: Tue, 17 Nov 2026 15:13:12 +0100 Subject: [PATCH 49/55] New sequences and better docs --- docsrc/sg_execution_times.rst | 46 -- pyepr/sequences/DEER.py | 525 ++++++++++++++++++- pyepr/sequences/ESEEM.py | 2 +- pyepr/sequences/base_sequences.py | 827 ++++++++++++++++++++++-------- 4 files changed, 1121 insertions(+), 279 deletions(-) delete mode 100644 docsrc/sg_execution_times.rst diff --git a/docsrc/sg_execution_times.rst b/docsrc/sg_execution_times.rst deleted file mode 100644 index 530f76e..0000000 --- a/docsrc/sg_execution_times.rst +++ /dev/null @@ -1,46 +0,0 @@ - -:orphan: - -.. _sphx_glr_sg_execution_times: - - -Computation times -================= -**00:00.133** total execution time for 4 files **from all galleries**: - -.. container:: - - .. raw:: html - - - - - - - - .. list-table:: - :header-rows: 1 - :class: table table-striped sg-datatable - - * - Example - - Time - - Mem (MB) - * - :ref:`sphx_glr_auto_examples_advanced_sequences_uhrig_decoupling_sequence.py` (``examples/advanced_sequences/uhrig_decoupling_sequence.py``) - - 00:00.133 - - 0.0 - * - :ref:`sphx_glr_auto_examples_advanced_sequences_advanced_sequence_axes.py` (``examples/advanced_sequences/advanced_sequence_axes.py``) - - 00:00.000 - - 0.0 - * - :ref:`sphx_glr_auto_examples_advanced_sequences_linking_sequence_parameter.py` (``examples/advanced_sequences/linking_sequence_parameter.py``) - - 00:00.000 - - 0.0 - * - :ref:`sphx_glr_auto_examples_tools_loading_cw.py` (``examples/tools/loading_cw.py``) - - 00:00.000 - - 0.0 diff --git a/pyepr/sequences/DEER.py b/pyepr/sequences/DEER.py index c50ce74..57f5e81 100644 --- a/pyepr/sequences/DEER.py +++ b/pyepr/sequences/DEER.py @@ -10,10 +10,6 @@ from pyepr.classes import Parameter class FourPulseDEERSequence(Sequence): - """ - Class for the 4-pulse DEER sequence. - """ - def __init__(self, *, B, freq,reptime,averages, shots, tau1, tau2, step=8, start=None, dim=None, phase_cycle='16-step', @@ -30,7 +26,7 @@ def __init__(self, *, B, freq,reptime,averages, shots, The B0 field, in Gauss freq : int or float The freq frequency in GHz - reptime : _type_ + reptime : float The shot repetition time in us averages : int The number of scans. @@ -46,7 +42,7 @@ def __init__(self, *, B, freq,reptime,averages, shots, The starting DEER time in us, also known as tmin. If it is None then it is 180ns before tau2. By default it is None. dim : int The number of points in the DEER time, by default it is calculated from the step and start values, and stops at tau2 - phase_cycle : str|list, optional + phase_cycle : str or list, optional The phase cycling scheme to use. Either a pre-defined option ('16-step' or 'DC'), can be supplied or a list of the phase cycles for each pulse. Default is '16-step'. @@ -160,13 +156,69 @@ def _build_pcyc(self, phase_cycle): def simulate(self,**kwargs): + r""" + Simulate the 4-pulse DEER sequence using DeerLab. + + Optional Parameters + ------------------- + rmean : float + The mean distance of the spin pair distribution in nm. Default is 4.0 nm + rstd : float + The standard deviation of the spin pair distribution in nm. Default is 0.75 nm + conc : float + The concentration of the spin pair in uM. Default is 100 uM + + Returns + ------- + t : np.ndarray + The DEER time axis in us + Vsim : np.ndarray + The simulated DEER signal + + Examples + -------- + + .. plot:: + :include-source: + + import pyepr as epr + import numpy as np + import matplotlib.pyplot as plt + N_gyro = 0.002803632236095 + freq = 34 + + exc_pulse = epr.GaussianPulse(tp=32,freq=0,flipangle=np.pi/2) + ref_pulse = epr.GaussianPulse(tp=32,freq=0,flipangle=np.pi) + pump_pulse = epr.ChirpPulse(tp=200,init_freq=-0.10,final_freq=-0.05,flipangle=np.pi) + seq = epr.FourPulseDEERSequence( + B=freq/N_gyro, + freq=freq, + reptime=3e3, + averages=1, + shots=10, + tau1=0.4, + tau2=3, + step=8, + start=0.1, + phase_cycle='16-step', + exc_pulse=exc_pulse, + ref_pulse=ref_pulse, + pump_pulse=pump_pulse + ) + + t, Vsim = seq.simulate(rmean=4.0, rstd=0.75, conc=100) + plt.plot(t, Vsim) + plt.xlabel(r'Time ($\mu$s)') + plt.ylabel(r'Signal (a.u.)') + """ + tau1 = val_in_us(self.tau1) tau2 = val_in_us(self.tau2) t = val_in_us(self.t) experimentInfo = dl.ex_4pdeer(tau1=tau1,tau2=tau2,pathways=[1,2,3]) reftimes = dict(zip(["reftime1","reftime2","reftime3"],experimentInfo.reftimes(tau1,tau2))) - mod_depths = {"lam1":0.4, "lam2":0.1, "lam3":0.2} + mod_depths = {"lam1":0.4, "lam2":0.05, "lam3":0.05} r = np.linspace(0.5,10,100) rmean = kwargs.pop('rmean', 4.0) @@ -181,10 +233,463 @@ def simulate(self,**kwargs): class FivePulseDEERSequence(Sequence): - - pass + + def __init__(self, *, B, freq,reptime,averages, shots, + tau1, tau2, tau3, step=8, start=None, dim=None, + phase_cycle='16-step', + **kwargs): + r""" + Initialize the 5-pulse DEER sequence. + + Sequence: + [\pi/2 - \tau_1-\tau_3 \pi_{pump} - \tau3 \pi - t \pi_{pump} - (\tau_2+\tau_1-t) - \pi - \tau2 - echo] + + Parameters + ---------- + B : int or float + The B0 field, in Gauss + freq : int or float + The freq frequency in GHz + reptime : float + The shot repetition time in us + averages : int + The number of scans. + shots : int + The number of shots per point + tau1 : int or float + The first interpulse delay in us + tau2 : int or float + The second interpulse delay in us + tau3 : int or float + The third interpulse delay in us + step : int or float + The step size for the DEER time in ns, by default it is 8 ns + start : int or float + The starting DEER time in us, also known as tmin. If it is None then it is 180ns before tau2. By default it is None. + dim : int + The number of points in the DEER time, by default it is calculated from the step and start values, and stops at tau2 + phase_cycle : str|list, optional + The phase cycling scheme to use. Either a pre-defined option + ('16-step' or 'DC'), can be supplied or a list of the phase cycles + for each pulse. Default is '16-step'. + + Examples + -------- + + .. plot:: + :include-source: + + import pyepr as epr + import numpy as np + from pyepr.sequences.DEER import FivePulseDEERSequence + N_gyro = 0.002803632236095 + freq = 34 + + exc_pulse = epr.GaussianPulse(tp=32,freq=0,flipangle=np.pi/2) + ref_pulse = epr.GaussianPulse(tp=32,freq=0,flipangle=np.pi) + pump_pulse = epr.ChirpPulse(tp=200,init_freq=-0.10,final_freq=-0.05,flipangle=np.pi) + seq = FivePulseDEERSequence( + B=freq/N_gyro, + freq=freq, + reptime=3e3, + averages=1, + shots=10, + tau1=3, + tau2=3, + tau3=0.3, + step=8, + start=0.1, + phase_cycle='16-step', + exc_pulse=exc_pulse, + ref_pulse=ref_pulse, + pump_pulse=pump_pulse + ) + + seq.draw() + print(seq) + + """ + + name = kwargs.pop('name',"FivePulseDEER") + + self._base_pulses = {} + self._base_pulses['exc'] = kwargs.pop('exc_pulse', p.RectPulse(tp=16, freq=0, flipangle=np.pi/2)) + self._base_pulses['pump'] = kwargs.pop('pump_pulse', p.RectPulse(tp=32, freq=-0.1, flipangle=np.pi)) + self._base_pulses['ref'] = kwargs.pop('ref_pulse', p.RectPulse(tp=32, freq=0, flipangle=np.pi)) + self._base_pulses['det'] = kwargs.pop('det_pulse', p.Detection(tp=256,freq=self._base_pulses['exc'].freq.value)) + + if self._base_pulses['det'].freq.value != self._base_pulses['exc'].freq.value: + warn("The detection pulse frequency is not equal to the excitation pulse frequency. This may lead to unexpected results.") + + self.tau1: Parameter = Parameter(name="tau1", value=tau1*1e3, unit="ns", description="Interpulse Delay 1", virtual=True) + """The first interpulse delay parameter in ns.""" + self.tau2: Parameter = Parameter(name="tau2", value=tau2*1e3, unit="ns", description="Interpulse Delay 2", virtual=True) + """The second interpulse delay parameter in ns.""" + self.tau3: Parameter = Parameter(name="tau3", value=tau3*1e3, unit="ns", description="Interpulse Delay 3", virtual=True) + """The third interpulse delay parameter in ns.""" + if start is None: + start = tau3*1e3 - 180 # Start 180ns before tau2 + else: + start *= 1e3 # Convert to ns + if dim is None: + dim = int((tau1+tau2)*1e3 / step) + 1 + + self.t: Parameter = Parameter(name="t", value=start, step=step, dim=dim, unit="ns", description="DEER Time", virtual=True) + """The pump pulse position parameter in ns.""" + super().__init__(name=name, B=B, freq=freq, reptime=reptime, averages=averages, shots=shots) + + self._build_sequence() + self._build_pcyc(phase_cycle) + + self.evolution([self.t]) + + def _build_sequence(self): + + self.addPulse(self._base_pulses['exc'].copy(t=0, pcyc={'phases':[0], 'dets':[1]})) + self.addPulse(self._base_pulses['pump'].copy(t=self.tau1-self.tau3, pcyc={'phases':[0], 'dets':[1]})) + self.addPulse(self._base_pulses['ref'].copy(t=self.tau1, pcyc={'phases':[0], 'dets':[1]})) + self.addPulse(self._base_pulses['pump'].copy(t=self.tau1+self.t, pcyc={'phases':[0], 'dets':[1]})) + self.addPulse(self._base_pulses['ref'].copy(t=2*self.tau1+self.tau2, pcyc={'phases':[0], 'dets':[1]})) + self.addPulse(self._base_pulses['det'].copy(t=2*(self.tau1+self.tau2), pcyc={'phases':[0], 'dets':[1]})) + + def _build_pcyc(self, phase_cycle): + + if isinstance(phase_cycle,list): + if len(phase_cycle) != 5: + raise ValueError("Phase cycle list must have 5 elements, one for each pulse.") + self._pcyc = phase_cycle + self.pcyc_name = "Custom Phase Cycle" + + elif phase_cycle == '16-step': + self._pcyc = [ + [[0],[1]], # No phase cycling for the excitation pulse + [[0],[1]], + [[0, np.pi/2, np.pi, -np.pi/2], [1, -1, 1, -1]], + [[0, np.pi/2, np.pi, -np.pi/2], [1, 1, 1, 1]], + [[0],[1]], + ] + self.pcyc_name = "16-step" + elif phase_cycle == '2-step': # Used only when the pump pulse is + self._pcyc = [ + [[0,np.pi],[1,-1]], # No phase cycling for the excitation pulse + [[0],[1]], + [[0],[1]], + [[0],[1]], + [[0],[1]], + ] + self.pcyc_name = "2-step" + else: + raise ValueError("Invalid phase cycle option. Choose from '16-step', '2-step', or provide a list of 5 phase cycles.") + + for i in range(len(self.pulses)-1): + self.pulses[i]._addPhaseCycle(*self._pcyc[i]) + + self._buildPhaseCycle() + + def simulate(self,**kwargs): + r""" + Simulate the 5-pulse DEER sequence using DeerLab. + + Optional Parameters + ------------------- + rmean : float + The mean distance of the spin pair distribution in nm. Default is 4.0 nm + rstd : float + The standard deviation of the spin pair distribution in nm. Default is 0.75 nm + conc : float + The concentration of the spin pair in uM. Default is 100 uM + + Returns + ------- + t : np.ndarray + The DEER time axis in us + Vsim : np.ndarray + The simulated DEER signal + + Examples + -------- + + .. plot:: + :include-source: + + import pyepr as epr + import numpy as np + import matplotlib.pyplot as plt + from pyepr.sequences.DEER import FivePulseDEERSequence + N_gyro = 0.002803632236095 + freq = 34 + + exc_pulse = epr.GaussianPulse(tp=32,freq=0,flipangle=np.pi/2) + ref_pulse = epr.GaussianPulse(tp=32,freq=0,flipangle=np.pi) + pump_pulse = epr.ChirpPulse(tp=200,init_freq=-0.10,final_freq=-0.05,flipangle=np.pi) + seq = FivePulseDEERSequence( + B=freq/N_gyro, + freq=freq, + reptime=3e3, + averages=1, + shots=10, + tau1=3, + tau2=3, + tau3=0.3, + step=8, + start=0.1, + phase_cycle='16-step', + exc_pulse=exc_pulse, + ref_pulse=ref_pulse, + pump_pulse=pump_pulse + ) + + t, Vsim = seq.simulate(rmean=4.0, rstd=0.75, conc=100) + plt.plot(t, Vsim) + plt.xlabel(r'Time ($\mu$s)') + plt.ylabel(r'Signal (a.u.)') + """ + + tau1 = val_in_us(self.tau1) + tau2 = val_in_us(self.tau2) + tau3 = val_in_us(self.tau3) + t = val_in_us(self.t) + + experimentInfo = dl.ex_fwd5pdeer(tau1=tau1,tau2=tau2,tau3=tau3,pathways=[1,5]) + reftimes = dict(zip(["reftime1","reftime5"],experimentInfo.reftimes(tau1,tau2,tau3))) + mod_depths = {"lam1":0.4, "lam5":0.1} + + r = np.linspace(0.5,10,100) + rmean = kwargs.pop('rmean', 4.0) + rstd = kwargs.pop('rstd', 0.75) + conc = kwargs.pop('conc', 100) + + Vmodel = dl.dipolarmodel(t,r,Pmodel=dl.dd_gauss, experiment=experimentInfo) + Vsim = Vmodel(mean=rmean, std=rstd, conc=conc, scale=1, **reftimes, **mod_depths) + + Vsim = add_phaseshift(Vsim, 0.05) + return t, Vsim + + + class ThreePulseDEERSequence(Sequence): - pass \ No newline at end of file + def __init__(self, *, B, freq, reptime, averages, shots, + tau1, step=8, start=None, dim=None, + phase_cycle='16-step', + **kwargs): + r""" + Initialize the 3-pulse DEER sequence. + + Sequence: + [\pi/2 - t - \pi_{pump} - (\tau_1-t) - \pi - \tau_1 - echo] + + The DEER time `t` is the delay between the excitation pulse and the + pump pulse. The pump pulse is swept across the first interpulse delay, + the main dipolar pathway therefore refocuses at `t=0`. + + Parameters + ---------- + B : int or float + The B0 field, in Gauss + freq : int or float + The freq frequency in GHz + reptime : _type_ + The shot repetition time in us + averages : int + The number of scans. + shots : int + The number of shots per point + tau1 : int or float + The interpulse delay in us + step : int or float + The step size for the DEER time in ns, by default it is 8 ns + start : int or float + The starting DEER time in us. If it is None then the pump pulse + starts immediately after the excitation pulse, so that the two + pulses do not overlap. By default it is None. + dim : int + The number of points in the DEER time, by default it is calculated + from the step and start values, and stops before the pump pulse + overlaps with the refocusing pulse. + phase_cycle : str|list, optional + The phase cycling scheme to use. Either a pre-defined option + ('8-step' or '2-step'), can be supplied or a list of the phase + cycles for each pulse. Default is '8-step'. + + Examples + -------- + + .. plot:: + :include-source: + + import pyepr as epr + import numpy as np + N_gyro = 0.002803632236095 + freq = 34 + + exc_pulse = epr.GaussianPulse(tp=32,freq=0,flipangle=np.pi/2) + ref_pulse = epr.GaussianPulse(tp=32,freq=0,flipangle=np.pi) + pump_pulse = epr.ChirpPulse(tp=200,init_freq=-0.10,final_freq=-0.05,flipangle=np.pi) + seq = epr.ThreePulseDEERSequence( + B=freq/N_gyro, + freq=freq, + reptime=3e3, + averages=1, + shots=10, + tau1=3, + step=8, + phase_cycle='8-step', + exc_pulse=exc_pulse, + ref_pulse=ref_pulse, + pump_pulse=pump_pulse + ) + + seq.draw() + print(seq) + """ + name = kwargs.pop('name', "ThreePulseDEER") + + self._base_pulses = {} + self._base_pulses['exc'] = kwargs.pop('exc_pulse', p.RectPulse(tp=16, freq=0, flipangle=np.pi/2)) + self._base_pulses['pump'] = kwargs.pop('pump_pulse', p.RectPulse(tp=32, freq=-0.1, flipangle=np.pi)) + self._base_pulses['ref'] = kwargs.pop('ref_pulse', p.RectPulse(tp=32, freq=0, flipangle=np.pi)) + self._base_pulses['det'] = kwargs.pop('det_pulse', p.Detection(tp=256, freq=self._base_pulses['exc'].freq.value)) + + if self._base_pulses['det'].freq.value != self._base_pulses['exc'].freq.value: + warn("The detection pulse frequency is not equal to the excitation pulse frequency. This may lead to unexpected results.") + + self.tau1: Parameter = Parameter(name="tau1", value=tau1*1e3, unit="ns", description="Interpulse Delay 1", virtual=True) + """The interpulse delay parameter in ns.""" + + exc_tp = self._base_pulses['exc'].tp.value + pump_tp = self._base_pulses['pump'].tp.value + ref_tp = self._base_pulses['ref'].tp.value + + if start is None: + start = exc_tp+5 # Start 5ns after the excitation pulse + else: + start *= 1e3 # Convert to ns + if dim is None: + stop = tau1*1e3 - (pump_tp + ref_tp) / 2 # Pump directly before the refocusing pulse + dim = int((stop - start) / step) + 1 + if dim < 1: + raise ValueError("tau1 is too short for the given pulses, start and step values.") + + self.t: Parameter = Parameter(name="t", value=start, step=step, dim=dim, unit="ns", description="DEER Time", virtual=True) + """The pump pulse position parameter in ns.""" + super().__init__(name=name, B=B, freq=freq, reptime=reptime, averages=averages, shots=shots) + + self._build_sequence() + self._build_pcyc(phase_cycle) + + self.evolution([self.t]) + + def _build_sequence(self): + + self.addPulse(self._base_pulses['exc'].copy(t=0, pcyc={'phases':[0], 'dets':[1]})) + self.addPulse(self._base_pulses['pump'].copy(t=self.t, pcyc={'phases':[0], 'dets':[1]})) + self.addPulse(self._base_pulses['ref'].copy(t=self.tau1, pcyc={'phases':[0], 'dets':[1]})) + self.addPulse(self._base_pulses['det'].copy(t=2*self.tau1, pcyc={'phases':[0], 'dets':[1]})) + + def _build_pcyc(self, phase_cycle): + + if isinstance(phase_cycle, list): + if len(phase_cycle) != 3: + raise ValueError("Phase cycle list must have 3 elements, one for each pulse.") + self._pcyc = phase_cycle + self.pcyc_name = "Custom Phase Cycle" + + elif phase_cycle == '8-step': + self._pcyc = [ + [[0, np.pi],[1,-1]], # No phase cycling for the excitation pulse + [[0],[1]], + [[0, np.pi/2, np.pi, -np.pi/2], [1, 1, 1, 1]], + ] + self.pcyc_name = "8-step" + elif phase_cycle == '2-step': + self._pcyc = [ + [[0, np.pi], [1, -1]], + [[0],[1]], + [[0],[1]], + ] + self.pcyc_name = "2-step" + else: + raise ValueError("Invalid phase cycle option. Choose from '16-step', '2-step', or provide a list of 3 phase cycles.") + + for i in range(len(self.pulses)-1): + self.pulses[i]._addPhaseCycle(*self._pcyc[i]) + + self._buildPhaseCycle() + + def simulate(self, **kwargs): + r""" + Simulate the 3-pulse DEER sequence using DeerLab. + + Optional Parameters + ------------------- + rmean : float + The mean distance of the spin pair distribution in nm. Default is 4.0 nm + rstd : float + The standard deviation of the spin pair distribution in nm. Default is 0.75 nm + conc : float + The concentration of the spin pair in uM. Default is 100 uM + + Returns + ------- + t : np.ndarray + The DEER time axis in us + Vsim : np.ndarray + The simulated DEER signal + + Examples + -------- + + .. plot:: + :include-source: + + import pyepr as epr + import numpy as np + import matplotlib.pyplot as plt + from pyepr.sequences.DEER import ThreePulseDEERSequence + N_gyro = 0.002803632236095 + freq = 34 + + exc_pulse = epr.GaussianPulse(tp=32,freq=0,flipangle=np.pi/2) + ref_pulse = epr.GaussianPulse(tp=32,freq=0,flipangle=np.pi) + pump_pulse = epr.ChirpPulse(tp=200,init_freq=-0.10,final_freq=-0.05,flipangle=np.pi) + seq = ThreePulseDEERSequence( + B=freq/N_gyro, + freq=freq, + reptime=3e3, + averages=1, + shots=10, + tau1=3, + step=8, + phase_cycle='8-step', + exc_pulse=exc_pulse, + ref_pulse=ref_pulse, + pump_pulse=pump_pulse + ) + + t, Vsim = seq.simulate(rmean=4.0, rstd=0.75, conc=100) + plt.plot(t, Vsim) + plt.xlabel(r'Time ($\\mu$s)') + plt.ylabel(r'Signal (a.u.)') + """ + + tau1 = val_in_us(self.tau1) + t = val_in_us(self.t) + + # DeerLab pathway 1 refocuses at t=tau, pathway 2 at t=0 (main pathway) + experimentInfo = dl.ex_3pdeer(tau=tau1, pathways=[1,2]) + reftimes = dict(zip(["reftime1","reftime2"], experimentInfo.reftimes(tau1))) + mod_depths = {"lam1":0.05, "lam2":0.4} + + r = np.linspace(0.5,10,100) + rmean = kwargs.pop('rmean', 4.0) + rstd = kwargs.pop('rstd', 0.75) + conc = kwargs.pop('conc', 100) + + Vmodel = dl.dipolarmodel(t, r, Pmodel=dl.dd_gauss, experiment=experimentInfo) + Vsim = Vmodel(mean=rmean, std=rstd, conc=conc, scale=1, **reftimes, **mod_depths) + + Vsim = add_phaseshift(Vsim, 0.05) + return t, Vsim \ No newline at end of file diff --git a/pyepr/sequences/ESEEM.py b/pyepr/sequences/ESEEM.py index d622176..a579091 100644 --- a/pyepr/sequences/ESEEM.py +++ b/pyepr/sequences/ESEEM.py @@ -100,7 +100,7 @@ def _build_sequence(self): self.evolution([self.T]) - def _simulate(self): + def simulate(self): raise NotImplementedError("Simulation for Three Pulse ESEEM is not implemented yet.") diff --git a/pyepr/sequences/base_sequences.py b/pyepr/sequences/base_sequences.py index b92383c..de00356 100644 --- a/pyepr/sequences/base_sequences.py +++ b/pyepr/sequences/base_sequences.py @@ -16,11 +16,12 @@ import base64 import numbers import warnings +from typing import Callable __all__ = [ 'Sequence', 'HahnEchoSequence', 'T1InversionRecoverySequence', 'HahnEchoRelaxationSequence', 'T2RelaxationSequence', 'FieldSweepSequence', - 'ReptimeScan', 'CarrPurcellSequence', 'ResonatorProfileSequence', + 'ReptimeScanSequence', 'ReptimeScan', 'CarrPurcellSequence', 'ResonatorProfileSequence', 'TWTProfileSequence', 'KBBSequence', 'KBBPulseProfileSequence', ] @@ -29,6 +30,15 @@ class Sequence: Represents an experimental pulse sequence. """ + time: Parameter + """The estimated run time of the sequence (HH:MM:SS), updated whenever the sequence changes.""" + pcyc_vars: list[int] + """The indices of the pulses that are phase cycled.""" + pcyc_cycles: np.ndarray + """The phase of each phase-cycled pulse for every step of the phase cycle.""" + pcyc_dets: np.ndarray + """The detection sign for every step of the phase cycle.""" + def __init__( self, *, name, B, reptime, averages, shots,LO=None, freq=None, **kwargs) -> None: """Represents an experimental pulse sequence. @@ -41,7 +51,7 @@ def __init__( The magnetic field for this sequence in Gauss. freq : float The central frequency of this sequence. I.e. The frequnecy at which - a zero offset pulse is at. + a zero offset pulse is at. reptime : float The shot repetition time in us. averages : int @@ -50,59 +60,88 @@ def __init__( The number of shots per point. LO : float The now deprecated local oscillator frequency. freq should be used. + + Examples + -------- + A custom sequence can be built by adding pulses to an empty sequence. + + .. plot:: + :include-source: + + import pyepr as epr + import numpy as np + epr.set_waveform_precision(1) + + seq = epr.Sequence( + name="CustomHahnEcho", B=12000, freq=34, reptime=1e3, + averages=1, shots=10) + seq.addPulse(epr.RectPulse(t=0, tp=16, freq=0, flipangle=np.pi/2)) + seq.addPulse(epr.RectPulse(t=500, tp=32, freq=0, flipangle=np.pi)) + seq.addPulse(epr.Detection(t=1000, tp=512)) + seq.draw() """ - self.pulses:list = [] - """"The list of pulses in this sequence.""" - + self.pulses: list[Pulse] = [] + """The list of pulses in this sequence.""" + self._axes_uuid = [] self._reduce_uuid = [] if isinstance(B, Parameter): - self.B = B.copy() + self.B: Parameter = B.copy() + """The static B0 field for the experiment in Gauss.""" else: - self.B = Parameter( + self.B: Parameter = Parameter( "B", B, "Gauss", "The static B0 field for the experiment") - + """The static B0 field for the experiment in Gauss.""" + if freq is not None: - self.freq = Parameter( + self.freq: Parameter = Parameter( "freq", freq, "GHz", "The central frequency of the sequence") + """The central frequency of the sequence in GHz.""" elif LO is not None: - self.freq = Parameter( + self.freq: Parameter = Parameter( "freq", LO, "GHz", "The central frequency of the sequence") + """The central frequency of the sequence in GHz.""" warnings.warn("LO is deprecated, please use freq instead", DeprecationWarning, stacklevel=2) else: raise ValueError("Either freq or LO must be specified") - + if isinstance(reptime, Parameter): - self.reptime = reptime.copy() + self.reptime: Parameter = reptime.copy() + """The shot repetition time in us.""" else: - self.reptime = Parameter( + self.reptime: Parameter = Parameter( "reptime", reptime, "us", "The shot repetition time") - - self.averages = Parameter("averages", int(averages), "None", + """The shot repetition time in us.""" + + self.averages: Parameter = Parameter("averages", int(averages), "None", "The number of averages to perform.") - - self.shots = Parameter( + """The number of averages (scans) to perform.""" + + self.shots: Parameter = Parameter( "shots", int(shots), "None", "The number of shots per scan.") + """The number of shots per point.""" if "det_window" in kwargs: - self.det_window = Parameter( + self.det_window: Parameter = Parameter( "det_window", kwargs["det_window"], "None", "The length of the default detection gate" ) + """The length of the default detection gate.""" else: - self.det_window = Parameter( + self.det_window: Parameter = Parameter( "det_window", 128, "None", "The length of the default detection gate" ) + """The length of the default detection gate.""" + - self.name: str = name """The name of this pulse sequence.""" self.progTable: dict = {"EventID": [], "Variable": [], "axis": [], @@ -684,145 +723,204 @@ def __init__(self, *, B, freq, reptime, averages, shots, **kwargs) -> None: The number of scans. shots : int The number of shots per point - + Optional Parameters ------------------- + tau : float or Parameter + The interpulse delay in ns, by default 500 ns + tp : float + The length of the default rectangular pulses in ns, by default 12 ns pi2_pulse : Pulse An autoEPR Pulse object describing the excitation pi/2 pulse. If - not specified a RectPulse will be created instead. + not specified a RectPulse will be created instead. pi_pulse : Pulse An autoEPR Pulse object describing the refocusing pi pulses. If - not specified a RectPulse will be created instead. + not specified a RectPulse will be created instead. det_event : Pulse An autoEPR Pulse object describing the detection even. If not specified a standard detection event will be created instead, - with an offset frequency of 0MHz. + with an offset frequency of 0MHz. + Examples + -------- .. plot:: :include-source: - + import pyepr as epr import numpy as np epr.set_waveform_precision(1) - seq = epr.HahnEchoRelaxationSequence( - B=12000, freq=34, reptime=1e3, averages=1, shots=10, start=300, step=40, dim=200) + seq = epr.HahnEchoSequence( + B=12000, freq=34, reptime=1e3, averages=1, shots=10, tau=500) seq.draw() """ - + name = kwargs.pop('name',"HahnEchoSequence") - + if "pi_pulse" in kwargs: - self.pi_pulse = kwargs["pi_pulse"] + self.pi_pulse: Pulse = kwargs["pi_pulse"] + """The refocusing pi pulse.""" if "pi2_pulse" in kwargs: - self.pi2_pulse = kwargs["pi2_pulse"] + self.pi2_pulse: Pulse = kwargs["pi2_pulse"] + """The excitation pi/2 pulse.""" if "det_event" in kwargs: - self.det_event = kwargs["det_event"] + self.det_event: Detection = kwargs["det_event"] + """The detection event.""" super().__init__( name=name, B=B, freq=freq, reptime=reptime, averages=averages, shots=shots, **kwargs) - if "tau" in kwargs: - tau = kwargs["tau"] - else: - tau = 500 - if "tp" in kwargs: - tp = kwargs["tp"] + tau = kwargs.get("tau", 500) + if isinstance(tau, Parameter): + self.tau: Parameter = tau + """The interpulse delay in ns.""" else: - tp = 12 + self.tau: Parameter = Parameter( + name="tau", value=tau, unit="ns", + description="The interpulse delay", virtual=True) + """The interpulse delay in ns.""" + tp = kwargs.get("tp", 12) if hasattr(self, "pi2_pulse"): self.addPulse(self.pi2_pulse.copy( t=0, pcyc={"phases":[0, np.pi], "dets": [1, -1]})) else: self.addPulse(RectPulse( # Exc pulse - t=0, tp=tp, freq=0, flipangle=np.pi/2, + t=0, tp=tp, freq=0, flipangle=np.pi/2, pcyc={"phases":[0, np.pi], "dets":[1, -1]} )) if hasattr(self, "pi_pulse"): pi_pulse = self.addPulse(self.pi_pulse.copy( - t=tau, pcyc={"phases":[0], "dets": [1]})) + t=self.tau, pcyc={"phases":[0], "dets": [1]})) else: pi_pulse = self.addPulse(RectPulse( # Pump 1 pulse - t=tau, tp=tp, freq=0, flipangle=np.pi + t=self.tau, tp=tp, freq=0, flipangle=np.pi )) if hasattr(self, "det_event"): - self.addPulse(self.det_event.copy(t=2*tau)) + self.addPulse(self.det_event.copy(t=2*self.tau)) else: - self.addPulse(Detection(t=2*tau, tp=512)) + self.addPulse(Detection(t=2*self.tau, tp=512)) -# ============================================================================= + def simulate(self, Tm=1e3): + """ + Simulates the Hahn echo intensity as a stretched exponential decay + of the interpulse delay, with a stretching exponent of 1.6. -class T1InversionRecoverySequence(Sequence): - r""" - Represents a T1 Inversion Recovery Sequence. + .. math:: + V(\\tau) = e^{-(\\tau/T_m)^{1.6}} - Sequence: - [\pi - t - \pi/2 - \tau - \pi - \tau - echo] - - Parameters - ---------- - B : int or float - The B0 field, in Gauss - LO : int or float - The LO frequency in GHz - reptime : _type_ - The shot repetition time in us - averages : int - The number of scans. - shots : int - The number of shots per point - start : float - The minimum interpulse delay in ns, by default 300 ns - step : float - The step size of the interpulse delay in ns, by default 50 ns - dim : int - The number of points in the X axis - tau: float - The Hahn echo interpulse delay in ns, by default 500 ns - - Optional Parameters - ------------------- - pi2_pulse : Pulse - An autoEPR Pulse object describing the excitation pi/2 pulse. If - not specified a RectPulse will be created instead. - pi_pulse : Pulse - An autoEPR Pulse object describing the refocusing pi pulses. If - not specified a RectPulse will be created instead. - - Examples - -------- - .. plot:: - :include-source: - - import pyepr as epr - epr.set_waveform_precision(1) - seq = epr.T1InversionRecoverySequence( - B=12000, freq=34, reptime=1e3, averages=1, shots=10, start=10000, step=2500, dim=500) - seq.draw() + Parameters + ---------- + Tm : float + The phase memory time in ns, by default 1e3 ns + Returns + ------- + xaxis : np.ndarray + The interpulse delay in ns (a single point) + data : np.ndarray + The simulated complex echo intensity (a single point) + + Examples + -------- + .. code-block:: python + + import pyepr as epr + seq = epr.HahnEchoSequence( + B=12000, freq=34, reptime=1e3, averages=1, shots=10, tau=500) + tau, data = seq.simulate(Tm=1e3) + print(tau, data) + """ + xaxis = np.atleast_1d(val_in_ns(self.tau)) + data = np.exp(-(xaxis/Tm)**1.6) + data = add_phaseshift(data, 0.05) + return xaxis, data + +# ============================================================================= + +class T1InversionRecoverySequence(Sequence): + """ + Represents a T1 Inversion Recovery Sequence. """ def __init__(self, *, B, freq, reptime, averages, shots,start=500, step=40, dim=200, **kwargs) -> None: + r"""Build a T1 inversion recovery sequence using either rectangular + pulses or specified pulses. + + Sequence: + [\pi - t - \pi/2 - \tau - \pi - \tau - echo] + + Parameters + ---------- + B : int or float + The B0 field, in Gauss + freq : int or float + The freq frequency in GHz + reptime : _type_ + The shot repetition time in us + averages : int + The number of scans. + shots : int + The number of shots per point + start : float + The minimum inversion recovery delay in ns, by default 500 ns + step : float + The step size of the inversion recovery delay in ns, by default 40 ns + dim : int + The number of points in the X axis, by default 200 + + Optional Parameters + ------------------- + tau : float + The Hahn echo interpulse delay in ns, by default 500 ns + tp : float + The length of the default rectangular pulses in ns, by default 12 ns + pi2_pulse : Pulse + An autoEPR Pulse object describing the excitation pi/2 pulse. If + not specified a RectPulse will be created instead. + pi_pulse : Pulse + An autoEPR Pulse object describing the inversion and refocusing + pi pulses. If not specified a RectPulse will be created instead. + det_event : Pulse + An autoEPR Pulse object describing the detection event. If + not specified a standard detection event will be created instead. + + Examples + -------- + .. plot:: + :include-source: + + import pyepr as epr + epr.set_waveform_precision(1) + seq = epr.T1InversionRecoverySequence( + B=12000, freq=34, reptime=1e3, averages=1, shots=10, start=10000, step=2500, dim=500) + seq.draw() + + """ name = "T1InversionRecoverySequence" tp = kwargs.get("tp", 12) - self.tau = Parameter(name="tau", value=500, unit="ns", description="The hahn ehco interpulse delay",virtual=True) - self.t = Parameter(name="t", value=start, step=step, dim=dim, unit="ns", description="The inversion recovery delay",virtual=True) + self.tau: Parameter = Parameter(name="tau", value=kwargs.get("tau", 500), unit="ns", description="The hahn echo interpulse delay",virtual=True) + """The Hahn echo interpulse delay in ns.""" + self.t: Parameter = Parameter(name="t", value=start, step=step, dim=dim, unit="ns", description="The inversion recovery delay",virtual=True) + """The inversion recovery delay in ns.""" super().__init__(name=name,B=B, freq=freq, reptime=reptime, averages=averages, shots=shots, **kwargs) if "pi_pulse" in kwargs: - self.pi_pulse = kwargs["pi_pulse"] + self.pi_pulse: Pulse = kwargs["pi_pulse"] + """The inversion and refocusing pi pulse.""" if "pi2_pulse" in kwargs: - self.pi2_pulse = kwargs["pi2_pulse"] + self.pi2_pulse: Pulse = kwargs["pi2_pulse"] + """The excitation pi/2 pulse.""" if "det_event" in kwargs: - self.det_event = kwargs["det_event"] + self.det_event: Detection = kwargs["det_event"] + """The detection event.""" if hasattr(self, "pi_pulse"): pi_pulse = self.addPulse(self.pi_pulse.copy( @@ -858,6 +956,37 @@ def __init__(self, *, B, freq, reptime, averages, shots,start=500, step=40, dim= def simulate(self, T1=1e4): """ Simulates the T1 recovery as a simple exponential recovery. + + .. math:: + V(t) = 1 - 2e^{-t/T_1} + + Parameters + ---------- + T1 : float + The longitudinal relaxation time in ns, by default 1e4 ns + + Returns + ------- + xaxis : np.ndarray + The inversion recovery delay in ns + data : np.ndarray + The simulated complex echo intensity + + Examples + -------- + .. plot:: + :include-source: + + import matplotlib.pyplot as plt + import pyepr as epr + epr.set_waveform_precision(1) + + seq = epr.T1InversionRecoverySequence( + B=12000, freq=34, reptime=1e3, averages=1, shots=10, start=500, step=500, dim=100) + x, data = seq.simulate(T1=1e4) + plt.plot(x, data.real) + plt.xlabel("Inversion Recovery Delay (ns)") + plt.ylabel("Signal Intensity (a.u.)") """ func = lambda x, a, T1: a*(1 - 2*np.exp(-x/T1)) xaxis = val_in_ns(self.t) @@ -868,63 +997,104 @@ def simulate(self, T1=1e4): class HahnEchoRelaxationSequence(HahnEchoSequence): - r""" + """ Represents a Hahn Echo relaxation sequence for measureing Tm. A Hahn Echo where the interpulse delay increases - - Sequence: + """ + + def __init__(self, *, B, freq, reptime, averages, shots,start=500, step=40, dim=200, **kwargs) -> None: + r"""Build a Hahn echo relaxation sequence, where the interpulse delay + is incremented, using either rectangular pulses or specified pulses. + + Sequence: [\pi/2 - \tau - \pi - \tau - echo] - Parameters - ---------- - B : int or float - The B0 field, in Gauss - freq : int or float - The freq frequency in GHz - reptime : _type_ - The shot repetition time in us - averages : int - The number of scans. - shots : int - The number of shots per point - start : float - The minimum interpulse delay in ns, by default 300 ns - step : float - The step size of the interpulse delay in ns, by default 50 ns - dim : int - The number of points in the X axis - - Optional Parameters - ------------------- - pi2_pulse : Pulse - An autoEPR Pulse object describing the excitation pi/2 pulse. If - not specified a RectPulse will be created instead. - pi_pulse : Pulse - An autoEPR Pulse object describing the refocusing pi pulses. If - not specified a RectPulse will be created instead. - - Examples - -------- - .. plot:: - :include-source: - - import pyepr as epr - epr.set_waveform_precision(1) - seq = epr.HahnEchoRelaxationSequence( - B=12000, freq=34, reptime=1e3, averages=1, shots=10, start=300, step=40, dim=200) - seq.draw() + Parameters + ---------- + B : int or float + The B0 field, in Gauss + freq : int or float + The freq frequency in GHz + reptime : _type_ + The shot repetition time in us + averages : int + The number of scans. + shots : int + The number of shots per point + start : float + The minimum interpulse delay in ns, by default 500 ns + step : float + The step size of the interpulse delay in ns, by default 40 ns + dim : int + The number of points in the X axis, by default 200 + Optional Parameters + ------------------- + pi2_pulse : Pulse + An autoEPR Pulse object describing the excitation pi/2 pulse. If + not specified a RectPulse will be created instead. + pi_pulse : Pulse + An autoEPR Pulse object describing the refocusing pi pulses. If + not specified a RectPulse will be created instead. - """ + Examples + -------- + .. plot:: + :include-source: - def __init__(self, *, B, freq, reptime, averages, shots,start=500, step=40, dim=200, **kwargs) -> None: + import pyepr as epr + epr.set_waveform_precision(1) + seq = epr.HahnEchoRelaxationSequence( + B=12000, freq=34, reptime=1e3, averages=1, shots=10, start=300, step=40, dim=200) + seq.draw() - self.tau = Parameter(name="tau", value=start,step=step,dim=dim, unit="ns", description="The interpulse delay",virtual=True) + """ + + self.tau: Parameter = Parameter(name="tau", value=start,step=step,dim=dim, unit="ns", description="The interpulse delay",virtual=True) + """The incremented interpulse delay in ns.""" super().__init__(B=B, freq=freq, reptime=reptime, averages=averages, shots=shots,tau=self.tau, **kwargs) - self.name = "T2RelaxationSequence" + self.name = "HahnEchoRelaxationSequence" self.evolution([self.tau]) def simulate(self,ESEEM_depth=0.1, Tm=1e3): + """ + Simulates the Hahn echo decay as a stretched exponential, with a + stretching exponent of 1.6, modulated by proton ESEEM. + + .. math:: + V(\\tau) = e^{-(\\tau/T_m)^{1.6}} + + Parameters + ---------- + ESEEM_depth : float + The depth of the proton ESEEM modulation, by default 0.1. Set to 0 + to disable the ESEEM modulation. + Tm : float + The phase memory time in ns, by default 1e3 ns + + Returns + ------- + xaxis : np.ndarray + The interpulse delay in ns + data : np.ndarray + The simulated complex echo intensity + + Examples + -------- + .. plot:: + :include-source: + + import matplotlib.pyplot as plt + import pyepr as epr + epr.set_waveform_precision(1) + + seq = epr.HahnEchoRelaxationSequence( + B=12000, freq=34, reptime=1e3, averages=1, shots=10, start=300, step=40, dim=200) + x, data = seq.simulate(ESEEM_depth=0.1, Tm=1e3) + plt.plot(x, data.real) + plt.xlabel("Interpulse Delay (ns)") + plt.ylabel("Signal Intensity (a.u.)") + """ func = lambda x, a, tau, e: a*np.exp(-(x/tau)**e) xaxis = val_in_ns(self.tau) data = func(xaxis,1,Tm,1.6) @@ -934,42 +1104,61 @@ def simulate(self,ESEEM_depth=0.1, Tm=1e3): return xaxis, data class T2RelaxationSequence(HahnEchoRelaxationSequence): - r""" + """ Represents a T2 relaxation sequence. This is an alias for HahnEchoRelaxationSequence. A Hahn Echo where the interpulse delay increases. + """ - Sequence: + def __init__(self, *, B, freq, reptime, averages, shots, start=500, step=40, dim=200, **kwargs) -> None: + r"""Build a T2 relaxation sequence. This is an alias for + :class:`HahnEchoRelaxationSequence`. + + Sequence: [\pi/2 - \tau - \pi - \tau - echo] - - Parameters - ---------- - B : int or float - The B0 field, in Gauss - freq : int or float - The freq frequency in GHz - reptime : _type_ - The shot repetition time in us - averages : int - The number of scans. - shots : int - The number of shots per point - start : float - The minimum interpulse delay in ns, by default 500 ns - step : float - The step size of the interpulse delay in ns, by default 40 ns - dim : int - The number of points in the X axis - - Optional Parameters - ------------------- - pi2_pulse : Pulse - An autoEPR Pulse object describing the excitation pi/2 pulse. If - not specified a RectPulse will be created instead. - pi_pulse : Pulse - An autoEPR Pulse object describing the refocusing pi pulses. If - not specified a RectPulse will be created instead. - """ - pass + + Parameters + ---------- + B : int or float + The B0 field, in Gauss + freq : int or float + The freq frequency in GHz + reptime : _type_ + The shot repetition time in us + averages : int + The number of scans. + shots : int + The number of shots per point + start : float + The minimum interpulse delay in ns, by default 500 ns + step : float + The step size of the interpulse delay in ns, by default 40 ns + dim : int + The number of points in the X axis, by default 200 + + Optional Parameters + ------------------- + pi2_pulse : Pulse + An autoEPR Pulse object describing the excitation pi/2 pulse. If + not specified a RectPulse will be created instead. + pi_pulse : Pulse + An autoEPR Pulse object describing the refocusing pi pulses. If + not specified a RectPulse will be created instead. + + Examples + -------- + .. plot:: + :include-source: + + import pyepr as epr + epr.set_waveform_precision(1) + seq = epr.T2RelaxationSequence( + B=12000, freq=34, reptime=1e3, averages=1, shots=10, start=300, step=40, dim=200) + seq.draw() + + """ + super().__init__( + B=B, freq=freq, reptime=reptime, averages=averages, shots=shots, + start=start, step=step, dim=dim, **kwargs) # ============================================================================= @@ -1001,16 +1190,20 @@ def __init__(self, *, B, freq, Bwidth, reptime, averages, shots, **kwargs) -> No The number of scans. shots : int The number of shots per point - + Optional Parameters ------------------- + step : float + The field step in Gauss, by default 1 G + tau : float + The Hahn echo interpulse delay in ns, by default 500 ns pi2_pulse : Pulse An autoEPR Pulse object describing the excitation pi/2 pulse. If - not specified a RectPulse will be created instead. + not specified a RectPulse will be created instead. pi_pulse : Pulse An autoEPR Pulse object describing the refocusing pi pulses. If - not specified a RectPulse will be created instead. - + not specified a RectPulse will be created instead. + Examples -------- .. plot:: @@ -1030,23 +1223,41 @@ def __init__(self, *, B, freq, Bwidth, reptime, averages, shots, **kwargs) -> No self.name = "FieldSweepSequence" dim = Bwidth // kwargs.get('step',1) - self.B = Parameter( + self.B: Parameter = Parameter( "B", value=B, start = -Bwidth/2, step=kwargs.get('step',1), dim=dim, unit="Gauss", description="Field sweep width" ) - + """The swept B0 field in Gauss, centred on the given field.""" + self.evolution([self.B]) - + def simulate(self): """ Simulate the Field Sweep spectra as a Nitroxide radical. - - returns + + Returns ------- axis : np.ndarray - The x-axis of the simulation + The magnetic field axis in Gauss data : np.ndarray - The y-axis of the simulation + The simulated complex echo intensity + + Examples + -------- + .. plot:: + :include-source: + import matplotlib.pyplot as plt + import pyepr as epr + epr.set_waveform_precision(1) + + N_gyro = 0.002803632236095 + freq = 34 + seq = epr.FieldSweepSequence( + B=freq/N_gyro, Bwidth=200, freq=freq, reptime=1e3, averages=1, shots=10) + B, data = seq.simulate() + plt.plot(B, data.real) + plt.xlabel("Magnetic Field (G)") + plt.ylabel("Signal Intensity (a.u.)") """ Vmodel = create_Nmodel(self.freq.value *1e3) axis = self.B.value + self.B.axis[0]['axis'] @@ -1065,7 +1276,8 @@ def simulate(self): # ============================================================================= -class ReptimeScan(HahnEchoSequence): + +class ReptimeScanSequence(HahnEchoSequence): """ Represents a reptime scan of a Hahn Echo Sequence. """ @@ -1111,8 +1323,8 @@ def __init__(self, *, B, freq, reptime, reptime_max, averages, shots, start=20, import pyepr as epr epr.set_waveform_precision(1) - seq = epr.ReptimeScan( - B=12000, freq=34, reptime=1000, averages=1, + seq = epr.ReptimeScanSequence( + B=12000, freq=34, reptime=1000, averages=1, shots=10, reptime_max=10000, start=20, dim=100) seq.draw() @@ -1142,9 +1354,26 @@ def simulate(self): Returns ------- t : np.ndarray - The x-axis of the simulation + The shot repetition time axis in us data : np.ndarray - The y-axis of the simulation + The simulated complex echo intensity + + Examples + -------- + .. plot:: + :include-source: + + import matplotlib.pyplot as plt + import pyepr as epr + epr.set_waveform_precision(1) + + seq = epr.ReptimeScanSequence( + B=12000, freq=34, reptime=1000, averages=1, + shots=10, reptime_max=10000, start=20, dim=100) + t, data = seq.simulate() + plt.plot(t, data.real) + plt.xlabel(r"Shot Repetition Time ($\\mu$s)") + plt.ylabel("Signal Intensity (a.u.)") """ def func(x,T1): return 1-np.exp(-x/T1) @@ -1155,6 +1384,15 @@ def func(x,T1): data = add_phaseshift(data, 0.05) return t, data +class ReptimeScan(ReptimeScanSequence): + """ + Deprecated alias for :class:`ReptimeScanSequence`. + """ + + def __init__(self,*args, **kwargs): + super().__init__(*args, **kwargs) + self.name = "ReptimeScan" + print("Warning: ReptimeScan is deprecated, use ReptimeScanSequence instead.") # ============================================================================= class CarrPurcellSequence(Sequence): @@ -1215,19 +1453,25 @@ def __init__(self, *, B, freq, reptime, averages, shots, super().__init__( name=name, B=B, freq=freq, reptime=reptime, averages=averages, shots=shots, **kwargs) - self.t = Parameter(name="tau", value=start,step=step,dim=dim, unit="ns", + self.t: Parameter = Parameter(name="tau", value=start,step=step,dim=dim, unit="ns", description="First interpulse delay", virtual=True) - self.n = Parameter(name="n", value=n, + """The first interpulse delay in ns, which is incremented.""" + self.n: Parameter = Parameter(name="n", value=n, description="The number of pi pulses", unit="None", virtual=True) - self.dim = Parameter(name="dim", value=dim, unit="None", + """The number of refocusing pi pulses.""" + self.dim: Parameter = Parameter(name="dim", value=dim, unit="None", description="The number of points in the X axis", virtual=True) + """The number of points in the X axis.""" if "pi_pulse" in kwargs: - self.pi_pulse = kwargs["pi_pulse"] + self.pi_pulse: Pulse = kwargs["pi_pulse"] + """The refocusing pi pulse.""" if "pi2_pulse" in kwargs: - self.pi2_pulse = kwargs["pi2_pulse"] + self.pi2_pulse: Pulse = kwargs["pi2_pulse"] + """The excitation pi/2 pulse.""" if "det_event" in kwargs: - self.det_event = kwargs["det_event"] + self.det_event: Detection = kwargs["det_event"] + """The detection event.""" self._build_sequence() @@ -1336,8 +1580,6 @@ def __init__(self, *, B, freq, reptime, averages, shots, fwidth=0.3,dtp=2, **kwa ---------- B : int or float The B0 field, in Gauss - Bwidth: int or float - The width of the field sweep, in Gauss freq : int or float The freq frequency in GHz reptime : _type_ @@ -1422,9 +1664,11 @@ def __init__(self, *, B, freq, reptime, averages, shots, fwidth=0.3,dtp=2, **kwa """Keyword arguments""" if "pi_pulse" in kwargs: - self.pi_pulse = kwargs["pi_pulse"] + self.pi_pulse: Pulse = kwargs["pi_pulse"] + """The refocusing pi pulse of the Hahn echo detection.""" if "pi2_pulse" in kwargs: - self.pi2_pulse = kwargs["pi2_pulse"] + self.pi2_pulse: Pulse = kwargs["pi2_pulse"] + """The excitation pi/2 pulse of the Hahn echo detection.""" self._build_sequence() @@ -1439,11 +1683,13 @@ def _build_sequence(self): fstep = self.fstep.value dim = np.floor(fwidth*2/fstep) center_freq = self.freq.value - self.freq = Parameter("freq", center_freq, start=-fwidth, step=fstep, dim=dim, unit="GHz", description="frequency") - self.B = Parameter( + self.freq: Parameter = Parameter("freq", center_freq, start=-fwidth, step=fstep, dim=dim, unit="GHz", description="frequency") + """The swept central frequency of the sequence in GHz.""" + self.B: Parameter = Parameter( "B",((center_freq)/self.gyro), start=-fwidth/self.gyro, step=fstep/self.gyro, dim=dim, unit="Gauss",link=self.freq,description="B0 Field" ) - + """The B0 field in Gauss, swept together with the frequency.""" + self.addPulse(RectPulse( # Hard pulse t=0, tp=tp, freq=0, flipangle="Hard" )) @@ -1487,7 +1733,33 @@ def simulate(self, Q=100, fc=None, nu1=75,damping=0.06): The maximum amplitude of the resonator profile, by default 75 MHz. This is a linear frequency scale. damping : float The damping factor of the resonator, by default 0.06. - + + Returns + ------- + axes : list[np.ndarray] + The test pulse length axis in ns and the frequency axis in GHz + data : np.ndarray + The simulated nutation data, with shape (len(tp), len(freq)) + + Examples + -------- + .. plot:: + :include-source: + + import matplotlib.pyplot as plt + import pyepr as epr + import numpy as np + epr.set_waveform_precision(1) + + N_gyro = 0.002803 + freq = 34 + seq = epr.ResonatorProfileSequence( + B=freq/N_gyro, freq=freq, reptime=3e3, averages=1, shots=10, + fwidth=0.3, fstep=0.02, dtp=1, dim=100) + [tp, f], data = seq.simulate(Q=100, nu1=75) + plt.pcolormesh(f, tp, data.real, shading='auto') + plt.xlabel("Frequency (GHz)") + plt.ylabel("Test Pulse Length (ns)") """ if fc is None: @@ -1504,7 +1776,8 @@ def lorenz_fcn(x, centre, sigma): mode = lambda x: lorenz_fcn(x, fc, fc/Q) axis = np.linspace(xmin,xmax) scale = nu1/mode(axis).max() - self.mode = lambda x: lorenz_fcn(x, fc, fc/Q) * scale + self.mode: Callable[[np.ndarray], np.ndarray] = lambda x: lorenz_fcn(x, fc, fc/Q) * scale + """The simulated resonator mode, giving the nutation frequency in MHz as a function of frequency in GHz.""" damped_oscilations = lambda x, f, c: np.cos(2*np.pi*f*x) * np.exp(-c*x) damped_oscilations_vec = np.vectorize(damped_oscilations) @@ -1527,19 +1800,73 @@ class TWTProfileSequence(Sequence): """ def __init__(self,*,B,freq,reptime,averages=1,shots=100,dtp=2,**kwargs) -> None: + r"""Build a TWT profile sequence, a nutation experiment where both the + length and the amplitude scale of the nutating pulse are varied. This + is used to characterise the (non-)linearity of the TWT amplifier. + + Sequence: + [p_{nut}(t_p, scale) - \tau_1 - \pi/2 - \tau_2 - \pi - \tau_2 - echo] + + Parameters + ---------- + B : int or float + The B0 field, in Gauss + freq : int or float + The freq frequency in GHz + reptime : _type_ + The shot repetition time in us + averages : int, optional + The number of scans, by default 1 + shots : int, optional + The number of shots per point, by default 100 + dtp : float, optional + The time step for the test pulse in ns, by default 2 ns + + Optional Parameters + ------------------- + tau1 : float + The delay between the nutating pulse and the Hahn Echo, + by default 2000 ns + tau2 : float + The interpulse delay in the Hahn Echo, by default 500 ns + pi2_pulse : Pulse + An autoEPR Pulse object describing the excitation pi/2 pulse. If + not specified a RectPulse will be created instead. + pi_pulse : Pulse + An autoEPR Pulse object describing the refocusing pi pulses. If + not specified a RectPulse will be created instead. + + Examples + -------- + .. plot:: + :include-source: + + import pyepr as epr + import numpy as np + epr.set_waveform_precision(1) + + seq = epr.TWTProfileSequence( + B=12000, freq=34, reptime=3e3, averages=1, shots=10, dtp=2) + seq.draw() + + """ name = "TWTProfileSequence" super().__init__( name=name, B=B, freq=freq, reptime=reptime, averages=averages, shots=shots, **kwargs) - - self.kwargs = kwargs - self.dtp = Parameter('dtp',dtp,'ns','Time step for the pulse') + + self.kwargs: dict = kwargs + """Keyword arguments""" + self.dtp: Parameter = Parameter('dtp',dtp,'ns','Time step for the pulse') + """Time step for the test pulse""" if "pi_pulse" in kwargs: - self.pi_pulse = kwargs["pi_pulse"] + self.pi_pulse: Pulse = kwargs["pi_pulse"] + """The refocusing pi pulse of the Hahn echo detection.""" if "pi2_pulse" in kwargs: - self.pi2_pulse = kwargs["pi2_pulse"] + self.pi2_pulse: Pulse = kwargs["pi2_pulse"] + """The excitation pi/2 pulse of the Hahn echo detection.""" self._build_sequence() @@ -1577,6 +1904,63 @@ def _build_sequence(self,): self.evolution([tp, scale]) + def simulate(self, nu1=75, damping=0.06, sat=None): + """ + Simulates the TWT profile as damped nutations, where the nutation + frequency is proportional to the amplitude scale of the test pulse. + + An optional saturation of the amplifier can be included, in which case + the nutation frequency follows a hyperbolic tangent of the scale. + + .. math:: + \\nu_1(s) = \\nu_{1,max} \\frac{\\tanh(s/s_{sat})}{\\tanh(1/s_{sat})} + + Parameters + ---------- + nu1 : float + The nutation frequency at full scale (scale=1) in MHz, by default 75 MHz + damping : float + The damping factor of the nutations, by default 0.06 + sat : float, optional + The saturation scale of the amplifier. If None the amplifier is + assumed to be linear, by default None + + Returns + ------- + axes : list[np.ndarray] + The test pulse length axis in ns and the amplitude scale axis + data : np.ndarray + The simulated nutation data, with shape (len(tp), len(scale)) + + Examples + -------- + .. plot:: + :include-source: + + import matplotlib.pyplot as plt + import pyepr as epr + epr.set_waveform_precision(1) + + seq = epr.TWTProfileSequence( + B=12000, freq=34, reptime=3e3, averages=1, shots=10, dtp=2) + [tp, scale], data = seq.simulate(nu1=75, sat=0.5) + plt.pcolormesh(scale, tp, data.real, shading='auto') + plt.xlabel("Amplitude Scale") + plt.ylabel("Test Pulse Length (ns)") + """ + tp_x = val_in_ns(self.pulses[0].tp) + scale_x = self.pulses[0].scale.value + self.pulses[0].scale.axis[0]['axis'] + + if sat is None: + nut_freqs = nu1 * scale_x + else: + nut_freqs = nu1 * np.tanh(scale_x/sat) / np.tanh(1/sat) + + data = np.cos(2*np.pi*tp_x.reshape(-1,1)*nut_freqs.reshape(1,-1)*1e-3) \ + * np.exp(-damping*tp_x.reshape(-1,1)) + data = add_phaseshift(data, 0.05) + return [tp_x, scale_x], data + # ============================================================================= class KBBSequence(Sequence): @@ -1589,25 +1973,24 @@ def __init__(self,*,B,freq,reptime,averages=1,shots=100,**kwargs) -> None: """ Parameters ---------- - B : _type_ - _description_ - freq : _type_ - _description_ - reptime : _type_ - _description_ + B : int or float + The B0 field, in Gauss + freq : int or float + The freq frequency in GHz + reptime : float + The shot repetition time in us averages : int, optional - _description_, by default 1 + The number of scans, by default 1 shots : int, optional - _description_, by default 100 - dtp : int, optional - _description_, by default 2 + The number of shots per point, by default 100 """ - name = "KBBSequence" + name = kwargs.pop("name", "KBBSequence") super().__init__( name=name, B=B, freq=freq, reptime=reptime, averages=averages, shots=shots, **kwargs) - - self.kwargs = kwargs + + self.kwargs: dict = kwargs + """Keyword arguments""" self._build_sequence() From cf9b127521e4787b96d3c3a21044e7e5b39f83e4 Mon Sep 17 00:00:00 2001 From: Hugo Karas Date: Tue, 17 Nov 2026 15:13:25 +0100 Subject: [PATCH 50/55] More examples --- .gitignore | 2 + docsrc/API_docs.rst | 4 +- docsrc/_static/gallery.css | 6 + docsrc/conf.py | 3 +- docsrc/examples/GALLERY_HEADER.rst | 2 +- .../automation/DEER_pump_frequency_sweep.py | 37 +++ docsrc/examples/automation/GALLERY_HEADER.rst | 6 + docsrc/examples/interfaces/ETH_AWG.py | 4 + docsrc/examples/interfaces/GALLERY_HEADER.rst | 5 + .../examples/interfaces/PulseSpel_Compile.py | 82 +++++++ .../PyEPR_Control_SuperConducting.py | 4 + docsrc/examples/interfaces/Xepr.py | 19 ++ docsrc/index.rst | 1 + docsrc/install.rst | 213 ++++++++++++++++-- docsrc/tutorial.rst | 2 +- 15 files changed, 365 insertions(+), 25 deletions(-) create mode 100644 docsrc/_static/gallery.css create mode 100644 docsrc/examples/automation/DEER_pump_frequency_sweep.py create mode 100644 docsrc/examples/automation/GALLERY_HEADER.rst create mode 100644 docsrc/examples/interfaces/ETH_AWG.py create mode 100644 docsrc/examples/interfaces/GALLERY_HEADER.rst create mode 100644 docsrc/examples/interfaces/PulseSpel_Compile.py create mode 100644 docsrc/examples/interfaces/PyEPR_Control_SuperConducting.py create mode 100644 docsrc/examples/interfaces/Xepr.py diff --git a/.gitignore b/.gitignore index 73d4947..b9756a9 100644 --- a/.gitignore +++ b/.gitignore @@ -134,3 +134,5 @@ poetry.lock *.lock docsrc/auto_examples/ + +_pulsespel_output/ \ No newline at end of file diff --git a/docsrc/API_docs.rst b/docsrc/API_docs.rst index 3fa8817..59d58ba 100644 --- a/docsrc/API_docs.rst +++ b/docsrc/API_docs.rst @@ -47,7 +47,7 @@ Relxation Sequences pyepr.sequences.HahnEchoRelaxationSequence pyepr.sequences.CarrPurcellSequence pyepr.sequences.T1InversionRecoverySequence - pyepr.sequences.ReptimeScan + pyepr.sequences.ReptimeScanSequence Dipolar EPR Sequences +++++++++++++++++++++ @@ -55,7 +55,9 @@ Dipolar EPR Sequences .. autoapisummary:: + pyepr.sequences.DEER.ThreePulseDEERSequence pyepr.sequences.DEER.FourPulseDEERSequence + pyepr.sequences.DEER.FivePulseDEERSequence Hyperfine Spectroscopy Sequences ++++++++++++++++++++++++++++++++ diff --git a/docsrc/_static/gallery.css b/docsrc/_static/gallery.css new file mode 100644 index 0000000..3048eab --- /dev/null +++ b/docsrc/_static/gallery.css @@ -0,0 +1,6 @@ +/* Code blocks given ":class: scroll-40" (e.g. the PulseSpel file tabs in + examples/interfaces/PulseSpel_Compile.py): show at most 40 lines, then scroll. */ +div.scroll-40 pre { + max-height: 40lh; + overflow-y: auto; +} diff --git a/docsrc/conf.py b/docsrc/conf.py index baef093..69b62e0 100644 --- a/docsrc/conf.py +++ b/docsrc/conf.py @@ -67,6 +67,7 @@ 'gallery_dirs': 'auto_examples', # path to where to save gallery generated output 'filename_pattern': r'.*\.py', 'subsection_order': ['examples/advanced_sequences', 'examples/tools', '*'], + 'remove_config_comments': True, # hide "# sphinx_gallery_..." settings from rendered code } # -- Options for HTML output ------------------------------------------------- @@ -74,7 +75,7 @@ html_theme = 'furo' html_static_path = ['_static'] -html_css_files = ['autoapi.css'] +html_css_files = ['autoapi.css', 'gallery.css'] html_theme_options = { # "announcement": "Version 0.7 out now!", "light_logo": "pyepr_logo_light.svg", diff --git a/docsrc/examples/GALLERY_HEADER.rst b/docsrc/examples/GALLERY_HEADER.rst index 216728d..1838ae7 100644 --- a/docsrc/examples/GALLERY_HEADER.rst +++ b/docsrc/examples/GALLERY_HEADER.rst @@ -1,4 +1,4 @@ -PyEPR Example Scripts +Examples ===================== Work in Progress: This gallery is under construction and will be expanded with more examples in the future. \ No newline at end of file diff --git a/docsrc/examples/automation/DEER_pump_frequency_sweep.py b/docsrc/examples/automation/DEER_pump_frequency_sweep.py new file mode 100644 index 0000000..31fed8f --- /dev/null +++ b/docsrc/examples/automation/DEER_pump_frequency_sweep.py @@ -0,0 +1,37 @@ +""" +Testing different pump-offsets in Four-Pulse DEER +================================================== +""" + +import pyepr as epr +import numpy as np + +obs_freq = 0 # Relative to the center frequency +pump_freqs = [-0.12,-0.10,-0.08,-0.06] + +exc_pulse = epr.RectPulse(tp=32,scale=0.1,flipangle=np.pi/2,freq=obs_freq) +ref_pulse = epr.RectPulse(tp=32,scale=0.2,flipangle=np.pi,freq=obs_freq) +pump_pulse = epr.RectPulse(tp=32,scale=0.2,flipangle=np.pi,freq=pump_freqs[0]) + +seq = epr.FourPulseDEERSequence( + B=12000, freq=34, reptime=3e3, averages=50, shots=25, + start=300, step=16, dim=512, + tau1=0.4,tau2=4, + pi2_pulse=exc_pulse, pi_pulse=ref_pulse, pump_pulse=pump_pulse) + +print(seq) +seq.draw() + + +#%% +# Connect to the spectrometer +#---------------------------- + + +#%% + +for pump_freq in pump_freqs: + print(f"Running DEER with pump offset frequency {pump_freq*1e3} MHz") + seq.pulses[2].freq.value = pump_freq + + # interface.launch() \ No newline at end of file diff --git a/docsrc/examples/automation/GALLERY_HEADER.rst b/docsrc/examples/automation/GALLERY_HEADER.rst new file mode 100644 index 0000000..963f774 --- /dev/null +++ b/docsrc/examples/automation/GALLERY_HEADER.rst @@ -0,0 +1,6 @@ +Automation +--------------------------- +One of the big advantages of using `PyEPR` is the ability to automate experiments, +and conduct detailed parameter analysis. + + diff --git a/docsrc/examples/interfaces/ETH_AWG.py b/docsrc/examples/interfaces/ETH_AWG.py new file mode 100644 index 0000000..e2dafd6 --- /dev/null +++ b/docsrc/examples/interfaces/ETH_AWG.py @@ -0,0 +1,4 @@ +""" +ETH Matlab Based AWG +=============================================== +""" \ No newline at end of file diff --git a/docsrc/examples/interfaces/GALLERY_HEADER.rst b/docsrc/examples/interfaces/GALLERY_HEADER.rst new file mode 100644 index 0000000..e43da35 --- /dev/null +++ b/docsrc/examples/interfaces/GALLERY_HEADER.rst @@ -0,0 +1,5 @@ +Interface Specific Examples +--------------------------- + + + diff --git a/docsrc/examples/interfaces/PulseSpel_Compile.py b/docsrc/examples/interfaces/PulseSpel_Compile.py new file mode 100644 index 0000000..9335a30 --- /dev/null +++ b/docsrc/examples/interfaces/PulseSpel_Compile.py @@ -0,0 +1,82 @@ +""" +PulseSpel Compile +=============================================== + +PyEPR can compile a Bruker PulseSpel pulse sequence from a PyEPR `sequence` object. +This allows for easy integration of PyEPR with Bruker Xepr software, +and allows for the use of PyEPR's powerful sequence building tools to create complex pulse sequences for EPR experiments. +""" + +#%% +# Import packages +# -------------------------------------------- +import pyepr as epr +from pyepr.hardware.Bruker_tools import write_pulsespel_file +import numpy as np +from pathlib import Path + +#%% +# Build Sequence +# -------------------------------------------- +# In this example we will build a simple 4 pulse Carr-Purcell sequence with a complete phase cycle. + +p90 = epr.RectPulse(tp=32,scale=0.1,flipangle=np.pi/2) +p180 = epr.RectPulse(tp=32,scale=0.2,flipangle=np.pi) +seq = epr.CarrPurcellSequence( + B=12000, freq=34, reptime=3e3, averages=1, shots=10, + start=300, step=16, dim=512,n=4, + pi2_pulse=p90, pi_pulse=p180) +print(seq) +seq.draw() + + +#%% +# Convert to PulseSpel and Save to File +# -------------------------------------------- + + +def_file, exp_file, shapes = write_pulsespel_file( + sequence=seq, + d0 = 617, #ns + AWG = True, # Use AWG or MPFU channels +) + +out_dir = Path('_pulsespel_output') +out_dir.mkdir(exist_ok=True) +(out_dir / 'CP4.def').write_text(def_file) +(out_dir / 'CP4.exp').write_text(exp_file) +(out_dir / 'CP4.shp').write_text('\n'.join(shapes)) +# sphinx_gallery_capture_repr_block = () + +#%% +# The generated files are: +# These are not as human-readable as commonly used PulseSpel files, but this isn't an issue. +# +# .. tab-set:: +# +# .. tab-item:: Definitions (.def) +# +# .. literalinclude:: /examples/interfaces/_pulsespel_output/CP4.def +# :language: none +# :class: scroll-40 +# +# .. tab-item:: Experiment (.exp) +# +# .. literalinclude:: /examples/interfaces/_pulsespel_output/CP4.exp +# :language: none +# :class: scroll-40 +# +# .. tab-item:: Shapes (.shp) +# +# .. literalinclude:: /examples/interfaces/_pulsespel_output/CP4.shp +# :language: none +# :class: scroll-40 + +#%% +# Limitations +# -------------------------------------------- +# +# Currently known limitations of the PulseSpel compiler include: +# +# - Does not support RF pulses (only microwave pulses are supported) +# - Does not support transient detection (only echo detection is supported) diff --git a/docsrc/examples/interfaces/PyEPR_Control_SuperConducting.py b/docsrc/examples/interfaces/PyEPR_Control_SuperConducting.py new file mode 100644 index 0000000..9344618 --- /dev/null +++ b/docsrc/examples/interfaces/PyEPR_Control_SuperConducting.py @@ -0,0 +1,4 @@ +""" +PyEPR Control Superconducting Interface +=============================================== +""" \ No newline at end of file diff --git a/docsrc/examples/interfaces/Xepr.py b/docsrc/examples/interfaces/Xepr.py new file mode 100644 index 0000000..ff2d09d --- /dev/null +++ b/docsrc/examples/interfaces/Xepr.py @@ -0,0 +1,19 @@ +""" +Xepr API Interface +=============================================== + +Connecting to a Bruker Xepr (or Xenon) based spectrometer needs to be done using the XeprAPI. +Using this API, PyEPR can control the spectrometer and upload pulse sequences to it for execution. +It also has a lower-level interface which allows for more advanced control of the spectrometer, +which can be useful for CW as well as pulse EPR experiments. + +This code may work with Xepr > 2.7, but is only recommened for Xepr 2.9 and above. +""" + +# %% +# Import packages including the Xepr interface +# -------------------------------------------- + +import pyepr as epr +# from pyepr.hardware.Bruker_AWG import BrukerAWG + diff --git a/docsrc/index.rst b/docsrc/index.rst index d714c0c..30a042b 100644 --- a/docsrc/index.rst +++ b/docsrc/index.rst @@ -34,6 +34,7 @@ PyEPR's Key Features ./install.rst ./tutorial.rst ./API_docs.rst + auto_examples/index.rst .. toctree:: :hidden: diff --git a/docsrc/install.rst b/docsrc/install.rst index f10a207..4a5b890 100644 --- a/docsrc/install.rst +++ b/docsrc/install.rst @@ -1,41 +1,212 @@ Installation ------------ -PyEPR can either be installed via pip or from source. +PyEPR is published on PyPI as ``pyepr-esr`` and supports **Python 3.11 or newer**. +It can be installed from PyPI or from source. -It is recommended that virtual environments are used to install PyEPR, one recommended way to do this is with poetry. +PyEPR is a standard Python package, so any Python package manager can install it. +This page gives instructions for `uv `_, a fast +package and project manager that we use for development, and for plain ``pip``. +Other tools, such as Poetry, Pixi or conda/mamba (installing PyEPR with ``pip`` +inside a conda environment), work too. Use whichever you are most comfortable with. -To install PyEPR via pip, simply run the following command: +.. important:: + + We recommend installing PyEPR in a **local virtual environment** with a + **recent Python version** (3.11 or newer). Do not install it into the + system Python that ships with your operating system: it is often outdated, + and installing packages into it can conflict with system tools. + + A virtual environment keeps PyEPR and its dependencies separate from other + projects. uv makes this easy because it can download a recent Python + version for you (for example ``uv venv --python 3.12``), so you do not need + to install Python yourself. + +Installing uv (optional) +++++++++++++++++++++++++ + +You only need this step if you want to use uv. If you do not already have it, +install it with: + +.. tab-set:: + :sync-group: os + + .. tab-item:: macOS / Linux + :sync: unix + + .. code-block:: bash + + curl -LsSf https://astral.sh/uv/install.sh | sh + + .. tab-item:: Windows + :sync: windows + + .. code-block:: powershell + + powershell -ExecutionPolicy ByPass -c "irm https://astral.sh/uv/install.ps1 | iex" + +For other install methods (Homebrew, pipx, WinGet, ...), see the +`uv installation guide `_. + +Installing from PyPI +++++++++++++++++++++ + +.. tab-set:: + :sync-group: tool + + .. tab-item:: uv (project) + :sync: uv + + To add PyEPR as a dependency of your own uv project (this creates the + virtual environment automatically): + + .. code-block:: bash + + uv init my-epr-project # skip if you already have a project + cd my-epr-project + uv add pyepr-esr + + Run scripts inside the project environment with ``uv run``: + + .. code-block:: bash + + uv run python my_script.py + + .. tab-item:: uv (pip interface) + :sync: uv-pip + + To install into a standalone virtual environment: + + .. code-block:: bash + + uv venv --python 3.12 + source .venv/bin/activate # Windows: .venv\Scripts\activate + uv pip install pyepr-esr + + .. tab-item:: pip + :sync: pip + + .. code-block:: bash + + python -m venv .venv + source .venv/bin/activate # Windows: .venv\Scripts\activate + python -m pip install pyepr-esr + +Installing from source +++++++++++++++++++++++ + +Install from source to get the latest development version, or if you want to +contribute to PyEPR. Clone the repository first: .. code-block:: bash - pip install pyepr-esr + git clone https://github.com/JeschkeLab/PyEPR.git + cd PyEPR + +Then install it: + +.. tab-set:: + :sync-group: tool + + .. tab-item:: uv (project) + :sync: uv + + ``uv sync`` creates a ``.venv`` in the repository and installs PyEPR in + editable mode, using the exact versions pinned in ``uv.lock``: + + .. code-block:: bash + + uv sync + + To also install the development (testing) and documentation tools: + + .. code-block:: bash + + uv sync --extra dev --extra doc + + .. tab-item:: uv (pip interface) + :sync: uv-pip + + .. code-block:: bash + + uv venv + source .venv/bin/activate # Windows: .venv\Scripts\activate + uv pip install -e ".[dev,doc]" -or with poetry: + Leave out ``[dev,doc]`` if you do not need the testing and + documentation tools. + + .. tab-item:: pip + :sync: pip + + .. code-block:: bash + + python -m venv .venv + source .venv/bin/activate # Windows: .venv\Scripts\activate + python -m pip install -e ".[dev,doc]" + + Leave out ``[dev,doc]`` if you do not need the testing and + documentation tools. + +The ``-e`` (editable) flag means changes to the source code take effect without +reinstalling. + +Verifying the installation +++++++++++++++++++++++++++ + +Check that PyEPR imports correctly and print its version: .. code-block:: bash - poetry add pyepr-esr + python -c "import pyepr; print(pyepr.__version__)" -To install PyEPR from source, clone the repository and run the following command: +or, inside a uv project: .. code-block:: bash - - git clone https://github.com/JeschkeLab/PyEPR - pip install . + uv run python -c "import pyepr; print(pyepr.__version__)" Requirements ++++++++++++ -PyEPR requires: - - Python >= 3.11 < 3.13 - - Numpy - - Scipy - - Matplotlib - - pyyaml - - xarray - - h5netcdf - - toml - - deerlab (https://github.com/JeschkeLab/DeerLab) - - psutil +The following are installed automatically with PyEPR: + +========================================================== ================ +Package Version +========================================================== ================ +Python >= 3.11 +`NumPy `_ >= 2.1, < 3.0 +`SciPy `_ >= 1.14.1 +`Matplotlib `_ >= 3.9.2 +`xarray `_ >= 2025 +`h5py `_ > 3.15 +`h5netcdf `_ > 1.4.0 +`DeerLab `_ >= 1.1.4, < 2.0 +PyYAML >= 6.0.2, < 7.0 +toml >= 0.10.2 +psutil >= 7.1.3 +requests >= 2.32 +========================================================== ================ + +Optional extras: + +- ``dev``: testing tools (``pytest``, ``gitpython``). +- ``doc``: tools to build this documentation (``sphinx``, ``furo``, + ``sphinx-gallery``, and related extensions). + +Install them with ``uv sync --extra dev`` (or ``--extra doc``) from a source +checkout, or with ``pip install "pyepr-esr[dev]"``. + +Hardware-specific requirements +++++++++++++++++++++++++++++++ + +You need these only to control a spectrometer. They cannot be installed from +PyPI and are not installed with PyEPR. + +- **Bruker spectrometers (Xepr):** Xepr 2.9 or newer must be installed on the + spectrometer computer, with its Python API enabled + (*Processing → XeprAPI → Enable XeprAPI* in Xepr). PyEPR finds the + ``XeprAPI`` module with ``Xepr --apipath``. +- **ETH AWG spectrometers:** requires MATLAB and the + `MATLAB Engine API for Python `_, + whose version must match your MATLAB release. diff --git a/docsrc/tutorial.rst b/docsrc/tutorial.rst index 78c5cfe..3728829 100644 --- a/docsrc/tutorial.rst +++ b/docsrc/tutorial.rst @@ -53,4 +53,4 @@ The following tutorials are available: tutorial_loading.md tutorial_sequencer.md tutorial_hardware.md - auto_examples/index.rst \ No newline at end of file + \ No newline at end of file From 78eed7f8ca9ab93dc8a929a1d78d86e7d91ed1a1 Mon Sep 17 00:00:00 2001 From: Hugo Karas Date: Tue, 17 Nov 2026 15:28:29 +0100 Subject: [PATCH 51/55] Update github workflows --- .github/workflows/Build_Deploy_Docs.yml | 25 ++++++----- .github/workflows/PyPI_upload.yml | 59 ------------------------- .github/workflows/TestBuild_Docs.yml | 19 ++++---- .github/workflows/TestPyPI_Upload.yml | 5 ++- .github/workflows/python-publish.yml | 3 +- 5 files changed, 27 insertions(+), 84 deletions(-) delete mode 100644 .github/workflows/PyPI_upload.yml diff --git a/.github/workflows/Build_Deploy_Docs.yml b/.github/workflows/Build_Deploy_Docs.yml index a8070f3..f2b18e3 100644 --- a/.github/workflows/Build_Deploy_Docs.yml +++ b/.github/workflows/Build_Deploy_Docs.yml @@ -7,34 +7,35 @@ jobs: build: runs-on: ubuntu-latest + permissions: + contents: write # needed to push to the gh-pages branch + steps: - name: Checkout repository - uses: actions/checkout@v3 + uses: actions/checkout@v4 - name: Set up Python - uses: actions/setup-python@v4 + uses: actions/setup-python@v5 with: python-version: '3.12' - - - name: Install Poetry - run: | - curl -sSL https://install.python-poetry.org | python - - echo "${HOME}/.local/bin" >> $GITHUB_PATH + + - name: Install uv + uses: astral-sh/setup-uv@v6 - name: Install dependencies - run: poetry install --with doc - + run: uv sync --extra doc + - name: Build documentation - run: poetry run sphinx-build -b html docsrc/ docsrc/_build/html > sphinx_build.log 2>&1 + run: uv run sphinx-build -b html docsrc/ docsrc/_build/html > sphinx_build.log 2>&1 - name: Upload build log uses: actions/upload-artifact@v4.6.2 if: always() with: name: sphinx-build-log path: sphinx_build.log - + - name: Deploy to GitHub Pages - uses: peaceiris/actions-gh-pages@v3 + uses: peaceiris/actions-gh-pages@v4 with: github_token: ${{ secrets.GITHUB_TOKEN }} publish_dir: docsrc/_build/html diff --git a/.github/workflows/PyPI_upload.yml b/.github/workflows/PyPI_upload.yml deleted file mode 100644 index 02053a4..0000000 --- a/.github/workflows/PyPI_upload.yml +++ /dev/null @@ -1,59 +0,0 @@ -name: Publish Python 🐍 distribution 📦 to PyPI - -on: - push: - branches: - - release/* - - -jobs: - build: - name: Build distribution 📦 - runs-on: ubuntu-latest - - steps: - - uses: actions/checkout@v4 - with: - persist-credentials: false - - name: Set up Python - uses: actions/setup-python@v5 - with: - python-version: "3.x" - - name: Install pypa/build - run: >- - python3 -m - pip install - build - --user - - name: Build a binary wheel and a source tarball - run: python3 -m build - - name: Store the distribution packages - uses: actions/upload-artifact@v4 - with: - name: python-package-distributions - path: dist/ - - publish-to-testpypi: - name: Publish Python 🐍 distribution 📦 to PyPI - needs: - - build - runs-on: ubuntu-latest - - environment: - name: pypi - url: https://pypi.org/p/PyEPR-ESR - - permissions: - id-token: write # IMPORTANT: mandatory for trusted publishing - - steps: - - name: Download all the dists - uses: actions/download-artifact@v4 - with: - name: python-package-distributions - path: dist/ - - name: Publish distribution 📦 to PyPI - uses: pypa/gh-action-pypi-publish@release/v1 - with: - verbose: true - repository-url: https://pypi.org/legacy/ diff --git a/.github/workflows/TestBuild_Docs.yml b/.github/workflows/TestBuild_Docs.yml index df5bf6a..5be8c4f 100644 --- a/.github/workflows/TestBuild_Docs.yml +++ b/.github/workflows/TestBuild_Docs.yml @@ -13,27 +13,24 @@ jobs: steps: - name: Checkout repository - uses: actions/checkout@v3 + uses: actions/checkout@v4 - name: Set up Python - uses: actions/setup-python@v4 + uses: actions/setup-python@v5 with: python-version: '3.12' - - - name: Install Poetry - run: | - curl -sSL https://install.python-poetry.org | python - - echo "${HOME}/.local/bin" >> $GITHUB_PATH + + - name: Install uv + uses: astral-sh/setup-uv@v6 - name: Install dependencies - run: poetry install --with doc - + run: uv sync --extra doc + - name: Build documentation - run: poetry run sphinx-build -b html docsrc/ docsrc/_build/html > sphinx_build.log 2>&1 + run: uv run sphinx-build -b html docsrc/ docsrc/_build/html > sphinx_build.log 2>&1 - name: Upload build log uses: actions/upload-artifact@v4.6.2 if: always() with: name: sphinx-build-log path: sphinx_build.log - diff --git a/.github/workflows/TestPyPI_Upload.yml b/.github/workflows/TestPyPI_Upload.yml index 511048d..fe8598d 100644 --- a/.github/workflows/TestPyPI_Upload.yml +++ b/.github/workflows/TestPyPI_Upload.yml @@ -39,7 +39,9 @@ jobs: needs: - build runs-on: ubuntu-latest - + # PRs from forks cannot obtain an OIDC token for trusted publishing + if: github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository + environment: name: testpypi url: https://test.pypi.org/p/PyEPR-ESR @@ -58,3 +60,4 @@ jobs: with: verbose: true repository-url: https://test.pypi.org/legacy/ + skip-existing: true # re-runs on the same version would otherwise fail diff --git a/.github/workflows/python-publish.yml b/.github/workflows/python-publish.yml index a53502c..0b267dd 100644 --- a/.github/workflows/python-publish.yml +++ b/.github/workflows/python-publish.yml @@ -86,10 +86,11 @@ jobs: - name: Download all the dists uses: actions/download-artifact@v4 with: - name: python-package-distributions + name: release-dists path: dist/ - name: Publish distribution 📦 to TestPyPI uses: pypa/gh-action-pypi-publish@release/v1 with: repository-url: https://test.pypi.org/legacy/ + skip-existing: true # version may already be on TestPyPI from the PR workflow From cf0765c96a9bc1e7b79e51bb76008e3934509704 Mon Sep 17 00:00:00 2001 From: Hugo Karas Date: Tue, 17 Nov 2026 15:28:37 +0100 Subject: [PATCH 52/55] Update Release Notes --- docsrc/API_docs.rst | 1 + docsrc/releasenotes.rst | 4 ++-- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/docsrc/API_docs.rst b/docsrc/API_docs.rst index 59d58ba..0c24ed0 100644 --- a/docsrc/API_docs.rst +++ b/docsrc/API_docs.rst @@ -25,6 +25,7 @@ Analysis Modules pyepr.ResonatorProfileAnalysis pyepr.CarrPurcellAnalysis pyepr.ReptimeAnalysis + pyepr.AmplifierLinearityAnalysis Sequences ~~~~~~~~~ diff --git a/docsrc/releasenotes.rst b/docsrc/releasenotes.rst index 4e2d4f5..6f5dff7 100644 --- a/docsrc/releasenotes.rst +++ b/docsrc/releasenotes.rst @@ -2,12 +2,12 @@ Release Notes ============= -Version 1.2 (2026-10-01): +Version 1.2 (2026-11-17): ++++++++++++++++++++++++++++ - Added `ThreePulseESEEMSequence` and `HYSCORESequence` sequences. - Added `ESEEMAnalysis` and `HYSCOREAnalysis` classes for analyzing ESEEM and HYSCORE data. +- Added `ThreePulseDEERSequence`, `FourPulseDEERSequence`, and `FivePulseDEERSequence` sequences for dipolar EPR experiments. - Expanded `dataset.epr.save` method to support saving in Bruker format. -- Expanded `eprload` function to support loading from MS400 dataformat. - Improved Documentation - Increase test coverage From 7868bb7a17638a8f417bdf6b74730d63b755499b Mon Sep 17 00:00:00 2001 From: Hugo Karas Date: Tue, 17 Nov 2026 15:34:00 +0100 Subject: [PATCH 53/55] Remove legacy sequences.py --- pyepr/sequences.py | 1665 -------------------------------------------- 1 file changed, 1665 deletions(-) delete mode 100644 pyepr/sequences.py diff --git a/pyepr/sequences.py b/pyepr/sequences.py deleted file mode 100644 index 98d5c7a..0000000 --- a/pyepr/sequences.py +++ /dev/null @@ -1,1665 +0,0 @@ -from pyepr.classes import Parameter -from pyepr.pulses import Pulse, Detection, Delay, RectPulse, ChirpPulse -from pyepr.utils import val_in_ns, val_in_us, add_phaseshift, _gen_ESEEM -from pyepr.fieldsweep_analysis import create_Nmodel -import pyepr.pulses as ad_pulses -import numpy as np -import matplotlib.pyplot as plt -import json -from itertools import product -import copy -from pyepr.utils import build_table, autoEPRDecoder -import json -from pyepr import __version__ -import uuid -import base64 -import numbers -import warnings - -class Sequence: - """ - Represents an experimental pulse sequence. - """ - - def __init__( - self, *, name, B, reptime, averages, shots,LO=None, freq=None, **kwargs) -> None: - """Represents an experimental pulse sequence. - - Parameters - ---------- - name : str - The name of this pulse sequence - B : float - The magnetic field for this sequence in Gauss. - freq : float - The central frequency of this sequence. I.e. The frequnecy at which - a zero offset pulse is at. - reptime : float - The shot repetition time in us. - averages : int - The number of scans to be accumulated. - shots : itn - The number of shots per point. - LO : float - The now deprecated local oscillator frequency. freq should be used. - """ - - self.pulses = [] - self.num_pulses = len(self.pulses) - self._axes_uuid = [] - self._reduce_uuid = [] - - if isinstance(B, Parameter): - self.B = B.copy() - else: - self.B = Parameter( - "B", B, "Gauss", - "The static B0 field for the experiment") - - if freq is not None: - self.freq = Parameter( - "freq", freq, "GHz", - "The central frequency of the sequence") - elif LO is not None: - self.freq = Parameter( - "freq", LO, "GHz", - "The central frequency of the sequence") - warnings.warn("LO is deprecated, please use freq instead", DeprecationWarning, stacklevel=2) - else: - raise ValueError("Either freq or LO must be specified") - - if isinstance(reptime, Parameter): - self.reptime = reptime.copy() - else: - self.reptime = Parameter( - "reptime", reptime, "us", - "The shot repetition time") - - self.averages = Parameter( - "averages", int(averages), "None", - "The number of averages to perform.") - - self.shots = Parameter( - "shots", int(shots), "None", - "The number of shots per scan.") - - if "det_window" in kwargs: - self.det_window = Parameter( - "det_window", kwargs["det_window"], "None", - "The length of the default detection gate" - ) - else: - self.det_window = Parameter( - "det_window", 128, "None", - "The length of the default detection gate" - ) - - - self.name = name - self.progTable = {"EventID": [], "Variable": [], "axis": [], - "axID": [], "uuid": [], "reduce": []} - pass - - def plot(self) -> None: - - pass - - def plot_pulse_exc(self, FieldSweep=None, ResonatorProfile=None): - - if FieldSweep is not None: - data = FieldSweep.data - data /= np.max(np.abs(data)) - ax = FieldSweep.fs_x - plt.plot(ax, data, label="Field Sweep", color='r') - - if ResonatorProfile is not None: - data = ResonatorProfile.prof_data / ResonatorProfile.prof_data.max() - plt.plot(ResonatorProfile.prof_frqs-self.LO.value, data, label="Resonator Profile", color='k') - - - def check_array_new(list,array, return_pos=False): - test = True - for i, ele in enumerate(list): - if np.allclose( - ele,array,rtol=1e-03, atol=1e-03, equal_nan=True): - test = False - if return_pos: - return i - return test - - axs = [] - fts = [] - labels = [] - for i, pulse in enumerate(self.pulses): - if type(pulse) == Delay: - continue - elif type(pulse) == Detection: - continue - ax, ft = pulse._calc_fft(1e4) - - if check_array_new(fts, ft): - axs.append(ax) - fts.append(ft) - labels.append([i]) - else: - j = check_array_new(fts, ft, return_pos=True) - labels[j].append(i) - - hatches = ['/', '\\', '|', '-', 'o', '.'] - - - for i in range(0,len(axs)): - ft = np.abs(fts[i]) - ft /= np.max(ft) - plt.fill(axs[i],ft, - label=f"Pulse id={str(labels[i])[1:-1]}", - hatch=hatches.pop(), alpha=0.3) - - plt.xlabel("Frequency (GHz)") - plt.legend() - - # Set correct axis, find mim and max freq - - for i, pulse in enumerate(self.pulses): - if hasattr(pulse, "freq"): - p_min = pulse.freq.value - p_max = pulse.freq.value - elif hasattr(pulse, "init_freq") & hasattr(pulse, "final_freq"): - p_min = pulse.init_freq.value - p_max = pulse.final_freq.value - elif hasattr(pulse, "init_freq") & hasattr(pulse, "BW"): - p_min = pulse.init_freq.value - p_max = p_min + pulse.BW.value - elif hasattr(pulse, "final_freq") & hasattr(pulse, "BW"): - p_max = pulse.init_freq.value - p_min = p_max - pulse.BW.value - # Check p_min < p_max - if p_min > p_max: - p_temp = p_min - p_min = p_max - p_max = p_temp - if i == 0: - min_frq = p_min - max_frq = p_max - else: - if min_frq > p_min: - min_frq = p_min - if max_frq < p_max: - max_frq = p_max - - min_frq = np.floor(min_frq*100)/100 - 0.2 - max_frq = np.ceil(max_frq*100)/100 + 0.2 - plt.xlim(min_frq, max_frq) - - - pass - - def addPulse(self, pulse): - """Adds a pulse to the next position in the sequence. - - Parameters - ---------- - pulse : Pulse - The object describing the pulse. - """ - if type(pulse) == Pulse or issubclass(type(pulse), Pulse): - self.pulses.append(pulse) - - elif type(pulse) == list: - for el in pulse: - self.pulses.append(el) - self.num_pulses = len(self.pulses) - self._buildPhaseCycle() - self._estimate_time() - - def _estimate_time(self) -> float: - """ - Calculates the estimated experiment time in seconds. - """ - self._buildPhaseCycle() - acqs = self.averages.value * self.shots.value * self.pcyc_dets.shape[0] - - reptime = np.mean(val_in_us(self.reptime)) - if hasattr(self,'evo_params'): - acqs *= np.prod([np.prod(param.dim) for param in self.evo_params]) - time = acqs * reptime * 1e-6 - - self.time = Parameter(name="time", value=f"{(time // 3600):.0f}:{(time % 3600) // 60:.0f}:{(time % 60):.0f}", unit="HH:MM:SS", - description="Estimated sequence run time") - return time - - def _buildPhaseCycle(self): - # Group phase-cycled pulses by link target, so linked pulses step - # through their phase cycle in phase (zipped) instead of being - # combined via a full outer product with the rest of the sequence. - groups = {} - for pulse in self.pulses: - if pulse.pcyc is None: - continue - link = pulse.pcyc.get("link") - key = pulse.uuid if link is None else link - groups.setdefault(key, []).append(pulse) - groups = list(groups.values()) - - phase_axes = [list(zip(*(p.pcyc["Phases"] for p in g))) for g in groups] - det_axes = [list(zip(*(p.pcyc["DetSigns"] for p in g))) for g in groups] - - self.pcyc_vars = [self.pulses.index(p) for g in groups for p in g] - self.pcyc_cycles = np.array([ - [phase for phases in row for phase in phases] - for row in product(*phase_axes)]) - self.pcyc_dets = np.array([ - np.prod([det for dets in row for det in dets]) - for row in product(*det_axes)]) - - return self.pcyc_vars, self.pcyc_cycles, self.pcyc_dets - - def evolution(self, params, reduce=[]): - """ - Sets what parameters are being evolved in the sequence, and which are - being automatically. - - `self.evo_params = params` - - Parameters - ---------- - params : list - A list of Parameter objects which are being evolved. Each every - entry in the list will be a new axis in the sequence. Only one parameter - per axis should be specified. - reduce : list - A list of Parameter objects which are being reduced. These are the - parameters which are being averaged over. These parameters should - also be in the params list. - - Returns - ------- - progTable : dict - A dictionary containing the progression of the sequence. - - - """ - self.evo_params = params - self._axes_uuid = [param.uuid for param in params] - self._reduce_uuid = [param.uuid for param in reduce] - - self._buildProgTable() - - - def _buildProgTable(self): - - progTable = {"EventID": [], "Variable": [], "axis": [], - "axID": [], "uuid": [], "reduce": []} - - for n, pulse in enumerate(self.pulses): - table = pulse.build_table() - for i in range(len(table["uuid"])): - if table["uuid"][i] in self._axes_uuid: - progTable["axID"].append(self._axes_uuid.index(table["uuid"][i])) - progTable["uuid"].append(table["uuid"][i]) - progTable["EventID"].append(n) - progTable["Variable"].append(table["Variable"][i]) - progTable["axis"].append(table["axis"][i]) - if table["uuid"][i] in self._reduce_uuid: - progTable["reduce"].append(True) - else: - progTable["reduce"].append(False) - - for var_name in vars(self): - var = getattr(self, var_name) - if type(var) is Parameter: - if not var.is_static() and not var.virtual: - for i in range(len(var.axis)): - if var.axis[i]["uuid"] in self._axes_uuid: - progTable["axID"].append(self._axes_uuid.index(var.axis[i]["uuid"])) - progTable["EventID"].append(None) - progTable["Variable"].append(var_name) - progTable["axis" ].append(var.axis[i]["axis"]) - progTable["uuid"].append(var.axis[i]["uuid"]) - if var.axis[i]["uuid"] in self._reduce_uuid: - progTable["reduce"].append(True) - else: - progTable["reduce"].append(False) - self.progTable = progTable - self._estimate_time() - return self.progTable - - @property - def seqtable_steps(self): - if len(self.evo_params) > 0: - return self.pcyc_dets.shape[0] * (len(self.pcyc_vars)+1) * np.prod([np.prod(param.dim) for param in self.evo_params]) - - @property - def shape(self): - """ - Gives the shape of the sequence,excluding the number of shots. - Return - ------ - list: - [nAvgs, axes_dims, nPcyc] - - """ - nAvgs = self.averages.value - nPcyc = self.pcyc_dets.shape[0] - nAxes = len(self.evo_params) - if nAxes > 0: - axes_dim = [] - for i in range(nAxes): - axes_dim.append(self.evo_params[i].dim[0]) - else: - axes_dim = [1] - - # Flip the axes dim so it is Z,Y,X... - axes_dim = axes_dim[::-1] - - shape = [nAvgs]+ axes_dim +[nPcyc] - - # Force list output to all be int - shape = np.array(shape).astype(int).tolist() - - return shape - - - - def adjust_step(self,waveform_precision): - """ - Adjust the step size of all axes and pulses to be an integer multiple of the waveform precision - This is to ensure that the waveform is generated correctly by the specific AWG - - Parameters - ---------- - waveform_precision : float - The precision of the waveform in ns - - """ - - for param in self.evo_params: - param.adjust_step(waveform_precision) - for pulse in self.pulses: - pulse.t.adjust_step(waveform_precision) - pulse.tp.adjust_step(waveform_precision) - - self._buildProgTable() - return self - - def shift_detfreq_to_zero(self): - det_pulse = None - for pulse in self.pulses: - if isinstance(pulse,Detection): - det_pulse = pulse - - det_freq = det_pulse.freq.value - self.freq.value -= det_freq - for pulse in self.pulses: - if hasattr(pulse,'freq'): - pulse.freq.value -= det_freq - if hasattr(pulse,'init_freq'): - pulse.init_freq.value -= det_freq - if hasattr(pulse,'final_freq'): - pulse.final_freq.value -= det_freq - return self - - def _checkRect(self) -> bool: - """Checks if all the pulses in the sequence are rectangular. - """ - test = True - - for pulse in self.pulses: - if type(pulse) is not RectPulse: - test = False - - return test - - def __str__(self): - - header = "#" * 79 + "\n" + "PyEPR Sequence Definition" + \ - "\n" + "#" * 79 + "\n" - - # Sequence Parameters - seq_param_string = "Sequence Parameters: \n" - seq_param_string += "{:<10} {:<12} {:<10} {:<30} \n".format( - 'Name', 'Value', 'Unit', 'Description') - - for param_key in vars(self): - param = getattr(self, param_key) - if type(param) is Parameter: - if param.unit is None: - unit = "" - else: - unit = param.unit - if type(param.value) is str: - seq_param_string += "{:<10} {:<12} {:<10} {:<30} \n".format( - param.name, param.value, unit, param.description) - elif param.value is None: - seq_param_string += "{:<10} {:<12} {:<10} {:<30} \n".format( - param.name, "None", unit, param.description) - else: - seq_param_string += "{:<10} {:<12.5g} {:<10} {:<30} \n".format( - param.name, param.value, unit, param.description) - - # Pulses - pulses_string = "\nEvents (Pulses, Delays, etc...): \n" - - params = ['iD', 't', 'tp', 'scale', 'type', 'Phase Cycle'] - params_widths = ["4", "8", "8", "8", "14", "40"] - - pulses_string += build_table(self.pulses, params, params_widths) - - def print_event_id(i): - if prog_table["EventID"][i] is None: - return "Seq" - else: - return str(prog_table["EventID"][i]) - - def get_unit(i): - pulse_num = prog_table["EventID"][i] - if pulse_num is None: - param = getattr(self, prog_table["Variable"][i]) - else: - param = getattr( - self.pulses[pulse_num], prog_table["Variable"][i]) - - if param.unit is None: - return "None" - else: - return param.unit - - - def test_unique_step(array): - diffs = np.diff(array)-np.diff(array)[0] - return np.isclose(diffs,np.zeros(diffs.shape)).all() - - # Progressive elements - prog_string = "\nProgression: \n" - if len(self.progTable["axID"]) >= 1: - prog_string += "{:<10} {:<10} {:<10} {:<10} {:<10} {:<10} \n".format( - 'Pulse', 'Prog. Axis', 'Parameter', 'Step', 'Dim', 'Unit') - for i in range(0, len(self.progTable["axID"])): - prog_table = self.progTable - axis = prog_table["axis"][i] - if test_unique_step(axis): - step = np.unique(np.diff(axis))[0] - fstring = "{:<10} {:<10} {:<10} {:<10.5g} {:<10} {:<10} \n" - else: - step = "Var" - fstring = "{:<10} {:<10} {:<10} {:<10} {:<10} {:<10} \n" - - prog_string += fstring.format( - print_event_id(i), prog_table["axID"][i], - prog_table["Variable"][i], step, - prog_table["axis"][i].shape[0], get_unit(i)) - - footer = "#" * 79 + "\n" +\ - f"Built by PyEPR Version: {__version__}" + "\n" + "#" * 79 - - return header + seq_param_string + pulses_string + prog_string + footer - - def copy(self): - return copy.deepcopy(self) - - def _to_dict(self): - to_return = {"version": __version__, "type": "Sequence", "subclass": str(type(self))} - - for key, var in vars(self).items(): - if isinstance(var, Parameter): - to_return[key] = var._to_dict() - if key == "pulses": - new_list = [] - for pulse in var: - new_list.append(pulse._to_dict()) - to_return[key] = new_list - else: - to_return[key] = var - - return to_return - - def _to_json(self): - class autoEPREncoder(json.JSONEncoder): - def default(self, obj): - if isinstance(obj, np.ndarray): - if (len(obj) > 0 ) and isinstance(obj[0], str): - return list(obj) - data = np.ascontiguousarray(obj.data) - data_b64 = base64.b64encode(data) - return dict(__ndarray__=str(data_b64), - dtype=str(obj.dtype), - shape=obj.shape) - if isinstance(obj, complex): - return str(obj) - if isinstance(obj, numbers.Number): - return str(obj) - if isinstance(obj, uuid.UUID): - return_dict = {"__uuid__": str(obj)} - return return_dict - if isinstance(obj, Parameter): - return obj._to_dict() - if isinstance(obj, Pulse): - return obj._to_dict() - if isinstance(obj, Sequence): - return obj._to_dict() - else: - return json.JSONEncoder.default(self, obj) - - return json.dumps(self._to_dict(), cls=autoEPREncoder, indent=4) - - def save(self, filename): - """Save the sequence to a JSON file. - - Parameters - ---------- - filename : str - Path to the JSON file. - - Returns - ------- - None - - Raises - ------ - TypeError - If the object cannot be serialized to JSON. - - Example - ------- - >>> obj = Sequence() - >>> obj.save("my_sequence.json") - """ - - - with open(filename, "w") as f: - f.write(self._to_json()) - - @classmethod - def _from_dict(cls, dct): - name = dct["name"] - B = Parameter._from_dict(dct["B"]) - freq = Parameter._from_dict(dct["freq"]) - reptime = Parameter._from_dict(dct["reptime"]) - averages = Parameter._from_dict(dct["averages"]) - shots = Parameter._from_dict(dct["shots"]) - new_sequence = cls( - name=name, B=B, freq=freq, reptime=reptime, averages=averages, shots=shots - ) - for key, var in dct.items(): - if isinstance(var, dict) and ("type" in var): - setattr(new_sequence, key, Parameter._from_dict(var)) - elif key == "pulses": - for pulse in var: - if hasattr(ad_pulses,pulse['type']): - new_sequence.pulses.append( - getattr(ad_pulses,pulse['type'])._from_dict(pulse)) - else: - new_sequence.pulses.append( - Pulse._from_dict(pulse)) - else: - setattr(new_sequence, key, var) - - return new_sequence - - @classmethod - def _from_json(cls, JSONstring): - dct = json.loads(JSONstring, object_hook=autoEPRDecoder) - return cls._from_dict(dct) - - @classmethod - def load(cls, filename): - """Load an object from a JSON file. - - Parameters - ---------- - filename : str - Path to the JSON file. - - Returns - ------- - obj : Sequence - The Sequence loaded from the JSON file. - - Raises - ------ - FileNotFoundError - If the file does not exist. - - Example - ------- - >>> obj = Sequence.load("my_sequence.json") - """ - with open(filename, "r") as f: - file_buffer = f.read() - return cls._from_json(file_buffer) - -# ============================================================================= -# Subclasses -# ============================================================================= - -class HahnEchoSequence(Sequence): - """ - Represents a Hahn-Echo sequence. - """ - def __init__(self, *, B, freq, reptime, averages, shots, **kwargs) -> None: - r"""Build a Hahn-Echo sequence using either rectangular pulses or - specified pulses. By default no progression is added to this sequence. - - Sequence: - [\pi/2 - \tau - \pi - \tau - echo] - - Parameters - ---------- - B : int or float - The B0 field, in Gauss - freq : int or float - The freq frequency in GHz - reptime : _type_ - The shot repetition time in us - averages : int - The number of scans. - shots : int - The number of shots per point - - Optional Parameters - ------------------- - pi2_pulse : Pulse - An autoEPR Pulse object describing the excitation pi/2 pulse. If - not specified a RectPulse will be created instead. - pi_pulse : Pulse - An autoEPR Pulse object describing the refocusing pi pulses. If - not specified a RectPulse will be created instead. - det_event : Pulse - An autoEPR Pulse object describing the detection even. If - not specified a standard detection event will be created instead, - with an offset frequency of 0MHz. - - """ - - name = kwargs.pop('name',"HahnEchoSequence") - - if "pi_pulse" in kwargs: - self.pi_pulse = kwargs["pi_pulse"] - if "pi2_pulse" in kwargs: - self.pi2_pulse = kwargs["pi2_pulse"] - if "det_event" in kwargs: - self.det_event = kwargs["det_event"] - - - super().__init__( - name=name, B=B, freq=freq, reptime=reptime, averages=averages, - shots=shots, **kwargs) - - if "tau" in kwargs: - tau = kwargs["tau"] - else: - tau = 500 - if "tp" in kwargs: - tp = kwargs["tp"] - else: - tp = 12 - - if hasattr(self, "pi2_pulse"): - self.addPulse(self.pi2_pulse.copy( - t=0, pcyc={"phases":[0, np.pi], "dets": [1, -1]})) - else: - self.addPulse(RectPulse( # Exc pulse - t=0, tp=tp, freq=0, flipangle=np.pi/2, - pcyc={"phases":[0, np.pi], "dets":[1, -1]} - )) - - if hasattr(self, "pi_pulse"): - pi_pulse = self.addPulse(self.pi_pulse.copy( - t=tau, pcyc={"phases":[0], "dets": [1]})) - else: - pi_pulse = self.addPulse(RectPulse( # Pump 1 pulse - t=tau, tp=tp, freq=0, flipangle=np.pi - )) - - if hasattr(self, "det_event"): - self.addPulse(self.det_event.copy(t=2*tau)) - else: - self.addPulse(Detection(t=2*tau, tp=512)) - -# ============================================================================= - -class T1InversionRecoverySequence(Sequence): - r""" - Represents a T1 Inversion Recovery Sequence. - - Sequence: - [\pi - t - \pi/2 - \tau - \pi - \tau - echo] - - Parameters - ---------- - B : int or float - The B0 field, in Gauss - LO : int or float - The LO frequency in GHz - reptime : _type_ - The shot repetition time in us - averages : int - The number of scans. - shots : int - The number of shots per point - start : float - The minimum interpulse delay in ns, by default 300 ns - step : float - The step size of the interpulse delay in ns, by default 50 ns - dim : int - The number of points in the X axis - tau: float - The Hahn echo interpulse delay in ns, by default 500 ns - - Optional Parameters - ------------------- - pi2_pulse : Pulse - An autoEPR Pulse object describing the excitation pi/2 pulse. If - not specified a RectPulse will be created instead. - pi_pulse : Pulse - An autoEPR Pulse object describing the refocusing pi pulses. If - not specified a RectPulse will be created instead. - """ - - def __init__(self, *, B, freq, reptime, averages, shots,start=500, step=40, dim=200, **kwargs) -> None: - name = "T1InversionRecoverySequence" - tp = kwargs.get("tp", 12) - - self.tau = Parameter(name="tau", value=500, unit="ns", description="The hahn ehco interpulse delay",virtual=True) - self.t = Parameter(name="t", value=start, step=step, dim=dim, unit="ns", description="The inversion recovery delay",virtual=True) - super().__init__(name=name,B=B, freq=freq, reptime=reptime, averages=averages, shots=shots, **kwargs) - - if "pi_pulse" in kwargs: - self.pi_pulse = kwargs["pi_pulse"] - if "pi2_pulse" in kwargs: - self.pi2_pulse = kwargs["pi2_pulse"] - if "det_event" in kwargs: - self.det_event = kwargs["det_event"] - - if hasattr(self, "pi_pulse"): - pi_pulse = self.addPulse(self.pi_pulse.copy( - t=0, pcyc={"phases":[0], "dets": [1]})) - else: - pi_pulse = self.addPulse(RectPulse( # Pump 1 pulse - t=0, tp=tp, freq=0, flipangle=np.pi - )) - - if hasattr(self, "pi2_pulse"): - self.addPulse(self.pi2_pulse.copy( - t=self.t, pcyc={"phases":[0, np.pi], "dets": [1, -1]})) - else: - self.addPulse(RectPulse( # Exc pulse - t=self.t, tp=tp, freq=0, flipangle=np.pi/2, - pcyc={"phases":[0, np.pi], "dets":[1, -1]} - )) - - if hasattr(self, "pi_pulse"): - pi_pulse = self.addPulse(self.pi_pulse.copy( - t=self.t+self.tau, pcyc={"phases":[0], "dets": [1]})) - else: - pi_pulse = self.addPulse(RectPulse( # Pump 1 pulse - t=self.t+self.tau, tp=tp, freq=0, flipangle=np.pi - )) - if hasattr(self, "det_event"): - self.addPulse(self.det_event.copy(t=self.t+2*self.tau)) - else: - self.addPulse(Detection(t=self.t+2*self.tau, tp=self.det_window.value)) - - self.evolution([self.t]) - - def simulate(self, T1=1e4): - """ - Simulates the T1 recovery as a simple exponential recovery. - """ - func = lambda x, a, T1: a*(1 - 2*np.exp(-x/T1)) - xaxis = val_in_ns(self.t) - data = func(xaxis,1,T1) - data = add_phaseshift(data, 0.05) - return xaxis, data -# ============================================================================= - - -class HahnEchoRelaxationSequence(HahnEchoSequence): - r""" - Represents a Hahn Echo relaxation sequence for measureing Tm. A Hahn Echo where the interpulse delay increases - - Sequence: - [\pi/2 - \tau - \pi - \tau - echo] - - Parameters - ---------- - B : int or float - The B0 field, in Gauss - freq : int or float - The freq frequency in GHz - reptime : _type_ - The shot repetition time in us - averages : int - The number of scans. - shots : int - The number of shots per point - start : float - The minimum interpulse delay in ns, by default 300 ns - step : float - The step size of the interpulse delay in ns, by default 50 ns - dim : int - The number of points in the X axis - - Optional Parameters - ------------------- - pi2_pulse : Pulse - An autoEPR Pulse object describing the excitation pi/2 pulse. If - not specified a RectPulse will be created instead. - pi_pulse : Pulse - An autoEPR Pulse object describing the refocusing pi pulses. If - not specified a RectPulse will be created instead. - """ - - def __init__(self, *, B, freq, reptime, averages, shots,start=500, step=40, dim=200, **kwargs) -> None: - - self.tau = Parameter(name="tau", value=start,step=step,dim=dim, unit="ns", description="The interpulse delay",virtual=True) - super().__init__(B=B, freq=freq, reptime=reptime, averages=averages, shots=shots,tau=self.tau, **kwargs) - - self.name = "T2RelaxationSequence" - self.evolution([self.tau]) - - def simulate(self,ESEEM_depth=0.1, Tm=1e3): - func = lambda x, a, tau, e: a*np.exp(-(x/tau)**e) - xaxis = val_in_ns(self.tau) - data = func(xaxis,1,Tm,1.6) - data = add_phaseshift(data, 0.05) - if ESEEM_depth != 0: - data *= _gen_ESEEM(xaxis, 7.842, ESEEM_depth) - return xaxis, data - -class T2RelaxationSequence(HahnEchoRelaxationSequence): - r""" - Represents a T2 relaxation sequence. This is an alias for HahnEchoRelaxationSequence. - A Hahn Echo where the interpulse delay increases. - - Sequence: - [\pi/2 - \tau - \pi - \tau - echo] - - Parameters - ---------- - B : int or float - The B0 field, in Gauss - freq : int or float - The freq frequency in GHz - reptime : _type_ - The shot repetition time in us - averages : int - The number of scans. - shots : int - The number of shots per point - start : float - The minimum interpulse delay in ns, by default 500 ns - step : float - The step size of the interpulse delay in ns, by default 40 ns - dim : int - The number of points in the X axis - - Optional Parameters - ------------------- - pi2_pulse : Pulse - An autoEPR Pulse object describing the excitation pi/2 pulse. If - not specified a RectPulse will be created instead. - pi_pulse : Pulse - An autoEPR Pulse object describing the refocusing pi pulses. If - not specified a RectPulse will be created instead. - """ - pass - -# ============================================================================= - -class FieldSweepSequence(HahnEchoSequence): - """ - Represents a Field Sweep (EDFS) sequence. - - - - """ - def __init__(self, *, B, freq, Bwidth, reptime, averages, shots, **kwargs) -> None: - r"""Build a Field Sweep (EDFS) sequence using either rectangular pulses or - specified pulses. - - Sequence: - [\pi/2 - \tau - \pi - \tau - echo] - - Parameters - ---------- - B : int or float - The B0 field, in Gauss - Bwidth: int or float - The width of the field sweep, in Gauss - freq : int or float - The freq frequency in GHz - reptime : _type_ - The shot repetition time in us - averages : int - The number of scans. - shots : int - The number of shots per point - - Optional Parameters - ------------------- - pi2_pulse : Pulse - An autoEPR Pulse object describing the excitation pi/2 pulse. If - not specified a RectPulse will be created instead. - pi_pulse : Pulse - An autoEPR Pulse object describing the refocusing pi pulses. If - not specified a RectPulse will be created instead. - """ - super().__init__( - B=B, freq=freq, reptime=reptime, averages=averages, - shots=shots, **kwargs) - self.name = "FieldSweepSequence" - - dim = Bwidth // kwargs.get('step',1) - self.B = Parameter( - "B", value=B, start = -Bwidth/2, step=kwargs.get('step',1), dim=dim, unit="Gauss", description="Field sweep width" - ) - - self.evolution([self.B]) - - def simulate(self): - """ - Simulate the Field Sweep spectra as a Nitroxide radical. - - returns - ------- - axis : np.ndarray - The x-axis of the simulation - data : np.ndarray - The y-axis of the simulation - - """ - Vmodel = create_Nmodel(self.freq.value *1e3) - axis = self.B.value + self.B.axis[0]['axis'] - sim_axis = axis * 0.1 - Boffset=0 - gy = 2.0061 - gz = 2.0021 - axy = 0.488 - az = 3.66 - GB = 0.45 - scale=1 - - data = Vmodel(sim_axis,Boffset,gy,gz,axy,az,GB,scale) - data = add_phaseshift(data, 0.05) - return axis,data - -# ============================================================================= - -class ReptimeScan(HahnEchoSequence): - """ - Represents a reptime scan of a Hahn Echo Sequence. - """ - def __init__(self, *, B, freq, reptime, reptime_max, averages, shots, start=20, dim=100, **kwargs) -> None: - r"""A Hahn echo sequence is perfomed with the shot repetition time increasing.1 - - Sequence: - [\pi/2 - \tau - \pi - \tau - echo] - - Parameters - ---------- - B : int or float - The B0 field, in Gauss - freq : int or float - The freq frequency in GHz - reptime: float - The default reptime, this is used for tuning pulses etc... - averages : int - The number of scans. - shots : int - The number of shots per point - reptime_max : float - The maximum shot repetition time in us - start : float - The minimum shot repetition time in us, by default 20 us - dim : int - The number of points in the reptime axis - - - Optional Parameters - ------------------- - pi2_pulse : Pulse - An autoEPR Pulse object describing the excitation pi/2 pulse. If - not specified a RectPulse will be created instead. - pi_pulse : Pulse - An autoEPR Pulse object describing the refocusing pi pulses. If - not specified a RectPulse will be created instead. - """ - min_reptime = start - step = (reptime_max-min_reptime)/dim - step = np.around(step,decimals=-1) - step = np.around(step,decimals=-1) - reptime = Parameter( - "reptime", reptime, start = min_reptime-reptime, step=step, dim=dim, unit="us", - description = "The shot repetition time") - - super().__init__( - B=B, freq=freq, reptime=reptime, averages=averages, - shots=shots, **kwargs) - self.name = "ReptimeScan" - - self.evolution([self.reptime]) - - def simulate(self): - """ - Simulates the reptime scan as an exponential recovery. - - .. math:: - V(t) = 1 - e^(-t/T1) - - Returns - ------- - t : np.ndarray - The x-axis of the simulation - data : np.ndarray - The y-axis of the simulation - """ - def func(x,T1): - return 1-np.exp(-x/T1) - t = self.reptime.value + self.reptime.axis[0]['axis'] - T1 = 2000 #us - - data = func(t,T1) - data = add_phaseshift(data, 0.05) - return t, data - -# ============================================================================= - -class CarrPurcellSequence(Sequence): - """ - Represents a Carr-Purcell sequence. - """ - def __init__(self, *, B, freq, reptime, averages, shots, - n,start=300,step=50, dim=100,**kwargs) -> None: - r"""Build a Carr-Purcell dynamical decoupling sequence using either - rectangular pulses or specified pulses. - - Sequence: - [\pi/2 [- \tau - \pi - \tau]^n - echo] - - Parameters - ---------- - B : int or float - The B0 field, in Gauss - freq : int or float - The freq frequency in GHz - reptime : _type_ - The shot repetition time in us - averages : int - The number of scans. - shots : int - The number of shots per point - n : int - The number refocusing pulses - start : float - The minimum interpulse delay in ns, by default 300 ns - step : float - The step size of the interpulse delay in ns, by default 50 ns - dim : int - The number of points in the X axis - - Optional Parameters - ------------------- - pi2_pulse : Pulse - An autoEPR Pulse object describing the excitation pi/2 pulse. If - not specified a RectPulse will be created instead. - pi_pulse : Pulse - An autoEPR Pulse object describing the refocusing pi pulses. If - not specified a RectPulse will be created instead. - """ - - name = "CarrPurcellSequence" - super().__init__( - name=name, B=B, freq=freq, reptime=reptime, averages=averages, - shots=shots, **kwargs) - self.t = Parameter(name="tau", value=start,step=step,dim=dim, unit="ns", - description="First interpulse delay", virtual=True) - self.n = Parameter(name="n", value=n, - description="The number of pi pulses", unit="None", virtual=True) - self.dim = Parameter(name="dim", value=dim, unit="None", - description="The number of points in the X axis", virtual=True) - - if "pi_pulse" in kwargs: - self.pi_pulse = kwargs["pi_pulse"] - if "pi2_pulse" in kwargs: - self.pi2_pulse = kwargs["pi2_pulse"] - if "det_event" in kwargs: - self.det_event = kwargs["det_event"] - - self._build_sequence() - - def _build_sequence(self): - - n = self.n.value - # dt = 20 - # dim = np.floor((self.tau.value/(2*self.n.value) -deadtime)/dt) - # # multipliers = [1] - # # multipliers += [1+2*i for i in range(1,n)] - # # multipliers += [2*n] - - # axis = np.arange(deadtime,tau/(2*n),10) - - if hasattr(self, "pi2_pulse"): - self.addPulse(self.pi2_pulse.copy( - t=0, pcyc={"phases":[0, np.pi], "dets": [1, -1]})) - else: - self.addPulse(RectPulse( # pi/2 - t=0, tp=16, freq=0, flipangle=np.pi/2, - pcyc={"phases":[0, np.pi], "dets": [1, -1]} - )) - - for i in range(n): - if i==(n-1): - phases = [0] - dets = [1] - elif i == (n-2): - phases = [0, np.pi] - dets = [1, 1] - else: - phases = [0, np.pi/2, np.pi, -np.pi/2] - dets = [1,-1,1,-1] - if hasattr(self, "pi_pulse"): - self.addPulse(self.pi_pulse.copy( - t=self.t*(2*i + 1), pcyc={"phases":phases, "dets": dets})) - else: - self.addPulse(RectPulse( # pi - t=self.t*(2*i + 1), tp=32, freq=0, flipangle=np.pi, - pcyc={"phases":phases, "dets": dets} - )) - if hasattr(self, "det_event"): - self.addPulse(self.det_event.copy(t=self.t*(2*n))) - else: - self.addPulse(Detection(t=self.t*(2*n), tp=512)) - - self.evolution([self.t]) - - def simulate(self,T_CP=2.5e3, e=1.8): - """ - Simulates the Carr-Purcell sequence as a single component stretched exponential decay. - - .. math:: - V(t) = e^{(-(t/T_{CP})^e)} - - Examples - -------- - - .. plot:: - :include-source: - - import matplotlib.pyplot as plt - import pyepr as epr - - seq = epr.CarrPurcellSequence(B=12000, freq=34, reptime=1000, averages=1, shots=10, n=4) - x,data = seq.simulate(T_CP=2.5e3, e=1.8) - plt.plot(x,data) - plt.xlabel("Interpulse Delay (ns)") - plt.ylabel("Signal Intensity (a.u.)") - - - Parameters - ---------- - T_CP : float - The Carr-Purcell relaxation time, by default 2.5e3 ns - e : float - The stretching exponent, by default 1.8 - - Returns - ------- - xaxis : np.ndarray - The x-axis of the simulation - data : np.ndarray - - """ - - - xaxis = val_in_ns(self.t) - func = lambda x, a, tau, e: a*np.exp(-(x/tau)**e) - data = func(xaxis,1,T_CP,e) - data = add_phaseshift(data, 0.05) - return xaxis, data -# ============================================================================= - -class ResonatorProfileSequence(Sequence): - """ - Builds nutation based Resonator Profile sequence. - """ - - def __init__(self, *, B, freq, reptime, averages, shots, fwidth=0.3,dtp=2, **kwargs) -> None: - r"""Build a resonator profile nutation sequence using either - rectangular pulses or specified pulses. - - Parameters - ---------- - B : int or float - The B0 field, in Gauss - Bwidth: int or float - The width of the field sweep, in Gauss - freq : int or float - The freq frequency in GHz - reptime : _type_ - The shot repetition time in us - averages : int - The number of scans. - shots : int - The number of shots per point - fwidth: float - The frequency width of the resonator profile in GHz, - by default 0.3GHz - fstep: float - The frequency step for the profile in GHz, by default 0.02GHz - - dtp: float - The time step for the test pulse in ns, by default 2 ns - step: - The frequency step parameter in GHz, by default 0.02GHz - dim: int - The number of points in the tp axis, by default set to 120/dtp, which is 60 points for dtp=2ns. - - Optional Parameters - ------------------- - tau1: float - The delay between the nutating pulse and the Hahn Echo, - by default 2000 ns - tau2: float - The interpulse delay in the Hahn Echo, - by default 500 ns - pi2_pulse : Pulse - An autoEPR Pulse object describing the excitation pi/2 pulse. If - not specified a RectPulse will be created instead. - pi_pulse : Pulse - An autoEPR Pulse object describing the refocusing pi pulses. If - not specified a RectPulse will be created instead. - """ - - name = "ResonatorProfileSequence" - super().__init__( - name=name, B=B, freq=freq, reptime=reptime, averages=averages, - shots=shots, **kwargs) - self.gyro = freq/B - self.fwidth = Parameter('fwidth',fwidth,'GHz','Half the frequency sw') - self.fstep = Parameter('fstep',kwargs.get('fstep',0.02),'GHz','Frequency step for the profile') - self.dtp = Parameter('dtp',dtp,'ns','Time step for the pulse') - - self.kwargs = kwargs - - if "pi_pulse" in kwargs: - self.pi_pulse = kwargs["pi_pulse"] - if "pi2_pulse" in kwargs: - self.pi2_pulse = kwargs["pi2_pulse"] - - self._build_sequence() - - def _build_sequence(self): - - tau1 = self.kwargs.get("tau1",2000) #2000 - tau2 = self.kwargs.get("tau2",500) #500 - fstep = self.kwargs.get("step",0.02) - dim = self.kwargs.get("dim",np.floor(120/self.dtp.value).astype(int)) - tp = Parameter("tp", 0, step=self.dtp.value, dim=dim, unit="ns", description="Test Pulse length") - fwidth= self.fwidth.value - fstep = self.fstep.value - dim = np.floor(fwidth*2/fstep) - center_freq = self.freq.value - self.freq = Parameter("freq", center_freq, start=-fwidth, step=fstep, dim=dim, unit="GHz", description="frequency") - self.B = Parameter( - "B",((center_freq)/self.gyro), start=-fwidth/self.gyro, step=fstep/self.gyro, dim=dim, - unit="Gauss",link=self.freq,description="B0 Field" ) - - self.addPulse(RectPulse( # Hard pulse - t=0, tp=tp, freq=0, flipangle="Hard" - )) - - if hasattr(self, "pi2_pulse"): - self.addPulse(self.pi2_pulse.copy( - t=tau1, pcyc={"phases":[0, np.pi], "dets": [1, -1]})) - else: - self.addPulse(RectPulse( # pi/2 - t=tau1, tp=16, freq=0, flipangle=np.pi/2, - pcyc={"phases":[0, np.pi], "dets": [1, -1]} - )) - - if hasattr(self, "pi_pulse"): - self.addPulse(self.pi_pulse.copy( - t=tau1+tau2)) - else: - self.addPulse(RectPulse( # pi/2 - t=tau1+tau2, tp=32, freq=0, flipangle=np.pi - )) - - self.addPulse(Detection(t=tau1+2*tau2, tp=512)) - - - self.pulses[0].scale.value = 1 - - - self.evolution([tp, self.freq]) - - def simulate(self, Q=100, fc=None, nu1=75,damping=0.06): - """ - Simulates a resonator profile sequence as a damped oscillation. - - Parameters - ---------- - Q : int - The quality factor of the resonator, by default 100 - fc : float - The center frequency of the resonator, by default None. If None the freq frequency is used. - nu1 : float - The maximum amplitude of the resonator profile, by default 75 MHz. This is a linear frequency scale. - damping : float - The damping factor of the resonator, by default 0.06. - - """ - - if fc is None: - fc = self.freq.value - - xmin = self.freq.value - self.fwidth.value - xmax = self.freq.value + self.fwidth.value - - - def lorenz_fcn(x, centre, sigma): - y = (0.5*sigma)/((x-centre)**2 + (0.5*sigma)**2) - return y - - mode = lambda x: lorenz_fcn(x, fc, fc/Q) - axis = np.linspace(xmin,xmax) - scale = nu1/mode(axis).max() - self.mode = lambda x: lorenz_fcn(x, fc, fc/Q) * scale - - damped_oscilations = lambda x, f, c: np.cos(2*np.pi*f*x) * np.exp(-c*x) - damped_oscilations_vec = np.vectorize(damped_oscilations) - freq_axis = self.freq.value + self.freq.axis[0]['axis'] - freq_len = freq_axis.shape[0] - tp_x = val_in_ns(self.pulses[0].tp) - tp_len = tp_x.shape[0] - nut_freqs = self.mode(freq_axis) - - damped_oscilations_vec - data = damped_oscilations_vec(tp_x.reshape(tp_len,1),nut_freqs.reshape(1,freq_len)*1e-3,damping) - return [tp_x, freq_axis], data - -# ============================================================================= - -class ThreePulseESEEMSequence(Sequence): - - def __init__(self, *, B, freq, reptime, averages, shots, tau=300, start=500, step=40, dim=200, **kwargs) -> None: - - self.tau = Parameter(name="tau", value=start,step=step,dim=dim, unit="ns", description="1st Inter Pulse Delay",virtual=True) - self.T = Parameter( - name='T', - description = 'Mixing Time', - unit = 'ns', - value=start, - step = step, - dim = dim, - virtual=True) - - super().__init__(name="ThreePulseESEEMSequence", - B=B, freq=freq, reptime=reptime, averages=averages, shots=shots, **kwargs) - - self._build_sequence() - - def _build_sequence(self): - if hasattr(self, "pi2_pulse"): - self.addPulse(self.pi2_pulse.copy( - t=0, pcyc={"phases":[0, np.pi], "dets": [1, -1]})) - else: - self.addPulse(RectPulse( # pi/2 - t=0, tp=16, freq=0, flipangle=np.pi/2, - pcyc={"phases":[0, np.pi], "dets": [1, -1]} - )) - - if hasattr(self, "pi2_pulse"): - self.addPulse(self.pi2_pulse.copy( - t=self.tau)) - else: - self.addPulse(RectPulse( # pi/2 - t=self.tau, tp=32, freq=0, flipangle=np.pi - )) - - if hasattr(self, "pi2_pulse"): - self.addPulse(self.pi2_pulse.copy( - t=self.tau+self.T)) - else: - self.addPulse(RectPulse( # pi/2 - t=self.tau+self.T, tp=32, freq=0, flipangle=np.pi - )) - - self.addPulse(Detection(t=self.tau+self.T+self.tau, tp=512)) - - self.evolution([self.T]) - - def _simulate(self): - raise NotImplementedError("Simulation for Three Pulse ESEEM is not implemented yet.") - - -class HYSCORESequence(Sequence): - def __init__(self, *, B, freq, reptime, averages, shots, tau=300, start=300, step=16, dim=128, **kwargs) -> None: - - self.tau = Parameter(name="tau", value=start,step=step,dim=dim, unit="ns", description="1st Inter Pulse Delay",virtual=True) - self.T1 = Parameter( - name='T1', - description = '1st Mixing Time', - unit = 'ns', - value=start, - step = step, - dim = dim, - virtual=True) - self.T2 = Parameter( - name='T2', - description = '2nd Mixing Time', - unit = 'ns', - value=start, - step = step, - dim = dim, - virtual=True) - - super().__init__( - name = "HYSCORESequence", - B=B, freq=freq, reptime=reptime, averages=averages, shots=shots, **kwargs) - - self._build_sequence() - - def _build_sequence(self): - - if hasattr(self, "pi2_pulse"): - p90 = self.pi2_pulse.copy(t=0, pcyc={'phases':[0], 'dets':[1]}) - else: - p90 = RectPulse( # pi/2 - t=0, tp=16, freq=0, flipangle=np.pi/2, - pcyc={"phases":[0], "dets": [1]} - ) - - if hasattr(self, "pi_pulse"): - p180 = self.pi_pulse.copy(t=0, pcyc={'phases':[0], 'dets':[1]}) - else: - p180 = RectPulse( # pi - t=0, tp=32, freq=0, flipangle=np.pi, - pcyc={"phases":[0], "dets": [1]} - ) - - det_event = Detection(t=0, tp=512) - - - self.addPulse(p90.copy(t=0, pcyc={'phases':[0], 'dets':[1]})) - self.addPulse(p90.copy(t=self.tau, pcyc={'phases':[0], 'dets':[1]})) - self.addPulse(p180.copy(t=self.tau+self.T1,pcyc={'phases':[0,np.pi/2,np.pi,3*np.pi/2,], 'dets':[1,-1,1,-1]})) - self.addPulse(p90.copy(t=self.tau+self.T1+self.T2,pcyc={'phases':[0], 'dets':[1]})) - - self.addPulse(det_event.copy(t=2*self.tau+self.T1+self.T2)) - self._buildPhaseCycle() - self.evolution([self.T1,self.T2]) - -# ============================================================================= - -class TWTProfileSequence(Sequence): - """ - Builds TWT based Resonator Profile sequence. - """ - - def __init__(self,*,B,freq,reptime,averages=1,shots=100,dtp=2,**kwargs) -> None: - - """ - - - Parameters - ---------- - B: float - The B0 field, in Gauss - freq: float - The freq frequency in GHz - reptime: float - The shot repetition time in us - averages: int - The number of scans. - shots: int - The number of shots per point - dtp: float - The time step for the test pulse in ns, by default 2 ns - tp_dim: int - The number of points in the tp axis, by default set to 120/dtp, which is 60 points for dtp=2ns. - step: float - The scale step parameter, by default 0.02 - dim: int - The number of points in the scale axis, by default 50 - tau1: float - The delay between the nutating pulse and the Hahn Echo, by default 2000 ns - tau2: float - The interpulse delay in the Hahn Echo, by default 500 ns - pi2_pulse : Pulse - A PyEPR `Pulse` object describing the excitation pi/2 pulse. - pi_pulse : Pulse - A PyEPR `Pulse` object describing the refocusing pi pulses. - - """ - - name = "TWTProfileSequence" - super().__init__( - name=name, B=B, freq=freq, reptime=reptime, averages=averages, - shots=shots, **kwargs) - - self.kwargs = kwargs - self.dtp = Parameter('dtp',dtp,'ns','Time step for the pulse') - - if "pi_pulse" in kwargs: - self.pi_pulse = kwargs["pi_pulse"] - if "pi2_pulse" in kwargs: - self.pi2_pulse = kwargs["pi2_pulse"] - - self._build_sequence() - - def _build_sequence(self,): - - tau1 = self.kwargs.get("tau1",2000) #2000 - tau2 = self.kwargs.get("tau2",500) #500 - - tp_dim = self.kwargs.get("tp_dim",np.floor(120/self.dtp.value).astype(int)) - tp = Parameter("tp", 0, step=self.dtp.value, dim=tp_dim, unit="ns", description="Test Pulse length") - - step = self.kwargs.get("step",0.02) - dim = self.kwargs.get("dim",50) - # limit the scale to a max of 1.0 - if step * dim > 1.0: - dim = int(1.0 / step) - warnings.warn(f"Scale axis limited to a maximum of 1.0, dim set to {dim}.") - - scale = Parameter("scale", 0, step=step, dim=dim, unit="None", description="Amplitude scale factor") - - self.addPulse(RectPulse( # Hard pulse - t=0, tp=tp, freq=0, flipangle="hard",scale=scale - )) - - if hasattr(self, "pi2_pulse"): - self.addPulse(self.pi2_pulse.copy( - t=tau1, pcyc={"phases":[0, np.pi], "dets": [1, -1]})) - else: - self.addPulse(RectPulse( # pi/2 - t=tau1, tp=16, freq=0, flipangle=np.pi/2, - pcyc={"phases":[0, np.pi], "dets": [1, -1]} - )) - - if hasattr(self, "pi_pulse"): - self.addPulse(self.pi_pulse.copy( - t=tau1+tau2)) - else: - self.addPulse(RectPulse( # pi/2 - t=tau1+tau2, tp=32, freq=0, flipangle=np.pi - )) - - self.addPulse(Detection(t=tau1+2*tau2, tp=512)) - - self.evolution([tp, scale]) - -# ============================================================================= - -class KBBSequence(Sequence): - """ - Builds a Kutnz-Boehlen-Bodenhausen echo sequence. - - """ - - def __init__(self,*,B,freq,reptime,averages=1,shots=100,**kwargs) -> None: - """ - Parameters - ---------- - B : _type_ - _description_ - freq : _type_ - _description_ - reptime : _type_ - _description_ - averages : int, optional - _description_, by default 1 - shots : int, optional - _description_, by default 100 - pi2_pulse : Pulse, optional - A PyEPR Pulse object describing the excitation pi/2 pulse. - If missing a ChirpPulse without amplitude will be created instead, with frequency sweep of -50 to 50 MHz and duration of 200 ns. - pi_pulse : Pulse, optional - A PyEPR Pulse object describing the refocusing pi pulses. - If missing a ChirpPulse without amplitude will be created instead, with frequency sweep of -50 to 50 MHz and duration of 100 ns. - det_event : Detection, optional - A PyEPR Detection object describing the detection event. - tau : float, optional - The interpulse delay in ns, by default 500 ns - """ - name = "KBBSequence" - super().__init__( - name=name, B=B, freq=freq, reptime=reptime, averages=averages, - shots=shots, **kwargs) - - self.kwargs = kwargs - - self._build_sequence() - - def _build_sequence(self,): - - tau_value = self.kwargs.get("tau",500) #500 - pi2_pulse = self.kwargs.get("pi2_pulse",ChirpPulse(tp=200,freq=0,flipangle=np.pi/2, init_freq=-0.05, final_freq=0.05)) - pi_pulse = self.kwargs.get("pi_pulse",ChirpPulse(tp=100,freq=0,flipangle=np.pi, init_freq=-0.05, final_freq=0.05)) - - self.addPulse(pi2_pulse.copy(t=0, pcyc={"phases":[0, np.pi], "dets": [1,-1]})) - self.addPulse(pi_pulse.copy(t=tau_value, pcyc={"phases":[0], "dets": [1]})) - self.addPulse(Detection(t=2*tau_value, tp=512)) - - self.evolution([]) - pass - -# ============================================================================= - -class KBBPulseProfileSequence(KBBSequence): - """ - Builds a KBB based Resonator Profile sequence. - """ - - def __init__(self,*,B,freq,reptime,averages=1,shots=100,dtp=2,**kwargs) -> None: - - name = "KBB_PulseProfileSequence" - super().__init__( - name=name, B=B, freq=freq, reptime=reptime, averages=averages, - shots=shots, **kwargs) - self._build_sequence() - - def _build_sequence(self,): - pass \ No newline at end of file From 878847c9f2410bac5d617cc03fbc70a6bb0135af Mon Sep 17 00:00:00 2001 From: Hugo Karas Date: Tue, 17 Nov 2026 15:44:22 +0100 Subject: [PATCH 54/55] Add phase cycles to MetaData --- pyepr/dataset.py | 50 +++++++++++++++++++++++++++++++++++++++++++++--- 1 file changed, 47 insertions(+), 3 deletions(-) diff --git a/pyepr/dataset.py b/pyepr/dataset.py index 9c6807b..cd28e73 100644 --- a/pyepr/dataset.py +++ b/pyepr/dataset.py @@ -14,7 +14,7 @@ import datetime __all__ = [ - 'get_all_axes', 'get_all_fixed_param', 'create_dataset_from_sequence', + 'get_all_axes', 'get_all_fixed_param', 'get_phase_cycle_attrs', 'create_dataset_from_sequence', 'create_dataset_from_axes', 'create_dataset_from_bruker', 'EPRAccessor', 'downconvert_dataset', 'find_peak', 'save_bruker', ] @@ -99,6 +99,31 @@ def get_all_fixed_param(sequence): fixed_param['pcyc_name'] = sequence.pcyc_name return fixed_param +def get_phase_cycle_attrs(sequence): + """ + Collect the phase cycle of a sequence as dataset attributes. + + Stores the per-pulse phases and detection signs (``pulse{i}_pcyc_phases``, + ``pulse{i}_pcyc_dets``) as well as the full built phase cycle of the + sequence (``pcyc_vars``, ``pcyc_cycles``, ``pcyc_dets``). + """ + pcyc_attrs = {} + for i, pulse in enumerate(sequence.pulses): + pcyc = getattr(pulse, 'pcyc', None) + if pcyc is None: + continue + type = "det" if isinstance(pulse, Detection) else "pulse" + pcyc_attrs[f"{type}{i}_pcyc_phases"] = np.asarray(pcyc["Phases"]) + pcyc_attrs[f"{type}{i}_pcyc_dets"] = np.asarray(pcyc["DetSigns"]) + + if hasattr(sequence, 'pcyc_vars'): + pcyc_attrs['pcyc_vars'] = np.asarray(sequence.pcyc_vars, dtype=int) + if hasattr(sequence, 'pcyc_cycles'): + pcyc_attrs['pcyc_cycles'] = np.asarray(sequence.pcyc_cycles) + if hasattr(sequence, 'pcyc_dets'): + pcyc_attrs['pcyc_dets'] = np.asarray(sequence.pcyc_dets) + return pcyc_attrs + def create_dataset_from_sequence(data, sequence: Sequence,extra_params={}): ndims = data.ndim default_labels = ['X','Y','Z','T'] @@ -106,6 +131,7 @@ def create_dataset_from_sequence(data, sequence: Sequence,extra_params={}): axes = get_all_axes(sequence) coords = {a:(default_labels[b['ax_id']],b['axis']) for a,b in axes.items()} attr = get_all_fixed_param(sequence) + attr.update(get_phase_cycle_attrs(sequence)) attr.update(extra_params) attr.update({'autoDEER_Version':__version__}) return xr.DataArray(data, dims=dims, coords=coords,attrs=attr) @@ -345,12 +371,30 @@ def sequence(self)->Sequence: try: pulse_build = getattr(epr_pulses,pulse_type) - pulses_obj.append(pulse_build(**params)) + pulse_obj = pulse_build(**params) except: continue - + + # netCDF stores one-element attributes as scalars, so re-wrap them + if f"{key}{i}_pcyc_phases" in dataset_attrs: + phases = np.atleast_1d(dataset_attrs[f"{key}{i}_pcyc_phases"]) + dets = np.atleast_1d(dataset_attrs.get(f"{key}{i}_pcyc_dets", np.ones(len(phases)))) + pulse_obj._addPhaseCycle(phases, detections=dets) + pulses_obj.append(pulse_obj) + sequence = Sequence(**seq_params) sequence.pulses = pulses_obj + sequence._buildPhaseCycle() + + # Restore the saved sequence-level phase cycle, which also preserves + # linked pulses. Only valid if every pulse was rebuilt (indices match). + if all(k in dataset_attrs for k in ['pcyc_vars', 'pcyc_cycles', 'pcyc_dets']) and len(pulses_obj) == n_events: + pcyc_vars = np.atleast_1d(dataset_attrs['pcyc_vars']).astype(int) + if len(pcyc_vars) == 0: + return sequence + sequence.pcyc_vars = pcyc_vars.tolist() + sequence.pcyc_cycles = np.atleast_1d(dataset_attrs['pcyc_cycles']).reshape(-1, len(pcyc_vars)) + sequence.pcyc_dets = np.atleast_1d(dataset_attrs['pcyc_dets']) return sequence From 185cb2b8136a96a6c96b6b558902aa9621451add Mon Sep 17 00:00:00 2001 From: Hugo Karas Date: Tue, 17 Nov 2026 15:45:39 +0100 Subject: [PATCH 55/55] Updated release notes --- docsrc/releasenotes.rst | 1 + 1 file changed, 1 insertion(+) diff --git a/docsrc/releasenotes.rst b/docsrc/releasenotes.rst index 6f5dff7..df22146 100644 --- a/docsrc/releasenotes.rst +++ b/docsrc/releasenotes.rst @@ -8,6 +8,7 @@ Version 1.2 (2026-11-17): - Added `ESEEMAnalysis` and `HYSCOREAnalysis` classes for analyzing ESEEM and HYSCORE data. - Added `ThreePulseDEERSequence`, `FourPulseDEERSequence`, and `FivePulseDEERSequence` sequences for dipolar EPR experiments. - Expanded `dataset.epr.save` method to support saving in Bruker format. +- Added phase cycles to dataset metadata - Improved Documentation - Increase test coverage