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 07a1230..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-pypi: - name: Publish Python 🐍 distribution 📦 to PyPI - needs: - - build - runs-on: ubuntu-latest - - environment: - name: pypi - url: https://pypi.org/project/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 - 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 7a44b0a..b340d3b 100644 --- a/.github/workflows/python-publish.yml +++ b/.github/workflows/python-publish.yml @@ -94,4 +94,5 @@ jobs: 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 diff --git a/.gitignore b/.gitignore index 50aa696..b9756a9 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 @@ -70,6 +72,7 @@ instance/ # Sphinx documentation docsrc/_build/ docsrc/autoapi/ +_build/ # PyBuilder target/ @@ -128,5 +131,8 @@ dmypy.json .DS_Store poetry.lock +*.lock docsrc/auto_examples/ + +_pulsespel_output/ \ No newline at end of file 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/docsrc/API_docs.rst b/docsrc/API_docs.rst index c6c4340..aa699ea 100644 --- a/docsrc/API_docs.rst +++ b/docsrc/API_docs.rst @@ -1,3 +1,5 @@ +.. rst-class:: api-docs + API doc ================= Classes @@ -23,21 +25,51 @@ Analysis Modules pyepr.ResonatorProfileAnalysis pyepr.CarrPurcellAnalysis pyepr.ReptimeAnalysis + pyepr.AmplifierLinearityAnalysis 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.TWTProfileSequence pyepr.sequences.T1InversionRecoverySequence +Relxation Sequences ++++++++++++++++++++++ +.. _RelaxationSequences: +.. autoapisummary:: + + pyepr.sequences.HahnEchoRelaxationSequence + pyepr.sequences.CarrPurcellSequence + pyepr.sequences.T1InversionRecoverySequence + pyepr.sequences.ReptimeScanSequence + +Dipolar EPR Sequences ++++++++++++++++++++++ +.. _DipolarSequences: + +.. autoapisummary:: + + pyepr.sequences.DEER.ThreePulseDEERSequence + pyepr.sequences.DEER.FourPulseDEERSequence + pyepr.sequences.DEER.FivePulseDEERSequence + +Hyperfine Spectroscopy Sequences +++++++++++++++++++++++++++++++++ +.. _HyperfineSequences: + +.. autoapisummary:: + + pyepr.sequences.ESEEM.ThreePulseESEEMSequence + pyepr.sequences.ESEEM.HYSCORESequence + Pulses ~~~~~~ .. _Pulses: @@ -48,36 +80,44 @@ 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 ~~~~~~~~~~~~~~~~~~~~ +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 ---------------- @@ -86,6 +126,8 @@ I/O ~~~ .. autoapisummary:: + :nosignatures: + pyepr.tools.eprload pyepr.utils.save_file pyepr.dataset.create_dataset_from_sequence @@ -97,6 +139,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/_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/_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 5524a89..69b62e0 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,11 +55,19 @@ 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', + '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 + '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 ------------------------------------------------- @@ -66,14 +75,34 @@ html_theme = 'furo' html_static_path = ['_static'] +html_css_files = ['autoapi.css', 'gallery.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/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/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/advanced_sequences/linking_sequence_parameter.py b/docsrc/examples/advanced_sequences/linking_sequence_parameter.py new file mode 100644 index 0000000..ce3ce73 --- /dev/null +++ b/docsrc/examples/advanced_sequences/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/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/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/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/tools/loading_cw.py b/docsrc/examples/tools/loading_cw.py new file mode 100644 index 0000000..9236e43 --- /dev/null +++ b/docsrc/examples/tools/loading_cw.py @@ -0,0 +1,19 @@ +""" +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. Nonetheless + +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/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/releasenotes.rst b/docsrc/releasenotes.rst index 9070159..df22146 100644 --- a/docsrc/releasenotes.rst +++ b/docsrc/releasenotes.rst @@ -1,6 +1,17 @@ Release Notes ============= + +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. +- Added phase cycles to dataset metadata +- Improved Documentation +- Increase test coverage + Version 1.1 (2026-05-27): ++++++++++++++++++++++++++++ - Added `AmplifierLinearityAnalysis` class for characterizing amplifier non-linearity. diff --git a/docsrc/sg_execution_times.rst b/docsrc/sg_execution_times.rst deleted file mode 100644 index 78433a9..0000000 --- a/docsrc/sg_execution_times.rst +++ /dev/null @@ -1,37 +0,0 @@ - -: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 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 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 1d9f42d..66587b5 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 @@ -82,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 diff --git a/pyepr/__init__.py b/pyepr/__init__.py index 8cf921f..66bc61e 100644 --- a/pyepr/__init__.py +++ b/pyepr/__init__.py @@ -1,8 +1,7 @@ from ._version import __version__, __copyright__ from .tools import eprload from .utils import * -from .classes import Parameter, Interface -from .sequences import * +from .classes import Parameter from .pulses import * from .criteria import * from .dataset import * @@ -10,4 +9,8 @@ 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 +from .plotting import plot_sequence_freq, draw_sequence +from .resonator_tune import LoSweepTuneSequence +from .hardware.BaseInterfaceClass import Interface +from .sequences import * \ No newline at end of file diff --git a/pyepr/classes.py b/pyepr/classes.py index b0df3bf..1d827ef 100644 --- a/pyepr/classes.py +++ b/pyepr/classes.py @@ -1,217 +1,13 @@ import numpy as np -import os -from pyepr import __version__ +from pyepr._version 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 yaml - - -# ============================================================================= - - -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 - 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 +from pyepr.config import get_waveform_precision # ============================================================================= @@ -263,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 @@ -534,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 @@ -612,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 @@ -648,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/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=[] 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 1bf4c2f..cd28e73 100644 --- a/pyepr/dataset.py +++ b/pyepr/dataset.py @@ -2,15 +2,22 @@ import matplotlib.pyplot as plt import re import scipy.fft as fft -from pyepr import __version__ -from pyepr.pulses import Detection +from pyepr._version import __version__ +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 import copy +import datetime + +__all__ = [ + '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', +] # ============================================================================= @@ -25,8 +32,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 +52,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 @@ -63,9 +70,10 @@ 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 - elif param.axis[0]['uuid'] in sequence.reduce_uuid: + 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 @@ -91,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'] @@ -98,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) @@ -177,7 +211,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 @@ -200,7 +237,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: @@ -212,8 +253,15 @@ 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): + 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) @@ -224,11 +272,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) @@ -238,13 +292,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 = {} @@ -262,7 +322,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 @@ -309,13 +370,31 @@ 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) - pulses_obj.append(pulse_build(**params)) + pulse_build = getattr(epr_pulses,pulse_type) + 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 @@ -381,7 +460,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 @@ -412,27 +492,41 @@ 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: 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': - 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 - 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 @@ -445,8 +539,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') @@ -459,7 +577,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 +589,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 @@ -484,3 +605,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/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/BaseInterfaceClass.py b/pyepr/hardware/BaseInterfaceClass.py new file mode 100644 index 0000000..4973e89 --- /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) + time.sleep(5) + 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) + time.sleep(5) + 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..dfbdaa6 100644 --- a/pyepr/hardware/Bruker_AWG.py +++ b/pyepr/hardware/Bruker_AWG.py @@ -1,10 +1,11 @@ -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 * +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 2f50c48..cc756a4 100644 --- a/pyepr/hardware/Bruker_MPFU.py +++ b/pyepr/hardware/Bruker_MPFU.py @@ -1,10 +1,11 @@ -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 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..0eca1d0 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 @@ -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.py b/pyepr/hardware/ETH_awg.py index ad1b653..460bcbf 100644 --- a/pyepr/hardware/ETH_awg.py +++ b/pyepr/hardware/ETH_awg.py @@ -1,6 +1,7 @@ import matlab.engine -from pyepr.classes import Interface, Parameter -from pyepr.pulses import Pulse, RectPulse, ChirpPulse, HSPulse, Delay, Detection +from pyepr.classes import Parameter +from pyepr.hardware.BaseInterfaceClass import Interface +from pyepr.pulses import Pulse, RectPulse, ChirpPulse, HSPulse, GaussianPulse, Delay, Detection from pyepr.sequences import Sequence, HahnEchoSequence, FieldSweepSequence import numpy as np import re @@ -12,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 @@ -473,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. @@ -516,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) @@ -539,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 @@ -605,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) @@ -674,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): @@ -800,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 @@ -853,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/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 f7c66bc..5c49b40 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") @@ -53,6 +54,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 +86,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 +156,30 @@ 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 +204,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(): @@ -187,31 +246,77 @@ 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,persistance=None): + """ + 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. + 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, 'persistance': persistance}) + 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 + """ 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: 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 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: @@ -250,12 +355,13 @@ def launch(self, sequence: Sequence , savename: str, IFgain=None, *args,**kwargs 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.") - 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 +378,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,11 +391,12 @@ 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'] - 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. @@ -304,6 +412,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 ------- @@ -325,6 +439,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) @@ -351,10 +469,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 @@ -586,7 +704,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/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/hardware/dummy.py b/pyepr/hardware/dummy.py index e5cf50f..a5d5a7d 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 * @@ -162,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") diff --git a/pyepr/plotting.py b/pyepr/plotting.py new file mode 100644 index 0000000..0111b31 --- /dev/null +++ b/pyepr/plotting.py @@ -0,0 +1,397 @@ +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): + """ + 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 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') + + return fig \ No newline at end of file diff --git a/pyepr/pulses.py b/pyepr/pulses.py index e9148e5..92aaa49 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) @@ -85,11 +93,7 @@ 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=[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 +105,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 +135,7 @@ def __init__(self, *, tp, t=None, scale=None, flipangle=None, pcyc=[0], self.name = name - self.Progression = False + self.uuid = uuid.uuid1() if flipangle is not None: self.flipangle = Parameter( @@ -133,8 +143,12 @@ 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"]) + elif issubclass(type(pcyc), Pulse): + self._addPhaseCycle(pcyc.pcyc["Phases"], detections=pcyc.pcyc["DetSigns"],link=pcyc.uuid) else: self._addPhaseCycle(pcyc, detections=None) pass @@ -150,7 +164,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. @@ -163,8 +177,15 @@ 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): + """ + Clears the attached phase cycle. + """ + self.pcyc = None + pass def _buildFMAM(self, func, ax=None): """ @@ -247,65 +268,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`? + Check if all parameters in the pulse object are static. - 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`? - - 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 +346,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 +364,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 +493,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 +533,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 +571,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: @@ -707,13 +591,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). + 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 @@ -722,6 +612,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) @@ -738,17 +631,27 @@ 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: + if new_pcyc is None: new_pulse.pcyc = None - elif type(new_pcyc) is dict: - new_pulse._addPhaseCycle(new_pcyc["phases"], detections=new_pcyc["dets"]) + 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._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" @@ -960,6 +863,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) @@ -972,6 +888,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): """ @@ -1002,10 +924,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") @@ -1018,6 +941,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)) @@ -1026,13 +950,37 @@ 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): - """ - 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,16 +1035,76 @@ 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 non-symetric 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( + 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 @@ -1141,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") # ============================================================================= @@ -1153,6 +1159,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 +1223,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 +1317,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/relaxation_analysis.py b/pyepr/relaxation_analysis.py index fd3a2b0..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 @@ -636,7 +641,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 +655,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 +664,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/resonator_profile_analysis.py b/pyepr/resonator_profile_analysis.py index 734f868..aaaeace 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) @@ -80,13 +86,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): @@ -268,7 +274,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 +294,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 +311,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 @@ -468,15 +353,13 @@ def find_unique(means,amps,stds, threshold=0.05): 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 @@ -486,32 +369,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) @@ -519,15 +397,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[0].get_ylim()) + axs[0].vlines(self.fc,*axs[0].get_ylim(),ls='--',color='0.7',lw=2) - 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) + 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)) + + secax2.set_xlabel('Relative Freq / GHz',fontsize=11) return fig @@ -680,7 +570,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/resonator_tune.py b/pyepr/resonator_tune.py new file mode 100644 index 0000000..727a9e9 --- /dev/null +++ b/pyepr/resonator_tune.py @@ -0,0 +1,67 @@ +from pyepr.sequences import Sequence +from pyepr.classes import Parameter +from pyepr.pulses import 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)) diff --git a/pyepr/sequences/DEER.py b/pyepr/sequences/DEER.py new file mode 100644 index 0000000..57f5e81 --- /dev/null +++ b/pyepr/sequences/DEER.py @@ -0,0 +1,695 @@ +# 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): + 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 : 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 + 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 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'. + + 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): + 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.05, "lam3":0.05} + + 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): + + 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): + + 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 new file mode 100644 index 0000000..a579091 --- /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.py b/pyepr/sequences/base_sequences.py similarity index 56% rename from pyepr/sequences.py rename to pyepr/sequences/base_sequences.py index 6899f7e..de00356 100644 --- a/pyepr/sequences.py +++ b/pyepr/sequences/base_sequences.py @@ -2,6 +2,7 @@ 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 @@ -10,17 +11,34 @@ import copy from pyepr.utils import build_table, autoEPRDecoder import json -from pyepr import __version__ +from pyepr._version import __version__ import uuid import base64 import numbers import warnings +from typing import Callable + +__all__ = [ + 'Sequence', 'HahnEchoSequence', 'T1InversionRecoverySequence', + 'HahnEchoRelaxationSequence', 'T2RelaxationSequence', 'FieldSweepSequence', + 'ReptimeScanSequence', 'ReptimeScan', 'CarrPurcellSequence', 'ResonatorProfileSequence', + 'TWTProfileSequence', 'KBBSequence', 'KBBPulseProfileSequence', +] 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. @@ -33,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 @@ -42,66 +60,104 @@ def __init__( 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 = [] + 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[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 = name - self.progTable = {"EventID": [], "Variable": [], "axis": [], + + 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 @@ -196,6 +252,13 @@ def check_array_new(list,array, return_pos=False): 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. @@ -210,7 +273,6 @@ def addPulse(self, pulse): elif type(pulse) == list: for el in pulse: self.pulses.append(el) - self.num_pulses = len(self.pulses) self._buildPhaseCycle() self._estimate_time() @@ -220,52 +282,40 @@ 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") 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=[]): @@ -294,8 +344,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 +358,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 +374,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) @@ -339,17 +389,19 @@ def _buildProgTable(self): return self.progTable @property - def seqtable_steps(self): + 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): + def shape(self) -> list[int]: """ - Gives the shape of the sequence,excluding the number of shots. - Return - ------ - list: + Gives the shape of the sequence,excluding the number of shots. + + Returns + ------- + list [nAvgs, axes_dims, nPcyc] """ @@ -397,6 +449,7 @@ def adjust_step(self,waveform_precision): 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): @@ -444,6 +497,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) @@ -506,6 +562,7 @@ def test_unique_step(array): 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): @@ -648,9 +705,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 @@ -663,121 +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.HahnEchoSequence( + B=12000, freq=34, reptime=1e3, averages=1, shots=10, tau=500) + seq.draw() + """ - - name = "HahnEchoSequence" - + + 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. + + .. math:: + V(\\tau) = e^{-(\\tau/T_m)^{1.6}} + + 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. - - 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. + 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( @@ -813,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) @@ -825,45 +999,102 @@ def simulate(self, T1=1e4): class HahnEchoRelaxationSequence(HahnEchoSequence): """ Represents a Hahn Echo relaxation sequence for measureing Tm. A Hahn Echo where the interpulse delay increases - - 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: + 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 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. - self.tau = Parameter(name="tau", value=start,step=step,dim=dim, unit="ns", description="The interpulse delay",virtual=True) + 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() + + """ + + 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) @@ -876,47 +1107,75 @@ 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 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 + + 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, 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) # ============================================================================= 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 @@ -931,39 +1190,74 @@ 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:: + :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" - - self.B = Parameter( - "B", value=B, start = -Bwidth/2, step=1, dim=Bwidth, unit="Gauss", description="Field sweep width" + dim = Bwidth // kwargs.get('step',1) + 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'] @@ -982,12 +1276,16 @@ def simulate(self): # ============================================================================= -class ReptimeScan(HahnEchoSequence): + +class ReptimeScanSequence(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 ---------- @@ -1017,6 +1315,19 @@ def __init__(self, *, B, freq, reptime, reptime_max, averages, shots, start=20, 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.ReptimeScanSequence( + 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 @@ -1043,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) @@ -1056,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): @@ -1064,9 +1401,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 @@ -1096,25 +1436,42 @@ def __init__(self, *, B, freq, reptime, averages, shots, 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", + 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() @@ -1168,7 +1525,24 @@ 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 + 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 ---------- @@ -1182,6 +1556,7 @@ def simulate(self,T_CP=2.5e3, e=1.8): xaxis : np.ndarray The x-axis of the simulation data : np.ndarray + """ @@ -1198,15 +1573,13 @@ 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 ---------- 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_ @@ -1225,6 +1598,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 ------------------- @@ -1240,23 +1615,60 @@ def __init__(self, *, B, freq, reptime, averages, shots, fwidth=0.3,dtp=2, **kwa 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 = 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 + 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"] + 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() @@ -1265,17 +1677,19 @@ 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 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" )) @@ -1319,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: @@ -1336,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) @@ -1350,6 +1791,7 @@ def lorenz_fcn(x, centre, sigma): 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): @@ -1358,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() @@ -1408,4 +1904,113 @@ 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): + """ + Builds a Kutnz-Boehlen-Bodenhausen echo sequence. + + """ + + def __init__(self,*,B,freq,reptime,averages=1,shots=100,**kwargs) -> None: + """ + 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, optional + The number of scans, by default 1 + shots : int, optional + The number of shots per point, by default 100 + """ + name = kwargs.pop("name", "KBBSequence") + super().__init__( + name=name, B=B, freq=freq, reptime=reptime, averages=averages, + shots=shots, **kwargs) + + self.kwargs: dict = kwargs + """Keyword arguments""" + + 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 diff --git a/pyepr/tools.py b/pyepr/tools.py index 01ccea3..3a7ac7b 100644 --- a/pyepr/tools.py +++ b/pyepr/tools.py @@ -1,14 +1,12 @@ 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 from scipy.io.matlab import MatReadError import xarray as xr - -log = logging.getLogger('autoDEER.Tools') +import warnings def eprload( @@ -42,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'," @@ -87,6 +80,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 +114,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 diff --git a/pyepr/utils.py b/pyepr/utils.py index 98e8d68..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 = "" @@ -43,7 +49,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/pyproject.toml b/pyproject.toml index 5495370..b5626da 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,48 +1,50 @@ -[tool.poetry] +[project] name = "pyEPR-ESR" -version = "1.1" +version = "1.2" 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", + "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"] 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 c1f2cd8..f89c65a 100644 --- a/tests/test_dataset.py +++ b/tests/test_dataset.py @@ -1,10 +1,10 @@ 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 +import os def test_create_dataset_from_sequence(): seq = FieldSweepSequence(B=12200, Bwidth=500, LO=34.4, reptime=3e3, averages=1, shots=100) @@ -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) @@ -105,3 +105,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 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) + 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 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 3885568..b861163 100644 --- a/tests/test_respro.py +++ b/tests/test_respro.py @@ -1,9 +1,10 @@ -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.resonator_profile_analysis import * +from pyepr.sequences import ResonatorProfileSequence +from pyepr.dataset import create_dataset_from_sequence, create_dataset_from_axes +from pyepr.fieldsweep_analysis 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): @@ -17,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 aff2bf8..73801fb 100644 --- a/tests/test_sequences.py +++ b/tests/test_sequences.py @@ -1,7 +1,11 @@ -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 +from pyepr.sequences.DEER import FourPulseDEERSequence, FivePulseDEERSequence, ThreePulseDEERSequence + def test_fieldsweep_simulate(): N_gyro = 0.002803632236095 @@ -54,4 +58,64 @@ 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 + + +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() + +