Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

NMRPulseSequence

The NMRPulseSequence class is a Pydantic BaseModel representing a sequence of NMRPulse objects.

Creating a Pulse Sequence

There are multiple ways to create a pulse sequence:

String-based initialization

The traditional way is to use a string where pulses are separated by ::

from hqs_nmr.pulse_sequence import NMRPulseSequence

pulse_sequence = NMRPulseSequence("90x:t5")

Method chaining

All convenience methods return self, allowing for method chaining:

pulse_sequence = (NMRPulseSequence()
    .rotation_pulse(90, "x")
    .time_evolution(5.0)
    .rotation_pulse(-90, "y"))

Adding Pulses

Using string representation

You can add more pulses to an existing sequence using the add_pulses method with a string:

pulse_sequence.add_pulses("t-5:-pi/2y:t0.1")

Using convenience methods

The class provides convenient methods for adding specific types of pulses:

Rotation Pulse

pulse_sequence.rotation_pulse(angle=90, axis="x", active_sites=None)

Creates and adds a rotation pulse with the specified angle (in degrees) and axis. Optionally, you can specify which spins the pulse should act on using active_sites (a list of spin indices).

Parameters:

  • angle (float): The rotation angle in degrees
  • axis (str): The rotation axis (“x”, “y”, or “z”)
  • active_sites (Optional[List[int]]): List of spin indices to apply the pulse to. If None, applies to all spins.

Example:

# Apply 90° rotation around x-axis to all spins
pulse_sequence.rotation_pulse(90, "x")

# Apply 180° rotation around y-axis only to spins 0 and 2
pulse_sequence.rotation_pulse(180, "y", active_sites=[0, 2])

Time Evolution

pulse_sequence.time_evolution(t=5.0, timestep=0.01)

Creates and adds a time evolution pulse for time t (in seconds) with the specified timestep.

Parameters:

  • t (float): The evolution time in seconds
  • timestep (Optional[float]): The time step for the simulation (default: 0.01)

Example:

# Evolve for 5 seconds with default timestep
pulse_sequence.time_evolution(5.0)

# Evolve for 2 seconds with custom timestep
pulse_sequence.time_evolution(2.0, timestep=0.001)

Selective Frequency Pulse

pulse_sequence.selective_frequency_pulse(
    spin_frequency_target_Hz=1000.0,
    theta=90,
    axis="x",
    fwhm_Hz=0.1
)

Creates and adds a selective frequency pulse that targets a specific spin frequency. The pulse acts on spins based on how close their shift is to the target frequency, with a Gaussian profile controlled by fwhm_Hz (the full width at half maximum in Hz).

Parameters:

  • spin_frequency_target_Hz (float): The target spin frequency in Hz
  • theta (float): The rotation angle in degrees
  • axis (str): The rotation axis (“x”, “y”, or “z”)
  • fwhm_Hz (Optional[float]): The full width at half maximum of the Gaussian profile in Hz (default: 0.1). Note that the SelectiveFrequencyPulse class itself defaults to 10 Hz when constructed directly.

Example:

# Apply selective pulse at 1000 Hz
pulse_sequence.selective_frequency_pulse(1000.0, 90, "x")

# Apply selective pulse with narrower frequency selectivity
pulse_sequence.selective_frequency_pulse(1000.0, 90, "x", fwhm_Hz=0.05)

Soft Pulse

pulse_sequence.soft_pulse(
    total_time=1.0,
    phi=0.0,
    shape_params={"t_0": 0.5, "sigma": 0.1, "amplitude": np.pi/2},
    timestep=None,
    shape="gaussian",
    integration_method="midpoint"
)

Creates and adds a soft pulse with a time-dependent envelope to the sequence. Soft pulses apply a smooth time-varying Hamiltonian over a finite duration, unlike rotation pulses which are instantaneous.

Parameters:

  • total_time (float): The duration of the pulse in seconds
  • phi (float): The phase of the pulse in radians
  • shape_params (Dict[str, Any]): Parameters for the pulse shape (see Soft Pulse for details on each shape)
  • timestep (Optional[float]): The time step for simulation (default: None, auto-calculated based on shape)
  • shape (str): The shape of the pulse (default: “gaussian”). Options include: “gaussian”, “constant”, “rectangular”, “half_gaussian”, “eburp2”, “iburp2”, “reburp”, “q3”, “q5”
  • integration_method (str): The integration method for Magnus expansion (default: “midpoint”). Options: “midpoint”, “gl”

Example:

import numpy as np

# Add a Gaussian soft pulse
pulse_sequence.soft_pulse(
    total_time=1.0,
    phi=0.0,
    shape_params={"t_0": 0.5, "sigma": 0.1, "amplitude": np.pi/2},
    shape="gaussian"
)

For detailed information about pulse shapes, parameters, integration methods, and more examples, see the Soft Pulse documentation.

Pydantic Serialization

Since NMRPulseSequence is a Pydantic BaseModel, it provides built-in serialization and deserialization capabilities:

Serialization to Dictionary

pulse_sequence = NMRPulseSequence("90x:t5:-90y|150f")
pulse_dict = pulse_sequence.model_dump()
# Returns:
# {'pulses': [{'active_sites': None,
#              'angle': <NMRPulseAngle.DEG_90: 90.0>,
#              'axis': <NMRPulseAxis.X: 'x'>,
#              'pulse_type': 'rotation'},
#             {'pulse_type': 'time_evolution', 't': 5.0, 'timestep': 0.01},
#             {'axis': <NMRPulseAxis.Y: 'y'>,
#              'fwhm_Hz': 10.0,
#              'pulse_type': 'selective_frequency',
#              'spin_frequency_target_Hz': 150.0,
#              'theta': <NMRPulseAngle.DEG_NEG_90: -90.0>}]}

Serialization to JSON

pulse_sequence = NMRPulseSequence("90x:t5:-90y|150f")
pulse_json = pulse_sequence.model_dump_json()

# Or with indentation for readability
pulse_json = pulse_sequence.model_dump_json(indent=2)
# Returns:
# ('{\n'
#  '  "pulses": [\n'
#  '    {\n'
#  '      "pulse_type": "rotation",\n'
#  '      "angle": 90.0,\n'
#  '      "axis": "x",\n'
#  '      "active_sites": null\n'
#  '    },\n'
#  '    {\n'
#  '      "pulse_type": "time_evolution",\n'
#  '      "t": 5.0,\n'
#  '      "timestep": 0.01\n'
#  '    },\n'
#  '    {\n'
#  '      "pulse_type": "selective_frequency",\n'
#  '      "spin_frequency_target_Hz": 150.0,\n'
#  '      "theta": -90.0,\n'
#  '      "axis": "y",\n'
#  '      "fwhm_Hz": 10.0\n'
#  '    }\n'
#  '  ]\n'
#  '}')

Deserialization from Dictionary

pulse_dict = {
    "pulses": [
        {"pulse_type": "rotation", "angle": 90.0, "axis": "x", "active_sites": None},
        {"pulse_type": "time_evolution", "t": 5.0, "timestep": 0.01},
        {
            "pulse_type": "selective_frequency",
            "spin_frequency_target_Hz": 150.0,
            "theta": -90.0,
            "axis": "y",
            "fwhm_Hz": 10.0,
        },
    ],
}
pulse_sequence = NMRPulseSequence.model_validate(pulse_dict)

Deserialization from JSON

pulse_json = """{
  "pulses": [
    {"pulse_type": "rotation", "angle": 90.0, "axis": "x", "active_sites": null},
    {"pulse_type": "time_evolution", "t": 5.0, "timestep": 0.01},
    {"pulse_type": "selective_frequency", "spin_frequency_target_Hz": 150.0, "theta": -90.0, "axis": "y", "fwhm_Hz": 10.0}
  ]
}"""
pulse_sequence = NMRPulseSequence.model_validate_json(pulse_json)

Saving and Loading from Files

# Save to JSON file
pulse_sequence = NMRPulseSequence("90x:t5:-90y|150f")
with open("pulse_sequence.json", "w") as f:
    f.write(pulse_sequence.model_dump_json(indent=2))

# Load from JSON file
with open("pulse_sequence.json", "r") as f:
    pulse_sequence = NMRPulseSequence.model_validate_json(f.read())

These serialization methods are useful for:

  • Saving pulse sequences to files
  • Transmitting pulse sequences over network APIs
  • Storing pulse sequences in databases
  • Creating reproducible experiment configurations

Main Methods

This class has two main methods for applying pulse sequences:

apply_pulse_sequence

def apply_pulse_sequence(
    self,
    eigenvectors: BlockDiagonalOperator,
    **kwargs: Any,
) -> np.ndarray:
    """Apply the pulse sequence operator to eigenvectors.

    Starts from the density matrix rho = S^z, applies each pulse P in the sequence
    to calculate rho = P @ rho @ P†, and transforms the final density matrix with
    the eigenvectors.

    Args:
        eigenvectors (BlockDiagonalOperator): The eigenvectors.
        kwargs: Additional keyword arguments for pulse application. Required kwargs depend on
            the pulse types in the sequence:
            
            num_spins (int): Required. The number of spins in the system.
            
            hamiltonian (np.ndarray): Required for TimeEvolutionPulse and SoftPulse.
                The Hamiltonian matrix to use during time evolution.
            
            eigen_hamiltonian (Tuple[np.ndarray, np.ndarray]): Optional alternative to
                hamiltonian for TimeEvolutionPulse. A tuple of (eigenvalues, eigenvectors)
                of the Hamiltonian for more efficient time evolution.
            
            nmr_parameters (NMRParameters): Required for SelectiveFrequencyPulse.
                The NMR parameters containing chemical shifts.
            
            calculation_parameters (NMRCalculationParameters): Required for SelectiveFrequencyPulse.
                The calculation parameters for converting shifts to frequencies.
    
    Returns:
        np.ndarray: The result of applying the pulse sequence: eigenvectors.rdot(eigenvectors.dot_h(P @ rho @ P†))
    """

get_pulse_sequence

def get_pulse_sequence(
    self,
    eigenvectors: BlockDiagonalOperator,
    **kwargs: Any,
) -> np.ndarray:
    """Applies the pulse sequence operator to eigenvectors.

    This method computes only the pulse operator P (not applied to a density matrix).
    It returns the total pulse operator for the entire sequence by multiplying
    all individual pulse operators together: P_total = P_n @ ... @ P_2 @ P_1

    Args:
        eigenvectors (BlockDiagonalOperator): The eigenvectors.
        kwargs: Additional keyword arguments for pulse application. Required kwargs depend on
            the pulse types in the sequence:
            
            num_spins (int): Required. The number of spins in the system.
            
            hamiltonian (np.ndarray): Required for TimeEvolutionPulse and SoftPulse.
                The Hamiltonian matrix to use during time evolution.
            
            eigen_hamiltonian (Tuple[np.ndarray, np.ndarray]): Optional alternative to
                hamiltonian for TimeEvolutionPulse. A tuple of (eigenvalues, eigenvectors)
                of the Hamiltonian for more efficient time evolution.
            
            nmr_parameters (NMRParameters): Required for SelectiveFrequencyPulse.
                The NMR parameters containing chemical shifts.
            
            calculation_parameters (NMRCalculationParameters): Required for SelectiveFrequencyPulse.
                The calculation parameters for converting shifts to frequencies.
    
    Returns:
        np.ndarray: The total pulse operator transformed by eigenvectors: 
            eigenvectors.rdot(eigenvectors.dot_h(P_total))
    """

apply_pulse_sequence_to_state

def apply_pulse_sequence_to_state(
    self,
    state: np.ndarray,
    **kwargs: Any,
) -> np.ndarray:
    """Applies the pulse sequence to a state vector.

    Args:
        state (np.ndarray): The state vector.
        kwargs: Additional keyword arguments for pulse application. Required kwargs depend on
            the pulse types in the sequence:
            
            num_spins (int): Required. The number of spins in the system.
            
            hamiltonian (np.ndarray): Required for TimeEvolutionPulse and SoftPulse.
                The Hamiltonian matrix to use during time evolution.
            
            eigen_hamiltonian (Tuple[np.ndarray, np.ndarray]): Optional alternative to
                hamiltonian for TimeEvolutionPulse. A tuple of (eigenvalues, eigenvectors)
                of the Hamiltonian for more efficient time evolution.
            
            nmr_parameters (NMRParameters): Required for SelectiveFrequencyPulse.
                The NMR parameters containing chemical shifts.
            
            calculation_parameters (NMRCalculationParameters): Required for SelectiveFrequencyPulse.
                The calculation parameters for converting shifts to frequencies.

    Returns:
        np.ndarray: The state vector after applying the pulse sequence: P_total @ state
    """

collect_expectation_values

def collect_expectation_values(
    self,
    measurement_operator: Union[np.ndarray, List[np.ndarray]],
    correlation_operator: Optional[np.ndarray] = None,
    **kwargs: Any,
) -> Tuple[Union[List[complex], list[List[complex]]], List[float]]:
    """Produce a list of expectation values for the given measurement operator(s).

    This function will apply all the pulses in the sequence on Sz and record expectation
    values after each instantaneous pulse or for each timesteps for time-based pulses.

    If only one measurement operator is provided a list containing the expectation
    values will be returned. A list of measurement operators can also be provided, in this
    case a list containing lists of expectation values for each operator will be returned.

    A list containing the timestep of each values will also be returned, starting from 0.

    NOTE: instantaneous pulses will have a timestep of 1e-13s.

    Args:
        measurement_operator (Union[np.ndarray, List[np.ndarray]]): The measurement operator.
        correlation_operator: Operator whose expectation value is recorded
        kwargs: Additional keyword arguments for pulse application. Required kwargs depend on
            the pulse types in the sequence:
            num_spins (int): Required. The number of spins in the system.
            hamiltonian (np.ndarray): Required for TimeEvolutionPulse and SoftPulse.
                The Hamiltonian matrix to use during time evolution.
            eigen_hamiltonian (Tuple[np.ndarray, np.ndarray]): Optional alternative to
                hamiltonian for TimeEvolutionPulse. A tuple of (eigenvalues, eigenvectors)
                of the Hamiltonian for more efficient time evolution.
            nmr_parameters (NMRParameters): Required for SelectiveFrequencyPulse.
                The NMR parameters containing chemical shifts.
            calculation_parameters (NMRCalculationParameters): Required for
                SelectiveFrequencyPulse.
                The calculation parameters for converting shifts to frequencies.

    Returns:
        Union[List[complex], list[List[complex]]]: The expectation values.
        List[float]: The measurement time of each value
    """

collect_expectation_values_from_state

def collect_expectation_values_from_state(
    self,
    state_vector: np.ndarray,
    measurement_operator: Union[np.ndarray, List[np.ndarray]],
    correlation_operator: Optional[np.ndarray] = None,
    **kwargs: Any,
) -> Tuple[Union[List[complex], list[List[complex]]], List[float]]:
    """Collects the expectation values when applying the pulse sequence on a state.

    This function will apply all the pulses in the sequence on the provided state and record
    expectation values after each instantaneous pulse or for each timesteps for time-based
    pulses.

    If only one measurement operator is provided a list containing the expectation
    values will be returned. A list of measurement operators can also be provided, in this
    case a list containing lists of expectation values for each operator will be returned.

    A list containing the timestep of each values will also be returned, starting from 0.

    NOTE: instantaneous pulses will have a timestep of 1e-13s.


    Args:
        state_vector: The initial state vector as a (2^N,) complex array.
        measurement_operator (Union[np.ndarray, List[np.ndarray]]): The measurement operator.
            each timestep.
        correlation_operator: Operator whose expectation value is recorded
        kwargs: Additional keyword arguments for pulse application. Required kwargs depend on
            the pulse types in the sequence:
            num_spins (int): Required. The number of spins in the system.
            hamiltonian (np.ndarray): Required for TimeEvolutionPulse and SoftPulse.
                The Hamiltonian matrix to use during time evolution.
            eigen_hamiltonian (Tuple[np.ndarray, np.ndarray]): Optional alternative to
                hamiltonian for TimeEvolutionPulse. A tuple of (eigenvalues, eigenvectors)
                of the Hamiltonian for more efficient time evolution.
            nmr_parameters (NMRParameters): Required for SelectiveFrequencyPulse.
                The NMR parameters containing chemical shifts.
            calculation_parameters (NMRCalculationParameters): Required for
                SelectiveFrequencyPulse.
                The calculation parameters for converting shifts to frequencies.

    Returns:
        List[complex]: The expectation values.
        List[float]: The measurement time of each value.
    """

Usage

The apply_pulse_sequence method is used by the pulse_solver in pulse_solver.py. It starts with and goes over each pulse P in the sequence to calculate . Finally the result is used to calculate .

The collect_expectation_values is used in the spin_echo notebook to perform a spin echo experiment. An inconvenience of this method is that the time evolutions need to be divided into many small time evolutions to have enough points.