CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-scqubits

Python library for simulating superconducting qubits with energy spectra, plotting, and QuTiP integration

Pending
Overview
Eval results
Files

file-io.mddocs/

File I/O

Flexible data persistence supporting HDF5 and CSV formats with object serialization. Enables storing and retrieving qubit calculations, parameter sweep results, and custom data structures.

Capabilities

Core I/O Functions

Primary functions for reading and writing scqubits objects to various file formats.

def read(filename: str) -> object:
    """
    Read scqubits object from file.
    
    Parameters:
    - filename (str): Path to file (supports .h5, .hdf5, .csv extensions)
    
    Returns:
    - object: Deserialized scqubits object
    """

def write(obj: object, filename: str, file_handle=None, overwrite: bool = False) -> None:
    """
    Write scqubits object to file.
    
    Parameters:
    - obj (object): Scqubits object to serialize
    - filename (str): Output file path
    - file_handle: Optional existing file handle
    - overwrite (bool): Whether to overwrite existing files
    """

Data Storage Classes

Container classes for organizing and persisting calculation results with metadata.

class DataStore:
    def __init__(self, system_params: dict = None):
        """
        Base class for data storage.
        
        Parameters:
        - system_params (dict): Dictionary of system parameters
        """
        
    def serialize(self) -> dict:
        """Convert object to serializable dictionary."""
        
    def deserialize(self, data_dict: dict) -> None:
        """Restore object from serialized dictionary."""
        
    def to_file(self, filename: str) -> None:
        """Save object to file."""
        
    @classmethod
    def from_file(cls, filename: str):
        """Load object from file."""

class SpectrumData(DataStore):
    def __init__(self, energy_table: np.ndarray, system_params: dict = None,
                 state_table: np.ndarray = None, matrixelem_table: np.ndarray = None):
        """
        Storage for eigenvalue/eigenvector calculation results.
        
        Parameters:
        - energy_table (np.ndarray): Eigenvalues array [param_point, eigenvalue_index]
        - system_params (dict): System parameters and metadata
        - state_table (np.ndarray): Eigenvectors array [param_point, state_index, component]
        - matrixelem_table (np.ndarray): Matrix elements [param_point, i, j]
        """
        
    def eigenvals(self, param_index: int = None) -> np.ndarray:
        """Get eigenvalues at specific parameter point."""
        
    def eigenvecs(self, param_index: int = None) -> np.ndarray:  
        """Get eigenvectors at specific parameter point."""
        
    def matrixelems(self, operator_name: str, param_index: int = None) -> np.ndarray:
        """Get matrix elements at specific parameter point."""

class WaveFunction(DataStore):
    def __init__(self, basis_labels: list, amplitudes: np.ndarray, energy: float = None):
        """
        Container for wavefunction data and visualization.
        
        Parameters:
        - basis_labels (list): Labels for basis states
        - amplitudes (np.ndarray): Complex amplitudes in given basis
        - energy (float): Energy eigenvalue
        """
        
    def plot(self, mode: str = 'abs_sqr', **kwargs):
        """
        Plot wavefunction.
        
        Parameters:
        - mode (str): Plotting mode ('abs_sqr', 'abs', 'real', 'imag')
        - **kwargs: Additional plotting parameters
        """

File Format Support

Utilities for handling different file formats and conversion between data types.

def convert_to_csv(input_filename: str, output_filename: str = None) -> None:
    """
    Convert HDF5 file to CSV format.
    
    Parameters:
    - input_filename (str): Input HDF5 file path
    - output_filename (str): Output CSV file path (auto-generated if None)
    """

def convert_to_hdf5(input_filename: str, output_filename: str = None) -> None:
    """
    Convert CSV file to HDF5 format.
    
    Parameters:
    - input_filename (str): Input CSV file path  
    - output_filename (str): Output HDF5 file path (auto-generated if None)
    """

def file_info(filename: str) -> dict:
    """
    Get information about stored file.
    
    Parameters:
    - filename (str): File path to analyze
    
    Returns:
    - dict: File metadata and contents summary
    """

Usage Examples

Basic Object Persistence

import scqubits as scq
import numpy as np

# Create and calculate transmon spectrum
transmon = scq.Transmon(EJ=25.0, EC=0.2, ng=0.0, ncut=30)
evals, evecs = transmon.eigensys(evals_count=6)

# Save transmon object
scq.io_utils.write(transmon, 'my_transmon.h5')

# Load transmon object
loaded_transmon = scq.io_utils.read('my_transmon.h5')

# Verify loaded object works
loaded_evals = loaded_transmon.eigenvals(evals_count=6)
print("Original energies:", evals[:3])
print("Loaded energies:", loaded_evals[:3])

Parameter Sweep Storage

# Create and run parameter sweep
ng_vals = np.linspace(-2, 2, 101)
hilbert_space = scq.HilbertSpace([transmon])

sweep = scq.ParameterSweep(
    hilbert_space=hilbert_space,
    paramvals_by_name={'ng': ng_vals},
    evals_count=6
)
sweep.run()

# Save entire sweep
scq.io_utils.write(sweep, 'transmon_ng_sweep.h5')

# Load and analyze saved sweep
loaded_sweep = scq.io_utils.read('transmon_ng_sweep.h5')
loaded_sweep.plot_evals_vs_paramvals(subtract_ground=True)

# Save just the spectrum data
spectrum_data = sweep.dressed_specdata()
scq.io_utils.write(spectrum_data, 'spectrum_data_only.h5')

Composite System Storage

# Create composite system
transmon = scq.Transmon(EJ=25.0, EC=0.2, ng=0.0, ncut=25)
cavity = scq.Oscillator(E_osc=6.0, truncated_dim=4)

system = scq.HilbertSpace([transmon, cavity])
system.add_interaction(
    g_strength=0.1,
    op1=transmon.n_operator,
    op2=cavity.creation_operator + cavity.annihilation_operator
)

# Save composite system
scq.io_utils.write(system, 'qubit_cavity_system.h5')

# Load and verify
loaded_system = scq.io_utils.read('qubit_cavity_system.h5')
original_spectrum = system.eigenvals(evals_count=8)
loaded_spectrum = loaded_system.eigenvals(evals_count=8)

print("Spectrum comparison:")
print("Original:", original_spectrum[:4])
print("Loaded:", loaded_spectrum[:4])

Custom Data Storage

# Create custom SpectrumData object
energy_data = np.random.random((50, 6))  # 50 parameter points, 6 eigenvalues
state_data = np.random.random((50, 6, 100)) + 1j * np.random.random((50, 6, 100))

spectrum_data = scq.SpectrumData(
    energy_table=energy_data,
    state_table=state_data,
    system_params={
        'system_type': 'transmon',
        'EJ': 25.0,
        'EC': 0.2,
        'parameter_name': 'ng',
        'parameter_values': np.linspace(-2, 2, 50)
    }
)

# Save custom data
scq.io_utils.write(spectrum_data, 'custom_spectrum.h5')

# Load and access data
loaded_spectrum = scq.io_utils.read('custom_spectrum.h5')
print("System parameters:", loaded_spectrum.system_params)
print("Energy table shape:", loaded_spectrum.energy_table.shape)

Wavefunction Storage

# Calculate and store wavefunction
transmon = scq.Transmon(EJ=25.0, EC=0.2, ng=0.5, ncut=30)
wavefunction = transmon.wavefunction(which=0)  # Ground state

# Save wavefunction
scq.io_utils.write(wavefunction, 'ground_state_wf.h5')

# Load and plot
loaded_wf = scq.io_utils.read('ground_state_wf.h5')
loaded_wf.plot(mode='abs_sqr')

File Format Conversion

# Save data in HDF5 format
scq.io_utils.write(transmon, 'transmon_data.h5')

# Convert to CSV for external analysis
scq.io_utils.convert_to_csv('transmon_data.h5', 'transmon_data.csv')

# Get file information
info = scq.io_utils.file_info('transmon_data.h5')
print("File contents:", info)

# Convert back to HDF5
scq.io_utils.convert_to_hdf5('transmon_data.csv', 'transmon_converted.h5')

Batch Processing

# Save multiple objects with systematic naming
systems = {
    'transmon_low_EC': scq.Transmon(EJ=25.0, EC=0.1, ng=0.0, ncut=30),
    'transmon_high_EC': scq.Transmon(EJ=25.0, EC=0.5, ng=0.0, ncut=30),
    'fluxonium': scq.Fluxonium(EJ=2.0, EC=0.5, EL=0.8, flux=0.0)
}

# Save all systems
for name, system in systems.items():
    filename = f'{name}_system.h5'
    scq.io_utils.write(system, filename)
    print(f"Saved {name} to {filename}")

# Load and compare spectra
spectra = {}
for name in systems.keys():
    filename = f'{name}_system.h5'
    loaded_system = scq.io_utils.read(filename)
    spectra[name] = loaded_system.eigenvals(evals_count=4)
    
print("\nComparison of energy spectra:")
for name, spectrum in spectra.items():
    print(f"{name}: {spectrum}")

Error Handling

# Safe file operations with error handling
try:
    # Attempt to load file
    data = scq.io_utils.read('nonexistent_file.h5')
except FileNotFoundError:
    print("File not found - creating new data")
    data = scq.Transmon(EJ=25.0, EC=0.2, ng=0.0, ncut=30)

# Safe write with overwrite protection
try:
    scq.io_utils.write(data, 'important_data.h5', overwrite=False)
    print("Data saved successfully")
except FileExistsError:
    print("File already exists - use overwrite=True to replace")
    
    # Explicit overwrite
    scq.io_utils.write(data, 'important_data.h5', overwrite=True)
    print("Data overwritten successfully")

Install with Tessl CLI

npx tessl i tessl/pypi-scqubits

docs

circuit-analysis.md

composite-systems.md

file-io.md

index.md

noise-analysis.md

parameter-sweeps.md

qubit-models.md

spectrum-analysis.md

units-settings.md

tile.json