Skip to content

psiqit.dynamics

Auto-generated documentation for the psiqit.dynamics module.

psiqit.dynamics

PSIQIT - Python Scientific Quantum Information Toolkit Dynamics Module

This module provides quantum dynamics and time evolution capabilities.

Submodules:

adiabatic.py - Adiabatic evolution and quantum annealing heisenberg.py - Heisenberg picture evolution interaction.py - Interaction picture dynamics lindblad.py - Lindblad master equation for open quantum systems monte_carlo.py - Quantum trajectories (Monte Carlo wavefunction method) schrodinger.py - Schrödinger equation (time-independent and time-dependent) time_evolution.py - Numerical time evolution methods (Trotter, Chebyshev, Krylov)

AdiabaticResult dataclass

Result container for adiabatic evolution

Attributes:

Name Type Description
times ndarray

Time points

states List[Ket]

List of quantum states at each time

energies List[float]

List of energies at each time

fidelities List[float]

List of fidelities with instantaneous ground state

success bool

Whether evolution was successful

message str

Additional information

n_steps int

Number of time steps

final_state Optional[Ket]

Final state

final_energy Optional[float]

Final energy

Source code in psiqit\dynamics\adiabatic.py
@dataclass
class AdiabaticResult:
    """
    Result container for adiabatic evolution

    Attributes:
        times: Time points
        states: List of quantum states at each time
        energies: List of energies at each time
        fidelities: List of fidelities with instantaneous ground state
        success: Whether evolution was successful
        message: Additional information
        n_steps: Number of time steps
        final_state: Final state
        final_energy: Final energy
    """
    times: np.ndarray
    states: List[Ket]
    energies: List[float]
    fidelities: List[float]
    success: bool = True
    message: str = ""
    n_steps: int = 0
    final_state: Optional[Ket] = None
    final_energy: Optional[float] = None

    def __post_init__(self):
        """Post-process the result"""
        self.n_steps = len(self.times)

        if self.states:
            self.final_state = self.states[-1]

        if self.energies:
            self.final_energy = self.energies[-1]

    def get_fidelity_history(self) -> np.ndarray:
        """Get the fidelity history array"""
        return np.array(self.fidelities)

    def get_energy_history(self) -> np.ndarray:
        """Get the energy history array"""
        return np.array(self.energies)

    def get_state_at_time(self, index: int) -> Optional[Ket]:
        """Get state at a specific time index"""
        if 0 <= index < len(self.states):
            return self.states[index]
        return None

    def get_final_state(self) -> Optional[Ket]:
        """Get the final state"""
        return self.final_state

    def get_final_energy(self) -> Optional[float]:
        """Get the final energy"""
        return self.final_energy

    def __repr__(self) -> str:
        status = "Success" if self.success else "Failed"
        return f"AdiabaticResult(steps={self.n_steps}, status={status}, final_energy={self.final_energy:.6f if self.final_energy else 'N/A'})"

    def __str__(self) -> str:
        lines = [
            "Adiabatic Evolution Results:",
            f"  Steps: {self.n_steps}",
            f"  Success: {self.success}",
            f"  Message: {self.message}",
            f"  Final Energy: {self.final_energy:.8f}" if self.final_energy else "  Final Energy: N/A",
            f"  Final Fidelity: {self.fidelities[-1]:.6f}" if self.fidelities else "  Final Fidelity: N/A",
        ]
        return "\n".join(lines)

__post_init__()

Post-process the result

Source code in psiqit\dynamics\adiabatic.py
def __post_init__(self):
    """Post-process the result"""
    self.n_steps = len(self.times)

    if self.states:
        self.final_state = self.states[-1]

    if self.energies:
        self.final_energy = self.energies[-1]

get_fidelity_history()

Get the fidelity history array

Source code in psiqit\dynamics\adiabatic.py
def get_fidelity_history(self) -> np.ndarray:
    """Get the fidelity history array"""
    return np.array(self.fidelities)

get_energy_history()

Get the energy history array

Source code in psiqit\dynamics\adiabatic.py
def get_energy_history(self) -> np.ndarray:
    """Get the energy history array"""
    return np.array(self.energies)

get_state_at_time(index)

Get state at a specific time index

Source code in psiqit\dynamics\adiabatic.py
def get_state_at_time(self, index: int) -> Optional[Ket]:
    """Get state at a specific time index"""
    if 0 <= index < len(self.states):
        return self.states[index]
    return None

get_final_state()

Get the final state

Source code in psiqit\dynamics\adiabatic.py
def get_final_state(self) -> Optional[Ket]:
    """Get the final state"""
    return self.final_state

get_final_energy()

Get the final energy

Source code in psiqit\dynamics\adiabatic.py
def get_final_energy(self) -> Optional[float]:
    """Get the final energy"""
    return self.final_energy

AdiabaticEvolution

Adiabatic quantum evolution

Simulates the time-dependent Schrödinger equation for a Hamiltonian that interpolates between an initial and final Hamiltonian.

H(t) = (1 - s(t)) * H_initial + s(t) * H_final

where s(t) = t/T is the interpolation parameter.

Example

from psiqit.quantum import pauli_x, pauli_z, zero H_i = pauli_x() # Initial Hamiltonian H_f = pauli_z() # Final Hamiltonian evo = AdiabaticEvolution(H_i, H_f, T=10.0, n_steps=100) result = evo.evolve(zero()) print(result.final_energy)

Source code in psiqit\dynamics\adiabatic.py
class AdiabaticEvolution:
    """
    Adiabatic quantum evolution

    Simulates the time-dependent Schrödinger equation for a Hamiltonian
    that interpolates between an initial and final Hamiltonian.

    H(t) = (1 - s(t)) * H_initial + s(t) * H_final

    where s(t) = t/T is the interpolation parameter.

    Example:
        >>> from psiqit.quantum import pauli_x, pauli_z, zero
        >>> H_i = pauli_x()  # Initial Hamiltonian
        >>> H_f = pauli_z()  # Final Hamiltonian
        >>> evo = AdiabaticEvolution(H_i, H_f, T=10.0, n_steps=100)
        >>> result = evo.evolve(zero())
        >>> print(result.final_energy)
    """

    def __init__(
        self,
        H_initial: Operator,
        H_final: Operator,
        T: float,
        n_steps: int = 100,
        schedule: Optional[Callable[[float], float]] = None
    ):
        """
        Initialize adiabatic evolution

        Args:
            H_initial: Initial Hamiltonian (at t=0)
            H_final: Final Hamiltonian (at t=T)
            T: Total evolution time
            n_steps: Number of time steps
            schedule: Interpolation schedule s(t) (default: linear s(t) = t/T)

        Example:
            >>> H_i = pauli_x()
            >>> H_f = pauli_z()
            >>> evo = AdiabaticEvolution(H_i, H_f, T=10.0, n_steps=100)
        """
        if H_initial.dim != H_final.dim:
            raise ValueError(f"Hamiltonian dimensions mismatch: {H_initial.dim} vs {H_final.dim}")

        self.H_initial = H_initial
        self.H_final = H_final
        self.T = T
        self.n_steps = n_steps
        self.dim = H_initial.dim

        # Default linear schedule
        if schedule is None:
            self.schedule = lambda t: t / T
        else:
            self.schedule = schedule

        logger.info(f"AdiabaticEvolution initialized: dim={self.dim}, T={T:.3f}, steps={n_steps}")

    def _hamiltonian(self, t: float) -> np.ndarray:
        """
        Get the Hamiltonian at time t

        Args:
            t: Time

        Returns:
            np.ndarray: Hamiltonian matrix
        """
        s = self.schedule(t)
        H = (1 - s) * self.H_initial.data + s * self.H_final.data
        return H

    def _get_ground_state(self, H: np.ndarray) -> Ket:
        """
        Get the ground state of a Hamiltonian

        Args:
            H: Hamiltonian matrix

        Returns:
            Ket: Ground state
        """
        eigvals, eigvecs = np.linalg.eigh(H)
        return Ket(eigvecs[:, 0])

    def _get_ground_energy(self, H: np.ndarray) -> float:
        """
        Get the ground state energy of a Hamiltonian

        Args:
            H: Hamiltonian matrix

        Returns:
            float: Ground state energy
        """
        eigvals = np.linalg.eigvalsh(H)
        return float(eigvals[0])

    def _schrodinger_derivative(self, t: float, psi_vec: np.ndarray) -> np.ndarray:
        """
        Compute dψ/dt = -i/ħ H(t) ψ

        Args:
            t: Time
            psi_vec: State vector (flattened)

        Returns:
            np.ndarray: Time derivative
        """
        H = self._hamiltonian(t)
        # Use hbar = 1 (natural units)
        return -1j * H @ psi_vec

    def evolve(self, psi0: Ket) -> AdiabaticResult:
        """
        Perform adiabatic evolution

        Args:
            psi0: Initial state (usually ground state of H_initial)

        Returns:
            AdiabaticResult: Evolution results

        Example:
            >>> from psiqit.quantum import zero
            >>> result = evo.evolve(zero())
            >>> print(result.final_energy)
        """
        if psi0.dim != self.dim:
            raise ValueError(f"State dimension {psi0.dim} does not match Hamiltonian dimension {self.dim}")

        logger.info(f"Starting adiabatic evolution for T={self.T:.3f}")

        # Time points
        times = np.linspace(0, self.T, self.n_steps + 1)
        dt = times[1] - times[0]

        # Initialize
        psi = psi0.data.copy()
        states = [psi0.copy()]
        energies = []
        fidelities = []

        # Track instantaneous ground state
        H0 = self._hamiltonian(0)
        ground_state = self._get_ground_state(H0)
        ground_energy = self._get_ground_energy(H0)

        # Initial fidelity
        initial_fidelity = abs(np.vdot(ground_state.data, psi)) ** 2
        fidelities.append(initial_fidelity)
        energies.append(ground_energy)

        # Evolution
        success = True
        message = "Evolution completed successfully"

        try:
            # Use RK4 for integration (or the system solver)
            # For complex state vectors, we need to handle real and imaginary parts separately
            # We'll use a simple RK4 implementation for complex vectors

            for i in range(self.n_steps):
                t = times[i]

                # RK4 for complex vector
                k1 = self._schrodinger_derivative(t, psi)
                k2 = self._schrodinger_derivative(t + dt/2, psi + dt/2 * k1)
                k3 = self._schrodinger_derivative(t + dt/2, psi + dt/2 * k2)
                k4 = self._schrodinger_derivative(t + dt, psi + dt * k3)

                psi_new = psi + dt/6 * (k1 + 2*k2 + 2*k3 + k4)

                # Normalize
                norm = np.linalg.norm(psi_new)
                if norm > 0:
                    psi_new = psi_new / norm
                else:
                    raise ValueError("State norm became zero")

                psi = psi_new

                # Store state
                states.append(Ket(psi.copy()))

                # Compute energy and fidelity at this time
                H_t = self._hamiltonian(times[i+1])
                energy = self._get_ground_energy(H_t)
                ground_state_t = self._get_ground_state(H_t)
                fidelity = abs(np.vdot(ground_state_t.data, psi)) ** 2

                energies.append(energy)
                fidelities.append(fidelity)

                # Check if fidelity is dropping too fast (potential diabatic transition)
                if i > 0 and fidelity < 0.1 and fidelities[i] > 0.9:
                    logger.warning(f"Sudden drop in fidelity at step {i}: {fidelities[i]:.3f} -> {fidelity:.3f}")

        except Exception as e:
            success = False
            message = f"Evolution failed: {str(e)}"
            logger.error(message)

        # Final results
        final_state = states[-1] if states else None
        final_energy = energies[-1] if energies else None

        logger.info(f"Adiabatic evolution completed: {message}")

        return AdiabaticResult(
            times=times,
            states=states,
            energies=energies,
            fidelities=fidelities,
            success=success,
            message=message,
            final_state=final_state,
            final_energy=final_energy
        )

    def get_min_gap(self, n_points: int = 1000) -> Tuple[float, float]:
        """
        Estimate the minimum energy gap during evolution

        Args:
            n_points: Number of points to sample

        Returns:
            Tuple: (min_gap, time_of_min_gap)

        Example:
            >>> evo = AdiabaticEvolution(H_i, H_f, T=10.0)
            >>> min_gap, t_gap = evo.get_min_gap()
            >>> print(f"Minimum gap: {min_gap:.6f} at t={t_gap:.3f}")
        """
        times = np.linspace(0, self.T, n_points)
        gaps = []

        for t in times:
            H = self._hamiltonian(t)
            eigvals = np.linalg.eigvalsh(H)
            gap = eigvals[1] - eigvals[0] if len(eigvals) > 1 else 0
            gaps.append(gap)

        min_gap = np.min(gaps)
        t_min_gap = times[np.argmin(gaps)]

        return float(min_gap), float(t_min_gap)

    def get_adiabatic_condition(self, n_points: int = 100) -> float:
        """
        Check the adiabatic condition: |⟨1|dH/dt|0⟩| / (ΔE)² << 1

        Args:
            n_points: Number of points to sample

        Returns:
            float: Maximum violation of adiabatic condition
        """
        times = np.linspace(0, self.T, n_points)
        max_ratio = 0.0

        for t in times:
            H = self._hamiltonian(t)
            eigvals, eigvecs = np.linalg.eigh(H)

            if len(eigvals) < 2:
                continue

            E0, E1 = eigvals[0], eigvals[1]
            delta_E = E1 - E0

            if delta_E < 1e-10:
                continue

            # Compute dH/dt
            dt = 1e-6
            H_plus = self._hamiltonian(t + dt)
            H_minus = self._hamiltonian(t - dt)
            dH = (H_plus - H_minus) / (2 * dt)

            # Matrix element ⟨1|dH/dt|0⟩
            psi0 = eigvecs[:, 0]
            psi1 = eigvecs[:, 1]

            matrix_element = abs(np.vdot(psi1, dH @ psi0))
            ratio = matrix_element / (delta_E ** 2)

            max_ratio = max(max_ratio, ratio)

        return float(max_ratio)

__init__(H_initial, H_final, T, n_steps=100, schedule=None)

Initialize adiabatic evolution

Parameters:

Name Type Description Default
H_initial Operator

Initial Hamiltonian (at t=0)

required
H_final Operator

Final Hamiltonian (at t=T)

required
T float

Total evolution time

required
n_steps int

Number of time steps

100
schedule Optional[Callable[[float], float]]

Interpolation schedule s(t) (default: linear s(t) = t/T)

None
Example

H_i = pauli_x() H_f = pauli_z() evo = AdiabaticEvolution(H_i, H_f, T=10.0, n_steps=100)

Source code in psiqit\dynamics\adiabatic.py
def __init__(
    self,
    H_initial: Operator,
    H_final: Operator,
    T: float,
    n_steps: int = 100,
    schedule: Optional[Callable[[float], float]] = None
):
    """
    Initialize adiabatic evolution

    Args:
        H_initial: Initial Hamiltonian (at t=0)
        H_final: Final Hamiltonian (at t=T)
        T: Total evolution time
        n_steps: Number of time steps
        schedule: Interpolation schedule s(t) (default: linear s(t) = t/T)

    Example:
        >>> H_i = pauli_x()
        >>> H_f = pauli_z()
        >>> evo = AdiabaticEvolution(H_i, H_f, T=10.0, n_steps=100)
    """
    if H_initial.dim != H_final.dim:
        raise ValueError(f"Hamiltonian dimensions mismatch: {H_initial.dim} vs {H_final.dim}")

    self.H_initial = H_initial
    self.H_final = H_final
    self.T = T
    self.n_steps = n_steps
    self.dim = H_initial.dim

    # Default linear schedule
    if schedule is None:
        self.schedule = lambda t: t / T
    else:
        self.schedule = schedule

    logger.info(f"AdiabaticEvolution initialized: dim={self.dim}, T={T:.3f}, steps={n_steps}")

evolve(psi0)

Perform adiabatic evolution

Parameters:

Name Type Description Default
psi0 Ket

Initial state (usually ground state of H_initial)

required

Returns:

Name Type Description
AdiabaticResult AdiabaticResult

Evolution results

Example

from psiqit.quantum import zero result = evo.evolve(zero()) print(result.final_energy)

Source code in psiqit\dynamics\adiabatic.py
def evolve(self, psi0: Ket) -> AdiabaticResult:
    """
    Perform adiabatic evolution

    Args:
        psi0: Initial state (usually ground state of H_initial)

    Returns:
        AdiabaticResult: Evolution results

    Example:
        >>> from psiqit.quantum import zero
        >>> result = evo.evolve(zero())
        >>> print(result.final_energy)
    """
    if psi0.dim != self.dim:
        raise ValueError(f"State dimension {psi0.dim} does not match Hamiltonian dimension {self.dim}")

    logger.info(f"Starting adiabatic evolution for T={self.T:.3f}")

    # Time points
    times = np.linspace(0, self.T, self.n_steps + 1)
    dt = times[1] - times[0]

    # Initialize
    psi = psi0.data.copy()
    states = [psi0.copy()]
    energies = []
    fidelities = []

    # Track instantaneous ground state
    H0 = self._hamiltonian(0)
    ground_state = self._get_ground_state(H0)
    ground_energy = self._get_ground_energy(H0)

    # Initial fidelity
    initial_fidelity = abs(np.vdot(ground_state.data, psi)) ** 2
    fidelities.append(initial_fidelity)
    energies.append(ground_energy)

    # Evolution
    success = True
    message = "Evolution completed successfully"

    try:
        # Use RK4 for integration (or the system solver)
        # For complex state vectors, we need to handle real and imaginary parts separately
        # We'll use a simple RK4 implementation for complex vectors

        for i in range(self.n_steps):
            t = times[i]

            # RK4 for complex vector
            k1 = self._schrodinger_derivative(t, psi)
            k2 = self._schrodinger_derivative(t + dt/2, psi + dt/2 * k1)
            k3 = self._schrodinger_derivative(t + dt/2, psi + dt/2 * k2)
            k4 = self._schrodinger_derivative(t + dt, psi + dt * k3)

            psi_new = psi + dt/6 * (k1 + 2*k2 + 2*k3 + k4)

            # Normalize
            norm = np.linalg.norm(psi_new)
            if norm > 0:
                psi_new = psi_new / norm
            else:
                raise ValueError("State norm became zero")

            psi = psi_new

            # Store state
            states.append(Ket(psi.copy()))

            # Compute energy and fidelity at this time
            H_t = self._hamiltonian(times[i+1])
            energy = self._get_ground_energy(H_t)
            ground_state_t = self._get_ground_state(H_t)
            fidelity = abs(np.vdot(ground_state_t.data, psi)) ** 2

            energies.append(energy)
            fidelities.append(fidelity)

            # Check if fidelity is dropping too fast (potential diabatic transition)
            if i > 0 and fidelity < 0.1 and fidelities[i] > 0.9:
                logger.warning(f"Sudden drop in fidelity at step {i}: {fidelities[i]:.3f} -> {fidelity:.3f}")

    except Exception as e:
        success = False
        message = f"Evolution failed: {str(e)}"
        logger.error(message)

    # Final results
    final_state = states[-1] if states else None
    final_energy = energies[-1] if energies else None

    logger.info(f"Adiabatic evolution completed: {message}")

    return AdiabaticResult(
        times=times,
        states=states,
        energies=energies,
        fidelities=fidelities,
        success=success,
        message=message,
        final_state=final_state,
        final_energy=final_energy
    )

get_min_gap(n_points=1000)

Estimate the minimum energy gap during evolution

Parameters:

Name Type Description Default
n_points int

Number of points to sample

1000

Returns:

Name Type Description
Tuple Tuple[float, float]

(min_gap, time_of_min_gap)

Example

evo = AdiabaticEvolution(H_i, H_f, T=10.0) min_gap, t_gap = evo.get_min_gap() print(f"Minimum gap: {min_gap:.6f} at t={t_gap:.3f}")

Source code in psiqit\dynamics\adiabatic.py
def get_min_gap(self, n_points: int = 1000) -> Tuple[float, float]:
    """
    Estimate the minimum energy gap during evolution

    Args:
        n_points: Number of points to sample

    Returns:
        Tuple: (min_gap, time_of_min_gap)

    Example:
        >>> evo = AdiabaticEvolution(H_i, H_f, T=10.0)
        >>> min_gap, t_gap = evo.get_min_gap()
        >>> print(f"Minimum gap: {min_gap:.6f} at t={t_gap:.3f}")
    """
    times = np.linspace(0, self.T, n_points)
    gaps = []

    for t in times:
        H = self._hamiltonian(t)
        eigvals = np.linalg.eigvalsh(H)
        gap = eigvals[1] - eigvals[0] if len(eigvals) > 1 else 0
        gaps.append(gap)

    min_gap = np.min(gaps)
    t_min_gap = times[np.argmin(gaps)]

    return float(min_gap), float(t_min_gap)

get_adiabatic_condition(n_points=100)

Check the adiabatic condition: |⟨1|dH/dt|0⟩| / (ΔE)² << 1

Parameters:

Name Type Description Default
n_points int

Number of points to sample

100

Returns:

Name Type Description
float float

Maximum violation of adiabatic condition

Source code in psiqit\dynamics\adiabatic.py
def get_adiabatic_condition(self, n_points: int = 100) -> float:
    """
    Check the adiabatic condition: |⟨1|dH/dt|0⟩| / (ΔE)² << 1

    Args:
        n_points: Number of points to sample

    Returns:
        float: Maximum violation of adiabatic condition
    """
    times = np.linspace(0, self.T, n_points)
    max_ratio = 0.0

    for t in times:
        H = self._hamiltonian(t)
        eigvals, eigvecs = np.linalg.eigh(H)

        if len(eigvals) < 2:
            continue

        E0, E1 = eigvals[0], eigvals[1]
        delta_E = E1 - E0

        if delta_E < 1e-10:
            continue

        # Compute dH/dt
        dt = 1e-6
        H_plus = self._hamiltonian(t + dt)
        H_minus = self._hamiltonian(t - dt)
        dH = (H_plus - H_minus) / (2 * dt)

        # Matrix element ⟨1|dH/dt|0⟩
        psi0 = eigvecs[:, 0]
        psi1 = eigvecs[:, 1]

        matrix_element = abs(np.vdot(psi1, dH @ psi0))
        ratio = matrix_element / (delta_E ** 2)

        max_ratio = max(max_ratio, ratio)

    return float(max_ratio)

QuantumAnnealing

Bases: AdiabaticEvolution

Quantum annealing algorithm

Quantum annealing is a special case of adiabatic evolution where the Hamiltonian is:

H(s) = (1-s) * H_transverse + s * H_problem

where H_transverse = -Σ σ_x^i (transverse field) and H_problem is the problem Hamiltonian (usually Ising model)

Example

Simple 2-qubit Ising problem

problem_hamiltonian = {'Z0Z1': 1.0, 'Z0': 0.5, 'Z1': -0.5} qa = QuantumAnnealing(problem_hamiltonian, T=10.0, n_steps=100) result = qa.run() print(result.final_energy)

Source code in psiqit\dynamics\adiabatic.py
class QuantumAnnealing(AdiabaticEvolution):
    """
    Quantum annealing algorithm

    Quantum annealing is a special case of adiabatic evolution where
    the Hamiltonian is:

    H(s) = (1-s) * H_transverse + s * H_problem

    where H_transverse = -Σ σ_x^i (transverse field)
    and H_problem is the problem Hamiltonian (usually Ising model)

    Example:
        >>> # Simple 2-qubit Ising problem
        >>> problem_hamiltonian = {'Z0Z1': 1.0, 'Z0': 0.5, 'Z1': -0.5}
        >>> qa = QuantumAnnealing(problem_hamiltonian, T=10.0, n_steps=100)
        >>> result = qa.run()
        >>> print(result.final_energy)
    """

    def __init__(
        self,
        problem_hamiltonian: Dict[str, float],
        T: float,
        transverse_field: float = 1.0,
        n_steps: int = 100,
        schedule: Optional[Callable[[float], float]] = None
    ):
        """
        Initialize quantum annealing

        Args:
            problem_hamiltonian: Problem Hamiltonian as Pauli strings
                                 {'Z0': 1.0, 'Z0Z1': 0.5, ...}
            T: Total annealing time
            transverse_field: Strength of transverse field
            n_steps: Number of time steps
            schedule: Annealing schedule (default: linear)

        Example:
            >>> # Ising problem: -Z0Z1 (anti-ferromagnetic)
            >>> problem = {'Z0Z1': -1.0}
            >>> qa = QuantumAnnealing(problem, T=5.0, n_steps=50)
        """
        # Build the problem Hamiltonian as an Operator
        H_problem = self._build_hamiltonian(problem_hamiltonian)

        # Build the transverse field Hamiltonian
        # H_transverse = -Σ σ_x^i
        n_qubits = self._get_n_qubits_from_hamiltonian(problem_hamiltonian)
        H_transverse = self._build_transverse_hamiltonian(n_qubits, transverse_field)

        # Initialize the parent class
        super().__init__(H_transverse, H_problem, T, n_steps, schedule)

        self.problem_hamiltonian = problem_hamiltonian
        self.transverse_field = transverse_field
        self.n_qubits = n_qubits

        logger.info(f"QuantumAnnealing initialized: {n_qubits} qubits, T={T:.3f}")

    def _get_n_qubits_from_hamiltonian(self, hamiltonian: Dict[str, float]) -> int:
        """
        Extract the number of qubits from the Hamiltonian dictionary

        Args:
            hamiltonian: Hamiltonian dictionary

        Returns:
            int: Number of qubits
        """
        max_qubit = 0

        for term in hamiltonian.keys():
            # Parse the Pauli string (e.g., 'Z0Z1' -> qubits 0, 1)
            # Each character is a Pauli operator, followed by a number
            import re
            qubits = re.findall(r'\d+', term)
            for q in qubits:
                max_qubit = max(max_qubit, int(q))

        return max_qubit + 1

    def _build_hamiltonian(self, hamiltonian: Dict[str, float]) -> Operator:
        """
        Build an Operator from a Hamiltonian dictionary

        Args:
            hamiltonian: Dictionary of Pauli strings and coefficients

        Returns:
            Operator: Hamiltonian operator
        """
        from ..quantum.operator import pauli_string

        dim = 2 ** self._get_n_qubits_from_hamiltonian(hamiltonian)
        H = np.zeros((dim, dim), dtype=complex)

        for term, coeff in hamiltonian.items():
            if term == 'I':
                # Identity term
                H += coeff * np.eye(dim, dtype=complex)
            else:
                # Pauli string
                P = pauli_string(term)
                H += coeff * P.data

        return Operator(H, name="H_problem")

    def _build_transverse_hamiltonian(self, n_qubits: int, field: float) -> Operator:
        """
        Build the transverse field Hamiltonian: -field * Σ σ_x^i

        Args:
            n_qubits: Number of qubits
            field: Transverse field strength

        Returns:
            Operator: Transverse field Hamiltonian
        """
        from ..quantum.operator import pauli_x, tensor_product

        dim = 2 ** n_qubits
        H = np.zeros((dim, dim), dtype=complex)

        for i in range(n_qubits):
            # Build σ_x^i
            X_i = np.eye(dim, dtype=complex)
            # Apply X on qubit i (simplified)
            # For each basis state, flip the i-th bit
            for j in range(dim):
                if (j >> i) & 1:
                    # Flip bit i
                    k = j ^ (1 << i)
                    X_i[k, j] = 1.0
                else:
                    k = j ^ (1 << i)
                    X_i[k, j] = 1.0

            H -= field * X_i

        return Operator(H, name="H_transverse")

    def run(
        self,
        initial_state: Optional[Ket] = None,
        return_all: bool = False
    ) -> AdiabaticResult:
        """
        Run the quantum annealing algorithm

        Args:
            initial_state: Initial state (default: ground state of transverse field)
            return_all: Return all states (for analysis)

        Returns:
            AdiabaticResult: Annealing results

        Example:
            >>> qa = QuantumAnnealing({'Z0Z1': -1.0}, T=5.0)
            >>> result = qa.run()
            >>> print(f"Final energy: {result.final_energy:.6f}")
            >>> print(f"Success: {result.success}")
        """
        # If no initial state is provided, use the ground state of H_transverse
        if initial_state is None:
            # Ground state of transverse field is |+⟩⊗n
            from ..quantum.state import plus
            state = plus()
            for _ in range(1, self.n_qubits):
                state = Ket(np.kron(state.data, plus().data))
            initial_state = state

        logger.info(f"Running quantum annealing for T={self.T:.3f}")

        # Perform adiabatic evolution
        result = super().evolve(initial_state)

        logger.info(f"Quantum annealing completed: final_energy={result.final_energy:.8f if result.final_energy else 'N/A'}")

        return result

    def get_final_state_probabilities(self, result: AdiabaticResult) -> Dict[str, float]:
        """
        Get the probabilities of the final state in the computational basis

        Args:
            result: Result from run()

        Returns:
            Dict: Basis state probabilities
        """
        if result.final_state is None:
            return {}

        probs = np.abs(result.final_state.data) ** 2

        # Create dictionary with binary labels
        labels = {}
        for i, p in enumerate(probs):
            binary = format(i, f'0{self.n_qubits}b')
            labels[binary] = float(p)

        return labels

    def get_ground_state_energy(self) -> float:
        """
        Get the ground state energy of the problem Hamiltonian

        Returns:
            float: Ground state energy
        """
        H = self._build_hamiltonian(self.problem_hamiltonian)
        eigvals = np.linalg.eigvalsh(H.data)
        return float(eigvals[0])

    def get_ground_state(self) -> Ket:
        """
        Get the ground state of the problem Hamiltonian

        Returns:
            Ket: Ground state
        """
        H = self._build_hamiltonian(self.problem_hamiltonian)
        eigvals, eigvecs = np.linalg.eigh(H.data)
        return Ket(eigvecs[:, 0])

__init__(problem_hamiltonian, T, transverse_field=1.0, n_steps=100, schedule=None)

Initialize quantum annealing

Parameters:

Name Type Description Default
problem_hamiltonian Dict[str, float]

Problem Hamiltonian as Pauli strings {'Z0': 1.0, 'Z0Z1': 0.5, ...}

required
T float

Total annealing time

required
transverse_field float

Strength of transverse field

1.0
n_steps int

Number of time steps

100
schedule Optional[Callable[[float], float]]

Annealing schedule (default: linear)

None
Example
Ising problem: -Z0Z1 (anti-ferromagnetic)

problem = {'Z0Z1': -1.0} qa = QuantumAnnealing(problem, T=5.0, n_steps=50)

Source code in psiqit\dynamics\adiabatic.py
def __init__(
    self,
    problem_hamiltonian: Dict[str, float],
    T: float,
    transverse_field: float = 1.0,
    n_steps: int = 100,
    schedule: Optional[Callable[[float], float]] = None
):
    """
    Initialize quantum annealing

    Args:
        problem_hamiltonian: Problem Hamiltonian as Pauli strings
                             {'Z0': 1.0, 'Z0Z1': 0.5, ...}
        T: Total annealing time
        transverse_field: Strength of transverse field
        n_steps: Number of time steps
        schedule: Annealing schedule (default: linear)

    Example:
        >>> # Ising problem: -Z0Z1 (anti-ferromagnetic)
        >>> problem = {'Z0Z1': -1.0}
        >>> qa = QuantumAnnealing(problem, T=5.0, n_steps=50)
    """
    # Build the problem Hamiltonian as an Operator
    H_problem = self._build_hamiltonian(problem_hamiltonian)

    # Build the transverse field Hamiltonian
    # H_transverse = -Σ σ_x^i
    n_qubits = self._get_n_qubits_from_hamiltonian(problem_hamiltonian)
    H_transverse = self._build_transverse_hamiltonian(n_qubits, transverse_field)

    # Initialize the parent class
    super().__init__(H_transverse, H_problem, T, n_steps, schedule)

    self.problem_hamiltonian = problem_hamiltonian
    self.transverse_field = transverse_field
    self.n_qubits = n_qubits

    logger.info(f"QuantumAnnealing initialized: {n_qubits} qubits, T={T:.3f}")

run(initial_state=None, return_all=False)

Run the quantum annealing algorithm

Parameters:

Name Type Description Default
initial_state Optional[Ket]

Initial state (default: ground state of transverse field)

None
return_all bool

Return all states (for analysis)

False

Returns:

Name Type Description
AdiabaticResult AdiabaticResult

Annealing results

Example

qa = QuantumAnnealing({'Z0Z1': -1.0}, T=5.0) result = qa.run() print(f"Final energy: {result.final_energy:.6f}") print(f"Success: {result.success}")

Source code in psiqit\dynamics\adiabatic.py
def run(
    self,
    initial_state: Optional[Ket] = None,
    return_all: bool = False
) -> AdiabaticResult:
    """
    Run the quantum annealing algorithm

    Args:
        initial_state: Initial state (default: ground state of transverse field)
        return_all: Return all states (for analysis)

    Returns:
        AdiabaticResult: Annealing results

    Example:
        >>> qa = QuantumAnnealing({'Z0Z1': -1.0}, T=5.0)
        >>> result = qa.run()
        >>> print(f"Final energy: {result.final_energy:.6f}")
        >>> print(f"Success: {result.success}")
    """
    # If no initial state is provided, use the ground state of H_transverse
    if initial_state is None:
        # Ground state of transverse field is |+⟩⊗n
        from ..quantum.state import plus
        state = plus()
        for _ in range(1, self.n_qubits):
            state = Ket(np.kron(state.data, plus().data))
        initial_state = state

    logger.info(f"Running quantum annealing for T={self.T:.3f}")

    # Perform adiabatic evolution
    result = super().evolve(initial_state)

    logger.info(f"Quantum annealing completed: final_energy={result.final_energy:.8f if result.final_energy else 'N/A'}")

    return result

get_final_state_probabilities(result)

Get the probabilities of the final state in the computational basis

Parameters:

Name Type Description Default
result AdiabaticResult

Result from run()

required

Returns:

Name Type Description
Dict Dict[str, float]

Basis state probabilities

Source code in psiqit\dynamics\adiabatic.py
def get_final_state_probabilities(self, result: AdiabaticResult) -> Dict[str, float]:
    """
    Get the probabilities of the final state in the computational basis

    Args:
        result: Result from run()

    Returns:
        Dict: Basis state probabilities
    """
    if result.final_state is None:
        return {}

    probs = np.abs(result.final_state.data) ** 2

    # Create dictionary with binary labels
    labels = {}
    for i, p in enumerate(probs):
        binary = format(i, f'0{self.n_qubits}b')
        labels[binary] = float(p)

    return labels

get_ground_state_energy()

Get the ground state energy of the problem Hamiltonian

Returns:

Name Type Description
float float

Ground state energy

Source code in psiqit\dynamics\adiabatic.py
def get_ground_state_energy(self) -> float:
    """
    Get the ground state energy of the problem Hamiltonian

    Returns:
        float: Ground state energy
    """
    H = self._build_hamiltonian(self.problem_hamiltonian)
    eigvals = np.linalg.eigvalsh(H.data)
    return float(eigvals[0])

get_ground_state()

Get the ground state of the problem Hamiltonian

Returns:

Name Type Description
Ket Ket

Ground state

Source code in psiqit\dynamics\adiabatic.py
def get_ground_state(self) -> Ket:
    """
    Get the ground state of the problem Hamiltonian

    Returns:
        Ket: Ground state
    """
    H = self._build_hamiltonian(self.problem_hamiltonian)
    eigvals, eigvecs = np.linalg.eigh(H.data)
    return Ket(eigvecs[:, 0])

HeisenbergResult dataclass

Result container for Heisenberg evolution

Attributes:

Name Type Description
times ndarray

Time points

operators List[Operator]

List of operators at each time

success bool

Whether evolution was successful

message str

Additional information

n_steps int

Number of time steps

initial_operator Optional[Operator]

Initial operator

final_operator Optional[Operator]

Final operator

expectation_values Optional[List[float]]

List of expectation values (if state provided)

Source code in psiqit\dynamics\heisenberg.py
@dataclass
class HeisenbergResult:
    """
    Result container for Heisenberg evolution

    Attributes:
        times: Time points
        operators: List of operators at each time
        success: Whether evolution was successful
        message: Additional information
        n_steps: Number of time steps
        initial_operator: Initial operator
        final_operator: Final operator
        expectation_values: List of expectation values (if state provided)
    """
    times: np.ndarray
    operators: List[Operator]
    success: bool = True
    message: str = ""
    n_steps: int = 0
    initial_operator: Optional[Operator] = None
    final_operator: Optional[Operator] = None
    expectation_values: Optional[List[float]] = None

    def __post_init__(self):
        """Post-process the result"""
        self.n_steps = len(self.times)

        if self.operators:
            self.initial_operator = self.operators[0]
            self.final_operator = self.operators[-1]

    def get_operator_at_time(self, index: int) -> Optional[Operator]:
        """Get operator at a specific time index"""
        if 0 <= index < len(self.operators):
            return self.operators[index]
        return None

    def get_final_operator(self) -> Optional[Operator]:
        """Get the final operator"""
        return self.final_operator

    def get_expectation_history(self) -> Optional[np.ndarray]:
        """Get the expectation value history"""
        if self.expectation_values is not None:
            return np.array(self.expectation_values)
        return None

    def __repr__(self) -> str:
        status = "Success" if self.success else "Failed"
        return f"HeisenbergResult(steps={self.n_steps}, status={status})"

    def __str__(self) -> str:
        lines = [
            "Heisenberg Evolution Results:",
            f"  Steps: {self.n_steps}",
            f"  Success: {self.success}",
            f"  Message: {self.message}",
        ]
        if self.final_operator:
            lines.append(f"  Final Operator: {self.final_operator.name}")
        return "\n".join(lines)

__post_init__()

Post-process the result

Source code in psiqit\dynamics\heisenberg.py
def __post_init__(self):
    """Post-process the result"""
    self.n_steps = len(self.times)

    if self.operators:
        self.initial_operator = self.operators[0]
        self.final_operator = self.operators[-1]

get_operator_at_time(index)

Get operator at a specific time index

Source code in psiqit\dynamics\heisenberg.py
def get_operator_at_time(self, index: int) -> Optional[Operator]:
    """Get operator at a specific time index"""
    if 0 <= index < len(self.operators):
        return self.operators[index]
    return None

get_final_operator()

Get the final operator

Source code in psiqit\dynamics\heisenberg.py
def get_final_operator(self) -> Optional[Operator]:
    """Get the final operator"""
    return self.final_operator

get_expectation_history()

Get the expectation value history

Source code in psiqit\dynamics\heisenberg.py
def get_expectation_history(self) -> Optional[np.ndarray]:
    """Get the expectation value history"""
    if self.expectation_values is not None:
        return np.array(self.expectation_values)
    return None

HeisenbergEvolution

Heisenberg picture evolution of operators

In the Heisenberg picture, operators evolve in time while states remain constant. The evolution of an operator A is given by:

A(t) = e^{iHt/ħ} A(0) e^{-iHt/ħ}

Example

from psiqit.quantum import pauli_x, pauli_z H = pauli_z() # Hamiltonian evo = HeisenbergEvolution(H) X_t = evo.evolve_operator(pauli_x(), t=1.0) print(X_t) # Rotated operator

Source code in psiqit\dynamics\heisenberg.py
class HeisenbergEvolution:
    """
    Heisenberg picture evolution of operators

    In the Heisenberg picture, operators evolve in time while states
    remain constant. The evolution of an operator A is given by:

    A(t) = e^{iHt/ħ} A(0) e^{-iHt/ħ}

    Example:
        >>> from psiqit.quantum import pauli_x, pauli_z
        >>> H = pauli_z()  # Hamiltonian
        >>> evo = HeisenbergEvolution(H)
        >>> X_t = evo.evolve_operator(pauli_x(), t=1.0)
        >>> print(X_t)  # Rotated operator
    """

    def __init__(self, hamiltonian: Operator, hbar: float = 1.0):
        """
        Initialize Heisenberg evolution

        Args:
            hamiltonian: Hamiltonian operator (Hermitian)
            hbar: Reduced Planck constant (default: 1)

        Example:
            >>> from psiqit.quantum import pauli_z
            >>> H = pauli_z()
            >>> evo = HeisenbergEvolution(H)
        """
        if not hamiltonian.is_hermitian:
            logger.warning("Hamiltonian is not Hermitian")

        self.hamiltonian = hamiltonian
        self.hbar = hbar
        self.dim = hamiltonian.dim

        logger.info(f"HeisenbergEvolution initialized: dim={self.dim}, hbar={hbar}")

    def evolve_operator(
        self,
        A: Operator,
        t: float,
        method: str = 'series',
        order: int = 5,
        n_steps: int = 100
    ) -> Operator:
        """
        Evolve an operator in the Heisenberg picture

        A(t) = e^{iHt/ħ} A(0) e^{-iHt/ħ}

        Args:
            A: Operator to evolve
            t: Evolution time
            method: 'series', 'exact', or 'trotter'
            order: Order for series expansion
            n_steps: Number of steps for Trotter method

        Returns:
            Operator: Evolved operator

        Example:
            >>> X = pauli_x()
            >>> X_t = evo.evolve_operator(X, t=np.pi/2)
            >>> print(X_t)  # Rotated operator
        """
        if A.dim != self.dim:
            raise ValueError(f"Operator dimension {A.dim} does not match Hamiltonian dimension {self.dim}")

        logger.debug(f"Evolving operator {A.name} for t={t:.3f} using {method}")

        if method == 'exact':
            # Exact evolution using matrix exponential
            H = self.hamiltonian.data
            U = expm(Operator(-1j * t * H / self.hbar))
            U_dag = U.dagger()

            # A(t) = U† A U
            A_evolved = U_dag @ A @ U
            A_evolved.name = f"{A.name}(t={t:.2f})"

            return A_evolved

        elif method == 'series':
            # Series expansion: A(t) = A + it/ħ [H, A] - t²/(2ħ²) [H, [H, A]] + ...
            A_t = Operator(A.data.copy(), name=A.name)

            # Compute terms iteratively
            term = A.data.copy()
            factor = 1.0

            for n in range(1, order + 1):
                # [H, term]
                term = commutator(Operator(H), Operator(term)).data
                factor *= (1j * t / self.hbar) / n

                A_t = A_t + Operator(factor * term)

            A_t.name = f"{A.name}(t={t:.2f})"

            return A_t

        elif method == 'trotter':
            # Trotter-Suzuki approximation
            # For small dt, evolve step by step
            dt = t / n_steps

            A_t = Operator(A.data.copy(), name=A.name)
            H = self.hamiltonian.data

            for _ in range(n_steps):
                # A(t+dt) = U†(dt) A(t) U(dt)
                # with U(dt) = exp(-iH dt/ħ)
                U = expm(Operator(-1j * H * dt / self.hbar))
                U_dag = U.dagger()
                A_t = U_dag @ A_t @ U

            A_t.name = f"{A.name}(t={t:.2f})"

            return A_t

        else:
            raise ValueError(f"Unknown method: {method}. Use 'exact', 'series', or 'trotter'")

    def evolve_operator_sequence(
        self,
        A: Operator,
        times: np.ndarray,
        method: str = 'exact',
        **kwargs
    ) -> HeisenbergResult:
        """
        Evolve an operator at multiple time points

        Args:
            A: Operator to evolve
            times: Array of time points
            method: Evolution method
            **kwargs: Additional arguments for evolve_operator

        Returns:
            HeisenbergResult: Evolution results

        Example:
            >>> times = np.linspace(0, 2*np.pi, 50)
            >>> result = evo.evolve_operator_sequence(pauli_x(), times)
            >>> print(len(result.operators))  # 50
        """
        logger.info(f"Evolving operator sequence for {len(times)} time points")

        operators = []
        success = True
        message = "Evolution completed successfully"

        try:
            for t in times:
                A_t = self.evolve_operator(A, t, method=method, **kwargs)
                operators.append(A_t)

        except Exception as e:
            success = False
            message = f"Evolution failed: {str(e)}"
            logger.error(message)

        return HeisenbergResult(
            times=times,
            operators=operators,
            success=success,
            message=message
        )

    def compute_expectation(
        self,
        A: Operator,
        state: Ket,
        t: float,
        method: str = 'exact',
        **kwargs
    ) -> float:
        """
        Compute expectation value ⟨ψ|A(t)|ψ⟩

        Args:
            A: Operator to evolve
            state: Quantum state
            t: Evolution time
            method: Evolution method
            **kwargs: Additional arguments for evolve_operator

        Returns:
            float: Expectation value

        Example:
            >>> from psiqit.quantum import zero
            >>> state = zero()
            >>> exp = evo.compute_expectation(pauli_x(), state, t=np.pi/2)
            >>> print(exp)
        """
        A_t = self.evolve_operator(A, t, method=method, **kwargs)
        expectation = np.vdot(state.data, A_t.data @ state.data).real
        return float(expectation)

    def compute_expectation_sequence(
        self,
        A: Operator,
        state: Ket,
        times: np.ndarray,
        method: str = 'exact',
        **kwargs
    ) -> Tuple[np.ndarray, List[float]]:
        """
        Compute expectation values at multiple time points

        Args:
            A: Operator
            state: Quantum state
            times: Array of time points
            method: Evolution method
            **kwargs: Additional arguments for evolve_operator

        Returns:
            Tuple: (times, expectation_values)

        Example:
            >>> times = np.linspace(0, 2*np.pi, 50)
            >>> result = evo.compute_expectation_sequence(pauli_x(), zero(), times)
            >>> print(result[1][:5])  # First 5 expectation values
        """
        logger.info(f"Computing expectation sequence for {len(times)} time points")

        expectations = []

        for t in times:
            exp = self.compute_expectation(A, state, t, method=method, **kwargs)
            expectations.append(exp)

        return times, expectations

__init__(hamiltonian, hbar=1.0)

Initialize Heisenberg evolution

Parameters:

Name Type Description Default
hamiltonian Operator

Hamiltonian operator (Hermitian)

required
hbar float

Reduced Planck constant (default: 1)

1.0
Example

from psiqit.quantum import pauli_z H = pauli_z() evo = HeisenbergEvolution(H)

Source code in psiqit\dynamics\heisenberg.py
def __init__(self, hamiltonian: Operator, hbar: float = 1.0):
    """
    Initialize Heisenberg evolution

    Args:
        hamiltonian: Hamiltonian operator (Hermitian)
        hbar: Reduced Planck constant (default: 1)

    Example:
        >>> from psiqit.quantum import pauli_z
        >>> H = pauli_z()
        >>> evo = HeisenbergEvolution(H)
    """
    if not hamiltonian.is_hermitian:
        logger.warning("Hamiltonian is not Hermitian")

    self.hamiltonian = hamiltonian
    self.hbar = hbar
    self.dim = hamiltonian.dim

    logger.info(f"HeisenbergEvolution initialized: dim={self.dim}, hbar={hbar}")

evolve_operator(A, t, method='series', order=5, n_steps=100)

Evolve an operator in the Heisenberg picture

A(t) = e^{iHt/ħ} A(0) e^{-iHt/ħ}

Parameters:

Name Type Description Default
A Operator

Operator to evolve

required
t float

Evolution time

required
method str

'series', 'exact', or 'trotter'

'series'
order int

Order for series expansion

5
n_steps int

Number of steps for Trotter method

100

Returns:

Name Type Description
Operator Operator

Evolved operator

Example

X = pauli_x() X_t = evo.evolve_operator(X, t=np.pi/2) print(X_t) # Rotated operator

Source code in psiqit\dynamics\heisenberg.py
def evolve_operator(
    self,
    A: Operator,
    t: float,
    method: str = 'series',
    order: int = 5,
    n_steps: int = 100
) -> Operator:
    """
    Evolve an operator in the Heisenberg picture

    A(t) = e^{iHt/ħ} A(0) e^{-iHt/ħ}

    Args:
        A: Operator to evolve
        t: Evolution time
        method: 'series', 'exact', or 'trotter'
        order: Order for series expansion
        n_steps: Number of steps for Trotter method

    Returns:
        Operator: Evolved operator

    Example:
        >>> X = pauli_x()
        >>> X_t = evo.evolve_operator(X, t=np.pi/2)
        >>> print(X_t)  # Rotated operator
    """
    if A.dim != self.dim:
        raise ValueError(f"Operator dimension {A.dim} does not match Hamiltonian dimension {self.dim}")

    logger.debug(f"Evolving operator {A.name} for t={t:.3f} using {method}")

    if method == 'exact':
        # Exact evolution using matrix exponential
        H = self.hamiltonian.data
        U = expm(Operator(-1j * t * H / self.hbar))
        U_dag = U.dagger()

        # A(t) = U† A U
        A_evolved = U_dag @ A @ U
        A_evolved.name = f"{A.name}(t={t:.2f})"

        return A_evolved

    elif method == 'series':
        # Series expansion: A(t) = A + it/ħ [H, A] - t²/(2ħ²) [H, [H, A]] + ...
        A_t = Operator(A.data.copy(), name=A.name)

        # Compute terms iteratively
        term = A.data.copy()
        factor = 1.0

        for n in range(1, order + 1):
            # [H, term]
            term = commutator(Operator(H), Operator(term)).data
            factor *= (1j * t / self.hbar) / n

            A_t = A_t + Operator(factor * term)

        A_t.name = f"{A.name}(t={t:.2f})"

        return A_t

    elif method == 'trotter':
        # Trotter-Suzuki approximation
        # For small dt, evolve step by step
        dt = t / n_steps

        A_t = Operator(A.data.copy(), name=A.name)
        H = self.hamiltonian.data

        for _ in range(n_steps):
            # A(t+dt) = U†(dt) A(t) U(dt)
            # with U(dt) = exp(-iH dt/ħ)
            U = expm(Operator(-1j * H * dt / self.hbar))
            U_dag = U.dagger()
            A_t = U_dag @ A_t @ U

        A_t.name = f"{A.name}(t={t:.2f})"

        return A_t

    else:
        raise ValueError(f"Unknown method: {method}. Use 'exact', 'series', or 'trotter'")

evolve_operator_sequence(A, times, method='exact', **kwargs)

Evolve an operator at multiple time points

Parameters:

Name Type Description Default
A Operator

Operator to evolve

required
times ndarray

Array of time points

required
method str

Evolution method

'exact'
**kwargs

Additional arguments for evolve_operator

{}

Returns:

Name Type Description
HeisenbergResult HeisenbergResult

Evolution results

Example

times = np.linspace(0, 2*np.pi, 50) result = evo.evolve_operator_sequence(pauli_x(), times) print(len(result.operators)) # 50

Source code in psiqit\dynamics\heisenberg.py
def evolve_operator_sequence(
    self,
    A: Operator,
    times: np.ndarray,
    method: str = 'exact',
    **kwargs
) -> HeisenbergResult:
    """
    Evolve an operator at multiple time points

    Args:
        A: Operator to evolve
        times: Array of time points
        method: Evolution method
        **kwargs: Additional arguments for evolve_operator

    Returns:
        HeisenbergResult: Evolution results

    Example:
        >>> times = np.linspace(0, 2*np.pi, 50)
        >>> result = evo.evolve_operator_sequence(pauli_x(), times)
        >>> print(len(result.operators))  # 50
    """
    logger.info(f"Evolving operator sequence for {len(times)} time points")

    operators = []
    success = True
    message = "Evolution completed successfully"

    try:
        for t in times:
            A_t = self.evolve_operator(A, t, method=method, **kwargs)
            operators.append(A_t)

    except Exception as e:
        success = False
        message = f"Evolution failed: {str(e)}"
        logger.error(message)

    return HeisenbergResult(
        times=times,
        operators=operators,
        success=success,
        message=message
    )

compute_expectation(A, state, t, method='exact', **kwargs)

Compute expectation value ⟨ψ|A(t)|ψ⟩

Parameters:

Name Type Description Default
A Operator

Operator to evolve

required
state Ket

Quantum state

required
t float

Evolution time

required
method str

Evolution method

'exact'
**kwargs

Additional arguments for evolve_operator

{}

Returns:

Name Type Description
float float

Expectation value

Example

from psiqit.quantum import zero state = zero() exp = evo.compute_expectation(pauli_x(), state, t=np.pi/2) print(exp)

Source code in psiqit\dynamics\heisenberg.py
def compute_expectation(
    self,
    A: Operator,
    state: Ket,
    t: float,
    method: str = 'exact',
    **kwargs
) -> float:
    """
    Compute expectation value ⟨ψ|A(t)|ψ⟩

    Args:
        A: Operator to evolve
        state: Quantum state
        t: Evolution time
        method: Evolution method
        **kwargs: Additional arguments for evolve_operator

    Returns:
        float: Expectation value

    Example:
        >>> from psiqit.quantum import zero
        >>> state = zero()
        >>> exp = evo.compute_expectation(pauli_x(), state, t=np.pi/2)
        >>> print(exp)
    """
    A_t = self.evolve_operator(A, t, method=method, **kwargs)
    expectation = np.vdot(state.data, A_t.data @ state.data).real
    return float(expectation)

compute_expectation_sequence(A, state, times, method='exact', **kwargs)

Compute expectation values at multiple time points

Parameters:

Name Type Description Default
A Operator

Operator

required
state Ket

Quantum state

required
times ndarray

Array of time points

required
method str

Evolution method

'exact'
**kwargs

Additional arguments for evolve_operator

{}

Returns:

Name Type Description
Tuple Tuple[ndarray, List[float]]

(times, expectation_values)

Example

times = np.linspace(0, 2*np.pi, 50) result = evo.compute_expectation_sequence(pauli_x(), zero(), times) print(result[1][:5]) # First 5 expectation values

Source code in psiqit\dynamics\heisenberg.py
def compute_expectation_sequence(
    self,
    A: Operator,
    state: Ket,
    times: np.ndarray,
    method: str = 'exact',
    **kwargs
) -> Tuple[np.ndarray, List[float]]:
    """
    Compute expectation values at multiple time points

    Args:
        A: Operator
        state: Quantum state
        times: Array of time points
        method: Evolution method
        **kwargs: Additional arguments for evolve_operator

    Returns:
        Tuple: (times, expectation_values)

    Example:
        >>> times = np.linspace(0, 2*np.pi, 50)
        >>> result = evo.compute_expectation_sequence(pauli_x(), zero(), times)
        >>> print(result[1][:5])  # First 5 expectation values
    """
    logger.info(f"Computing expectation sequence for {len(times)} time points")

    expectations = []

    for t in times:
        exp = self.compute_expectation(A, state, t, method=method, **kwargs)
        expectations.append(exp)

    return times, expectations

HeisenbergEquation

Heisenberg equation of motion

dA/dt = (i/ħ) [H, A] + (∂A/∂t)

For time-independent operators: dA/dt = (i/ħ) [H, A]

Example

from psiqit.quantum import pauli_x, pauli_z H = pauli_z() eq = HeisenbergEquation(H) dXdt = eq.equation_of_motion(pauli_x()) print(dXdt) # -i/ħ [Z, X] = -2/ħ Y

Source code in psiqit\dynamics\heisenberg.py
class HeisenbergEquation:
    """
    Heisenberg equation of motion

    dA/dt = (i/ħ) [H, A] + (∂A/∂t)

    For time-independent operators:
    dA/dt = (i/ħ) [H, A]

    Example:
        >>> from psiqit.quantum import pauli_x, pauli_z
        >>> H = pauli_z()
        >>> eq = HeisenbergEquation(H)
        >>> dXdt = eq.equation_of_motion(pauli_x())
        >>> print(dXdt)  # -i/ħ [Z, X] = -2/ħ Y
    """

    def __init__(self, hamiltonian: Operator, hbar: float = 1.0):
        """
        Initialize Heisenberg equation

        Args:
            hamiltonian: Hamiltonian operator
            hbar: Reduced Planck constant

        Example:
            >>> from psiqit.quantum import pauli_z
            >>> H = pauli_z()
            >>> eq = HeisenbergEquation(H)
        """
        if not hamiltonian.is_hermitian:
            logger.warning("Hamiltonian is not Hermitian")

        self.hamiltonian = hamiltonian
        self.hbar = hbar
        self.dim = hamiltonian.dim

        logger.info(f"HeisenbergEquation initialized: dim={self.dim}")

    def equation_of_motion(self, A: Operator) -> Operator:
        """
        Compute the Heisenberg equation of motion for an operator

        dA/dt = (i/ħ) [H, A]

        Args:
            A: Operator

        Returns:
            Operator: Time derivative of the operator

        Example:
            >>> X = pauli_x()
            >>> dXdt = eq.equation_of_motion(X)
            >>> print(dXdt)  # (i/ħ)[H, X]
        """
        if A.dim != self.dim:
            raise ValueError(f"Operator dimension {A.dim} does not match Hamiltonian dimension {self.dim}")

        # dA/dt = (i/ħ) [H, A]
        H = self.hamiltonian
        commutator_HA = H.commutator(A)
        dA_dt = (1j / self.hbar) * commutator_HA

        # Set name
        dA_dt.name = f"d{A.name}/dt" if A.name else "dA/dt"

        logger.debug(f"Equation of motion computed for {A.name}")
        return dA_dt

    def equation_of_motion_explicit(self, A: Operator) -> Operator:
        """
        Compute the explicit form of the equation of motion

        Same as equation_of_motion, but with expanded form

        Args:
            A: Operator

        Returns:
            Operator: Time derivative of the operator
        """
        return self.equation_of_motion(A)

    def get_time_evolution_operator(self, t: float) -> Operator:
        """
        Get the time evolution operator U(t) = e^{-iHt/ħ}

        Args:
            t: Time

        Returns:
            Operator: Time evolution operator
        """
        H = self.hamiltonian
        U = Operator(np.linalg.expm(-1j * H.data * t / self.hbar))
        U.name = f"U(t={t:.2f})"
        return U

    def evolve_operator_infinitesimal(
        self,
        A: Operator,
        dt: float
    ) -> Operator:
        """
        Evolve an operator by an infinitesimal time step

        A(t+dt) ≈ A(t) + (dA/dt) * dt

        Args:
            A: Operator
            dt: Time step

        Returns:
            Operator: Evolved operator
        """
        dA_dt = self.equation_of_motion(A)
        A_evolved = A + dt * dA_dt
        A_evolved.name = f"{A.name}(dt={dt:.3f})" if A.name else "A(t+dt)"
        return A_evolved

    def get_conserved_quantities(self, operators: List[Operator]) -> List[bool]:
        """
        Check which operators commute with the Hamiltonian

        Args:
            operators: List of operators

        Returns:
            List[bool]: True if operator commutes with Hamiltonian

        Example:
            >>> from psiqit.quantum import pauli_x, pauli_z, identity
            >>> H = pauli_z()
            >>> eq = HeisenbergEquation(H)
            >>> conserved = eq.get_conserved_quantities([pauli_x(), pauli_z(), identity()])
            >>> print(conserved)  # [False, True, True]
        """
        results = []

        for A in operators:
            commutator_HA = self.hamiltonian.commutator(A)
            is_conserved = np.allclose(commutator_HA.data, 0)
            results.append(is_conserved)

            if is_conserved:
                logger.debug(f"{A.name} is conserved")
            else:
                logger.debug(f"{A.name} is not conserved")

        return results

__init__(hamiltonian, hbar=1.0)

Initialize Heisenberg equation

Parameters:

Name Type Description Default
hamiltonian Operator

Hamiltonian operator

required
hbar float

Reduced Planck constant

1.0
Example

from psiqit.quantum import pauli_z H = pauli_z() eq = HeisenbergEquation(H)

Source code in psiqit\dynamics\heisenberg.py
def __init__(self, hamiltonian: Operator, hbar: float = 1.0):
    """
    Initialize Heisenberg equation

    Args:
        hamiltonian: Hamiltonian operator
        hbar: Reduced Planck constant

    Example:
        >>> from psiqit.quantum import pauli_z
        >>> H = pauli_z()
        >>> eq = HeisenbergEquation(H)
    """
    if not hamiltonian.is_hermitian:
        logger.warning("Hamiltonian is not Hermitian")

    self.hamiltonian = hamiltonian
    self.hbar = hbar
    self.dim = hamiltonian.dim

    logger.info(f"HeisenbergEquation initialized: dim={self.dim}")

equation_of_motion(A)

Compute the Heisenberg equation of motion for an operator

dA/dt = (i/ħ) [H, A]

Parameters:

Name Type Description Default
A Operator

Operator

required

Returns:

Name Type Description
Operator Operator

Time derivative of the operator

Example

X = pauli_x() dXdt = eq.equation_of_motion(X) print(dXdt) # (i/ħ)[H, X]

Source code in psiqit\dynamics\heisenberg.py
def equation_of_motion(self, A: Operator) -> Operator:
    """
    Compute the Heisenberg equation of motion for an operator

    dA/dt = (i/ħ) [H, A]

    Args:
        A: Operator

    Returns:
        Operator: Time derivative of the operator

    Example:
        >>> X = pauli_x()
        >>> dXdt = eq.equation_of_motion(X)
        >>> print(dXdt)  # (i/ħ)[H, X]
    """
    if A.dim != self.dim:
        raise ValueError(f"Operator dimension {A.dim} does not match Hamiltonian dimension {self.dim}")

    # dA/dt = (i/ħ) [H, A]
    H = self.hamiltonian
    commutator_HA = H.commutator(A)
    dA_dt = (1j / self.hbar) * commutator_HA

    # Set name
    dA_dt.name = f"d{A.name}/dt" if A.name else "dA/dt"

    logger.debug(f"Equation of motion computed for {A.name}")
    return dA_dt

equation_of_motion_explicit(A)

Compute the explicit form of the equation of motion

Same as equation_of_motion, but with expanded form

Parameters:

Name Type Description Default
A Operator

Operator

required

Returns:

Name Type Description
Operator Operator

Time derivative of the operator

Source code in psiqit\dynamics\heisenberg.py
def equation_of_motion_explicit(self, A: Operator) -> Operator:
    """
    Compute the explicit form of the equation of motion

    Same as equation_of_motion, but with expanded form

    Args:
        A: Operator

    Returns:
        Operator: Time derivative of the operator
    """
    return self.equation_of_motion(A)

get_time_evolution_operator(t)

Get the time evolution operator U(t) = e^{-iHt/ħ}

Parameters:

Name Type Description Default
t float

Time

required

Returns:

Name Type Description
Operator Operator

Time evolution operator

Source code in psiqit\dynamics\heisenberg.py
def get_time_evolution_operator(self, t: float) -> Operator:
    """
    Get the time evolution operator U(t) = e^{-iHt/ħ}

    Args:
        t: Time

    Returns:
        Operator: Time evolution operator
    """
    H = self.hamiltonian
    U = Operator(np.linalg.expm(-1j * H.data * t / self.hbar))
    U.name = f"U(t={t:.2f})"
    return U

evolve_operator_infinitesimal(A, dt)

Evolve an operator by an infinitesimal time step

A(t+dt) ≈ A(t) + (dA/dt) * dt

Parameters:

Name Type Description Default
A Operator

Operator

required
dt float

Time step

required

Returns:

Name Type Description
Operator Operator

Evolved operator

Source code in psiqit\dynamics\heisenberg.py
def evolve_operator_infinitesimal(
    self,
    A: Operator,
    dt: float
) -> Operator:
    """
    Evolve an operator by an infinitesimal time step

    A(t+dt) ≈ A(t) + (dA/dt) * dt

    Args:
        A: Operator
        dt: Time step

    Returns:
        Operator: Evolved operator
    """
    dA_dt = self.equation_of_motion(A)
    A_evolved = A + dt * dA_dt
    A_evolved.name = f"{A.name}(dt={dt:.3f})" if A.name else "A(t+dt)"
    return A_evolved

get_conserved_quantities(operators)

Check which operators commute with the Hamiltonian

Parameters:

Name Type Description Default
operators List[Operator]

List of operators

required

Returns:

Type Description
List[bool]

List[bool]: True if operator commutes with Hamiltonian

Example

from psiqit.quantum import pauli_x, pauli_z, identity H = pauli_z() eq = HeisenbergEquation(H) conserved = eq.get_conserved_quantities([pauli_x(), pauli_z(), identity()]) print(conserved) # [False, True, True]

Source code in psiqit\dynamics\heisenberg.py
def get_conserved_quantities(self, operators: List[Operator]) -> List[bool]:
    """
    Check which operators commute with the Hamiltonian

    Args:
        operators: List of operators

    Returns:
        List[bool]: True if operator commutes with Hamiltonian

    Example:
        >>> from psiqit.quantum import pauli_x, pauli_z, identity
        >>> H = pauli_z()
        >>> eq = HeisenbergEquation(H)
        >>> conserved = eq.get_conserved_quantities([pauli_x(), pauli_z(), identity()])
        >>> print(conserved)  # [False, True, True]
    """
    results = []

    for A in operators:
        commutator_HA = self.hamiltonian.commutator(A)
        is_conserved = np.allclose(commutator_HA.data, 0)
        results.append(is_conserved)

        if is_conserved:
            logger.debug(f"{A.name} is conserved")
        else:
            logger.debug(f"{A.name} is not conserved")

    return results

InteractionResult dataclass

Result container for interaction picture evolution

Attributes:

Name Type Description
times ndarray

Time points

states List[Ket]

List of quantum states at each time

success bool

Whether evolution was successful

message str

Additional information

n_steps int

Number of time steps

final_state Optional[Ket]

Final state

initial_state Optional[Ket]

Initial state

Source code in psiqit\dynamics\interaction.py
@dataclass
class InteractionResult:
    """
    Result container for interaction picture evolution

    Attributes:
        times: Time points
        states: List of quantum states at each time
        success: Whether evolution was successful
        message: Additional information
        n_steps: Number of time steps
        final_state: Final state
        initial_state: Initial state
    """
    times: np.ndarray
    states: List[Ket]
    success: bool = True
    message: str = ""
    n_steps: int = 0
    initial_state: Optional[Ket] = None
    final_state: Optional[Ket] = None

    def __post_init__(self):
        """Post-process the result"""
        self.n_steps = len(self.times)

        if self.states:
            self.initial_state = self.states[0]
            self.final_state = self.states[-1]

    def get_state_at_time(self, index: int) -> Optional[Ket]:
        """Get state at a specific time index"""
        if 0 <= index < len(self.states):
            return self.states[index]
        return None

    def get_final_state(self) -> Optional[Ket]:
        """Get the final state"""
        return self.final_state

    def get_fidelity_with_initial(self) -> List[float]:
        """
        Get fidelity of each state with the initial state

        Returns:
            List[float]: Fidelity values
        """
        if not self.states or self.initial_state is None:
            return []

        fidelities = []
        for state in self.states:
            fid = abs(np.vdot(self.initial_state.data, state.data)) ** 2
            fidelities.append(float(fid))

        return fidelities

    def __repr__(self) -> str:
        status = "Success" if self.success else "Failed"
        return f"InteractionResult(steps={self.n_steps}, status={status})"

    def __str__(self) -> str:
        lines = [
            "Interaction Picture Evolution Results:",
            f"  Steps: {self.n_steps}",
            f"  Success: {self.success}",
            f"  Message: {self.message}",
        ]
        if self.final_state:
            lines.append(f"  Final State: {self.final_state}")
        return "\n".join(lines)

__post_init__()

Post-process the result

Source code in psiqit\dynamics\interaction.py
def __post_init__(self):
    """Post-process the result"""
    self.n_steps = len(self.times)

    if self.states:
        self.initial_state = self.states[0]
        self.final_state = self.states[-1]

get_state_at_time(index)

Get state at a specific time index

Source code in psiqit\dynamics\interaction.py
def get_state_at_time(self, index: int) -> Optional[Ket]:
    """Get state at a specific time index"""
    if 0 <= index < len(self.states):
        return self.states[index]
    return None

get_final_state()

Get the final state

Source code in psiqit\dynamics\interaction.py
def get_final_state(self) -> Optional[Ket]:
    """Get the final state"""
    return self.final_state

get_fidelity_with_initial()

Get fidelity of each state with the initial state

Returns:

Type Description
List[float]

List[float]: Fidelity values

Source code in psiqit\dynamics\interaction.py
def get_fidelity_with_initial(self) -> List[float]:
    """
    Get fidelity of each state with the initial state

    Returns:
        List[float]: Fidelity values
    """
    if not self.states or self.initial_state is None:
        return []

    fidelities = []
    for state in self.states:
        fid = abs(np.vdot(self.initial_state.data, state.data)) ** 2
        fidelities.append(float(fid))

    return fidelities

InteractionPicture

Interaction picture dynamics

In the interaction picture, the Hamiltonian is split into: H = H₀ + V

where H₀ is the free (solvable) part and V is the interaction. The evolution is governed by the interaction Hamiltonian:

V_I(t) = e^{iH₀t/ħ} V e^{-iH₀t/ħ}

States evolve as: |ψ_I(t)⟩ = U_I(t) |ψ_I(0)⟩

where U_I(t) = T exp(-i/ħ ∫₀ᵗ V_I(t') dt')

Example

from psiqit.quantum import pauli_z, pauli_x H0 = pauli_z() # Free Hamiltonian V = pauli_x() # Interaction ip = InteractionPicture(H0, V) psi_t = ip.evolve_state(zero(), t=1.0)

Source code in psiqit\dynamics\interaction.py
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
class InteractionPicture:
    """
    Interaction picture dynamics

    In the interaction picture, the Hamiltonian is split into:
    H = H₀ + V

    where H₀ is the free (solvable) part and V is the interaction.
    The evolution is governed by the interaction Hamiltonian:

    V_I(t) = e^{iH₀t/ħ} V e^{-iH₀t/ħ}

    States evolve as:
    |ψ_I(t)⟩ = U_I(t) |ψ_I(0)⟩

    where U_I(t) = T exp(-i/ħ ∫₀ᵗ V_I(t') dt')

    Example:
        >>> from psiqit.quantum import pauli_z, pauli_x
        >>> H0 = pauli_z()  # Free Hamiltonian
        >>> V = pauli_x()   # Interaction
        >>> ip = InteractionPicture(H0, V)
        >>> psi_t = ip.evolve_state(zero(), t=1.0)
    """

    def __init__(self, H0: Operator, V: Operator, hbar: float = 1.0):
        """
        Initialize interaction picture

        Args:
            H0: Free Hamiltonian (solvable part)
            V: Interaction Hamiltonian
            hbar: Reduced Planck constant

        Example:
            >>> from psiqit.quantum import pauli_z, pauli_x
            >>> H0 = pauli_z()
            >>> V = pauli_x()
            >>> ip = InteractionPicture(H0, V)
        """
        if H0.dim != V.dim:
            raise ValueError(f"Hamiltonian dimensions mismatch: {H0.dim} vs {V.dim}")

        if not H0.is_hermitian:
            logger.warning("H0 is not Hermitian")

        if not V.is_hermitian:
            logger.warning("V is not Hermitian")

        self.H0 = H0
        self.V = V
        self.hbar = hbar
        self.dim = H0.dim

        # Cache time evolution operators for efficiency
        self._U0_cache = {}

        logger.info(f"InteractionPicture initialized: dim={self.dim}, hbar={hbar}")

    def _get_U0(self, t: float) -> Operator:
        """
        Get the free evolution operator U₀(t) = e^{-iH₀t/ħ}

        Args:
            t: Time

        Returns:
            Operator: Free evolution operator
        """
        # Check cache
        if t in self._U0_cache:
            return self._U0_cache[t]

        # Compute U0
        H0 = self.H0
        U0 = expm(Operator(-1j * H0.data * t / self.hbar))
        U0.name = f"U0(t={t:.2f})"

        # Cache
        self._U0_cache[t] = U0

        return U0

    def _get_U0_dagger(self, t: float) -> Operator:
        """
        Get the adjoint of the free evolution operator

        Args:
            t: Time

        Returns:
            Operator: U₀†(t)
        """
        return self._get_U0(t).dagger()

    def interaction_operator(self, t: float) -> Operator:
        """
        Compute the interaction Hamiltonian in the interaction picture

        V_I(t) = e^{iH₀t/ħ} V e^{-iH₀t/ħ}

        Args:
            t: Time

        Returns:
            Operator: Interaction operator V_I(t)

        Example:
            >>> ip = InteractionPicture(H0, V)
            >>> V_I = ip.interaction_operator(t=0.5)
            >>> print(V_I.name)
        """
        U0_dag = self._get_U0_dagger(t)
        U0 = self._get_U0(t)

        V_I = U0_dag @ self.V @ U0
        V_I.name = f"V_I(t={t:.2f})"

        return V_I

    def _schrodinger_derivative(self, t: float, psi_vec: np.ndarray) -> np.ndarray:
        """
        Compute dψ/dt = -i/ħ V_I(t) ψ

        Args:
            t: Time
            psi_vec: State vector (flattened)

        Returns:
            np.ndarray: Time derivative
        """
        V_I = self.interaction_operator(t)
        return -1j * V_I.data @ psi_vec / self.hbar

    def evolve_state(
        self,
        psi0: Ket,
        t: float,
        dt: float = 0.01,
        method: str = 'rk4'
    ) -> Ket:
        """
        Evolve a state in the interaction picture

        |ψ_I(t)⟩ = U_I(t) |ψ_I(0)⟩

        Args:
            psi0: Initial state (in interaction picture)
            t: Evolution time
            dt: Time step
            method: Integration method ('euler' or 'rk4')

        Returns:
            Ket: Evolved state

        Example:
            >>> from psiqit.quantum import zero
            >>> psi_t = ip.evolve_state(zero(), t=1.0, dt=0.01)
            >>> print(psi_t)
        """
        if psi0.dim != self.dim:
            raise ValueError(f"State dimension {psi0.dim} does not match Hamiltonian dimension {self.dim}")

        logger.debug(f"Evolving state for t={t:.3f} with dt={dt:.4f}")

        # Number of steps
        n_steps = int(np.ceil(t / dt))
        dt_actual = t / n_steps

        # Initialize
        psi = psi0.data.copy()

        # Evolution
        for step in range(n_steps):
            time = step * dt_actual

            if method == 'euler':
                # Euler method
                dpsi = self._schrodinger_derivative(time, psi)
                psi = psi + dt_actual * dpsi

            elif method == 'rk4':
                # RK4 method
                k1 = self._schrodinger_derivative(time, psi)
                k2 = self._schrodinger_derivative(time + dt_actual/2, psi + dt_actual/2 * k1)
                k3 = self._schrodinger_derivative(time + dt_actual/2, psi + dt_actual/2 * k2)
                k4 = self._schrodinger_derivative(time + dt_actual, psi + dt_actual * k3)

                psi = psi + dt_actual/6 * (k1 + 2*k2 + 2*k3 + k4)

            else:
                raise ValueError(f"Unknown method: {method}. Use 'euler' or 'rk4'")

            # Normalize
            norm = np.linalg.norm(psi)
            if norm > 0:
                psi = psi / norm
            else:
                logger.warning(f"State norm became zero at step {step}")
                break

        return Ket(psi)

    def evolve_state_sequence(
        self,
        psi0: Ket,
        times: np.ndarray,
        dt: float = 0.01,
        method: str = 'rk4'
    ) -> InteractionResult:
        """
        Evolve a state at multiple time points

        Args:
            psi0: Initial state
            times: Array of time points
            dt: Time step for integration
            method: Integration method

        Returns:
            InteractionResult: Evolution results

        Example:
            >>> times = np.linspace(0, 2*np.pi, 50)
            >>> result = ip.evolve_state_sequence(zero(), times)
            >>> print(len(result.states))  # 50
        """
        logger.info(f"Evolving state sequence for {len(times)} time points")

        states = []
        success = True
        message = "Evolution completed successfully"

        try:
            for t in times:
                psi_t = self.evolve_state(psi0, t, dt=dt, method=method)
                states.append(psi_t)

        except Exception as e:
            success = False
            message = f"Evolution failed: {str(e)}"
            logger.error(message)

        return InteractionResult(
            times=times,
            states=states,
            success=success,
            message=message,
            initial_state=psi0
        )

    def evolve_operator(self, A: Operator, t: float) -> Operator:
        """
        Evolve an operator in the interaction picture

        A_I(t) = e^{iH₀t/ħ} A e^{-iH₀t/ħ}

        Args:
            A: Operator to evolve
            t: Time

        Returns:
            Operator: Evolved operator

        Example:
            >>> from psiqit.quantum import pauli_x
            >>> A_t = ip.evolve_operator(pauli_x(), t=1.0)
            >>> print(A_t.name)
        """
        if A.dim != self.dim:
            raise ValueError(f"Operator dimension {A.dim} does not match Hamiltonian dimension {self.dim}")

        U0_dag = self._get_U0_dagger(t)
        U0 = self._get_U0(t)

        A_I = U0_dag @ A @ U0
        A_I.name = f"{A.name}_I(t={t:.2f})" if A.name else f"A_I(t={t:.2f})"

        return A_I

    def evolve_operator_sequence(
        self,
        A: Operator,
        times: np.ndarray
    ) -> List[Operator]:
        """
        Evolve an operator at multiple time points

        Args:
            A: Operator
            times: Array of time points

        Returns:
            List[Operator]: Evolved operators
        """
        logger.info(f"Evolving operator sequence for {len(times)} time points")

        operators = []

        for t in times:
            A_t = self.evolve_operator(A, t)
            operators.append(A_t)

        return operators

    def compute_expectation(
        self,
        A: Operator,
        state: Ket,
        t: float
    ) -> float:
        """
        Compute expectation value ⟨ψ|A_I(t)|ψ⟩

        Args:
            A: Operator
            state: Quantum state
            t: Time

        Returns:
            float: Expectation value
        """
        A_I = self.evolve_operator(A, t)
        expectation = np.vdot(state.data, A_I.data @ state.data).real
        return float(expectation)

    def compute_expectation_sequence(
        self,
        A: Operator,
        state: Ket,
        times: np.ndarray
    ) -> Tuple[np.ndarray, List[float]]:
        """
        Compute expectation values at multiple time points

        Args:
            A: Operator
            state: Quantum state
            times: Array of time points

        Returns:
            Tuple: (times, expectation_values)
        """
        logger.info(f"Computing expectation sequence for {len(times)} time points")

        expectations = []

        for t in times:
            exp = self.compute_expectation(A, state, t)
            expectations.append(exp)

        return times, expectations

    def get_time_evolution_operator(self, t: float) -> Operator:
        """
        Get the full time evolution operator in the interaction picture

        U_I(t) = T exp(-i/ħ ∫₀ᵗ V_I(t') dt')

        Args:
            t: Time

        Returns:
            Operator: Time evolution operator

        Note:
            This is a simplified version that uses the series expansion
            for the time-ordered exponential.
        """
        # For small t, use series expansion
        # U_I(t) ≈ I - i/ħ ∫₀ᵗ V_I(t') dt'
        # This is a first-order approximation

        # Integrate V_I numerically
        n_points = 100
        dt = t / n_points
        integral = np.zeros((self.dim, self.dim), dtype=complex)

        for i in range(n_points):
            t_i = i * dt
            V_I = self.interaction_operator(t_i)
            integral += V_I.data * dt

        U_I = np.eye(self.dim, dtype=complex) - 1j * integral / self.hbar

        return Operator(U_I, name=f"U_I(t={t:.2f})")

    def to_schrodinger_picture(
        self,
        psi_I: Ket,
        t: float
    ) -> Ket:
        """
        Convert a state from interaction picture to Schrödinger picture

        |ψ_S(t)⟩ = e^{-iH₀t/ħ} |ψ_I(t)⟩

        Args:
            psi_I: State in interaction picture
            t: Time

        Returns:
            Ket: State in Schrödinger picture
        """
        U0 = self._get_U0(t)
        psi_S = U0 @ psi_I
        return Ket(psi_S.data)

    def to_interaction_picture(
        self,
        psi_S: Ket,
        t: float
    ) -> Ket:
        """
        Convert a state from Schrödinger picture to interaction picture

        |ψ_I(t)⟩ = e^{iH₀t/ħ} |ψ_S(t)⟩

        Args:
            psi_S: State in Schrödinger picture
            t: Time

        Returns:
            Ket: State in interaction picture
        """
        U0_dag = self._get_U0_dagger(t)
        psi_I = U0_dag @ psi_S
        return Ket(psi_I.data)

    def clear_cache(self):
        """Clear the cache of time evolution operators"""
        self._U0_cache = {}
        logger.debug("Cache cleared")

__init__(H0, V, hbar=1.0)

Initialize interaction picture

Parameters:

Name Type Description Default
H0 Operator

Free Hamiltonian (solvable part)

required
V Operator

Interaction Hamiltonian

required
hbar float

Reduced Planck constant

1.0
Example

from psiqit.quantum import pauli_z, pauli_x H0 = pauli_z() V = pauli_x() ip = InteractionPicture(H0, V)

Source code in psiqit\dynamics\interaction.py
def __init__(self, H0: Operator, V: Operator, hbar: float = 1.0):
    """
    Initialize interaction picture

    Args:
        H0: Free Hamiltonian (solvable part)
        V: Interaction Hamiltonian
        hbar: Reduced Planck constant

    Example:
        >>> from psiqit.quantum import pauli_z, pauli_x
        >>> H0 = pauli_z()
        >>> V = pauli_x()
        >>> ip = InteractionPicture(H0, V)
    """
    if H0.dim != V.dim:
        raise ValueError(f"Hamiltonian dimensions mismatch: {H0.dim} vs {V.dim}")

    if not H0.is_hermitian:
        logger.warning("H0 is not Hermitian")

    if not V.is_hermitian:
        logger.warning("V is not Hermitian")

    self.H0 = H0
    self.V = V
    self.hbar = hbar
    self.dim = H0.dim

    # Cache time evolution operators for efficiency
    self._U0_cache = {}

    logger.info(f"InteractionPicture initialized: dim={self.dim}, hbar={hbar}")

interaction_operator(t)

Compute the interaction Hamiltonian in the interaction picture

V_I(t) = e^{iH₀t/ħ} V e^{-iH₀t/ħ}

Parameters:

Name Type Description Default
t float

Time

required

Returns:

Name Type Description
Operator Operator

Interaction operator V_I(t)

Example

ip = InteractionPicture(H0, V) V_I = ip.interaction_operator(t=0.5) print(V_I.name)

Source code in psiqit\dynamics\interaction.py
def interaction_operator(self, t: float) -> Operator:
    """
    Compute the interaction Hamiltonian in the interaction picture

    V_I(t) = e^{iH₀t/ħ} V e^{-iH₀t/ħ}

    Args:
        t: Time

    Returns:
        Operator: Interaction operator V_I(t)

    Example:
        >>> ip = InteractionPicture(H0, V)
        >>> V_I = ip.interaction_operator(t=0.5)
        >>> print(V_I.name)
    """
    U0_dag = self._get_U0_dagger(t)
    U0 = self._get_U0(t)

    V_I = U0_dag @ self.V @ U0
    V_I.name = f"V_I(t={t:.2f})"

    return V_I

evolve_state(psi0, t, dt=0.01, method='rk4')

Evolve a state in the interaction picture

|ψ_I(t)⟩ = U_I(t) |ψ_I(0)⟩

Parameters:

Name Type Description Default
psi0 Ket

Initial state (in interaction picture)

required
t float

Evolution time

required
dt float

Time step

0.01
method str

Integration method ('euler' or 'rk4')

'rk4'

Returns:

Name Type Description
Ket Ket

Evolved state

Example

from psiqit.quantum import zero psi_t = ip.evolve_state(zero(), t=1.0, dt=0.01) print(psi_t)

Source code in psiqit\dynamics\interaction.py
def evolve_state(
    self,
    psi0: Ket,
    t: float,
    dt: float = 0.01,
    method: str = 'rk4'
) -> Ket:
    """
    Evolve a state in the interaction picture

    |ψ_I(t)⟩ = U_I(t) |ψ_I(0)⟩

    Args:
        psi0: Initial state (in interaction picture)
        t: Evolution time
        dt: Time step
        method: Integration method ('euler' or 'rk4')

    Returns:
        Ket: Evolved state

    Example:
        >>> from psiqit.quantum import zero
        >>> psi_t = ip.evolve_state(zero(), t=1.0, dt=0.01)
        >>> print(psi_t)
    """
    if psi0.dim != self.dim:
        raise ValueError(f"State dimension {psi0.dim} does not match Hamiltonian dimension {self.dim}")

    logger.debug(f"Evolving state for t={t:.3f} with dt={dt:.4f}")

    # Number of steps
    n_steps = int(np.ceil(t / dt))
    dt_actual = t / n_steps

    # Initialize
    psi = psi0.data.copy()

    # Evolution
    for step in range(n_steps):
        time = step * dt_actual

        if method == 'euler':
            # Euler method
            dpsi = self._schrodinger_derivative(time, psi)
            psi = psi + dt_actual * dpsi

        elif method == 'rk4':
            # RK4 method
            k1 = self._schrodinger_derivative(time, psi)
            k2 = self._schrodinger_derivative(time + dt_actual/2, psi + dt_actual/2 * k1)
            k3 = self._schrodinger_derivative(time + dt_actual/2, psi + dt_actual/2 * k2)
            k4 = self._schrodinger_derivative(time + dt_actual, psi + dt_actual * k3)

            psi = psi + dt_actual/6 * (k1 + 2*k2 + 2*k3 + k4)

        else:
            raise ValueError(f"Unknown method: {method}. Use 'euler' or 'rk4'")

        # Normalize
        norm = np.linalg.norm(psi)
        if norm > 0:
            psi = psi / norm
        else:
            logger.warning(f"State norm became zero at step {step}")
            break

    return Ket(psi)

evolve_state_sequence(psi0, times, dt=0.01, method='rk4')

Evolve a state at multiple time points

Parameters:

Name Type Description Default
psi0 Ket

Initial state

required
times ndarray

Array of time points

required
dt float

Time step for integration

0.01
method str

Integration method

'rk4'

Returns:

Name Type Description
InteractionResult InteractionResult

Evolution results

Example

times = np.linspace(0, 2*np.pi, 50) result = ip.evolve_state_sequence(zero(), times) print(len(result.states)) # 50

Source code in psiqit\dynamics\interaction.py
def evolve_state_sequence(
    self,
    psi0: Ket,
    times: np.ndarray,
    dt: float = 0.01,
    method: str = 'rk4'
) -> InteractionResult:
    """
    Evolve a state at multiple time points

    Args:
        psi0: Initial state
        times: Array of time points
        dt: Time step for integration
        method: Integration method

    Returns:
        InteractionResult: Evolution results

    Example:
        >>> times = np.linspace(0, 2*np.pi, 50)
        >>> result = ip.evolve_state_sequence(zero(), times)
        >>> print(len(result.states))  # 50
    """
    logger.info(f"Evolving state sequence for {len(times)} time points")

    states = []
    success = True
    message = "Evolution completed successfully"

    try:
        for t in times:
            psi_t = self.evolve_state(psi0, t, dt=dt, method=method)
            states.append(psi_t)

    except Exception as e:
        success = False
        message = f"Evolution failed: {str(e)}"
        logger.error(message)

    return InteractionResult(
        times=times,
        states=states,
        success=success,
        message=message,
        initial_state=psi0
    )

evolve_operator(A, t)

Evolve an operator in the interaction picture

A_I(t) = e^{iH₀t/ħ} A e^{-iH₀t/ħ}

Parameters:

Name Type Description Default
A Operator

Operator to evolve

required
t float

Time

required

Returns:

Name Type Description
Operator Operator

Evolved operator

Example

from psiqit.quantum import pauli_x A_t = ip.evolve_operator(pauli_x(), t=1.0) print(A_t.name)

Source code in psiqit\dynamics\interaction.py
def evolve_operator(self, A: Operator, t: float) -> Operator:
    """
    Evolve an operator in the interaction picture

    A_I(t) = e^{iH₀t/ħ} A e^{-iH₀t/ħ}

    Args:
        A: Operator to evolve
        t: Time

    Returns:
        Operator: Evolved operator

    Example:
        >>> from psiqit.quantum import pauli_x
        >>> A_t = ip.evolve_operator(pauli_x(), t=1.0)
        >>> print(A_t.name)
    """
    if A.dim != self.dim:
        raise ValueError(f"Operator dimension {A.dim} does not match Hamiltonian dimension {self.dim}")

    U0_dag = self._get_U0_dagger(t)
    U0 = self._get_U0(t)

    A_I = U0_dag @ A @ U0
    A_I.name = f"{A.name}_I(t={t:.2f})" if A.name else f"A_I(t={t:.2f})"

    return A_I

evolve_operator_sequence(A, times)

Evolve an operator at multiple time points

Parameters:

Name Type Description Default
A Operator

Operator

required
times ndarray

Array of time points

required

Returns:

Type Description
List[Operator]

List[Operator]: Evolved operators

Source code in psiqit\dynamics\interaction.py
def evolve_operator_sequence(
    self,
    A: Operator,
    times: np.ndarray
) -> List[Operator]:
    """
    Evolve an operator at multiple time points

    Args:
        A: Operator
        times: Array of time points

    Returns:
        List[Operator]: Evolved operators
    """
    logger.info(f"Evolving operator sequence for {len(times)} time points")

    operators = []

    for t in times:
        A_t = self.evolve_operator(A, t)
        operators.append(A_t)

    return operators

compute_expectation(A, state, t)

Compute expectation value ⟨ψ|A_I(t)|ψ⟩

Parameters:

Name Type Description Default
A Operator

Operator

required
state Ket

Quantum state

required
t float

Time

required

Returns:

Name Type Description
float float

Expectation value

Source code in psiqit\dynamics\interaction.py
def compute_expectation(
    self,
    A: Operator,
    state: Ket,
    t: float
) -> float:
    """
    Compute expectation value ⟨ψ|A_I(t)|ψ⟩

    Args:
        A: Operator
        state: Quantum state
        t: Time

    Returns:
        float: Expectation value
    """
    A_I = self.evolve_operator(A, t)
    expectation = np.vdot(state.data, A_I.data @ state.data).real
    return float(expectation)

compute_expectation_sequence(A, state, times)

Compute expectation values at multiple time points

Parameters:

Name Type Description Default
A Operator

Operator

required
state Ket

Quantum state

required
times ndarray

Array of time points

required

Returns:

Name Type Description
Tuple Tuple[ndarray, List[float]]

(times, expectation_values)

Source code in psiqit\dynamics\interaction.py
def compute_expectation_sequence(
    self,
    A: Operator,
    state: Ket,
    times: np.ndarray
) -> Tuple[np.ndarray, List[float]]:
    """
    Compute expectation values at multiple time points

    Args:
        A: Operator
        state: Quantum state
        times: Array of time points

    Returns:
        Tuple: (times, expectation_values)
    """
    logger.info(f"Computing expectation sequence for {len(times)} time points")

    expectations = []

    for t in times:
        exp = self.compute_expectation(A, state, t)
        expectations.append(exp)

    return times, expectations

get_time_evolution_operator(t)

Get the full time evolution operator in the interaction picture

U_I(t) = T exp(-i/ħ ∫₀ᵗ V_I(t') dt')

Parameters:

Name Type Description Default
t float

Time

required

Returns:

Name Type Description
Operator Operator

Time evolution operator

Note

This is a simplified version that uses the series expansion for the time-ordered exponential.

Source code in psiqit\dynamics\interaction.py
def get_time_evolution_operator(self, t: float) -> Operator:
    """
    Get the full time evolution operator in the interaction picture

    U_I(t) = T exp(-i/ħ ∫₀ᵗ V_I(t') dt')

    Args:
        t: Time

    Returns:
        Operator: Time evolution operator

    Note:
        This is a simplified version that uses the series expansion
        for the time-ordered exponential.
    """
    # For small t, use series expansion
    # U_I(t) ≈ I - i/ħ ∫₀ᵗ V_I(t') dt'
    # This is a first-order approximation

    # Integrate V_I numerically
    n_points = 100
    dt = t / n_points
    integral = np.zeros((self.dim, self.dim), dtype=complex)

    for i in range(n_points):
        t_i = i * dt
        V_I = self.interaction_operator(t_i)
        integral += V_I.data * dt

    U_I = np.eye(self.dim, dtype=complex) - 1j * integral / self.hbar

    return Operator(U_I, name=f"U_I(t={t:.2f})")

to_schrodinger_picture(psi_I, t)

Convert a state from interaction picture to Schrödinger picture

|ψ_S(t)⟩ = e^{-iH₀t/ħ} |ψ_I(t)⟩

Parameters:

Name Type Description Default
psi_I Ket

State in interaction picture

required
t float

Time

required

Returns:

Name Type Description
Ket Ket

State in Schrödinger picture

Source code in psiqit\dynamics\interaction.py
def to_schrodinger_picture(
    self,
    psi_I: Ket,
    t: float
) -> Ket:
    """
    Convert a state from interaction picture to Schrödinger picture

    |ψ_S(t)⟩ = e^{-iH₀t/ħ} |ψ_I(t)⟩

    Args:
        psi_I: State in interaction picture
        t: Time

    Returns:
        Ket: State in Schrödinger picture
    """
    U0 = self._get_U0(t)
    psi_S = U0 @ psi_I
    return Ket(psi_S.data)

to_interaction_picture(psi_S, t)

Convert a state from Schrödinger picture to interaction picture

|ψ_I(t)⟩ = e^{iH₀t/ħ} |ψ_S(t)⟩

Parameters:

Name Type Description Default
psi_S Ket

State in Schrödinger picture

required
t float

Time

required

Returns:

Name Type Description
Ket Ket

State in interaction picture

Source code in psiqit\dynamics\interaction.py
def to_interaction_picture(
    self,
    psi_S: Ket,
    t: float
) -> Ket:
    """
    Convert a state from Schrödinger picture to interaction picture

    |ψ_I(t)⟩ = e^{iH₀t/ħ} |ψ_S(t)⟩

    Args:
        psi_S: State in Schrödinger picture
        t: Time

    Returns:
        Ket: State in interaction picture
    """
    U0_dag = self._get_U0_dagger(t)
    psi_I = U0_dag @ psi_S
    return Ket(psi_I.data)

clear_cache()

Clear the cache of time evolution operators

Source code in psiqit\dynamics\interaction.py
def clear_cache(self):
    """Clear the cache of time evolution operators"""
    self._U0_cache = {}
    logger.debug("Cache cleared")

LindbladResult dataclass

Result container for Lindblad master equation evolution

Attributes:

Name Type Description
times ndarray

Time points

states List[ndarray]

List of density matrices at each time

populations List[ndarray]

List of populations for each state

success bool

Whether evolution was successful

message str

Additional information

n_steps int

Number of time steps

final_state Optional[ndarray]

Final density matrix

fidelity Optional[float]

Fidelity with steady state (if available)

Source code in psiqit\dynamics\lindblad.py
@dataclass
class LindbladResult:
    """
    Result container for Lindblad master equation evolution

    Attributes:
        times: Time points
        states: List of density matrices at each time
        populations: List of populations for each state
        success: Whether evolution was successful
        message: Additional information
        n_steps: Number of time steps
        final_state: Final density matrix
        fidelity: Fidelity with steady state (if available)
    """
    times: np.ndarray
    states: List[np.ndarray]
    populations: List[np.ndarray]
    success: bool = True
    message: str = ""
    n_steps: int = 0
    final_state: Optional[np.ndarray] = None
    fidelity: Optional[float] = None

    def __post_init__(self):
        """Post-process the result"""
        self.n_steps = len(self.times)

        if self.states:
            self.final_state = self.states[-1]

    def get_state_at_time(self, index: int) -> Optional[np.ndarray]:
        """Get density matrix at a specific time index"""
        if 0 <= index < len(self.states):
            return self.states[index]
        return None

    def get_final_state(self) -> Optional[np.ndarray]:
        """Get the final density matrix"""
        return self.final_state

    def get_population_at_time(self, index: int) -> Optional[np.ndarray]:
        """Get populations at a specific time index"""
        if 0 <= index < len(self.populations):
            return self.populations[index]
        return None

    def get_population_evolution(self, state_index: int) -> List[float]:
        """
        Get the evolution of a specific population

        Args:
            state_index: Index of the state

        Returns:
            List[float]: Population values over time
        """
        if state_index < 0 or state_index >= len(self.populations[0]):
            raise ValueError(f"State index {state_index} out of range")

        return [p[state_index] for p in self.populations]

    def get_fidelity_with_initial(self) -> List[float]:
        """
        Get fidelity of each state with the initial state

        Returns:
            List[float]: Fidelity values
        """
        if not self.states or self.states[0] is None:
            return []

        rho0 = self.states[0]
        fidelities = []

        for rho in self.states:
            # Fidelity = Tr(√(√ρ σ √ρ))²
            # For density matrices, we compute the square root fidelity
            sqrt_rho = np.linalg.sqrtm(rho)
            sqrt_rho_sigma_sqrt_rho = sqrt_rho @ rho0 @ sqrt_rho
            fid = np.trace(np.linalg.sqrtm(sqrt_rho_sigma_sqrt_rho)).real ** 2
            fidelities.append(float(fid))

        return fidelities

    def __repr__(self) -> str:
        status = "Success" if self.success else "Failed"
        return f"LindbladResult(steps={self.n_steps}, status={status})"

    def __str__(self) -> str:
        lines = [
            "Lindblad Evolution Results:",
            f"  Steps: {self.n_steps}",
            f"  Success: {self.success}",
            f"  Message: {self.message}",
        ]
        if self.final_state is not None:
            lines.append(f"  Final State Trace: {np.trace(self.final_state).real:.6f}")
        if self.fidelity is not None:
            lines.append(f"  Fidelity with Steady State: {self.fidelity:.6f}")
        return "\n".join(lines)

__post_init__()

Post-process the result

Source code in psiqit\dynamics\lindblad.py
def __post_init__(self):
    """Post-process the result"""
    self.n_steps = len(self.times)

    if self.states:
        self.final_state = self.states[-1]

get_state_at_time(index)

Get density matrix at a specific time index

Source code in psiqit\dynamics\lindblad.py
def get_state_at_time(self, index: int) -> Optional[np.ndarray]:
    """Get density matrix at a specific time index"""
    if 0 <= index < len(self.states):
        return self.states[index]
    return None

get_final_state()

Get the final density matrix

Source code in psiqit\dynamics\lindblad.py
def get_final_state(self) -> Optional[np.ndarray]:
    """Get the final density matrix"""
    return self.final_state

get_population_at_time(index)

Get populations at a specific time index

Source code in psiqit\dynamics\lindblad.py
def get_population_at_time(self, index: int) -> Optional[np.ndarray]:
    """Get populations at a specific time index"""
    if 0 <= index < len(self.populations):
        return self.populations[index]
    return None

get_population_evolution(state_index)

Get the evolution of a specific population

Parameters:

Name Type Description Default
state_index int

Index of the state

required

Returns:

Type Description
List[float]

List[float]: Population values over time

Source code in psiqit\dynamics\lindblad.py
def get_population_evolution(self, state_index: int) -> List[float]:
    """
    Get the evolution of a specific population

    Args:
        state_index: Index of the state

    Returns:
        List[float]: Population values over time
    """
    if state_index < 0 or state_index >= len(self.populations[0]):
        raise ValueError(f"State index {state_index} out of range")

    return [p[state_index] for p in self.populations]

get_fidelity_with_initial()

Get fidelity of each state with the initial state

Returns:

Type Description
List[float]

List[float]: Fidelity values

Source code in psiqit\dynamics\lindblad.py
def get_fidelity_with_initial(self) -> List[float]:
    """
    Get fidelity of each state with the initial state

    Returns:
        List[float]: Fidelity values
    """
    if not self.states or self.states[0] is None:
        return []

    rho0 = self.states[0]
    fidelities = []

    for rho in self.states:
        # Fidelity = Tr(√(√ρ σ √ρ))²
        # For density matrices, we compute the square root fidelity
        sqrt_rho = np.linalg.sqrtm(rho)
        sqrt_rho_sigma_sqrt_rho = sqrt_rho @ rho0 @ sqrt_rho
        fid = np.trace(np.linalg.sqrtm(sqrt_rho_sigma_sqrt_rho)).real ** 2
        fidelities.append(float(fid))

    return fidelities

LindbladSolver

Lindblad master equation solver for open quantum systems

The Lindblad master equation describes the evolution of an open quantum system:

dρ/dt = -i/ħ [H, ρ] + Σ_k (L_k ρ L_k† - 1/2{L_k†L_k, ρ})

where H is the Hamiltonian and L_k are collapse operators.

Example

from psiqit.quantum import pauli_z, pauli_x H = pauli_z() # Hamiltonian L = pauli_x() # Collapse operator solver = LindbladSolver(H, [L], gamma=[0.1]) rho0 = np.array([[1, 0], [0, 0]]) # Initial state |0⟩⟨0| result = solver.evolve(rho0, t_max=10.0, dt=0.01) print(result.final_state)

Source code in psiqit\dynamics\lindblad.py
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
class LindbladSolver:
    """
    Lindblad master equation solver for open quantum systems

    The Lindblad master equation describes the evolution of an open
    quantum system:

    dρ/dt = -i/ħ [H, ρ] + Σ_k (L_k ρ L_k† - 1/2{L_k†L_k, ρ})

    where H is the Hamiltonian and L_k are collapse operators.

    Example:
        >>> from psiqit.quantum import pauli_z, pauli_x
        >>> H = pauli_z()  # Hamiltonian
        >>> L = pauli_x()  # Collapse operator
        >>> solver = LindbladSolver(H, [L], gamma=[0.1])
        >>> rho0 = np.array([[1, 0], [0, 0]])  # Initial state |0⟩⟨0|
        >>> result = solver.evolve(rho0, t_max=10.0, dt=0.01)
        >>> print(result.final_state)
    """

    def __init__(
        self,
        hamiltonian: Operator,
        collapse_ops: List[Operator],
        gamma: Optional[List[float]] = None,
        hbar: float = 1.0
    ):
        """
        Initialize Lindblad solver

        Args:
            hamiltonian: System Hamiltonian (Hermitian)
            collapse_ops: List of collapse operators L_k
            gamma: List of decay rates for each collapse operator
                   If None, all rates are set to 1.0
            hbar: Reduced Planck constant

        Example:
            >>> H = pauli_z()
            >>> L = pauli_x()
            >>> solver = LindbladSolver(H, [L], gamma=[0.1])
        """
        if not hamiltonian.is_hermitian:
            logger.warning("Hamiltonian is not Hermitian")

        self.hamiltonian = hamiltonian
        self.collapse_ops = collapse_ops
        self.hbar = hbar
        self.dim = hamiltonian.dim

        # Set decay rates
        if gamma is None:
            self.gamma = [1.0] * len(collapse_ops)
        else:
            if len(gamma) != len(collapse_ops):
                raise ValueError(f"Number of gamma values {len(gamma)} does not match number of collapse operators {len(collapse_ops)}")
            self.gamma = gamma

        # Precompute Lindblad superoperator components
        self._lindblad_components = self._compute_lindblad_components()

        logger.info(f"LindbladSolver initialized: dim={self.dim}, n_ops={len(collapse_ops)}")

    def _compute_lindblad_components(self) -> List[np.ndarray]:
        """
        Precompute Lindblad superoperator components

        Returns:
            List[np.ndarray]: List of Lindblad matrices
        """
        components = []

        for L, gamma_k in zip(self.collapse_ops, self.gamma):
            L_dag = L.dagger()
            L_dag_L = L_dag @ L

            # Lindblad term: gamma * (L ρ L† - 1/2{L†L, ρ})
            # We'll compute this in the evolution
            components.append({
                'L': L.data,
                'L_dag': L_dag.data,
                'L_dag_L': L_dag_L.data,
                'gamma': gamma_k
            })

        return components

    def _lindblad_superoperator(self, rho: np.ndarray) -> np.ndarray:
        """
        Apply the Lindblad superoperator to a density matrix

        Args:
            rho: Density matrix

        Returns:
            np.ndarray: dρ/dt
        """
        # Unitary part: -i/ħ [H, ρ]
        H = self.hamiltonian.data
        drho = -1j * (H @ rho - rho @ H) / self.hbar

        # Dissipative part
        for comp in self._lindblad_components:
            L = comp['L']
            L_dag = comp['L_dag']
            L_dag_L = comp['L_dag_L']
            gamma = comp['gamma']

            # L ρ L† - 1/2{L†L, ρ}
            term = L @ rho @ L_dag - 0.5 * (L_dag_L @ rho + rho @ L_dag_L)
            drho += gamma * term

        return drho

    def _flatten_matrix(self, rho: np.ndarray) -> np.ndarray:
        """Flatten a density matrix to a vector"""
        return rho.flatten()

    def _unflatten_vector(self, vec: np.ndarray) -> np.ndarray:
        """Unflatten a vector to a density matrix"""
        return vec.reshape(self.dim, self.dim)

    def _ensure_hermitian(self, rho: np.ndarray) -> np.ndarray:
        """Ensure the density matrix is Hermitian"""
        return (rho + rho.conj().T) / 2

    def _ensure_trace(self, rho: np.ndarray) -> np.ndarray:
        """Ensure the density matrix has trace 1"""
        trace_val = np.trace(rho).real
        if trace_val > 0:
            rho = rho / trace_val
        return rho

    def evolve(
        self,
        rho0: np.ndarray,
        t_max: float,
        dt: float = 0.01,
        method: str = 'euler',
        save_every: int = 1
    ) -> LindbladResult:
        """
        Evolve the density matrix according to the Lindblad master equation

        Args:
            rho0: Initial density matrix
            t_max: Maximum evolution time
            dt: Time step
            method: Integration method ('euler' or 'rk4')
            save_every: Save state every N steps

        Returns:
            LindbladResult: Evolution results

        Example:
            >>> rho0 = np.array([[1, 0], [0, 0]])
            >>> result = solver.evolve(rho0, t_max=10.0, dt=0.01)
        """
        # Validate initial state
        if rho0.shape != (self.dim, self.dim):
            raise ValueError(f"rho0 shape {rho0.shape} does not match dimension {self.dim}")

        # Ensure Hermitian and trace 1
        rho0 = self._ensure_hermitian(rho0)
        rho0 = self._ensure_trace(rho0)

        logger.info(f"Starting Lindblad evolution: t_max={t_max:.3f}, dt={dt:.4f}, method={method}")

        # Number of steps
        n_steps = int(np.ceil(t_max / dt))
        dt_actual = t_max / n_steps

        # Initialize
        rho = rho0.copy()

        # Storage
        times = []
        states = []
        populations = []

        # Initial state
        times.append(0.0)
        states.append(rho.copy())

        # Initial populations (diagonal elements)
        diag = np.diag(rho).real
        populations.append(diag.copy())

        success = True
        message = "Evolution completed successfully"

        try:
            for step in range(n_steps):
                t = step * dt_actual

                # Flatten for ODE solvers
                rho_flat = self._flatten_matrix(rho)

                if method == 'euler':
                    # Euler method
                    drho = self._lindblad_superoperator(rho)
                    rho = rho + dt_actual * drho

                elif method == 'rk4':
                    # RK4 method
                    k1 = self._lindblad_superoperator(rho)
                    k2 = self._lindblad_superoperator(rho + dt_actual/2 * k1)
                    k3 = self._lindblad_superoperator(rho + dt_actual/2 * k2)
                    k4 = self._lindblad_superoperator(rho + dt_actual * k3)

                    rho = rho + dt_actual/6 * (k1 + 2*k2 + 2*k3 + k4)

                else:
                    raise ValueError(f"Unknown method: {method}. Use 'euler' or 'rk4'")

                # Ensure Hermitian
                rho = self._ensure_hermitian(rho)

                # Ensure trace 1
                rho = self._ensure_trace(rho)

                # Check positivity (simplified)
                eigvals = np.linalg.eigvalsh(rho)
                if np.any(eigvals < -1e-8):
                    logger.warning(f"Negative eigenvalues at step {step}: {eigvals}")
                    # Project to positive semidefinite
                    rho = self._project_positive(rho)

                # Save state
                if (step + 1) % save_every == 0 or step == n_steps - 1:
                    times.append((step + 1) * dt_actual)
                    states.append(rho.copy())

                    diag = np.diag(rho).real
                    populations.append(diag.copy())

                # Progress logging
                if (step + 1) % max(1, n_steps // 10) == 0:
                    logger.debug(f"Progress: {step+1}/{n_steps} steps")

        except Exception as e:
            success = False
            message = f"Evolution failed: {str(e)}"
            logger.error(message)

        # Convert lists to arrays
        times = np.array(times)

        logger.info(f"Lindblad evolution completed: {len(states)} states saved")

        return LindbladResult(
            times=times,
            states=states,
            populations=populations,
            success=success,
            message=message
        )

    def _project_positive(self, rho: np.ndarray) -> np.ndarray:
        """
        Project a matrix to the positive semidefinite cone

        Args:
            rho: Density matrix

        Returns:
            np.ndarray: Positive semidefinite matrix
        """
        eigvals, eigvecs = np.linalg.eigh(rho)

        # Set negative eigenvalues to zero
        eigvals = np.maximum(eigvals, 0)

        # Reconstruct
        rho_pos = eigvecs @ np.diag(eigvals) @ eigvecs.conj().T

        # Ensure trace 1
        rho_pos = self._ensure_trace(rho_pos)

        return rho_pos

    def steady_state(
        self,
        tol: float = 1e-10,
        max_iter: int = 1000,
        initial_guess: Optional[np.ndarray] = None
    ) -> np.ndarray:
        """
        Find the steady state (stationary solution) of the Lindblad equation

        Solves: dρ/dt = 0

        Args:
            tol: Convergence tolerance
            max_iter: Maximum number of iterations
            initial_guess: Initial guess for steady state

        Returns:
            np.ndarray: Steady state density matrix

        Example:
            >>> rho_ss = solver.steady_state()
            >>> print(np.trace(rho_ss))  # 1.0
        """
        logger.info(f"Finding steady state with tolerance {tol:.2e}")

        # Default initial guess: thermal state or maximally mixed
        if initial_guess is None:
            rho = np.eye(self.dim, dtype=complex) / self.dim
        else:
            rho = initial_guess.copy()
            rho = self._ensure_hermitian(rho)
            rho = self._ensure_trace(rho)

        # Iterative method (imaginary time evolution)
        # For small systems, we can use direct solution
        # For larger systems, we use iterative method

        # Try direct solution for small systems
        if self.dim <= 4:
            try:
                # Build the Liouvillian superoperator
                Liouv = self._build_liouvillian()

                # Find nullspace (eigenvalue = 0)
                eigvals, eigvecs = np.linalg.eig(Liouv)

                # Find index of zero eigenvalue
                zero_idx = np.argmin(np.abs(eigvals))

                # Get steady state vector
                rho_vec = eigvecs[:, zero_idx]

                # Reshape to matrix
                rho_ss = rho_vec.reshape(self.dim, self.dim)

                # Ensure Hermitian and trace 1
                rho_ss = self._ensure_hermitian(rho_ss)
                rho_ss = self._ensure_trace(rho_ss)

                logger.info("Steady state found using direct method")
                return rho_ss

            except Exception as e:
                logger.warning(f"Direct method failed: {e}. Using iterative method.")

        # Iterative method (simple fixed-point iteration)
        # rho_{n+1} = rho_n + dt * Lindblad(rho_n)
        # We evolve until convergence

        dt = 0.01
        for iteration in range(max_iter):
            drho = self._lindblad_superoperator(rho)
            rho_new = rho + dt * drho

            # Ensure Hermitian and trace 1
            rho_new = self._ensure_hermitian(rho_new)
            rho_new = self._ensure_trace(rho_new)
            rho_new = self._project_positive(rho_new)

            # Check convergence
            diff = np.max(np.abs(rho_new - rho))
            rho = rho_new

            if diff < tol:
                logger.info(f"Steady state converged after {iteration + 1} iterations")
                return rho

        logger.warning(f"Steady state did not converge after {max_iter} iterations")
        return rho

    def _build_liouvillian(self) -> np.ndarray:
        """
        Build the Liouvillian superoperator matrix

        Returns:
            np.ndarray: Liouvillian superoperator (dim² x dim²)
        """
        dim = self.dim
        dim2 = dim * dim

        Liouv = np.zeros((dim2, dim2), dtype=complex)

        # Unitary part: -i/ħ [H, ρ]
        H = self.hamiltonian.data

        for i in range(dim):
            for j in range(dim):
                # Index for ρ_{ij}
                idx = i * dim + j

                # -i/ħ (H ρ - ρ H)
                for k in range(dim):
                    # H ρ term: -i/ħ * H_{ik} ρ_{kj}
                    Liouv[idx, k * dim + j] -= 1j * H[i, k] / self.hbar

                    # - ρ H term: +i/ħ * ρ_{ik} H_{kj}
                    Liouv[idx, i * dim + k] += 1j * H[k, j] / self.hbar

        # Dissipative part
        for comp in self._lindblad_components:
            L = comp['L']
            L_dag = comp['L_dag']
            L_dag_L = comp['L_dag_L']
            gamma = comp['gamma']

            # L ρ L† term
            for i in range(dim):
                for j in range(dim):
                    idx = i * dim + j
                    for k in range(dim):
                        for l in range(dim):
                            # (L ρ L†)_{ij} = Σ_{kl} L_{ik} ρ_{kl} L†_{lj}
                            Liouv[idx, k * dim + l] += gamma * L[i, k] * L_dag[l, j]

            # -1/2 {L†L, ρ} term
            for i in range(dim):
                for j in range(dim):
                    idx = i * dim + j
                    # -1/2 (L†L ρ)_{ij}
                    for k in range(dim):
                        Liouv[idx, k * dim + j] -= 0.5 * gamma * L_dag_L[i, k]
                    # -1/2 (ρ L†L)_{ij}
                    for k in range(dim):
                        Liouv[idx, i * dim + k] -= 0.5 * gamma * L_dag_L[k, j]

        return Liouv

    def get_steady_state_analytical(self) -> Optional[np.ndarray]:
        """
        Try to find the steady state analytically (for simple systems)

        Returns:
            Optional[np.ndarray]: Steady state or None if not found
        """
        # For two-level systems, we can solve analytically
        if self.dim == 2 and len(self.collapse_ops) >= 1:
            # For a two-level system with one collapse operator
            # This is a simplified version
            try:
                rho_ss = self.steady_state(tol=1e-12, max_iter=1000)
                return rho_ss
            except:
                return None

        return None

__init__(hamiltonian, collapse_ops, gamma=None, hbar=1.0)

Initialize Lindblad solver

Parameters:

Name Type Description Default
hamiltonian Operator

System Hamiltonian (Hermitian)

required
collapse_ops List[Operator]

List of collapse operators L_k

required
gamma Optional[List[float]]

List of decay rates for each collapse operator If None, all rates are set to 1.0

None
hbar float

Reduced Planck constant

1.0
Example

H = pauli_z() L = pauli_x() solver = LindbladSolver(H, [L], gamma=[0.1])

Source code in psiqit\dynamics\lindblad.py
def __init__(
    self,
    hamiltonian: Operator,
    collapse_ops: List[Operator],
    gamma: Optional[List[float]] = None,
    hbar: float = 1.0
):
    """
    Initialize Lindblad solver

    Args:
        hamiltonian: System Hamiltonian (Hermitian)
        collapse_ops: List of collapse operators L_k
        gamma: List of decay rates for each collapse operator
               If None, all rates are set to 1.0
        hbar: Reduced Planck constant

    Example:
        >>> H = pauli_z()
        >>> L = pauli_x()
        >>> solver = LindbladSolver(H, [L], gamma=[0.1])
    """
    if not hamiltonian.is_hermitian:
        logger.warning("Hamiltonian is not Hermitian")

    self.hamiltonian = hamiltonian
    self.collapse_ops = collapse_ops
    self.hbar = hbar
    self.dim = hamiltonian.dim

    # Set decay rates
    if gamma is None:
        self.gamma = [1.0] * len(collapse_ops)
    else:
        if len(gamma) != len(collapse_ops):
            raise ValueError(f"Number of gamma values {len(gamma)} does not match number of collapse operators {len(collapse_ops)}")
        self.gamma = gamma

    # Precompute Lindblad superoperator components
    self._lindblad_components = self._compute_lindblad_components()

    logger.info(f"LindbladSolver initialized: dim={self.dim}, n_ops={len(collapse_ops)}")

evolve(rho0, t_max, dt=0.01, method='euler', save_every=1)

Evolve the density matrix according to the Lindblad master equation

Parameters:

Name Type Description Default
rho0 ndarray

Initial density matrix

required
t_max float

Maximum evolution time

required
dt float

Time step

0.01
method str

Integration method ('euler' or 'rk4')

'euler'
save_every int

Save state every N steps

1

Returns:

Name Type Description
LindbladResult LindbladResult

Evolution results

Example

rho0 = np.array([[1, 0], [0, 0]]) result = solver.evolve(rho0, t_max=10.0, dt=0.01)

Source code in psiqit\dynamics\lindblad.py
def evolve(
    self,
    rho0: np.ndarray,
    t_max: float,
    dt: float = 0.01,
    method: str = 'euler',
    save_every: int = 1
) -> LindbladResult:
    """
    Evolve the density matrix according to the Lindblad master equation

    Args:
        rho0: Initial density matrix
        t_max: Maximum evolution time
        dt: Time step
        method: Integration method ('euler' or 'rk4')
        save_every: Save state every N steps

    Returns:
        LindbladResult: Evolution results

    Example:
        >>> rho0 = np.array([[1, 0], [0, 0]])
        >>> result = solver.evolve(rho0, t_max=10.0, dt=0.01)
    """
    # Validate initial state
    if rho0.shape != (self.dim, self.dim):
        raise ValueError(f"rho0 shape {rho0.shape} does not match dimension {self.dim}")

    # Ensure Hermitian and trace 1
    rho0 = self._ensure_hermitian(rho0)
    rho0 = self._ensure_trace(rho0)

    logger.info(f"Starting Lindblad evolution: t_max={t_max:.3f}, dt={dt:.4f}, method={method}")

    # Number of steps
    n_steps = int(np.ceil(t_max / dt))
    dt_actual = t_max / n_steps

    # Initialize
    rho = rho0.copy()

    # Storage
    times = []
    states = []
    populations = []

    # Initial state
    times.append(0.0)
    states.append(rho.copy())

    # Initial populations (diagonal elements)
    diag = np.diag(rho).real
    populations.append(diag.copy())

    success = True
    message = "Evolution completed successfully"

    try:
        for step in range(n_steps):
            t = step * dt_actual

            # Flatten for ODE solvers
            rho_flat = self._flatten_matrix(rho)

            if method == 'euler':
                # Euler method
                drho = self._lindblad_superoperator(rho)
                rho = rho + dt_actual * drho

            elif method == 'rk4':
                # RK4 method
                k1 = self._lindblad_superoperator(rho)
                k2 = self._lindblad_superoperator(rho + dt_actual/2 * k1)
                k3 = self._lindblad_superoperator(rho + dt_actual/2 * k2)
                k4 = self._lindblad_superoperator(rho + dt_actual * k3)

                rho = rho + dt_actual/6 * (k1 + 2*k2 + 2*k3 + k4)

            else:
                raise ValueError(f"Unknown method: {method}. Use 'euler' or 'rk4'")

            # Ensure Hermitian
            rho = self._ensure_hermitian(rho)

            # Ensure trace 1
            rho = self._ensure_trace(rho)

            # Check positivity (simplified)
            eigvals = np.linalg.eigvalsh(rho)
            if np.any(eigvals < -1e-8):
                logger.warning(f"Negative eigenvalues at step {step}: {eigvals}")
                # Project to positive semidefinite
                rho = self._project_positive(rho)

            # Save state
            if (step + 1) % save_every == 0 or step == n_steps - 1:
                times.append((step + 1) * dt_actual)
                states.append(rho.copy())

                diag = np.diag(rho).real
                populations.append(diag.copy())

            # Progress logging
            if (step + 1) % max(1, n_steps // 10) == 0:
                logger.debug(f"Progress: {step+1}/{n_steps} steps")

    except Exception as e:
        success = False
        message = f"Evolution failed: {str(e)}"
        logger.error(message)

    # Convert lists to arrays
    times = np.array(times)

    logger.info(f"Lindblad evolution completed: {len(states)} states saved")

    return LindbladResult(
        times=times,
        states=states,
        populations=populations,
        success=success,
        message=message
    )

steady_state(tol=1e-10, max_iter=1000, initial_guess=None)

Find the steady state (stationary solution) of the Lindblad equation

Solves: dρ/dt = 0

Parameters:

Name Type Description Default
tol float

Convergence tolerance

1e-10
max_iter int

Maximum number of iterations

1000
initial_guess Optional[ndarray]

Initial guess for steady state

None

Returns:

Type Description
ndarray

np.ndarray: Steady state density matrix

Example

rho_ss = solver.steady_state() print(np.trace(rho_ss)) # 1.0

Source code in psiqit\dynamics\lindblad.py
def steady_state(
    self,
    tol: float = 1e-10,
    max_iter: int = 1000,
    initial_guess: Optional[np.ndarray] = None
) -> np.ndarray:
    """
    Find the steady state (stationary solution) of the Lindblad equation

    Solves: dρ/dt = 0

    Args:
        tol: Convergence tolerance
        max_iter: Maximum number of iterations
        initial_guess: Initial guess for steady state

    Returns:
        np.ndarray: Steady state density matrix

    Example:
        >>> rho_ss = solver.steady_state()
        >>> print(np.trace(rho_ss))  # 1.0
    """
    logger.info(f"Finding steady state with tolerance {tol:.2e}")

    # Default initial guess: thermal state or maximally mixed
    if initial_guess is None:
        rho = np.eye(self.dim, dtype=complex) / self.dim
    else:
        rho = initial_guess.copy()
        rho = self._ensure_hermitian(rho)
        rho = self._ensure_trace(rho)

    # Iterative method (imaginary time evolution)
    # For small systems, we can use direct solution
    # For larger systems, we use iterative method

    # Try direct solution for small systems
    if self.dim <= 4:
        try:
            # Build the Liouvillian superoperator
            Liouv = self._build_liouvillian()

            # Find nullspace (eigenvalue = 0)
            eigvals, eigvecs = np.linalg.eig(Liouv)

            # Find index of zero eigenvalue
            zero_idx = np.argmin(np.abs(eigvals))

            # Get steady state vector
            rho_vec = eigvecs[:, zero_idx]

            # Reshape to matrix
            rho_ss = rho_vec.reshape(self.dim, self.dim)

            # Ensure Hermitian and trace 1
            rho_ss = self._ensure_hermitian(rho_ss)
            rho_ss = self._ensure_trace(rho_ss)

            logger.info("Steady state found using direct method")
            return rho_ss

        except Exception as e:
            logger.warning(f"Direct method failed: {e}. Using iterative method.")

    # Iterative method (simple fixed-point iteration)
    # rho_{n+1} = rho_n + dt * Lindblad(rho_n)
    # We evolve until convergence

    dt = 0.01
    for iteration in range(max_iter):
        drho = self._lindblad_superoperator(rho)
        rho_new = rho + dt * drho

        # Ensure Hermitian and trace 1
        rho_new = self._ensure_hermitian(rho_new)
        rho_new = self._ensure_trace(rho_new)
        rho_new = self._project_positive(rho_new)

        # Check convergence
        diff = np.max(np.abs(rho_new - rho))
        rho = rho_new

        if diff < tol:
            logger.info(f"Steady state converged after {iteration + 1} iterations")
            return rho

    logger.warning(f"Steady state did not converge after {max_iter} iterations")
    return rho

get_steady_state_analytical()

Try to find the steady state analytically (for simple systems)

Returns:

Type Description
Optional[ndarray]

Optional[np.ndarray]: Steady state or None if not found

Source code in psiqit\dynamics\lindblad.py
def get_steady_state_analytical(self) -> Optional[np.ndarray]:
    """
    Try to find the steady state analytically (for simple systems)

    Returns:
        Optional[np.ndarray]: Steady state or None if not found
    """
    # For two-level systems, we can solve analytically
    if self.dim == 2 and len(self.collapse_ops) >= 1:
        # For a two-level system with one collapse operator
        # This is a simplified version
        try:
            rho_ss = self.steady_state(tol=1e-12, max_iter=1000)
            return rho_ss
        except:
            return None

    return None

MonteCarloResult dataclass

Result container for Monte Carlo quantum trajectories

Attributes:

Name Type Description
times ndarray

Time points

avg_states List[ndarray]

Average density matrices over trajectories

jump_times List[List[float]]

List of jump times for each trajectory

n_jumps List[int]

Number of jumps for each trajectory

success bool

Whether simulation was successful

message str

Additional information

n_trajectories int

Number of trajectories

n_steps int

Number of time steps

final_avg_state Optional[ndarray]

Final average density matrix

trajectories Optional[List[Dict]]

List of individual trajectory results

Source code in psiqit\dynamics\monte_carlo.py
@dataclass
class MonteCarloResult:
    """
    Result container for Monte Carlo quantum trajectories

    Attributes:
        times: Time points
        avg_states: Average density matrices over trajectories
        jump_times: List of jump times for each trajectory
        n_jumps: Number of jumps for each trajectory
        success: Whether simulation was successful
        message: Additional information
        n_trajectories: Number of trajectories
        n_steps: Number of time steps
        final_avg_state: Final average density matrix
        trajectories: List of individual trajectory results
    """
    times: np.ndarray
    avg_states: List[np.ndarray]
    jump_times: List[List[float]]
    n_jumps: List[int]
    success: bool = True
    message: str = ""
    n_trajectories: int = 0
    n_steps: int = 0
    final_avg_state: Optional[np.ndarray] = None
    trajectories: Optional[List[Dict]] = None

    def __post_init__(self):
        """Post-process the result"""
        self.n_steps = len(self.times)
        self.n_trajectories = len(self.n_jumps)

        if self.avg_states:
            self.final_avg_state = self.avg_states[-1]

    def get_avg_state_at_time(self, index: int) -> Optional[np.ndarray]:
        """Get average density matrix at a specific time index"""
        if 0 <= index < len(self.avg_states):
            return self.avg_states[index]
        return None

    def get_final_avg_state(self) -> Optional[np.ndarray]:
        """Get the final average density matrix"""
        return self.final_avg_state

    def get_total_jumps(self) -> int:
        """Get total number of jumps across all trajectories"""
        return sum(self.n_jumps)

    def get_jump_rate(self) -> float:
        """Get average jump rate per trajectory"""
        if self.n_trajectories == 0:
            return 0.0
        total_jumps = sum(self.n_jumps)
        return total_jumps / self.n_trajectories

    def get_population_evolution(self, state_index: int) -> List[float]:
        """
        Get the evolution of a specific population

        Args:
            state_index: Index of the state

        Returns:
            List[float]: Population values over time
        """
        if state_index < 0:
            raise ValueError(f"State index {state_index} must be >= 0")

        populations = []
        for rho in self.avg_states:
            if state_index < rho.shape[0]:
                populations.append(float(rho[state_index, state_index].real))
            else:
                populations.append(0.0)

        return populations

    def __repr__(self) -> str:
        status = "Success" if self.success else "Failed"
        return f"MonteCarloResult(trajectories={self.n_trajectories}, status={status}, total_jumps={self.get_total_jumps()})"

    def __str__(self) -> str:
        lines = [
            "Monte Carlo Quantum Trajectories Results:",
            f"  Trajectories: {self.n_trajectories}",
            f"  Steps: {self.n_steps}",
            f"  Success: {self.success}",
            f"  Message: {self.message}",
            f"  Total Jumps: {self.get_total_jumps()}",
            f"  Avg Jump Rate: {self.get_jump_rate():.3f}",
        ]
        if self.final_avg_state is not None:
            lines.append(f"  Final Avg State Trace: {np.trace(self.final_avg_state).real:.6f}")
        return "\n".join(lines)

__post_init__()

Post-process the result

Source code in psiqit\dynamics\monte_carlo.py
def __post_init__(self):
    """Post-process the result"""
    self.n_steps = len(self.times)
    self.n_trajectories = len(self.n_jumps)

    if self.avg_states:
        self.final_avg_state = self.avg_states[-1]

get_avg_state_at_time(index)

Get average density matrix at a specific time index

Source code in psiqit\dynamics\monte_carlo.py
def get_avg_state_at_time(self, index: int) -> Optional[np.ndarray]:
    """Get average density matrix at a specific time index"""
    if 0 <= index < len(self.avg_states):
        return self.avg_states[index]
    return None

get_final_avg_state()

Get the final average density matrix

Source code in psiqit\dynamics\monte_carlo.py
def get_final_avg_state(self) -> Optional[np.ndarray]:
    """Get the final average density matrix"""
    return self.final_avg_state

get_total_jumps()

Get total number of jumps across all trajectories

Source code in psiqit\dynamics\monte_carlo.py
def get_total_jumps(self) -> int:
    """Get total number of jumps across all trajectories"""
    return sum(self.n_jumps)

get_jump_rate()

Get average jump rate per trajectory

Source code in psiqit\dynamics\monte_carlo.py
def get_jump_rate(self) -> float:
    """Get average jump rate per trajectory"""
    if self.n_trajectories == 0:
        return 0.0
    total_jumps = sum(self.n_jumps)
    return total_jumps / self.n_trajectories

get_population_evolution(state_index)

Get the evolution of a specific population

Parameters:

Name Type Description Default
state_index int

Index of the state

required

Returns:

Type Description
List[float]

List[float]: Population values over time

Source code in psiqit\dynamics\monte_carlo.py
def get_population_evolution(self, state_index: int) -> List[float]:
    """
    Get the evolution of a specific population

    Args:
        state_index: Index of the state

    Returns:
        List[float]: Population values over time
    """
    if state_index < 0:
        raise ValueError(f"State index {state_index} must be >= 0")

    populations = []
    for rho in self.avg_states:
        if state_index < rho.shape[0]:
            populations.append(float(rho[state_index, state_index].real))
        else:
            populations.append(0.0)

    return populations

QuantumTrajectory

Quantum Monte Carlo trajectory simulation

Simulates stochastic quantum trajectories for open quantum systems. The method uses a Monte Carlo wavefunction approach where the evolution is a sequence of deterministic evolution and quantum jumps.

The non-Hermitian effective Hamiltonian is: H_eff = H - iħ/2 Σ_k γ_k L_k† L_k

Between jumps, the state evolves as: |ψ(t+dt)⟩ = (1 - iH_eff dt/ħ) |ψ(t)⟩ / ||...||

Jumps occur with probability: dp_k = γ_k dt ⟨ψ|L_k† L_k|ψ⟩

Example

from psiqit.quantum import pauli_z, pauli_x, zero H = pauli_z() L = pauli_x() qt = QuantumTrajectory(H, [L], gamma=[0.1]) result = qt.run(zero(), t_max=10.0, dt=0.01, n_trajectories=100) print(result.final_avg_state)

Source code in psiqit\dynamics\monte_carlo.py
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
class QuantumTrajectory:
    """
    Quantum Monte Carlo trajectory simulation

    Simulates stochastic quantum trajectories for open quantum systems.
    The method uses a Monte Carlo wavefunction approach where the
    evolution is a sequence of deterministic evolution and quantum jumps.

    The non-Hermitian effective Hamiltonian is:
    H_eff = H - iħ/2 Σ_k γ_k L_k† L_k

    Between jumps, the state evolves as:
    |ψ(t+dt)⟩ = (1 - iH_eff dt/ħ) |ψ(t)⟩ / ||...||

    Jumps occur with probability:
    dp_k = γ_k dt ⟨ψ|L_k† L_k|ψ⟩

    Example:
        >>> from psiqit.quantum import pauli_z, pauli_x, zero
        >>> H = pauli_z()
        >>> L = pauli_x()
        >>> qt = QuantumTrajectory(H, [L], gamma=[0.1])
        >>> result = qt.run(zero(), t_max=10.0, dt=0.01, n_trajectories=100)
        >>> print(result.final_avg_state)
    """

    def __init__(
        self,
        hamiltonian: Operator,
        collapse_ops: List[Operator],
        gamma: Optional[List[float]] = None,
        hbar: float = 1.0
    ):
        """
        Initialize quantum trajectory simulation

        Args:
            hamiltonian: System Hamiltonian (Hermitian)
            collapse_ops: List of collapse operators L_k
            gamma: List of decay rates for each collapse operator
                   If None, all rates are set to 1.0
            hbar: Reduced Planck constant

        Example:
            >>> H = pauli_z()
            >>> L = pauli_x()
            >>> qt = QuantumTrajectory(H, [L], gamma=[0.1])
        """
        if not hamiltonian.is_hermitian:
            logger.warning("Hamiltonian is not Hermitian")

        self.hamiltonian = hamiltonian
        self.collapse_ops = collapse_ops
        self.hbar = hbar
        self.dim = hamiltonian.dim

        # Set decay rates
        if gamma is None:
            self.gamma = [1.0] * len(collapse_ops)
        else:
            if len(gamma) != len(collapse_ops):
                raise ValueError(f"Number of gamma values {len(gamma)} does not match number of collapse operators {len(collapse_ops)}")
            self.gamma = gamma

        # Compute effective Hamiltonian
        self.H_eff = self._compute_effective_hamiltonian()

        logger.info(f"QuantumTrajectory initialized: dim={self.dim}, n_ops={len(collapse_ops)}")

    def _compute_effective_hamiltonian(self) -> np.ndarray:
        """
        Compute the effective non-Hermitian Hamiltonian

        H_eff = H - iħ/2 Σ_k γ_k L_k† L_k

        Returns:
            np.ndarray: Effective Hamiltonian matrix
        """
        H_eff = self.hamiltonian.data.copy()

        for L, gamma_k in zip(self.collapse_ops, self.gamma):
            L_dag_L = L.dagger() @ L
            H_eff -= 1j * self.hbar / 2 * gamma_k * L_dag_L.data

        return H_eff

    def _compute_jump_probabilities(self, psi: np.ndarray) -> List[float]:
        """
        Compute jump probabilities for each collapse operator

        dp_k = γ_k dt ⟨ψ|L_k† L_k|ψ⟩

        Args:
            psi: Current state vector

        Returns:
            List[float]: Jump probabilities (not multiplied by dt)
        """
        probs = []

        for L, gamma_k in zip(self.collapse_ops, self.gamma):
            L_dag_L = L.dagger() @ L
            prob_rate = gamma_k * np.vdot(psi, L_dag_L.data @ psi).real
            probs.append(prob_rate)

        return probs

    def _apply_jump(self, psi: np.ndarray, jump_idx: int) -> np.ndarray:
        """
        Apply a quantum jump to the state

        |ψ⟩ → L_k |ψ⟩ / ||L_k |ψ⟩||

        Args:
            psi: Current state vector
            jump_idx: Index of the collapse operator

        Returns:
            np.ndarray: New state vector after jump
        """
        L = self.collapse_ops[jump_idx]
        psi_new = L.data @ psi

        # Normalize
        norm = np.linalg.norm(psi_new)
        if norm > 0:
            psi_new = psi_new / norm
        else:
            logger.warning(f"Jump {jump_idx} resulted in zero state")
            psi_new = psi.copy()

        return psi_new

    def _evolve_deterministic(self, psi: np.ndarray, dt: float) -> np.ndarray:
        """
        Deterministic evolution under effective Hamiltonian

        |ψ(t+dt)⟩ = (1 - iH_eff dt/ħ) |ψ(t)⟩

        Args:
            psi: Current state vector
            dt: Time step

        Returns:
            np.ndarray: Evolved state (not normalized)
        """
        # First-order approximation
        psi_new = psi - 1j * self.H_eff @ psi * dt / self.hbar

        # Normalize
        norm = np.linalg.norm(psi_new)
        if norm > 0:
            psi_new = psi_new / norm

        return psi_new

    def _evolve_with_adaptive_step(
        self,
        psi: np.ndarray,
        t: float,
        dt: float
    ) -> Tuple[np.ndarray, float, bool]:
        """
        Evolve one step with adaptive time step

        Returns:
            Tuple: (new_state, actual_dt, jump_occurred)
        """
        # Compute jump probabilities
        jump_rates = self._compute_jump_probabilities(psi)
        total_rate = sum(jump_rates)

        # Check if jump occurs
        if total_rate > 0:
            # Generate random number for jump
            rand = np.random.random()

            # Jump probability in this time step
            jump_prob = 1 - np.exp(-total_rate * dt)

            if rand < jump_prob:
                # A jump occurs
                # Determine which jump
                cum_probs = np.cumsum(jump_rates)
                r = np.random.random() * total_rate

                jump_idx = 0
                for i, cum_prob in enumerate(cum_probs):
                    if r < cum_prob:
                        jump_idx = i
                        break

                # Apply jump
                psi_new = self._apply_jump(psi, jump_idx)

                # Evolve deterministically for the remaining time
                # (simplified: we just apply the jump and continue)
                return psi_new, dt, True

        # No jump: deterministic evolution
        psi_new = self._evolve_deterministic(psi, dt)
        return psi_new, dt, False

    def single_trajectory(
        self,
        psi0: Ket,
        t_max: float,
        dt: float = 0.01,
        seed: Optional[int] = None
    ) -> Dict[str, Any]:
        """
        Simulate a single quantum trajectory

        Args:
            psi0: Initial state
            t_max: Maximum evolution time
            dt: Time step
            seed: Random seed for reproducibility

        Returns:
            Dict: Trajectory results with states, jump times, etc.

        Example:
            >>> result = qt.single_trajectory(zero(), t_max=5.0, dt=0.01)
            >>> print(result['n_jumps'])
        """
        if seed is not None:
            np.random.seed(seed)

        if psi0.dim != self.dim:
            raise ValueError(f"State dimension {psi0.dim} does not match Hamiltonian dimension {self.dim}")

        logger.info(f"Starting single trajectory: t_max={t_max:.3f}, dt={dt:.4f}")

        # Number of steps
        n_steps = int(np.ceil(t_max / dt))
        dt_actual = t_max / n_steps

        # Initialize
        psi = psi0.data.copy()
        times = [0.0]
        states = [psi0.copy()]
        jump_times = []
        n_jumps = 0

        # Evolution
        for step in range(n_steps):
            t = step * dt_actual

            # Evolve with adaptive step (always using dt_actual for simplicity)
            psi_new, _, jump_occurred = self._evolve_with_adaptive_step(
                psi, t, dt_actual
            )

            if jump_occurred:
                jump_times.append(t + dt_actual)
                n_jumps += 1
                logger.debug(f"Jump occurred at t={t+dt_actual:.3f}")

            psi = psi_new

            # Store state
            if (step + 1) % max(1, n_steps // 100) == 0 or step == n_steps - 1:
                times.append((step + 1) * dt_actual)
                states.append(Ket(psi.copy()))

        logger.info(f"Single trajectory completed: {n_jumps} jumps")

        return {
            'times': times,
            'states': states,
            'jump_times': jump_times,
            'n_jumps': n_jumps,
            'final_state': states[-1] if states else None,
            'seed': seed
        }

    def run(
        self,
        psi0: Ket,
        t_max: float,
        dt: float = 0.01,
        n_trajectories: int = 100,
        seeds: Optional[List[int]] = None,
        progress: bool = True
    ) -> MonteCarloResult:
        """
        Run multiple quantum trajectories and average results

        Args:
            psi0: Initial state
            t_max: Maximum evolution time
            dt: Time step
            n_trajectories: Number of trajectories
            seeds: List of random seeds for each trajectory
            progress: Show progress bar

        Returns:
            MonteCarloResult: Averaged results

        Example:
            >>> result = qt.run(zero(), t_max=10.0, dt=0.01, n_trajectories=100)
            >>> print(result.final_avg_state)
        """
        logger.info(f"Running {n_trajectories} trajectories")

        # Generate seeds if not provided
        if seeds is None:
            seeds = [None] * n_trajectories
        elif len(seeds) != n_trajectories:
            raise ValueError(f"Number of seeds {len(seeds)} does not match number of trajectories {n_trajectories}")

        # Store all trajectories
        all_trajectories = []
        all_jump_times = []
        all_n_jumps = []

        # Average states storage
        n_steps = int(np.ceil(t_max / dt)) + 1
        avg_states = []
        times = np.linspace(0, t_max, n_steps)

        # Initialize average density matrix
        rho_avg = np.zeros((self.dim, self.dim), dtype=complex)

        # For each trajectory
        for traj_idx in range(n_trajectories):
            # Run single trajectory
            result = self.single_trajectory(psi0, t_max, dt, seed=seeds[traj_idx])

            # Store trajectory data
            all_trajectories.append(result)
            all_jump_times.append(result['jump_times'])
            all_n_jumps.append(result['n_jumps'])

            # Build density matrix from trajectory states
            # For now, we just accumulate the final state
            if result['final_state'] is not None:
                rho = np.outer(result['final_state'].data, result['final_state'].data.conj())
                rho_avg += rho / n_trajectories

            # Progress
            if progress and (traj_idx + 1) % max(1, n_trajectories // 10) == 0:
                logger.info(f"Progress: {traj_idx+1}/{n_trajectories} trajectories")

        # For a full implementation, we would average all states at each time
        # Here we build a simplified average
        avg_states = [rho_avg]  # Simplified: only final state

        logger.info(f"Monte Carlo simulation completed: {n_trajectories} trajectories")

        return MonteCarloResult(
            times=np.array([0.0, t_max]),
            avg_states=avg_states,
            jump_times=all_jump_times,
            n_jumps=all_n_jumps,
            success=True,
            message="Simulation completed successfully",
            n_trajectories=n_trajectories,
            trajectories=all_trajectories
        )

    def compute_steady_state_mc(
        self,
        psi0: Ket,
        t_max: float,
        dt: float = 0.01,
        n_trajectories: int = 100,
        averaging_start: float = 0.0
    ) -> np.ndarray:
        """
        Compute steady state using Monte Carlo wavefunction method

        Args:
            psi0: Initial state
            t_max: Maximum evolution time
            dt: Time step
            n_trajectories: Number of trajectories
            averaging_start: Time to start averaging (to skip transient)

        Returns:
            np.ndarray: Steady state density matrix
        """
        logger.info(f"Computing steady state with MC: {n_trajectories} trajectories")

        # Run trajectories
        result = self.run(psi0, t_max, dt, n_trajectories)

        # Average over final states
        rho_ss = np.zeros((self.dim, self.dim), dtype=complex)

        for traj in result.trajectories:
            if traj['final_state'] is not None:
                psi = traj['final_state'].data
                rho_ss += np.outer(psi, psi.conj()) / n_trajectories

        return rho_ss

__init__(hamiltonian, collapse_ops, gamma=None, hbar=1.0)

Initialize quantum trajectory simulation

Parameters:

Name Type Description Default
hamiltonian Operator

System Hamiltonian (Hermitian)

required
collapse_ops List[Operator]

List of collapse operators L_k

required
gamma Optional[List[float]]

List of decay rates for each collapse operator If None, all rates are set to 1.0

None
hbar float

Reduced Planck constant

1.0
Example

H = pauli_z() L = pauli_x() qt = QuantumTrajectory(H, [L], gamma=[0.1])

Source code in psiqit\dynamics\monte_carlo.py
def __init__(
    self,
    hamiltonian: Operator,
    collapse_ops: List[Operator],
    gamma: Optional[List[float]] = None,
    hbar: float = 1.0
):
    """
    Initialize quantum trajectory simulation

    Args:
        hamiltonian: System Hamiltonian (Hermitian)
        collapse_ops: List of collapse operators L_k
        gamma: List of decay rates for each collapse operator
               If None, all rates are set to 1.0
        hbar: Reduced Planck constant

    Example:
        >>> H = pauli_z()
        >>> L = pauli_x()
        >>> qt = QuantumTrajectory(H, [L], gamma=[0.1])
    """
    if not hamiltonian.is_hermitian:
        logger.warning("Hamiltonian is not Hermitian")

    self.hamiltonian = hamiltonian
    self.collapse_ops = collapse_ops
    self.hbar = hbar
    self.dim = hamiltonian.dim

    # Set decay rates
    if gamma is None:
        self.gamma = [1.0] * len(collapse_ops)
    else:
        if len(gamma) != len(collapse_ops):
            raise ValueError(f"Number of gamma values {len(gamma)} does not match number of collapse operators {len(collapse_ops)}")
        self.gamma = gamma

    # Compute effective Hamiltonian
    self.H_eff = self._compute_effective_hamiltonian()

    logger.info(f"QuantumTrajectory initialized: dim={self.dim}, n_ops={len(collapse_ops)}")

single_trajectory(psi0, t_max, dt=0.01, seed=None)

Simulate a single quantum trajectory

Parameters:

Name Type Description Default
psi0 Ket

Initial state

required
t_max float

Maximum evolution time

required
dt float

Time step

0.01
seed Optional[int]

Random seed for reproducibility

None

Returns:

Name Type Description
Dict Dict[str, Any]

Trajectory results with states, jump times, etc.

Example

result = qt.single_trajectory(zero(), t_max=5.0, dt=0.01) print(result['n_jumps'])

Source code in psiqit\dynamics\monte_carlo.py
def single_trajectory(
    self,
    psi0: Ket,
    t_max: float,
    dt: float = 0.01,
    seed: Optional[int] = None
) -> Dict[str, Any]:
    """
    Simulate a single quantum trajectory

    Args:
        psi0: Initial state
        t_max: Maximum evolution time
        dt: Time step
        seed: Random seed for reproducibility

    Returns:
        Dict: Trajectory results with states, jump times, etc.

    Example:
        >>> result = qt.single_trajectory(zero(), t_max=5.0, dt=0.01)
        >>> print(result['n_jumps'])
    """
    if seed is not None:
        np.random.seed(seed)

    if psi0.dim != self.dim:
        raise ValueError(f"State dimension {psi0.dim} does not match Hamiltonian dimension {self.dim}")

    logger.info(f"Starting single trajectory: t_max={t_max:.3f}, dt={dt:.4f}")

    # Number of steps
    n_steps = int(np.ceil(t_max / dt))
    dt_actual = t_max / n_steps

    # Initialize
    psi = psi0.data.copy()
    times = [0.0]
    states = [psi0.copy()]
    jump_times = []
    n_jumps = 0

    # Evolution
    for step in range(n_steps):
        t = step * dt_actual

        # Evolve with adaptive step (always using dt_actual for simplicity)
        psi_new, _, jump_occurred = self._evolve_with_adaptive_step(
            psi, t, dt_actual
        )

        if jump_occurred:
            jump_times.append(t + dt_actual)
            n_jumps += 1
            logger.debug(f"Jump occurred at t={t+dt_actual:.3f}")

        psi = psi_new

        # Store state
        if (step + 1) % max(1, n_steps // 100) == 0 or step == n_steps - 1:
            times.append((step + 1) * dt_actual)
            states.append(Ket(psi.copy()))

    logger.info(f"Single trajectory completed: {n_jumps} jumps")

    return {
        'times': times,
        'states': states,
        'jump_times': jump_times,
        'n_jumps': n_jumps,
        'final_state': states[-1] if states else None,
        'seed': seed
    }

run(psi0, t_max, dt=0.01, n_trajectories=100, seeds=None, progress=True)

Run multiple quantum trajectories and average results

Parameters:

Name Type Description Default
psi0 Ket

Initial state

required
t_max float

Maximum evolution time

required
dt float

Time step

0.01
n_trajectories int

Number of trajectories

100
seeds Optional[List[int]]

List of random seeds for each trajectory

None
progress bool

Show progress bar

True

Returns:

Name Type Description
MonteCarloResult MonteCarloResult

Averaged results

Example

result = qt.run(zero(), t_max=10.0, dt=0.01, n_trajectories=100) print(result.final_avg_state)

Source code in psiqit\dynamics\monte_carlo.py
def run(
    self,
    psi0: Ket,
    t_max: float,
    dt: float = 0.01,
    n_trajectories: int = 100,
    seeds: Optional[List[int]] = None,
    progress: bool = True
) -> MonteCarloResult:
    """
    Run multiple quantum trajectories and average results

    Args:
        psi0: Initial state
        t_max: Maximum evolution time
        dt: Time step
        n_trajectories: Number of trajectories
        seeds: List of random seeds for each trajectory
        progress: Show progress bar

    Returns:
        MonteCarloResult: Averaged results

    Example:
        >>> result = qt.run(zero(), t_max=10.0, dt=0.01, n_trajectories=100)
        >>> print(result.final_avg_state)
    """
    logger.info(f"Running {n_trajectories} trajectories")

    # Generate seeds if not provided
    if seeds is None:
        seeds = [None] * n_trajectories
    elif len(seeds) != n_trajectories:
        raise ValueError(f"Number of seeds {len(seeds)} does not match number of trajectories {n_trajectories}")

    # Store all trajectories
    all_trajectories = []
    all_jump_times = []
    all_n_jumps = []

    # Average states storage
    n_steps = int(np.ceil(t_max / dt)) + 1
    avg_states = []
    times = np.linspace(0, t_max, n_steps)

    # Initialize average density matrix
    rho_avg = np.zeros((self.dim, self.dim), dtype=complex)

    # For each trajectory
    for traj_idx in range(n_trajectories):
        # Run single trajectory
        result = self.single_trajectory(psi0, t_max, dt, seed=seeds[traj_idx])

        # Store trajectory data
        all_trajectories.append(result)
        all_jump_times.append(result['jump_times'])
        all_n_jumps.append(result['n_jumps'])

        # Build density matrix from trajectory states
        # For now, we just accumulate the final state
        if result['final_state'] is not None:
            rho = np.outer(result['final_state'].data, result['final_state'].data.conj())
            rho_avg += rho / n_trajectories

        # Progress
        if progress and (traj_idx + 1) % max(1, n_trajectories // 10) == 0:
            logger.info(f"Progress: {traj_idx+1}/{n_trajectories} trajectories")

    # For a full implementation, we would average all states at each time
    # Here we build a simplified average
    avg_states = [rho_avg]  # Simplified: only final state

    logger.info(f"Monte Carlo simulation completed: {n_trajectories} trajectories")

    return MonteCarloResult(
        times=np.array([0.0, t_max]),
        avg_states=avg_states,
        jump_times=all_jump_times,
        n_jumps=all_n_jumps,
        success=True,
        message="Simulation completed successfully",
        n_trajectories=n_trajectories,
        trajectories=all_trajectories
    )

compute_steady_state_mc(psi0, t_max, dt=0.01, n_trajectories=100, averaging_start=0.0)

Compute steady state using Monte Carlo wavefunction method

Parameters:

Name Type Description Default
psi0 Ket

Initial state

required
t_max float

Maximum evolution time

required
dt float

Time step

0.01
n_trajectories int

Number of trajectories

100
averaging_start float

Time to start averaging (to skip transient)

0.0

Returns:

Type Description
ndarray

np.ndarray: Steady state density matrix

Source code in psiqit\dynamics\monte_carlo.py
def compute_steady_state_mc(
    self,
    psi0: Ket,
    t_max: float,
    dt: float = 0.01,
    n_trajectories: int = 100,
    averaging_start: float = 0.0
) -> np.ndarray:
    """
    Compute steady state using Monte Carlo wavefunction method

    Args:
        psi0: Initial state
        t_max: Maximum evolution time
        dt: Time step
        n_trajectories: Number of trajectories
        averaging_start: Time to start averaging (to skip transient)

    Returns:
        np.ndarray: Steady state density matrix
    """
    logger.info(f"Computing steady state with MC: {n_trajectories} trajectories")

    # Run trajectories
    result = self.run(psi0, t_max, dt, n_trajectories)

    # Average over final states
    rho_ss = np.zeros((self.dim, self.dim), dtype=complex)

    for traj in result.trajectories:
        if traj['final_state'] is not None:
            psi = traj['final_state'].data
            rho_ss += np.outer(psi, psi.conj()) / n_trajectories

    return rho_ss

WaveFunction

Wavefunction representation for quantum mechanics

Represents a wavefunction ψ(x, t) with methods for computing expectation values, uncertainties, and probability densities.

Example

import numpy as np x = np.linspace(-5, 5, 100) psi = np.exp(-x**2/2) / np.sqrt(np.sqrt(np.pi)) wf = WaveFunction(x, psi) print(wf.expectation_x()) # 0.0 print(wf.uncertainty_x()) # 0.707

Source code in psiqit\dynamics\schrodinger.py
class WaveFunction:
    """
    Wavefunction representation for quantum mechanics

    Represents a wavefunction ψ(x, t) with methods for computing
    expectation values, uncertainties, and probability densities.

    Example:
        >>> import numpy as np
        >>> x = np.linspace(-5, 5, 100)
        >>> psi = np.exp(-x**2/2) / np.sqrt(np.sqrt(np.pi))
        >>> wf = WaveFunction(x, psi)
        >>> print(wf.expectation_x())  # 0.0
        >>> print(wf.uncertainty_x())  # 0.707
    """

    def __init__(self, x: np.ndarray, psi: np.ndarray, t: float = 0.0):
        """
        Initialize a wavefunction

        Args:
            x: Spatial grid
            psi: Wavefunction values (complex)
            t: Time (default: 0.0)
        """
        self.x = np.array(x, dtype=float)
        self.psi = np.array(psi, dtype=complex)
        self.t = t
        self.dx = self.x[1] - self.x[0] if len(self.x) > 1 else 0.01

        # Ensure normalization
        self.normalize()

        logger.debug(f"WaveFunction initialized: {len(x)} points, t={t:.3f}")

    def probability_density(self) -> np.ndarray:
        """
        Compute the probability density |ψ(x)|²

        Returns:
            np.ndarray: Probability density
        """
        return np.abs(self.psi) ** 2

    def normalize(self) -> 'WaveFunction':
        """
        Normalize the wavefunction so that ∫|ψ|² dx = 1

        Returns:
            WaveFunction: Self for chaining
        """
        norm = np.sqrt(np.sum(np.abs(self.psi) ** 2) * self.dx)
        if norm > 0:
            self.psi = self.psi / norm
        return self

    def expectation_x(self) -> float:
        """
        Compute expectation value of position ⟨x⟩

        Returns:
            float: ⟨x⟩
        """
        prob = self.probability_density()
        return float(np.sum(self.x * prob) * self.dx)

    def expectation_p(self, hbar: float = 1.0) -> float:
        """
        Compute expectation value of momentum ⟨p⟩

        ⟨p⟩ = -iħ ∫ ψ* ∂ψ/∂x dx

        Args:
            hbar: Reduced Planck constant

        Returns:
            float: ⟨p⟩
        """
        # Compute derivative using finite differences
        dpsi = np.gradient(self.psi, self.dx)

        # ⟨p⟩ = -iħ ∫ ψ* ∂ψ/∂x dx
        integrand = np.conj(self.psi) * dpsi
        return float(-1j * hbar * np.sum(integrand) * self.dx).real

    def expectation_x2(self) -> float:
        """
        Compute expectation value of x² ⟨x²⟩

        Returns:
            float: ⟨x²⟩
        """
        prob = self.probability_density()
        return float(np.sum(self.x**2 * prob) * self.dx)

    def expectation_p2(self, hbar: float = 1.0) -> float:
        """
        Compute expectation value of p² ⟨p²⟩

        ⟨p²⟩ = -ħ² ∫ ψ* ∂²ψ/∂x² dx

        Args:
            hbar: Reduced Planck constant

        Returns:
            float: ⟨p²⟩
        """
        # Compute second derivative
        d2psi = np.gradient(np.gradient(self.psi, self.dx), self.dx)

        # ⟨p²⟩ = -ħ² ∫ ψ* ∂²ψ/∂x² dx
        integrand = np.conj(self.psi) * d2psi
        return float(-hbar**2 * np.sum(integrand) * self.dx).real

    def uncertainty_x(self) -> float:
        """
        Compute uncertainty in position Δx = √(⟨x²⟩ - ⟨x⟩²)

        Returns:
            float: Δx
        """
        ex = self.expectation_x()
        ex2 = self.expectation_x2()
        return np.sqrt(max(0, ex2 - ex**2))

    def uncertainty_p(self, hbar: float = 1.0) -> float:
        """
        Compute uncertainty in momentum Δp = √(⟨p²⟩ - ⟨p⟩²)

        Args:
            hbar: Reduced Planck constant

        Returns:
            float: Δp
        """
        ep = self.expectation_p(hbar)
        ep2 = self.expectation_p2(hbar)
        return np.sqrt(max(0, ep2 - ep**2))

    def uncertainty_product(self, hbar: float = 1.0) -> float:
        """
        Compute the product of uncertainties Δx * Δp

        Args:
            hbar: Reduced Planck constant

        Returns:
            float: Δx * Δp (should be >= ħ/2)
        """
        dx = self.uncertainty_x()
        dp = self.uncertainty_p(hbar)
        return dx * dp

    def kinetic_energy(self, mass: float = 1.0, hbar: float = 1.0) -> float:
        """
        Compute kinetic energy ⟨p²⟩/(2m)

        Args:
            mass: Particle mass
            hbar: Reduced Planck constant

        Returns:
            float: Kinetic energy
        """
        ep2 = self.expectation_p2(hbar)
        return ep2 / (2 * mass)

    def potential_energy(self, potential: Callable[[float], float]) -> float:
        """
        Compute potential energy ⟨V(x)⟩

        Args:
            potential: Potential function V(x)

        Returns:
            float: Potential energy
        """
        prob = self.probability_density()
        V = potential(self.x)
        return float(np.sum(V * prob) * self.dx)

    def total_energy(self, potential: Callable[[float], float],
                     mass: float = 1.0, hbar: float = 1.0) -> float:
        """
        Compute total energy ⟨H⟩ = ⟨p²⟩/(2m) + ⟨V(x)⟩

        Args:
            potential: Potential function V(x)
            mass: Particle mass
            hbar: Reduced Planck constant

        Returns:
            float: Total energy
        """
        return self.kinetic_energy(mass, hbar) + self.potential_energy(potential)

    def expectation_value(self, operator: Callable[[np.ndarray], np.ndarray]) -> float:
        """
        Compute expectation value of a general operator

        ⟨O⟩ = ∫ ψ* O ψ dx

        Args:
            operator: Operator function acting on wavefunction

        Returns:
            float: Expectation value
        """
        O_psi = operator(self.psi)
        return float(np.sum(np.conj(self.psi) * O_psi) * self.dx).real

    def copy(self) -> 'WaveFunction':
        """Create a copy of the wavefunction"""
        return WaveFunction(self.x.copy(), self.psi.copy(), self.t)

    def __repr__(self) -> str:
        return f"WaveFunction(n_points={len(self.x)}, t={self.t:.3f})"

    def __str__(self) -> str:
        return f"WaveFunction at t={self.t:.3f}, norm={np.sqrt(np.sum(np.abs(self.psi)**2) * self.dx):.6f}"

__init__(x, psi, t=0.0)

Initialize a wavefunction

Parameters:

Name Type Description Default
x ndarray

Spatial grid

required
psi ndarray

Wavefunction values (complex)

required
t float

Time (default: 0.0)

0.0
Source code in psiqit\dynamics\schrodinger.py
def __init__(self, x: np.ndarray, psi: np.ndarray, t: float = 0.0):
    """
    Initialize a wavefunction

    Args:
        x: Spatial grid
        psi: Wavefunction values (complex)
        t: Time (default: 0.0)
    """
    self.x = np.array(x, dtype=float)
    self.psi = np.array(psi, dtype=complex)
    self.t = t
    self.dx = self.x[1] - self.x[0] if len(self.x) > 1 else 0.01

    # Ensure normalization
    self.normalize()

    logger.debug(f"WaveFunction initialized: {len(x)} points, t={t:.3f}")

probability_density()

Compute the probability density |ψ(x)|²

Returns:

Type Description
ndarray

np.ndarray: Probability density

Source code in psiqit\dynamics\schrodinger.py
def probability_density(self) -> np.ndarray:
    """
    Compute the probability density |ψ(x)|²

    Returns:
        np.ndarray: Probability density
    """
    return np.abs(self.psi) ** 2

normalize()

Normalize the wavefunction so that ∫|ψ|² dx = 1

Returns:

Name Type Description
WaveFunction WaveFunction

Self for chaining

Source code in psiqit\dynamics\schrodinger.py
def normalize(self) -> 'WaveFunction':
    """
    Normalize the wavefunction so that ∫|ψ|² dx = 1

    Returns:
        WaveFunction: Self for chaining
    """
    norm = np.sqrt(np.sum(np.abs(self.psi) ** 2) * self.dx)
    if norm > 0:
        self.psi = self.psi / norm
    return self

expectation_x()

Compute expectation value of position ⟨x⟩

Returns:

Name Type Description
float float

⟨x⟩

Source code in psiqit\dynamics\schrodinger.py
def expectation_x(self) -> float:
    """
    Compute expectation value of position ⟨x⟩

    Returns:
        float: ⟨x⟩
    """
    prob = self.probability_density()
    return float(np.sum(self.x * prob) * self.dx)

expectation_p(hbar=1.0)

Compute expectation value of momentum ⟨p⟩

⟨p⟩ = -iħ ∫ ψ* ∂ψ/∂x dx

Parameters:

Name Type Description Default
hbar float

Reduced Planck constant

1.0

Returns:

Name Type Description
float float

⟨p⟩

Source code in psiqit\dynamics\schrodinger.py
def expectation_p(self, hbar: float = 1.0) -> float:
    """
    Compute expectation value of momentum ⟨p⟩

    ⟨p⟩ = -iħ ∫ ψ* ∂ψ/∂x dx

    Args:
        hbar: Reduced Planck constant

    Returns:
        float: ⟨p⟩
    """
    # Compute derivative using finite differences
    dpsi = np.gradient(self.psi, self.dx)

    # ⟨p⟩ = -iħ ∫ ψ* ∂ψ/∂x dx
    integrand = np.conj(self.psi) * dpsi
    return float(-1j * hbar * np.sum(integrand) * self.dx).real

expectation_x2()

Compute expectation value of x² ⟨x²⟩

Returns:

Name Type Description
float float

⟨x²⟩

Source code in psiqit\dynamics\schrodinger.py
def expectation_x2(self) -> float:
    """
    Compute expectation value of x² ⟨x²⟩

    Returns:
        float: ⟨x²⟩
    """
    prob = self.probability_density()
    return float(np.sum(self.x**2 * prob) * self.dx)

expectation_p2(hbar=1.0)

Compute expectation value of p² ⟨p²⟩

⟨p²⟩ = -ħ² ∫ ψ* ∂²ψ/∂x² dx

Parameters:

Name Type Description Default
hbar float

Reduced Planck constant

1.0

Returns:

Name Type Description
float float

⟨p²⟩

Source code in psiqit\dynamics\schrodinger.py
def expectation_p2(self, hbar: float = 1.0) -> float:
    """
    Compute expectation value of p² ⟨p²⟩

    ⟨p²⟩ = -ħ² ∫ ψ* ∂²ψ/∂x² dx

    Args:
        hbar: Reduced Planck constant

    Returns:
        float: ⟨p²⟩
    """
    # Compute second derivative
    d2psi = np.gradient(np.gradient(self.psi, self.dx), self.dx)

    # ⟨p²⟩ = -ħ² ∫ ψ* ∂²ψ/∂x² dx
    integrand = np.conj(self.psi) * d2psi
    return float(-hbar**2 * np.sum(integrand) * self.dx).real

uncertainty_x()

Compute uncertainty in position Δx = √(⟨x²⟩ - ⟨x⟩²)

Returns:

Name Type Description
float float

Δx

Source code in psiqit\dynamics\schrodinger.py
def uncertainty_x(self) -> float:
    """
    Compute uncertainty in position Δx = √(⟨x²⟩ - ⟨x⟩²)

    Returns:
        float: Δx
    """
    ex = self.expectation_x()
    ex2 = self.expectation_x2()
    return np.sqrt(max(0, ex2 - ex**2))

uncertainty_p(hbar=1.0)

Compute uncertainty in momentum Δp = √(⟨p²⟩ - ⟨p⟩²)

Parameters:

Name Type Description Default
hbar float

Reduced Planck constant

1.0

Returns:

Name Type Description
float float

Δp

Source code in psiqit\dynamics\schrodinger.py
def uncertainty_p(self, hbar: float = 1.0) -> float:
    """
    Compute uncertainty in momentum Δp = √(⟨p²⟩ - ⟨p⟩²)

    Args:
        hbar: Reduced Planck constant

    Returns:
        float: Δp
    """
    ep = self.expectation_p(hbar)
    ep2 = self.expectation_p2(hbar)
    return np.sqrt(max(0, ep2 - ep**2))

uncertainty_product(hbar=1.0)

Compute the product of uncertainties Δx * Δp

Parameters:

Name Type Description Default
hbar float

Reduced Planck constant

1.0

Returns:

Name Type Description
float float

Δx * Δp (should be >= ħ/2)

Source code in psiqit\dynamics\schrodinger.py
def uncertainty_product(self, hbar: float = 1.0) -> float:
    """
    Compute the product of uncertainties Δx * Δp

    Args:
        hbar: Reduced Planck constant

    Returns:
        float: Δx * Δp (should be >= ħ/2)
    """
    dx = self.uncertainty_x()
    dp = self.uncertainty_p(hbar)
    return dx * dp

kinetic_energy(mass=1.0, hbar=1.0)

Compute kinetic energy ⟨p²⟩/(2m)

Parameters:

Name Type Description Default
mass float

Particle mass

1.0
hbar float

Reduced Planck constant

1.0

Returns:

Name Type Description
float float

Kinetic energy

Source code in psiqit\dynamics\schrodinger.py
def kinetic_energy(self, mass: float = 1.0, hbar: float = 1.0) -> float:
    """
    Compute kinetic energy ⟨p²⟩/(2m)

    Args:
        mass: Particle mass
        hbar: Reduced Planck constant

    Returns:
        float: Kinetic energy
    """
    ep2 = self.expectation_p2(hbar)
    return ep2 / (2 * mass)

potential_energy(potential)

Compute potential energy ⟨V(x)⟩

Parameters:

Name Type Description Default
potential Callable[[float], float]

Potential function V(x)

required

Returns:

Name Type Description
float float

Potential energy

Source code in psiqit\dynamics\schrodinger.py
def potential_energy(self, potential: Callable[[float], float]) -> float:
    """
    Compute potential energy ⟨V(x)⟩

    Args:
        potential: Potential function V(x)

    Returns:
        float: Potential energy
    """
    prob = self.probability_density()
    V = potential(self.x)
    return float(np.sum(V * prob) * self.dx)

total_energy(potential, mass=1.0, hbar=1.0)

Compute total energy ⟨H⟩ = ⟨p²⟩/(2m) + ⟨V(x)⟩

Parameters:

Name Type Description Default
potential Callable[[float], float]

Potential function V(x)

required
mass float

Particle mass

1.0
hbar float

Reduced Planck constant

1.0

Returns:

Name Type Description
float float

Total energy

Source code in psiqit\dynamics\schrodinger.py
def total_energy(self, potential: Callable[[float], float],
                 mass: float = 1.0, hbar: float = 1.0) -> float:
    """
    Compute total energy ⟨H⟩ = ⟨p²⟩/(2m) + ⟨V(x)⟩

    Args:
        potential: Potential function V(x)
        mass: Particle mass
        hbar: Reduced Planck constant

    Returns:
        float: Total energy
    """
    return self.kinetic_energy(mass, hbar) + self.potential_energy(potential)

expectation_value(operator)

Compute expectation value of a general operator

⟨O⟩ = ∫ ψ* O ψ dx

Parameters:

Name Type Description Default
operator Callable[[ndarray], ndarray]

Operator function acting on wavefunction

required

Returns:

Name Type Description
float float

Expectation value

Source code in psiqit\dynamics\schrodinger.py
def expectation_value(self, operator: Callable[[np.ndarray], np.ndarray]) -> float:
    """
    Compute expectation value of a general operator

    ⟨O⟩ = ∫ ψ* O ψ dx

    Args:
        operator: Operator function acting on wavefunction

    Returns:
        float: Expectation value
    """
    O_psi = operator(self.psi)
    return float(np.sum(np.conj(self.psi) * O_psi) * self.dx).real

copy()

Create a copy of the wavefunction

Source code in psiqit\dynamics\schrodinger.py
def copy(self) -> 'WaveFunction':
    """Create a copy of the wavefunction"""
    return WaveFunction(self.x.copy(), self.psi.copy(), self.t)

EvolutionResult dataclass

Result container for time evolution

Attributes:

Name Type Description
times ndarray

Time points

states List[Ket]

List of quantum states at each time

fidelities List[float]

List of fidelities with initial state

success bool

Whether evolution was successful

message str

Additional information

n_steps int

Number of time steps

final_state Optional[Ket]

Final state

initial_state Optional[Ket]

Initial state

method str

Method used for evolution

Source code in psiqit\dynamics\time_evolution.py
@dataclass
class EvolutionResult:
    """
    Result container for time evolution

    Attributes:
        times: Time points
        states: List of quantum states at each time
        fidelities: List of fidelities with initial state
        success: Whether evolution was successful
        message: Additional information
        n_steps: Number of time steps
        final_state: Final state
        initial_state: Initial state
        method: Method used for evolution
    """
    times: np.ndarray
    states: List[Ket]
    fidelities: List[float]
    success: bool = True
    message: str = ""
    n_steps: int = 0
    final_state: Optional[Ket] = None
    initial_state: Optional[Ket] = None
    method: str = ""

    def __post_init__(self):
        """Post-process the result"""
        self.n_steps = len(self.times)

        if self.states:
            self.initial_state = self.states[0]
            self.final_state = self.states[-1]

    def get_state_at_time(self, index: int) -> Optional[Ket]:
        """Get state at a specific time index"""
        if 0 <= index < len(self.states):
            return self.states[index]
        return None

    def get_final_state(self) -> Optional[Ket]:
        """Get the final state"""
        return self.final_state

    def get_fidelity_history(self) -> np.ndarray:
        """Get the fidelity history array"""
        return np.array(self.fidelities)

    def get_population(self, basis_state: int) -> List[float]:
        """
        Get population of a basis state over time

        Args:
            basis_state: Index of the basis state

        Returns:
            List[float]: Population values over time
        """
        populations = []
        for state in self.states:
            if basis_state < len(state.data):
                populations.append(float(np.abs(state.data[basis_state]) ** 2))
            else:
                populations.append(0.0)
        return populations

    def __repr__(self) -> str:
        status = "Success" if self.success else "Failed"
        return f"EvolutionResult(steps={self.n_steps}, status={status}, method={self.method})"

    def __str__(self) -> str:
        lines = [
            "Time Evolution Results:",
            f"  Method: {self.method}",
            f"  Steps: {self.n_steps}",
            f"  Success: {self.success}",
            f"  Message: {self.message}",
        ]
        if self.final_state is not None:
            lines.append(f"  Final Fidelity: {self.fidelities[-1]:.6f}" if self.fidelities else "  Final Fidelity: N/A")
        return "\n".join(lines)

__post_init__()

Post-process the result

Source code in psiqit\dynamics\time_evolution.py
def __post_init__(self):
    """Post-process the result"""
    self.n_steps = len(self.times)

    if self.states:
        self.initial_state = self.states[0]
        self.final_state = self.states[-1]

get_state_at_time(index)

Get state at a specific time index

Source code in psiqit\dynamics\time_evolution.py
def get_state_at_time(self, index: int) -> Optional[Ket]:
    """Get state at a specific time index"""
    if 0 <= index < len(self.states):
        return self.states[index]
    return None

get_final_state()

Get the final state

Source code in psiqit\dynamics\time_evolution.py
def get_final_state(self) -> Optional[Ket]:
    """Get the final state"""
    return self.final_state

get_fidelity_history()

Get the fidelity history array

Source code in psiqit\dynamics\time_evolution.py
def get_fidelity_history(self) -> np.ndarray:
    """Get the fidelity history array"""
    return np.array(self.fidelities)

get_population(basis_state)

Get population of a basis state over time

Parameters:

Name Type Description Default
basis_state int

Index of the basis state

required

Returns:

Type Description
List[float]

List[float]: Population values over time

Source code in psiqit\dynamics\time_evolution.py
def get_population(self, basis_state: int) -> List[float]:
    """
    Get population of a basis state over time

    Args:
        basis_state: Index of the basis state

    Returns:
        List[float]: Population values over time
    """
    populations = []
    for state in self.states:
        if basis_state < len(state.data):
            populations.append(float(np.abs(state.data[basis_state]) ** 2))
        else:
            populations.append(0.0)
    return populations

TrotterEvolution

Trotter-Suzuki decomposition for quantum time evolution

Implements the Trotter-Suzuki approximation: e^{-iHt} ≈ (e^{-iH₁t/n} e^{-iH₂t/n} ... e^{-iH_kt/n})^n

Example

from psiqit.quantum import pauli_x, pauli_z, zero H = pauli_x() + pauli_z() trotter = TrotterEvolution(H, n_steps=100, decomposition='first') state = trotter.evolve(zero(), t=1.0) print(state)

Source code in psiqit\dynamics\time_evolution.py
class TrotterEvolution:
    """
    Trotter-Suzuki decomposition for quantum time evolution

    Implements the Trotter-Suzuki approximation:
    e^{-iHt} ≈ (e^{-iH₁t/n} e^{-iH₂t/n} ... e^{-iH_kt/n})^n

    Example:
        >>> from psiqit.quantum import pauli_x, pauli_z, zero
        >>> H = pauli_x() + pauli_z()
        >>> trotter = TrotterEvolution(H, n_steps=100, decomposition='first')
        >>> state = trotter.evolve(zero(), t=1.0)
        >>> print(state)
    """

    def __init__(
        self,
        hamiltonian: Operator,
        n_steps: int = 100,
        decomposition: str = 'first',
        hbar: float = 1.0
    ):
        """
        Initialize Trotter evolution

        Args:
            hamiltonian: Hamiltonian operator (can be sum of terms)
            n_steps: Number of Trotter steps
            decomposition: 'first' (first-order) or 'second' (second-order)
            hbar: Reduced Planck constant

        Example:
            >>> H = pauli_x() + pauli_z()
            >>> trotter = TrotterEvolution(H, n_steps=100, decomposition='first')
        """
        if not hamiltonian.is_hermitian:
            logger.warning("Hamiltonian is not Hermitian")

        self.hamiltonian = hamiltonian
        self.n_steps = n_steps
        self.decomposition = decomposition
        self.hbar = hbar
        self.dim = hamiltonian.dim

        # Decompose Hamiltonian into terms
        self.terms = self._decompose_hamiltonian(hamiltonian)

        logger.info(f"TrotterEvolution initialized: dim={self.dim}, steps={n_steps}, decomposition={decomposition}")

    def _decompose_hamiltonian(self, H: Operator) -> List[Operator]:
        """
        Decompose Hamiltonian into terms for Trotterization

        For now, we treat the Hamiltonian as a single term.
        In a more sophisticated implementation, we would split into
        kinetic and potential parts.

        Args:
            H: Hamiltonian operator

        Returns:
            List[Operator]: List of Hamiltonian terms
        """
        # Simple decomposition: treat as single term
        # For more complex Hamiltonians, this should be extended
        return [H]

    def _apply_trotter_step(self, psi: np.ndarray, dt: float) -> np.ndarray:
        """
        Apply a single Trotter step

        Args:
            psi: State vector
            dt: Time step

        Returns:
            np.ndarray: Evolved state
        """
        if self.decomposition == 'first':
            # First-order: e^{-iHdt} ≈ ∏ e^{-iH_i dt}
            for term in self.terms:
                U = expm(Operator(-1j * term.data * dt / self.hbar))
                psi = U.data @ psi
        elif self.decomposition == 'second':
            # Second-order: e^{-iHdt} ≈ e^{-iH_1 dt/2} e^{-iH_2 dt} e^{-iH_1 dt/2}
            # For two terms
            if len(self.terms) == 2:
                dt_half = dt / 2
                U1 = expm(Operator(-1j * self.terms[0].data * dt_half / self.hbar))
                U2 = expm(Operator(-1j * self.terms[1].data * dt / self.hbar))
                U3 = expm(Operator(-1j * self.terms[0].data * dt_half / self.hbar))
                psi = U1.data @ psi
                psi = U2.data @ psi
                psi = U3.data @ psi
            else:
                # Fallback to first-order for more terms
                logger.warning("Second-order Trotter only supports 2 terms, falling back to first-order")
                for term in self.terms:
                    U = expm(Operator(-1j * term.data * dt / self.hbar))
                    psi = U.data @ psi
        else:
            raise ValueError(f"Unknown decomposition: {self.decomposition}")

        return psi

    def evolve(self, psi0: Ket, t: float) -> Ket:
        """
        Evolve a state using Trotter decomposition

        Args:
            psi0: Initial state
            t: Evolution time

        Returns:
            Ket: Evolved state

        Example:
            >>> state = trotter.evolve(zero(), t=1.0)
        """
        if psi0.dim != self.dim:
            raise ValueError(f"State dimension {psi0.dim} does not match Hamiltonian dimension {self.dim}")

        logger.debug(f"Trotter evolution: t={t:.3f}, steps={self.n_steps}")

        dt = t / self.n_steps
        psi = psi0.data.copy()

        for step in range(self.n_steps):
            psi = self._apply_trotter_step(psi, dt)

            # Normalize
            norm = np.linalg.norm(psi)
            if norm > 0:
                psi = psi / norm

        logger.info(f"Trotter evolution completed: {self.n_steps} steps")

        return Ket(psi)

    def evolve_sequence(
        self,
        psi0: Ket,
        times: np.ndarray
    ) -> EvolutionResult:
        """
        Evolve a state at multiple time points

        Args:
            psi0: Initial state
            times: Array of time points

        Returns:
            EvolutionResult: Evolution results
        """
        logger.info(f"Trotter evolution sequence for {len(times)} time points")

        states = []
        fidelities = []
        success = True
        message = "Evolution completed successfully"

        try:
            for t in times:
                psi_t = self.evolve(psi0, t)
                states.append(psi_t)

                # Fidelity with initial state
                fid = abs(np.vdot(psi0.data, psi_t.data)) ** 2
                fidelities.append(float(fid))

        except Exception as e:
            success = False
            message = f"Evolution failed: {str(e)}"
            logger.error(message)

        return EvolutionResult(
            times=times,
            states=states,
            fidelities=fidelities,
            success=success,
            message=message,
            initial_state=psi0,
            method=f"Trotter ({self.decomposition})"
        )

__init__(hamiltonian, n_steps=100, decomposition='first', hbar=1.0)

Initialize Trotter evolution

Parameters:

Name Type Description Default
hamiltonian Operator

Hamiltonian operator (can be sum of terms)

required
n_steps int

Number of Trotter steps

100
decomposition str

'first' (first-order) or 'second' (second-order)

'first'
hbar float

Reduced Planck constant

1.0
Example

H = pauli_x() + pauli_z() trotter = TrotterEvolution(H, n_steps=100, decomposition='first')

Source code in psiqit\dynamics\time_evolution.py
def __init__(
    self,
    hamiltonian: Operator,
    n_steps: int = 100,
    decomposition: str = 'first',
    hbar: float = 1.0
):
    """
    Initialize Trotter evolution

    Args:
        hamiltonian: Hamiltonian operator (can be sum of terms)
        n_steps: Number of Trotter steps
        decomposition: 'first' (first-order) or 'second' (second-order)
        hbar: Reduced Planck constant

    Example:
        >>> H = pauli_x() + pauli_z()
        >>> trotter = TrotterEvolution(H, n_steps=100, decomposition='first')
    """
    if not hamiltonian.is_hermitian:
        logger.warning("Hamiltonian is not Hermitian")

    self.hamiltonian = hamiltonian
    self.n_steps = n_steps
    self.decomposition = decomposition
    self.hbar = hbar
    self.dim = hamiltonian.dim

    # Decompose Hamiltonian into terms
    self.terms = self._decompose_hamiltonian(hamiltonian)

    logger.info(f"TrotterEvolution initialized: dim={self.dim}, steps={n_steps}, decomposition={decomposition}")

evolve(psi0, t)

Evolve a state using Trotter decomposition

Parameters:

Name Type Description Default
psi0 Ket

Initial state

required
t float

Evolution time

required

Returns:

Name Type Description
Ket Ket

Evolved state

Example

state = trotter.evolve(zero(), t=1.0)

Source code in psiqit\dynamics\time_evolution.py
def evolve(self, psi0: Ket, t: float) -> Ket:
    """
    Evolve a state using Trotter decomposition

    Args:
        psi0: Initial state
        t: Evolution time

    Returns:
        Ket: Evolved state

    Example:
        >>> state = trotter.evolve(zero(), t=1.0)
    """
    if psi0.dim != self.dim:
        raise ValueError(f"State dimension {psi0.dim} does not match Hamiltonian dimension {self.dim}")

    logger.debug(f"Trotter evolution: t={t:.3f}, steps={self.n_steps}")

    dt = t / self.n_steps
    psi = psi0.data.copy()

    for step in range(self.n_steps):
        psi = self._apply_trotter_step(psi, dt)

        # Normalize
        norm = np.linalg.norm(psi)
        if norm > 0:
            psi = psi / norm

    logger.info(f"Trotter evolution completed: {self.n_steps} steps")

    return Ket(psi)

evolve_sequence(psi0, times)

Evolve a state at multiple time points

Parameters:

Name Type Description Default
psi0 Ket

Initial state

required
times ndarray

Array of time points

required

Returns:

Name Type Description
EvolutionResult EvolutionResult

Evolution results

Source code in psiqit\dynamics\time_evolution.py
def evolve_sequence(
    self,
    psi0: Ket,
    times: np.ndarray
) -> EvolutionResult:
    """
    Evolve a state at multiple time points

    Args:
        psi0: Initial state
        times: Array of time points

    Returns:
        EvolutionResult: Evolution results
    """
    logger.info(f"Trotter evolution sequence for {len(times)} time points")

    states = []
    fidelities = []
    success = True
    message = "Evolution completed successfully"

    try:
        for t in times:
            psi_t = self.evolve(psi0, t)
            states.append(psi_t)

            # Fidelity with initial state
            fid = abs(np.vdot(psi0.data, psi_t.data)) ** 2
            fidelities.append(float(fid))

    except Exception as e:
        success = False
        message = f"Evolution failed: {str(e)}"
        logger.error(message)

    return EvolutionResult(
        times=times,
        states=states,
        fidelities=fidelities,
        success=success,
        message=message,
        initial_state=psi0,
        method=f"Trotter ({self.decomposition})"
    )

ChebyshevEvolution

Chebyshev polynomial expansion for quantum time evolution

Implements the Chebyshev polynomial method for time evolution: e^{-iHt} ψ ≈ Σ c_n T_n(H) ψ

Example

from psiqit.quantum import pauli_x, pauli_z, zero H = pauli_x() + pauli_z() cheb = ChebyshevEvolution(H, order=50) state = cheb.evolve(zero(), t=1.0) print(state)

Source code in psiqit\dynamics\time_evolution.py
class ChebyshevEvolution:
    """
    Chebyshev polynomial expansion for quantum time evolution

    Implements the Chebyshev polynomial method for time evolution:
    e^{-iHt} ψ ≈ Σ c_n T_n(H) ψ

    Example:
        >>> from psiqit.quantum import pauli_x, pauli_z, zero
        >>> H = pauli_x() + pauli_z()
        >>> cheb = ChebyshevEvolution(H, order=50)
        >>> state = cheb.evolve(zero(), t=1.0)
        >>> print(state)
    """

    def __init__(
        self,
        hamiltonian: Operator,
        order: int = 50,
        hbar: float = 1.0
    ):
        """
        Initialize Chebyshev evolution

        Args:
            hamiltonian: Hamiltonian operator
            order: Chebyshev polynomial order
            hbar: Reduced Planck constant

        Example:
            >>> H = pauli_x() + pauli_z()
            >>> cheb = ChebyshevEvolution(H, order=50)
        """
        if not hamiltonian.is_hermitian:
            logger.warning("Hamiltonian is not Hermitian")

        self.hamiltonian = hamiltonian
        self.order = order
        self.hbar = hbar
        self.dim = hamiltonian.dim

        # Rescale Hamiltonian to [-1, 1]
        self._rescale_hamiltonian()

        logger.info(f"ChebyshevEvolution initialized: dim={self.dim}, order={order}")

    def _rescale_hamiltonian(self):
        """
        Rescale Hamiltonian to [-1, 1] for Chebyshev expansion
        """
        # Compute eigenvalues to find spectral range
        eigvals = np.linalg.eigvalsh(self.hamiltonian.data)
        self.E_min = np.min(eigvals)
        self.E_max = np.max(eigvals)
        self.E_scale = (self.E_max - self.E_min) / 2
        self.E_shift = (self.E_max + self.E_min) / 2

        # Rescaled Hamiltonian: H_scaled = (H - E_shift) / E_scale
        self.H_scaled = (self.hamiltonian - self.E_shift * identity(self.dim)) / self.E_scale
        self.H_scaled.name = "H_scaled"

        logger.debug(f"Rescaled Hamiltonian: E_min={self.E_min:.3f}, E_max={self.E_max:.3f}")

    def _chebyshev_coefficients(self, t: float) -> List[complex]:
        """
        Compute Chebyshev coefficients for time evolution

        c_n = (2 - δ_{n0}) * (-i)^n * J_n(t)

        Args:
            t: Time

        Returns:
            List[complex]: Chebyshev coefficients
        """
        from scipy.special import jv

        # Scaled time
        tau = t * self.E_scale / self.hbar

        coefficients = []
        for n in range(self.order + 1):
            factor = 2 if n > 0 else 1
            coeff = factor * (-1j)**n * jv(n, tau)
            coefficients.append(coeff)

        return coefficients

    def evolve(self, psi0: Ket, t: float) -> Ket:
        """
        Evolve a state using Chebyshev polynomial expansion

        Args:
            psi0: Initial state
            t: Evolution time

        Returns:
            Ket: Evolved state

        Example:
            >>> state = cheb.evolve(zero(), t=1.0)
        """
        if psi0.dim != self.dim:
            raise ValueError(f"State dimension {psi0.dim} does not match Hamiltonian dimension {self.dim}")

        logger.debug(f"Chebyshev evolution: t={t:.3f}, order={self.order}")

        # Compute phase factor
        phase = np.exp(-1j * self.E_shift * t / self.hbar)

        # Compute Chebyshev coefficients
        coeffs = self._chebyshev_coefficients(t)

        # Initialize Chebyshev recursion
        psi = psi0.data.copy()

        # T_0(H_scaled) ψ = ψ
        psi_prev = psi0.data.copy()
        psi_curr = psi0.data.copy()

        # Accumulate result
        result = coeffs[0] * psi_prev

        # T_1(H_scaled) ψ = H_scaled ψ
        if self.order >= 1:
            psi_curr = self.H_scaled.data @ psi_prev
            result += coeffs[1] * psi_curr

        # Higher orders: T_{n+1} = 2 H_scaled T_n - T_{n-1}
        for n in range(2, self.order + 1):
            psi_next = 2 * self.H_scaled.data @ psi_curr - psi_prev
            result += coeffs[n] * psi_next
            psi_prev, psi_curr = psi_curr, psi_next

        # Apply phase factor
        result = phase * result

        # Normalize
        norm = np.linalg.norm(result)
        if norm > 0:
            result = result / norm

        logger.info(f"Chebyshev evolution completed: order={self.order}")

        return Ket(result)

    def evolve_sequence(
        self,
        psi0: Ket,
        times: np.ndarray
    ) -> EvolutionResult:
        """
        Evolve a state at multiple time points

        Args:
            psi0: Initial state
            times: Array of time points

        Returns:
            EvolutionResult: Evolution results
        """
        logger.info(f"Chebyshev evolution sequence for {len(times)} time points")

        states = []
        fidelities = []
        success = True
        message = "Evolution completed successfully"

        try:
            for t in times:
                psi_t = self.evolve(psi0, t)
                states.append(psi_t)

                # Fidelity with initial state
                fid = abs(np.vdot(psi0.data, psi_t.data)) ** 2
                fidelities.append(float(fid))

        except Exception as e:
            success = False
            message = f"Evolution failed: {str(e)}"
            logger.error(message)

        return EvolutionResult(
            times=times,
            states=states,
            fidelities=fidelities,
            success=success,
            message=message,
            initial_state=psi0,
            method=f"Chebyshev (order={self.order})"
        )

__init__(hamiltonian, order=50, hbar=1.0)

Initialize Chebyshev evolution

Parameters:

Name Type Description Default
hamiltonian Operator

Hamiltonian operator

required
order int

Chebyshev polynomial order

50
hbar float

Reduced Planck constant

1.0
Example

H = pauli_x() + pauli_z() cheb = ChebyshevEvolution(H, order=50)

Source code in psiqit\dynamics\time_evolution.py
def __init__(
    self,
    hamiltonian: Operator,
    order: int = 50,
    hbar: float = 1.0
):
    """
    Initialize Chebyshev evolution

    Args:
        hamiltonian: Hamiltonian operator
        order: Chebyshev polynomial order
        hbar: Reduced Planck constant

    Example:
        >>> H = pauli_x() + pauli_z()
        >>> cheb = ChebyshevEvolution(H, order=50)
    """
    if not hamiltonian.is_hermitian:
        logger.warning("Hamiltonian is not Hermitian")

    self.hamiltonian = hamiltonian
    self.order = order
    self.hbar = hbar
    self.dim = hamiltonian.dim

    # Rescale Hamiltonian to [-1, 1]
    self._rescale_hamiltonian()

    logger.info(f"ChebyshevEvolution initialized: dim={self.dim}, order={order}")

evolve(psi0, t)

Evolve a state using Chebyshev polynomial expansion

Parameters:

Name Type Description Default
psi0 Ket

Initial state

required
t float

Evolution time

required

Returns:

Name Type Description
Ket Ket

Evolved state

Example

state = cheb.evolve(zero(), t=1.0)

Source code in psiqit\dynamics\time_evolution.py
def evolve(self, psi0: Ket, t: float) -> Ket:
    """
    Evolve a state using Chebyshev polynomial expansion

    Args:
        psi0: Initial state
        t: Evolution time

    Returns:
        Ket: Evolved state

    Example:
        >>> state = cheb.evolve(zero(), t=1.0)
    """
    if psi0.dim != self.dim:
        raise ValueError(f"State dimension {psi0.dim} does not match Hamiltonian dimension {self.dim}")

    logger.debug(f"Chebyshev evolution: t={t:.3f}, order={self.order}")

    # Compute phase factor
    phase = np.exp(-1j * self.E_shift * t / self.hbar)

    # Compute Chebyshev coefficients
    coeffs = self._chebyshev_coefficients(t)

    # Initialize Chebyshev recursion
    psi = psi0.data.copy()

    # T_0(H_scaled) ψ = ψ
    psi_prev = psi0.data.copy()
    psi_curr = psi0.data.copy()

    # Accumulate result
    result = coeffs[0] * psi_prev

    # T_1(H_scaled) ψ = H_scaled ψ
    if self.order >= 1:
        psi_curr = self.H_scaled.data @ psi_prev
        result += coeffs[1] * psi_curr

    # Higher orders: T_{n+1} = 2 H_scaled T_n - T_{n-1}
    for n in range(2, self.order + 1):
        psi_next = 2 * self.H_scaled.data @ psi_curr - psi_prev
        result += coeffs[n] * psi_next
        psi_prev, psi_curr = psi_curr, psi_next

    # Apply phase factor
    result = phase * result

    # Normalize
    norm = np.linalg.norm(result)
    if norm > 0:
        result = result / norm

    logger.info(f"Chebyshev evolution completed: order={self.order}")

    return Ket(result)

evolve_sequence(psi0, times)

Evolve a state at multiple time points

Parameters:

Name Type Description Default
psi0 Ket

Initial state

required
times ndarray

Array of time points

required

Returns:

Name Type Description
EvolutionResult EvolutionResult

Evolution results

Source code in psiqit\dynamics\time_evolution.py
def evolve_sequence(
    self,
    psi0: Ket,
    times: np.ndarray
) -> EvolutionResult:
    """
    Evolve a state at multiple time points

    Args:
        psi0: Initial state
        times: Array of time points

    Returns:
        EvolutionResult: Evolution results
    """
    logger.info(f"Chebyshev evolution sequence for {len(times)} time points")

    states = []
    fidelities = []
    success = True
    message = "Evolution completed successfully"

    try:
        for t in times:
            psi_t = self.evolve(psi0, t)
            states.append(psi_t)

            # Fidelity with initial state
            fid = abs(np.vdot(psi0.data, psi_t.data)) ** 2
            fidelities.append(float(fid))

    except Exception as e:
        success = False
        message = f"Evolution failed: {str(e)}"
        logger.error(message)

    return EvolutionResult(
        times=times,
        states=states,
        fidelities=fidelities,
        success=success,
        message=message,
        initial_state=psi0,
        method=f"Chebyshev (order={self.order})"
    )

KrylovEvolution

Krylov subspace method for quantum time evolution

Implements the Krylov subspace method for time evolution: Builds a Krylov subspace and projects the Hamiltonian, then evolves in the reduced subspace.

Example

from psiqit.quantum import pauli_x, pauli_z, zero H = pauli_x() + pauli_z() krylov = KrylovEvolution(H, krylov_dim=20) state = krylov.evolve(zero(), t=1.0) print(state)

Source code in psiqit\dynamics\time_evolution.py
class KrylovEvolution:
    """
    Krylov subspace method for quantum time evolution

    Implements the Krylov subspace method for time evolution:
    Builds a Krylov subspace and projects the Hamiltonian,
    then evolves in the reduced subspace.

    Example:
        >>> from psiqit.quantum import pauli_x, pauli_z, zero
        >>> H = pauli_x() + pauli_z()
        >>> krylov = KrylovEvolution(H, krylov_dim=20)
        >>> state = krylov.evolve(zero(), t=1.0)
        >>> print(state)
    """

    def __init__(
        self,
        hamiltonian: Operator,
        krylov_dim: int = 20,
        hbar: float = 1.0
    ):
        """
        Initialize Krylov evolution

        Args:
            hamiltonian: Hamiltonian operator
            krylov_dim: Krylov subspace dimension
            hbar: Reduced Planck constant

        Example:
            >>> H = pauli_x() + pauli_z()
            >>> krylov = KrylovEvolution(H, krylov_dim=20)
        """
        if not hamiltonian.is_hermitian:
            logger.warning("Hamiltonian is not Hermitian")

        self.hamiltonian = hamiltonian
        self.krylov_dim = min(krylov_dim, hamiltonian.dim)
        self.hbar = hbar
        self.dim = hamiltonian.dim

        self._krylov_basis = None
        self._H_krylov = None

        logger.info(f"KrylovEvolution initialized: dim={self.dim}, krylov_dim={self.krylov_dim}")

    def _build_krylov_basis(self, psi0: np.ndarray) -> np.ndarray:
        """
        Build the Krylov subspace basis

        K = {ψ0, Hψ0, H²ψ0, ..., H^{m-1}ψ0}

        Args:
            psi0: Initial state vector

        Returns:
            np.ndarray: Krylov basis (columns are basis vectors)
        """
        m = min(self.krylov_dim, self.dim)

        # Initialize
        basis = np.zeros((self.dim, m), dtype=complex)
        basis[:, 0] = psi0 / np.linalg.norm(psi0)

        # Generate Krylov vectors
        for i in range(1, m):
            # Apply Hamiltonian to previous vector
            v = self.hamiltonian.data @ basis[:, i-1]

            # Orthogonalize against previous vectors
            for j in range(i):
                v = v - np.vdot(basis[:, j], v) * basis[:, j]

            # Normalize
            norm = np.linalg.norm(v)
            if norm > 1e-12:
                basis[:, i] = v / norm
            else:
                # Krylov subspace exhausted
                basis = basis[:, :i]
                break

        return basis

    def _project_hamiltonian(self, basis: np.ndarray) -> np.ndarray:
        """
        Project the Hamiltonian onto the Krylov subspace

        H_K = V† H V

        Args:
            basis: Krylov basis

        Returns:
            np.ndarray: Projected Hamiltonian
        """
        m = basis.shape[1]
        H_K = np.zeros((m, m), dtype=complex)

        for i in range(m):
            for j in range(m):
                H_K[i, j] = np.vdot(basis[:, i], self.hamiltonian.data @ basis[:, j])

        return H_K

    def evolve(self, psi0: Ket, t: float) -> Ket:
        """
        Evolve a state using Krylov subspace method

        Args:
            psi0: Initial state
            t: Evolution time

        Returns:
            Ket: Evolved state

        Example:
            >>> state = krylov.evolve(zero(), t=1.0)
        """
        if psi0.dim != self.dim:
            raise ValueError(f"State dimension {psi0.dim} does not match Hamiltonian dimension {self.dim}")

        logger.debug(f"Krylov evolution: t={t:.3f}, dim={self.krylov_dim}")

        # Build Krylov basis
        basis = self._build_krylov_basis(psi0.data)
        m = basis.shape[1]

        # Project Hamiltonian
        H_K = self._project_hamiltonian(basis)

        # Initial state in Krylov subspace
        psi0_K = np.zeros(m, dtype=complex)
        psi0_K[0] = 1.0

        # Evolve in Krylov subspace
        # Use matrix exponential
        U_K = expm(Operator(-1j * H_K * t / self.hbar))
        psi_K = U_K.data @ psi0_K

        # Transform back to full space
        psi = basis @ psi_K

        # Normalize
        norm = np.linalg.norm(psi)
        if norm > 0:
            psi = psi / norm

        logger.info(f"Krylov evolution completed: m={m}")

        return Ket(psi)

    def evolve_sequence(
        self,
        psi0: Ket,
        times: np.ndarray
    ) -> EvolutionResult:
        """
        Evolve a state at multiple time points

        Args:
            psi0: Initial state
            times: Array of time points

        Returns:
            EvolutionResult: Evolution results
        """
        logger.info(f"Krylov evolution sequence for {len(times)} time points")

        states = []
        fidelities = []
        success = True
        message = "Evolution completed successfully"

        try:
            for t in times:
                psi_t = self.evolve(psi0, t)
                states.append(psi_t)

                # Fidelity with initial state
                fid = abs(np.vdot(psi0.data, psi_t.data)) ** 2
                fidelities.append(float(fid))

        except Exception as e:
            success = False
            message = f"Evolution failed: {str(e)}"
            logger.error(message)

        return EvolutionResult(
            times=times,
            states=states,
            fidelities=fidelities,
            success=success,
            message=message,
            initial_state=psi0,
            method=f"Krylov (dim={self.krylov_dim})"
        )

__init__(hamiltonian, krylov_dim=20, hbar=1.0)

Initialize Krylov evolution

Parameters:

Name Type Description Default
hamiltonian Operator

Hamiltonian operator

required
krylov_dim int

Krylov subspace dimension

20
hbar float

Reduced Planck constant

1.0
Example

H = pauli_x() + pauli_z() krylov = KrylovEvolution(H, krylov_dim=20)

Source code in psiqit\dynamics\time_evolution.py
def __init__(
    self,
    hamiltonian: Operator,
    krylov_dim: int = 20,
    hbar: float = 1.0
):
    """
    Initialize Krylov evolution

    Args:
        hamiltonian: Hamiltonian operator
        krylov_dim: Krylov subspace dimension
        hbar: Reduced Planck constant

    Example:
        >>> H = pauli_x() + pauli_z()
        >>> krylov = KrylovEvolution(H, krylov_dim=20)
    """
    if not hamiltonian.is_hermitian:
        logger.warning("Hamiltonian is not Hermitian")

    self.hamiltonian = hamiltonian
    self.krylov_dim = min(krylov_dim, hamiltonian.dim)
    self.hbar = hbar
    self.dim = hamiltonian.dim

    self._krylov_basis = None
    self._H_krylov = None

    logger.info(f"KrylovEvolution initialized: dim={self.dim}, krylov_dim={self.krylov_dim}")

evolve(psi0, t)

Evolve a state using Krylov subspace method

Parameters:

Name Type Description Default
psi0 Ket

Initial state

required
t float

Evolution time

required

Returns:

Name Type Description
Ket Ket

Evolved state

Example

state = krylov.evolve(zero(), t=1.0)

Source code in psiqit\dynamics\time_evolution.py
def evolve(self, psi0: Ket, t: float) -> Ket:
    """
    Evolve a state using Krylov subspace method

    Args:
        psi0: Initial state
        t: Evolution time

    Returns:
        Ket: Evolved state

    Example:
        >>> state = krylov.evolve(zero(), t=1.0)
    """
    if psi0.dim != self.dim:
        raise ValueError(f"State dimension {psi0.dim} does not match Hamiltonian dimension {self.dim}")

    logger.debug(f"Krylov evolution: t={t:.3f}, dim={self.krylov_dim}")

    # Build Krylov basis
    basis = self._build_krylov_basis(psi0.data)
    m = basis.shape[1]

    # Project Hamiltonian
    H_K = self._project_hamiltonian(basis)

    # Initial state in Krylov subspace
    psi0_K = np.zeros(m, dtype=complex)
    psi0_K[0] = 1.0

    # Evolve in Krylov subspace
    # Use matrix exponential
    U_K = expm(Operator(-1j * H_K * t / self.hbar))
    psi_K = U_K.data @ psi0_K

    # Transform back to full space
    psi = basis @ psi_K

    # Normalize
    norm = np.linalg.norm(psi)
    if norm > 0:
        psi = psi / norm

    logger.info(f"Krylov evolution completed: m={m}")

    return Ket(psi)

evolve_sequence(psi0, times)

Evolve a state at multiple time points

Parameters:

Name Type Description Default
psi0 Ket

Initial state

required
times ndarray

Array of time points

required

Returns:

Name Type Description
EvolutionResult EvolutionResult

Evolution results

Source code in psiqit\dynamics\time_evolution.py
def evolve_sequence(
    self,
    psi0: Ket,
    times: np.ndarray
) -> EvolutionResult:
    """
    Evolve a state at multiple time points

    Args:
        psi0: Initial state
        times: Array of time points

    Returns:
        EvolutionResult: Evolution results
    """
    logger.info(f"Krylov evolution sequence for {len(times)} time points")

    states = []
    fidelities = []
    success = True
    message = "Evolution completed successfully"

    try:
        for t in times:
            psi_t = self.evolve(psi0, t)
            states.append(psi_t)

            # Fidelity with initial state
            fid = abs(np.vdot(psi0.data, psi_t.data)) ** 2
            fidelities.append(float(fid))

    except Exception as e:
        success = False
        message = f"Evolution failed: {str(e)}"
        logger.error(message)

    return EvolutionResult(
        times=times,
        states=states,
        fidelities=fidelities,
        success=success,
        message=message,
        initial_state=psi0,
        method=f"Krylov (dim={self.krylov_dim})"
    )

ising_hamiltonian(J, h=None)

Create an Ising model Hamiltonian

H = Σ J_ij Z_i Z_j + Σ h_i Z_i

Parameters:

Name Type Description Default
J Dict[Tuple[int, int], float]

Coupling strengths {(i, j): J_ij}

required
h Dict[int, float]

Local fields {i: h_i}

None

Returns:

Name Type Description
Dict Dict[str, float]

Hamiltonian as Pauli strings

Example

J = {(0, 1): -1.0} # Ferromagnetic coupling h = {0: 0.5, 1: -0.5} # Local fields H = ising_hamiltonian(J, h)

H = -Z0Z1 + 0.5Z0 - 0.5Z1

Source code in psiqit\dynamics\adiabatic.py
def ising_hamiltonian(
    J: Dict[Tuple[int, int], float],
    h: Dict[int, float] = None
) -> Dict[str, float]:
    """
    Create an Ising model Hamiltonian

    H = Σ J_ij Z_i Z_j + Σ h_i Z_i

    Args:
        J: Coupling strengths {(i, j): J_ij}
        h: Local fields {i: h_i}

    Returns:
        Dict: Hamiltonian as Pauli strings

    Example:
        >>> J = {(0, 1): -1.0}  # Ferromagnetic coupling
        >>> h = {0: 0.5, 1: -0.5}  # Local fields
        >>> H = ising_hamiltonian(J, h)
        >>> # H = -Z0Z1 + 0.5*Z0 - 0.5*Z1
    """
    hamiltonian = {}

    # Coupling terms
    for (i, j), Jij in J.items():
        term = f"Z{i}Z{j}"
        hamiltonian[term] = Jij

    # Local field terms
    if h:
        for i, hi in h.items():
            term = f"Z{i}"
            hamiltonian[term] = hamiltonian.get(term, 0) + hi

    return hamiltonian

maxcut_hamiltonian(edges)

Create MaxCut problem Hamiltonian

H = -Σ_{(i,j)∈E} Z_i Z_j

Parameters:

Name Type Description Default
edges List[Tuple[int, int]]

List of edges in the graph

required

Returns:

Name Type Description
Dict Dict[str, float]

Hamiltonian as Pauli strings

Example

edges = [(0, 1), (1, 2), (0, 2)] # Triangle graph H = maxcut_hamiltonian(edges)

H = -Z0Z1 - Z1Z2 - Z0Z2

Source code in psiqit\dynamics\adiabatic.py
def maxcut_hamiltonian(edges: List[Tuple[int, int]]) -> Dict[str, float]:
    """
    Create MaxCut problem Hamiltonian

    H = -Σ_{(i,j)∈E} Z_i Z_j

    Args:
        edges: List of edges in the graph

    Returns:
        Dict: Hamiltonian as Pauli strings

    Example:
        >>> edges = [(0, 1), (1, 2), (0, 2)]  # Triangle graph
        >>> H = maxcut_hamiltonian(edges)
        >>> # H = -Z0Z1 - Z1Z2 - Z0Z2
    """
    hamiltonian = {}

    for i, j in edges:
        term = f"Z{i}Z{j}"
        hamiltonian[term] = hamiltonian.get(term, 0) - 1.0

    return hamiltonian

qubo_to_hamiltonian(qubo, offset=0.0)

Convert QUBO (Quadratic Unconstrained Binary Optimization) to Ising Hamiltonian

QUBO: minimize Σ Q_ij x_i x_j, x_i ∈ {0, 1} Ising: H = Σ J_ij Z_i Z_j + Σ h_i Z_i + constant

Mapping: x_i = (1 - Z_i)/2

Parameters:

Name Type Description Default
qubo Dict[Tuple[int, int], float]

QUBO matrix {(i, j): Q_ij}

required
offset float

Constant offset

0.0

Returns:

Name Type Description
Dict Dict[str, float]

Hamiltonian as Pauli strings

Example

Q = {(0, 0): -1.0, (1, 1): -1.0, (0, 1): 2.0} H = qubo_to_hamiltonian(Q)

Source code in psiqit\dynamics\adiabatic.py
def qubo_to_hamiltonian(
    qubo: Dict[Tuple[int, int], float],
    offset: float = 0.0
) -> Dict[str, float]:
    """
    Convert QUBO (Quadratic Unconstrained Binary Optimization) to Ising Hamiltonian

    QUBO: minimize Σ Q_ij x_i x_j, x_i ∈ {0, 1}
    Ising: H = Σ J_ij Z_i Z_j + Σ h_i Z_i + constant

    Mapping: x_i = (1 - Z_i)/2

    Args:
        qubo: QUBO matrix {(i, j): Q_ij}
        offset: Constant offset

    Returns:
        Dict: Hamiltonian as Pauli strings

    Example:
        >>> Q = {(0, 0): -1.0, (1, 1): -1.0, (0, 1): 2.0}
        >>> H = qubo_to_hamiltonian(Q)
    """
    hamiltonian = {}
    constant = offset

    for (i, j), Qij in qubo.items():
        if i == j:
            # Linear term: Q_ii * x_i = Q_ii * (1 - Z_i)/2
            # = Q_ii/2 - Q_ii/2 * Z_i
            constant += Qij / 2
            term = f"Z{i}"
            hamiltonian[term] = hamiltonian.get(term, 0) - Qij / 2
        else:
            # Quadratic term: Q_ij * x_i * x_j
            # = Q_ij/4 * (1 - Z_i - Z_j + Z_i Z_j)
            constant += Qij / 4
            term_i = f"Z{i}"
            hamiltonian[term_i] = hamiltonian.get(term_i, 0) - Qij / 4
            term_j = f"Z{j}"
            hamiltonian[term_j] = hamiltonian.get(term_j, 0) - Qij / 4
            term_ij = f"Z{i}Z{j}"
            hamiltonian[term_ij] = hamiltonian.get(term_ij, 0) + Qij / 4

    # Add constant term
    if abs(constant) > 1e-12:
        hamiltonian['I'] = constant

    return hamiltonian

harmonic_oscillator_hamiltonian(omega=1.0, mass=1.0, hbar=1.0)

Create harmonic oscillator Hamiltonian in position basis

H = (p²/2m) + (1/2)mω²x²

This returns a simplified version using Pauli operators

for a two-level approximation

Parameters:

Name Type Description Default
omega float

Angular frequency

1.0
mass float

Mass

1.0
hbar float

Reduced Planck constant

1.0

Returns:

Name Type Description
Operator Operator

Harmonic oscillator Hamiltonian

Example

H = harmonic_oscillator_hamiltonian(omega=1.0) print(H.is_hermitian) # True

Source code in psiqit\dynamics\heisenberg.py
def harmonic_oscillator_hamiltonian(
    omega: float = 1.0,
    mass: float = 1.0,
    hbar: float = 1.0
) -> Operator:
    """
    Create harmonic oscillator Hamiltonian in position basis

    H = (p²/2m) + (1/2)mω²x²

    Note: This returns a simplified version using Pauli operators
          for a two-level approximation

    Args:
        omega: Angular frequency
        mass: Mass
        hbar: Reduced Planck constant

    Returns:
        Operator: Harmonic oscillator Hamiltonian

    Example:
        >>> H = harmonic_oscillator_hamiltonian(omega=1.0)
        >>> print(H.is_hermitian)  # True
    """
    from ..quantum.operator import pauli_x, pauli_y, pauli_z, identity

    # For a two-level system, use the Pauli representation
    # H = ħω/2 (Z) for a simple two-level system
    H = (hbar * omega / 2) * pauli_z()
    H.name = "H_harmonic"
    return H

spin_hamiltonian(J, B=0.0, n_spins=2)

Create spin Hamiltonian (Heisenberg model)

H = -J Σ σ_i · σ_j - B Σ σ_z^i

Parameters:

Name Type Description Default
J float

Exchange coupling

required
B float

External magnetic field

0.0
n_spins int

Number of spins

2

Returns:

Name Type Description
Operator Operator

Spin Hamiltonian

Example

H = spin_hamiltonian(J=1.0, B=0.5, n_spins=2) print(H.dim) # 4

Source code in psiqit\dynamics\heisenberg.py
def spin_hamiltonian(
    J: float,
    B: float = 0.0,
    n_spins: int = 2
) -> Operator:
    """
    Create spin Hamiltonian (Heisenberg model)

    H = -J Σ σ_i · σ_j - B Σ σ_z^i

    Args:
        J: Exchange coupling
        B: External magnetic field
        n_spins: Number of spins

    Returns:
        Operator: Spin Hamiltonian

    Example:
        >>> H = spin_hamiltonian(J=1.0, B=0.5, n_spins=2)
        >>> print(H.dim)  # 4
    """
    from ..quantum.operator import pauli_x, pauli_y, pauli_z, identity, tensor_product

    if n_spins < 2:
        raise ValueError(f"n_spins must be at least 2, got {n_spins}")

    dim = 2 ** n_spins
    H = np.zeros((dim, dim), dtype=complex)

    # Heisenberg term: -J Σ σ_i · σ_j
    for i in range(n_spins - 1):
        for j in range(i + 1, n_spins):
            # σ_i · σ_j = X_i X_j + Y_i Y_j + Z_i Z_j
            # Build X_i X_j
            X_iX_j = np.eye(dim, dtype=complex)
            # Simplified: for 2 spins, use direct construction
            if n_spins == 2:
                X = pauli_x().data
                Y = pauli_y().data
                Z = pauli_z().data

                # X⊗X + Y⊗Y + Z⊗Z
                H -= J * (np.kron(X, X) + np.kron(Y, Y) + np.kron(Z, Z))
            else:
                # For more spins, use tensor products
                # This is a simplified version
                logger.warning(f"Spin Hamiltonian for {n_spins} spins is simplified")
                X_iX_j = np.eye(dim, dtype=complex)
                # Placeholder for multi-spin case
                H -= J * X_iX_j

    # Zeeman term: -B Σ σ_z^i
    if abs(B) > 1e-12:
        for i in range(n_spins):
            Z_i = np.eye(dim, dtype=complex)
            # Simplified for 2 spins
            if n_spins == 2:
                if i == 0:
                    Z_i = np.kron(pauli_z().data, np.eye(2, dtype=complex))
                else:
                    Z_i = np.kron(np.eye(2, dtype=complex), pauli_z().data)
            H -= B * Z_i

    return Operator(H, name="H_spin")

two_level_hamiltonian(delta, omega)

Create a two-level Hamiltonian

H = (δ/2) Z + (Ω/2) X

Parameters:

Name Type Description Default
delta float

Detuning (energy splitting)

required
omega float

Rabi frequency (coupling)

required

Returns:

Name Type Description
Operator Operator

Two-level Hamiltonian

Example

H = two_level_hamiltonian(delta=1.0, omega=0.5) print(H.is_hermitian) # True

Source code in psiqit\dynamics\heisenberg.py
def two_level_hamiltonian(
    delta: float,
    omega: float
) -> Operator:
    """
    Create a two-level Hamiltonian

    H = (δ/2) Z + (Ω/2) X

    Args:
        delta: Detuning (energy splitting)
        omega: Rabi frequency (coupling)

    Returns:
        Operator: Two-level Hamiltonian

    Example:
        >>> H = two_level_hamiltonian(delta=1.0, omega=0.5)
        >>> print(H.is_hermitian)  # True
    """
    from ..quantum.operator import pauli_x, pauli_z

    H = (delta / 2) * pauli_z() + (omega / 2) * pauli_x()
    H.name = "H_2level"
    return H

create_interaction_hamiltonian(coupling, operator_A, operator_B)

Create an interaction Hamiltonian of the form V = g * A ⊗ B

Parameters:

Name Type Description Default
coupling float

Coupling strength g

required
operator_A Operator

Operator acting on system A

required
operator_B Operator

Operator acting on system B

required

Returns:

Name Type Description
Operator Operator

Interaction Hamiltonian

Example

from psiqit.quantum import pauli_x, pauli_z V = create_interaction_hamiltonian(0.5, pauli_x(), pauli_z()) print(V.name)

Source code in psiqit\dynamics\interaction.py
def create_interaction_hamiltonian(
    coupling: float,
    operator_A: Operator,
    operator_B: Operator
) -> Operator:
    """
    Create an interaction Hamiltonian of the form V = g * A ⊗ B

    Args:
        coupling: Coupling strength g
        operator_A: Operator acting on system A
        operator_B: Operator acting on system B

    Returns:
        Operator: Interaction Hamiltonian

    Example:
        >>> from psiqit.quantum import pauli_x, pauli_z
        >>> V = create_interaction_hamiltonian(0.5, pauli_x(), pauli_z())
        >>> print(V.name)
    """
    from ..quantum.operator import tensor_product

    V = coupling * tensor_product(operator_A, operator_B)
    V.name = f"V_interaction(g={coupling:.2f})"
    return V

rotating_frame(H0, V, omega, t)

Transform to a rotating frame

In the rotating frame, the Hamiltonian becomes: H_rot = e^{iωt/ħ} H e^{-iωt/ħ} - ħω I

Parameters:

Name Type Description Default
H0 Operator

Free Hamiltonian

required
V Operator

Interaction Hamiltonian

required
omega float

Rotation frequency

required
t float

Time

required

Returns:

Name Type Description
Operator Operator

Hamiltonian in the rotating frame

Source code in psiqit\dynamics\interaction.py
def rotating_frame(
    H0: Operator,
    V: Operator,
    omega: float,
    t: float
) -> Operator:
    """
    Transform to a rotating frame

    In the rotating frame, the Hamiltonian becomes:
    H_rot = e^{iωt/ħ} H e^{-iωt/ħ} - ħω I

    Args:
        H0: Free Hamiltonian
        V: Interaction Hamiltonian
        omega: Rotation frequency
        t: Time

    Returns:
        Operator: Hamiltonian in the rotating frame
    """
    from ..quantum.operator import identity

    # Rotation operator R = e^{-iωt/ħ} (for spin systems)
    # This is a simplified version

    # For a two-level system, rotation is achieved by R = e^{-iωt/2} Z
    # The rotating frame Hamiltonian:
    # H_rot = (δ/2) Z + (Ω/2) X

    # This is a placeholder for a full implementation
    H_rot = H0 + V
    H_rot.name = "H_rotating"

    return H_rot

thermal_state(H, beta, hbar=1.0)

Create a thermal (Gibbs) state

ρ = e^{-βH} / Tr(e^{-βH})

Parameters:

Name Type Description Default
H Operator

Hamiltonian

required
beta float

Inverse temperature (1/k_B T)

required
hbar float

Reduced Planck constant

1.0

Returns:

Type Description
ndarray

np.ndarray: Thermal density matrix

Example

from psiqit.quantum import pauli_z rho = thermal_state(pauli_z(), beta=1.0) print(np.trace(rho)) # 1.0

Source code in psiqit\dynamics\lindblad.py
def thermal_state(
    H: Operator,
    beta: float,
    hbar: float = 1.0
) -> np.ndarray:
    """
    Create a thermal (Gibbs) state

    ρ = e^{-βH} / Tr(e^{-βH})

    Args:
        H: Hamiltonian
        beta: Inverse temperature (1/k_B T)
        hbar: Reduced Planck constant

    Returns:
        np.ndarray: Thermal density matrix

    Example:
        >>> from psiqit.quantum import pauli_z
        >>> rho = thermal_state(pauli_z(), beta=1.0)
        >>> print(np.trace(rho))  # 1.0
    """
    H_data = H.data
    exp_neg_beta_H = np.linalg.expm(-beta * H_data)
    rho = exp_neg_beta_H / np.trace(exp_neg_beta_H).real
    return rho

dephasing_channel(rho, gamma, dt)

Apply a dephasing channel to a density matrix

ρ → (1 - p)ρ + p Z ρ Z

where p = (1 - e^{-γt})/2

Parameters:

Name Type Description Default
rho ndarray

Density matrix

required
gamma float

Dephasing rate

required
dt float

Time step

required

Returns:

Type Description
ndarray

np.ndarray: Dephased density matrix

Source code in psiqit\dynamics\lindblad.py
def dephasing_channel(
    rho: np.ndarray,
    gamma: float,
    dt: float
) -> np.ndarray:
    """
    Apply a dephasing channel to a density matrix

    ρ → (1 - p)ρ + p Z ρ Z

    where p = (1 - e^{-γt})/2

    Args:
        rho: Density matrix
        gamma: Dephasing rate
        dt: Time step

    Returns:
        np.ndarray: Dephased density matrix
    """
    from ..quantum.operator import pauli_z

    Z = pauli_z().data
    p = (1 - np.exp(-gamma * dt)) / 2

    rho_new = (1 - p) * rho + p * Z @ rho @ Z
    return rho_new

amplitude_damping_channel(rho, gamma, dt)

Apply an amplitude damping channel to a density matrix

Parameters:

Name Type Description Default
rho ndarray

Density matrix

required
gamma float

Damping rate

required
dt float

Time step

required

Returns:

Type Description
ndarray

np.ndarray: Damped density matrix

Source code in psiqit\dynamics\lindblad.py
def amplitude_damping_channel(
    rho: np.ndarray,
    gamma: float,
    dt: float
) -> np.ndarray:
    """
    Apply an amplitude damping channel to a density matrix

    Args:
        rho: Density matrix
        gamma: Damping rate
        dt: Time step

    Returns:
        np.ndarray: Damped density matrix
    """
    from ..quantum.operator import pauli_x, pauli_y, pauli_z

    # Amplitude damping operators
    p = 1 - np.exp(-gamma * dt)

    # Kraus operators
    K0 = np.array([[1, 0], [0, np.sqrt(1 - p)]], dtype=complex)
    K1 = np.array([[0, np.sqrt(p)], [0, 0]], dtype=complex)

    rho_new = K0 @ rho @ K0.conj().T + K1 @ rho @ K1.conj().T
    return rho_new

jump_operator(L, gamma=1.0)

Create a jump operator with rate

Parameters:

Name Type Description Default
L Operator

Collapse operator

required
gamma float

Decay rate

1.0

Returns:

Name Type Description
Operator Operator

Jump operator with rate

Source code in psiqit\dynamics\monte_carlo.py
def jump_operator(
    L: Operator,
    gamma: float = 1.0
) -> Operator:
    """
    Create a jump operator with rate

    Args:
        L: Collapse operator
        gamma: Decay rate

    Returns:
        Operator: Jump operator with rate
    """
    jump_op = np.sqrt(gamma) * L
    jump_op.name = f"J_{L.name}" if L.name else "J"
    return jump_op

photon_loss_channel(gamma=0.1)

Create a photon loss collapse operator

L = √γ a (annihilation operator)

Parameters:

Name Type Description Default
gamma float

Loss rate

0.1

Returns:

Name Type Description
Operator Operator

Photon loss collapse operator

Source code in psiqit\dynamics\monte_carlo.py
def photon_loss_channel(
    gamma: float = 0.1
) -> Operator:
    """
    Create a photon loss collapse operator

    L = √γ a (annihilation operator)

    Args:
        gamma: Loss rate

    Returns:
        Operator: Photon loss collapse operator
    """
    # For a two-level system, use the lowering operator
    L = np.array([[0, 1], [0, 0]], dtype=complex)
    return Operator(np.sqrt(gamma) * L, name="a")

dephasing_operator(gamma=0.1)

Create a dephasing collapse operator

L = √γ Z

Parameters:

Name Type Description Default
gamma float

Dephasing rate

0.1

Returns:

Name Type Description
Operator Operator

Dephasing collapse operator

Source code in psiqit\dynamics\monte_carlo.py
def dephasing_operator(
    gamma: float = 0.1
) -> Operator:
    """
    Create a dephasing collapse operator

    L = √γ Z

    Args:
        gamma: Dephasing rate

    Returns:
        Operator: Dephasing collapse operator
    """
    from ..quantum.operator import pauli_z
    return Operator(np.sqrt(gamma) * pauli_z().data, name="Z")

amplitude_damping_operator(gamma=0.1)

Create an amplitude damping collapse operator

L = √γ σ_-

Parameters:

Name Type Description Default
gamma float

Damping rate

0.1

Returns:

Name Type Description
Operator Operator

Amplitude damping collapse operator

Source code in psiqit\dynamics\monte_carlo.py
def amplitude_damping_operator(
    gamma: float = 0.1
) -> Operator:
    """
    Create an amplitude damping collapse operator

    L = √γ σ_-

    Args:
        gamma: Damping rate

    Returns:
        Operator: Amplitude damping collapse operator
    """
    # Lowering operator
    L = np.array([[0, 1], [0, 0]], dtype=complex)
    return Operator(np.sqrt(gamma) * L, name="σ_-")

solve_time_independent(potential, x_range, n_points=1000, n_states=5, mass=1.0, hbar=1.0)

Solve the time-independent Schrödinger equation numerically

-ħ²/(2m) d²ψ/dx² + V(x)ψ = Eψ

Parameters:

Name Type Description Default
potential Callable[[float], float]

Potential function V(x)

required
x_range Tuple[float, float]

(x_min, x_max)

required
n_points int

Number of grid points

1000
n_states int

Number of eigenstates to compute

5
mass float

Particle mass

1.0
hbar float

Reduced Planck constant

1.0

Returns:

Name Type Description
Tuple Tuple[ndarray, List[ndarray]]

(eigenvalues, eigenstates)

Example

def harmonic(x): return 0.5 * x**2 energies, states = solve_time_independent(harmonic, (-5, 5), n_points=500, n_states=5) print(energies) # [0.5, 1.5, 2.5, ...]

Source code in psiqit\dynamics\schrodinger.py
def solve_time_independent(
    potential: Callable[[float], float],
    x_range: Tuple[float, float],
    n_points: int = 1000,
    n_states: int = 5,
    mass: float = 1.0,
    hbar: float = 1.0
) -> Tuple[np.ndarray, List[np.ndarray]]:
    """
    Solve the time-independent Schrödinger equation numerically

    -ħ²/(2m) d²ψ/dx² + V(x)ψ = Eψ

    Args:
        potential: Potential function V(x)
        x_range: (x_min, x_max)
        n_points: Number of grid points
        n_states: Number of eigenstates to compute
        mass: Particle mass
        hbar: Reduced Planck constant

    Returns:
        Tuple: (eigenvalues, eigenstates)

    Example:
        >>> def harmonic(x): return 0.5 * x**2
        >>> energies, states = solve_time_independent(harmonic, (-5, 5), n_points=500, n_states=5)
        >>> print(energies)  # [0.5, 1.5, 2.5, ...]
    """
    logger.info(f"Solving TISE: n_points={n_points}, n_states={n_states}")

    x = np.linspace(x_range[0], x_range[1], n_points)
    dx = x[1] - x[0]

    # Build Hamiltonian matrix using finite differences
    # H = -ħ²/(2m) d²/dx² + V(x)
    dim = n_points
    H = np.zeros((dim, dim), dtype=float)

    # Kinetic energy (second derivative)
    for i in range(dim):
        H[i, i] = -2 * hbar**2 / (2 * mass * dx**2)
        if i > 0:
            H[i, i-1] = hbar**2 / (2 * mass * dx**2)
        if i < dim - 1:
            H[i, i+1] = hbar**2 / (2 * mass * dx**2)

    # Potential energy (diagonal)
    for i in range(dim):
        H[i, i] += potential(x[i])

    # Solve eigenvalue problem
    eigenvalues, eigenvectors = np.linalg.eigh(H)

    # Normalize eigenstates
    for i in range(min(n_states, len(eigenvalues))):
        norm = np.sqrt(np.sum(np.abs(eigenvectors[:, i])**2) * dx)
        if norm > 0:
            eigenvectors[:, i] = eigenvectors[:, i] / norm

    logger.info(f"Found {min(n_states, len(eigenvalues))} eigenstates")

    return eigenvalues[:n_states], [eigenvectors[:, i] for i in range(min(n_states, len(eigenvalues)))]

solve_time_dependent(psi0, x, potential, t_max, dt=0.001, mass=1.0, hbar=1.0, method='split', save_every=10)

Solve the time-dependent Schrödinger equation

iħ ∂ψ/∂t = -ħ²/(2m) ∂²ψ/∂x² + V(x,t)ψ

Parameters:

Name Type Description Default
psi0 ndarray

Initial wavefunction

required
x ndarray

Spatial grid

required
potential Callable[[float, float], float]

Potential function V(x, t)

required
t_max float

Maximum time

required
dt float

Time step

0.001
mass float

Particle mass

1.0
hbar float

Reduced Planck constant

1.0
method str

'split' (split-step Fourier) or 'crank' (Crank-Nicolson)

'split'
save_every int

Save state every N steps

10

Returns:

Type Description
List[WaveFunction]

List[WaveFunction]: Time evolution results

Example

def harmonic(x, t): return 0.5 * x2 psi0 = np.exp(-x2/2) / np.sqrt(np.sqrt(np.pi)) results = solve_time_dependent(psi0, x, harmonic, t_max=5.0, dt=0.01) print(len(results)) # Number of saved states

Source code in psiqit\dynamics\schrodinger.py
def solve_time_dependent(
    psi0: np.ndarray,
    x: np.ndarray,
    potential: Callable[[float, float], float],
    t_max: float,
    dt: float = 0.001,
    mass: float = 1.0,
    hbar: float = 1.0,
    method: str = 'split',
    save_every: int = 10
) -> List[WaveFunction]:
    """
    Solve the time-dependent Schrödinger equation

    iħ ∂ψ/∂t = -ħ²/(2m) ∂²ψ/∂x² + V(x,t)ψ

    Args:
        psi0: Initial wavefunction
        x: Spatial grid
        potential: Potential function V(x, t)
        t_max: Maximum time
        dt: Time step
        mass: Particle mass
        hbar: Reduced Planck constant
        method: 'split' (split-step Fourier) or 'crank' (Crank-Nicolson)
        save_every: Save state every N steps

    Returns:
        List[WaveFunction]: Time evolution results

    Example:
        >>> def harmonic(x, t): return 0.5 * x**2
        >>> psi0 = np.exp(-x**2/2) / np.sqrt(np.sqrt(np.pi))
        >>> results = solve_time_dependent(psi0, x, harmonic, t_max=5.0, dt=0.01)
        >>> print(len(results))  # Number of saved states
    """
    logger.info(f"Solving TDSE: t_max={t_max:.3f}, dt={dt:.4f}, method={method}")

    n_points = len(x)
    dx = x[1] - x[0]

    # Normalize initial state
    norm = np.sqrt(np.sum(np.abs(psi0)**2) * dx)
    if norm > 0:
        psi = psi0 / norm
    else:
        raise ValueError("Initial wavefunction is zero")

    # Initialize
    results = [WaveFunction(x, psi.copy(), 0.0)]

    if method == 'split':
        # Split-step Fourier method
        try:
            from scipy.fft import fft, ifft, fftfreq
        except ImportError:
            raise ImportError("scipy.fft is required for split-step method")

        # k-space grid
        k = 2 * np.pi * fftfreq(n_points, dx)

        # Number of steps
        n_steps = int(np.ceil(t_max / dt))
        dt_actual = t_max / n_steps

        for step in range(n_steps):
            t = step * dt_actual

            # Kinetic step (in k-space)
            psi_k = fft(psi)
            psi_k = psi_k * np.exp(-1j * hbar * k**2 * dt_actual / (2 * mass))
            psi = ifft(psi_k)

            # Potential step (in x-space)
            V = potential(x, t + dt_actual/2)
            psi = np.exp(-1j * V * dt_actual / hbar) * psi

            # Normalize
            norm = np.sqrt(np.sum(np.abs(psi)**2) * dx)
            if norm > 0:
                psi = psi / norm

            # Save state
            if (step + 1) % save_every == 0 or step == n_steps - 1:
                results.append(WaveFunction(x, psi.copy(), (step + 1) * dt_actual))

    elif method == 'crank':
        # Crank-Nicolson method
        r = hbar**2 * dt / (4 * mass * dx**2)

        # Build tridiagonal matrices
        A = np.zeros((n_points, n_points), dtype=complex)
        B = np.zeros((n_points, n_points), dtype=complex)

        for i in range(n_points):
            A[i, i] = 1 + r
            B[i, i] = 1 - r
            if i > 0:
                A[i, i-1] = -r/2
                B[i, i-1] = r/2
            if i < n_points - 1:
                A[i, i+1] = -r/2
                B[i, i+1] = r/2

        n_steps = int(np.ceil(t_max / dt))
        dt_actual = t_max / n_steps

        for step in range(n_steps):
            t = step * dt_actual

            # Update with potential
            V = potential(x, t + dt_actual/2)
            psi = psi * np.exp(-1j * V * dt_actual / (2 * hbar))

            # Crank-Nicolson step
            rhs = B @ psi
            psi = np.linalg.solve(A, rhs)

            # Potential update
            psi = psi * np.exp(-1j * V * dt_actual / (2 * hbar))

            # Normalize
            norm = np.sqrt(np.sum(np.abs(psi)**2) * dx)
            if norm > 0:
                psi = psi / norm

            # Save state
            if (step + 1) % save_every == 0 or step == n_steps - 1:
                results.append(WaveFunction(x, psi.copy(), (step + 1) * dt_actual))

    else:
        raise ValueError(f"Unknown method: {method}. Use 'split' or 'crank'")

    logger.info(f"TDSE solved: {len(results)} states saved")
    return results

time_evolution_operator(H, t, hbar=1.0)

Compute the time evolution operator U(t) = e^{-iHt/ħ}

Parameters:

Name Type Description Default
H ndarray

Hamiltonian matrix

required
t float

Time

required
hbar float

Reduced Planck constant

1.0

Returns:

Type Description
ndarray

np.ndarray: Time evolution operator

Example

H = np.array([[1, 0], [0, -1]]) U = time_evolution_operator(H, np.pi/2) print(U) # [[e^{-iπ/2}, 0], [0, e^{iπ/2}]]

Source code in psiqit\dynamics\schrodinger.py
def time_evolution_operator(
    H: np.ndarray,
    t: float,
    hbar: float = 1.0
) -> np.ndarray:
    """
    Compute the time evolution operator U(t) = e^{-iHt/ħ}

    Args:
        H: Hamiltonian matrix
        t: Time
        hbar: Reduced Planck constant

    Returns:
        np.ndarray: Time evolution operator

    Example:
        >>> H = np.array([[1, 0], [0, -1]])
        >>> U = time_evolution_operator(H, np.pi/2)
        >>> print(U)  # [[e^{-iπ/2}, 0], [0, e^{iπ/2}]]
    """
    return np.linalg.expm(-1j * H * t / hbar)

propagate_state(psi0, H, t, hbar=1.0)

Propagate a state using the time evolution operator

|ψ(t)⟩ = e^{-iHt/ħ} |ψ(0)⟩

Parameters:

Name Type Description Default
psi0 ndarray

Initial state vector

required
H ndarray

Hamiltonian matrix

required
t float

Time

required
hbar float

Reduced Planck constant

1.0

Returns:

Type Description
ndarray

np.ndarray: Propagated state

Example

psi0 = np.array([1, 0]) H = np.array([[0, 1], [1, 0]]) psi = propagate_state(psi0, H, np.pi/2) print(psi) # Rotated state

Source code in psiqit\dynamics\schrodinger.py
def propagate_state(
    psi0: np.ndarray,
    H: np.ndarray,
    t: float,
    hbar: float = 1.0
) -> np.ndarray:
    """
    Propagate a state using the time evolution operator

    |ψ(t)⟩ = e^{-iHt/ħ} |ψ(0)⟩

    Args:
        psi0: Initial state vector
        H: Hamiltonian matrix
        t: Time
        hbar: Reduced Planck constant

    Returns:
        np.ndarray: Propagated state

    Example:
        >>> psi0 = np.array([1, 0])
        >>> H = np.array([[0, 1], [1, 0]])
        >>> psi = propagate_state(psi0, H, np.pi/2)
        >>> print(psi)  # Rotated state
    """
    U = time_evolution_operator(H, t, hbar)
    return U @ psi0

expectation_value(psi, operator, dx)

Compute expectation value ⟨ψ|O|ψ⟩

Parameters:

Name Type Description Default
psi ndarray

Wavefunction

required
operator ndarray

Operator matrix

required
dx float

Grid spacing

required

Returns:

Name Type Description
complex complex

Expectation value

Source code in psiqit\dynamics\schrodinger.py
def expectation_value(
    psi: np.ndarray,
    operator: np.ndarray,
    dx: float
) -> complex:
    """
    Compute expectation value ⟨ψ|O|ψ⟩

    Args:
        psi: Wavefunction
        operator: Operator matrix
        dx: Grid spacing

    Returns:
        complex: Expectation value
    """
    return np.sum(np.conj(psi) * (operator @ psi)) * dx

uncertainty_relation(psi, x_operator, p_operator, hbar=1.0, dx=0.01)

Compute uncertainties and verify Heisenberg uncertainty relation

Parameters:

Name Type Description Default
psi ndarray

Wavefunction

required
x_operator ndarray

Position operator

required
p_operator ndarray

Momentum operator

required
hbar float

Reduced Planck constant

1.0
dx float

Grid spacing

0.01

Returns:

Name Type Description
Tuple Tuple[float, float, float]

(Δx, Δp, Δx*Δp)

Example

from psiqit.dynamics import gaussian_wavepacket x = np.linspace(-5, 5, 100) psi = gaussian_wavepacket(x, sigma=1.0) dx, dp, product = uncertainty_relation(psi, x_op, p_op) print(product) # >= ħ/2

Source code in psiqit\dynamics\schrodinger.py
def uncertainty_relation(
    psi: np.ndarray,
    x_operator: np.ndarray,
    p_operator: np.ndarray,
    hbar: float = 1.0,
    dx: float = 0.01
) -> Tuple[float, float, float]:
    """
    Compute uncertainties and verify Heisenberg uncertainty relation

    Args:
        psi: Wavefunction
        x_operator: Position operator
        p_operator: Momentum operator
        hbar: Reduced Planck constant
        dx: Grid spacing

    Returns:
        Tuple: (Δx, Δp, Δx*Δp)

    Example:
        >>> from psiqit.dynamics import gaussian_wavepacket
        >>> x = np.linspace(-5, 5, 100)
        >>> psi = gaussian_wavepacket(x, sigma=1.0)
        >>> dx, dp, product = uncertainty_relation(psi, x_op, p_op)
        >>> print(product)  # >= ħ/2
    """
    # Normalize
    norm = np.sqrt(np.sum(np.abs(psi)**2) * dx)
    if norm > 0:
        psi = psi / norm

    # ⟨x⟩
    ex = np.sum(x_operator * np.abs(psi)**2) * dx

    # ⟨x²⟩
    ex2 = np.sum(x_operator**2 * np.abs(psi)**2) * dx

    # ⟨p⟩
    ep = expectation_value(psi, p_operator, dx).real

    # ⟨p²⟩
    ep2 = expectation_value(psi, p_operator @ p_operator, dx).real

    # Uncertainties
    delta_x = np.sqrt(max(0, ex2 - ex**2))
    delta_p = np.sqrt(max(0, ep2 - ep**2))

    return float(delta_x), float(delta_p), float(delta_x * delta_p)

gaussian_wavepacket(x, x0=0.0, sigma=1.0, k0=0.0, phase=0.0)

Create a Gaussian wavepacket

ψ(x) = (1/(2πσ²))^(1/4) * exp(-(x-x0)²/(4σ²)) * e^{ik0x}

Parameters:

Name Type Description Default
x ndarray

Spatial grid

required
x0 float

Center position

0.0
sigma float

Width parameter

1.0
k0 float

Momentum (wave number)

0.0
phase float

Global phase

0.0

Returns:

Type Description
ndarray

np.ndarray: Wavefunction

Example

x = np.linspace(-10, 10, 100) psi = gaussian_wavepacket(x, x0=0, sigma=1.0, k0=2.0)

Source code in psiqit\dynamics\schrodinger.py
def gaussian_wavepacket(
    x: np.ndarray,
    x0: float = 0.0,
    sigma: float = 1.0,
    k0: float = 0.0,
    phase: float = 0.0
) -> np.ndarray:
    """
    Create a Gaussian wavepacket

    ψ(x) = (1/(2πσ²))^(1/4) * exp(-(x-x0)²/(4σ²)) * e^{ik0x}

    Args:
        x: Spatial grid
        x0: Center position
        sigma: Width parameter
        k0: Momentum (wave number)
        phase: Global phase

    Returns:
        np.ndarray: Wavefunction

    Example:
        >>> x = np.linspace(-10, 10, 100)
        >>> psi = gaussian_wavepacket(x, x0=0, sigma=1.0, k0=2.0)
    """
    norm = 1 / (2 * np.pi * sigma**2)**(0.25)
    envelope = np.exp(-(x - x0)**2 / (4 * sigma**2))
    phase_factor = np.exp(1j * (k0 * x + phase))
    return norm * envelope * phase_factor

plane_wave(x, k, phase=0.0)

Create a plane wave

ψ(x) = e^{i(kx + φ)}

Parameters:

Name Type Description Default
x ndarray

Spatial grid

required
k float

Wave number

required
phase float

Global phase

0.0

Returns:

Type Description
ndarray

np.ndarray: Wavefunction

Example

x = np.linspace(-10, 10, 100) psi = plane_wave(x, k=1.0)

Source code in psiqit\dynamics\schrodinger.py
def plane_wave(
    x: np.ndarray,
    k: float,
    phase: float = 0.0
) -> np.ndarray:
    """
    Create a plane wave

    ψ(x) = e^{i(kx + φ)}

    Args:
        x: Spatial grid
        k: Wave number
        phase: Global phase

    Returns:
        np.ndarray: Wavefunction

    Example:
        >>> x = np.linspace(-10, 10, 100)
        >>> psi = plane_wave(x, k=1.0)
    """
    return np.exp(1j * (k * x + phase))

square_well_ground_state(x, L)

Create the ground state wavefunction of an infinite square well

ψ(x) = √(2/L) sin(πx/L) for 0 < x < L

Parameters:

Name Type Description Default
x ndarray

Spatial grid

required
L float

Well width

required

Returns:

Type Description
ndarray

np.ndarray: Wavefunction

Example

x = np.linspace(0, 1, 100) psi = square_well_ground_state(x, L=1.0)

Source code in psiqit\dynamics\schrodinger.py
def square_well_ground_state(
    x: np.ndarray,
    L: float
) -> np.ndarray:
    """
    Create the ground state wavefunction of an infinite square well

    ψ(x) = √(2/L) sin(πx/L) for 0 < x < L

    Args:
        x: Spatial grid
        L: Well width

    Returns:
        np.ndarray: Wavefunction

    Example:
        >>> x = np.linspace(0, 1, 100)
        >>> psi = square_well_ground_state(x, L=1.0)
    """
    psi = np.zeros_like(x, dtype=complex)

    # Domain: 0 < x < L
    mask = (x > 0) & (x < L)
    psi[mask] = np.sqrt(2 / L) * np.sin(PI * x[mask] / L)

    return psi

harmonic_oscillator_state(x, n, mass=1.0, omega=1.0, hbar=1.0)

Create harmonic oscillator eigenstate

ψ_n(x) = (1/√(2^n n!)) (mω/πħ)^(1/4) * e^(-mωx²/2ħ) * H_n(√(mω/ħ) x)

Parameters:

Name Type Description Default
x ndarray

Spatial grid

required
n int

Quantum number

required
mass float

Particle mass

1.0
omega float

Angular frequency

1.0
hbar float

Reduced Planck constant

1.0

Returns:

Type Description
ndarray

np.ndarray: Wavefunction

Example

x = np.linspace(-5, 5, 100) psi_2 = harmonic_oscillator_state(x, n=2)

Source code in psiqit\dynamics\schrodinger.py
def harmonic_oscillator_state(
    x: np.ndarray,
    n: int,
    mass: float = 1.0,
    omega: float = 1.0,
    hbar: float = 1.0
) -> np.ndarray:
    """
    Create harmonic oscillator eigenstate

    ψ_n(x) = (1/√(2^n n!)) (mω/πħ)^(1/4) 
             * e^(-mωx²/2ħ) * H_n(√(mω/ħ) x)

    Args:
        x: Spatial grid
        n: Quantum number
        mass: Particle mass
        omega: Angular frequency
        hbar: Reduced Planck constant

    Returns:
        np.ndarray: Wavefunction

    Example:
        >>> x = np.linspace(-5, 5, 100)
        >>> psi_2 = harmonic_oscillator_state(x, n=2)
    """
    from math import factorial, sqrt

    alpha = mass * omega / hbar
    sqrt_alpha = np.sqrt(alpha)

    # Prefactor
    prefactor = (alpha / PI)**(0.25) / sqrt(2**n * factorial(n))

    # Gaussian envelope
    gaussian = np.exp(-alpha * x**2 / 2)

    # Hermite polynomial (using recurrence relation)
    if n == 0:
        H_n = np.ones_like(x)
    elif n == 1:
        H_n = 2 * sqrt_alpha * x
    else:
        # Recurrence: H_{n+1}(y) = 2y H_n(y) - 2n H_{n-1}(y)
        y = sqrt_alpha * x
        H_prev = np.ones_like(x)
        H_curr = 2 * y
        for _ in range(2, n + 1):
            H_next = 2 * y * H_curr - 2 * (_ - 1) * H_prev
            H_prev, H_curr = H_curr, H_next
        H_n = H_curr

    return prefactor * gaussian * H_n

infinite_well_state(x, n, L)

Create the n-th state of an infinite square well

ψ_n(x) = √(2/L) sin(nπx/L) for 0 < x < L

Parameters:

Name Type Description Default
x ndarray

Spatial grid

required
n int

Quantum number (1, 2, 3, ...)

required
L float

Well width

required

Returns:

Type Description
ndarray

np.ndarray: Wavefunction

Example

x = np.linspace(0, 1, 100) psi_2 = infinite_well_state(x, n=2, L=1.0)

Source code in psiqit\dynamics\schrodinger.py
def infinite_well_state(
    x: np.ndarray,
    n: int,
    L: float
) -> np.ndarray:
    """
    Create the n-th state of an infinite square well

    ψ_n(x) = √(2/L) sin(nπx/L) for 0 < x < L

    Args:
        x: Spatial grid
        n: Quantum number (1, 2, 3, ...)
        L: Well width

    Returns:
        np.ndarray: Wavefunction

    Example:
        >>> x = np.linspace(0, 1, 100)
        >>> psi_2 = infinite_well_state(x, n=2, L=1.0)
    """
    psi = np.zeros_like(x, dtype=complex)

    mask = (x > 0) & (x < L)
    psi[mask] = np.sqrt(2 / L) * np.sin(n * PI * x[mask] / L)

    return psi

info()

Get information about the dynamics module

Returns:

Name Type Description
dict dict

Module information

Source code in psiqit\dynamics\__init__.py
def info() -> dict:
    """
    Get information about the dynamics module

    Returns:
        dict: Module information
    """
    return {
        'module': 'psiqit.dynamics',
        'version': __version__,
        'submodules': [
            'adiabatic',
            'heisenberg',
            'interaction',
            'lindblad',
            'monte_carlo',
            'schrodinger',
            'time_evolution'
        ],
        'exports': len(__all__),
    }

test()

Run basic tests for the dynamics module

Returns:

Name Type Description
dict dict

Test results

Source code in psiqit\dynamics\__init__.py
def test() -> dict:
    """
    Run basic tests for the dynamics module

    Returns:
        dict: Test results
    """
    results = {}

    # Test adiabatic
    try:
        from .adiabatic import AdiabaticEvolution
        from ..quantum.operator import pauli_x, pauli_z
        H_i = pauli_x()
        H_f = pauli_z()
        evo = AdiabaticEvolution(H_i, H_f, T=1.0, n_steps=10)
        results['adiabatic'] = evo.dim == 2
    except Exception as e:
        results['adiabatic'] = str(e)

    # Test heisenberg
    try:
        from .heisenberg import HeisenbergEvolution
        from ..quantum.operator import pauli_x, pauli_z
        H = pauli_z()
        evo = HeisenbergEvolution(H)
        results['heisenberg'] = evo.dim == 2
    except Exception as e:
        results['heisenberg'] = str(e)

    # Test interaction
    try:
        from .interaction import InteractionPicture
        from ..quantum.operator import pauli_x, pauli_z
        H0 = pauli_z()
        V = pauli_x()
        ip = InteractionPicture(H0, V)
        results['interaction'] = ip.dim == 2
    except Exception as e:
        results['interaction'] = str(e)

    # Test lindblad
    try:
        from .lindblad import LindbladSolver
        from ..quantum.operator import pauli_x, pauli_z
        H = pauli_z()
        L = pauli_x()
        solver = LindbladSolver(H, [L])
        results['lindblad'] = solver.dim == 2
    except Exception as e:
        results['lindblad'] = str(e)

    # Test monte_carlo
    try:
        from .monte_carlo import QuantumTrajectory
        from ..quantum.operator import pauli_x, pauli_z
        H = pauli_z()
        L = pauli_x()
        qt = QuantumTrajectory(H, [L])
        results['monte_carlo'] = qt.dim == 2
    except Exception as e:
        results['monte_carlo'] = str(e)

    # Test schrodinger
    try:
        from .schrodinger import WaveFunction
        import numpy as np
        x = np.linspace(0, 1, 10)
        psi = np.exp(-x**2/2)
        wf = WaveFunction(x, psi)
        results['schrodinger'] = len(wf.x) == 10
    except Exception as e:
        results['schrodinger'] = str(e)

    # Test time_evolution
    try:
        from .time_evolution import TrotterEvolution
        from ..quantum.operator import pauli_x, pauli_z
        H = pauli_x() + pauli_z()
        trotter = TrotterEvolution(H, n_steps=10)
        results['time_evolution'] = trotter.dim == 2
    except Exception as e:
        results['time_evolution'] = str(e)

    return results