Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

update QRC template / placeholders #5

Merged
merged 1 commit into from
May 17, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion CONTRIBUTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,6 @@ Run the following and make changes as needed to satisfy format checks:

```bash
isort qbraid_algorithms tests tools
ruff fix qbraid_algorithms examples tests tools
ruff format qbraid_algorithms examples tests tools
qbraid admin headers qbraid_algorithms tests tools --type=gpl --fix
```
17 changes: 14 additions & 3 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ classifiers = [
"Topic :: Scientific/Engineering",
"Topic :: Scientific/Engineering :: Physics"
]
dependencies = ["torch", "numpy"]
dependencies = ["torch>=2.3.0,<3.0", "numpy>=1.17,<1.27", "bloqade>=0.15.12,<0.16"]

[project.urls]
Homepage = "https://github.com/qBraid/qbraid-algorithms"
Expand All @@ -51,8 +51,19 @@ force_grid_wrap = 0
use_parentheses = true
line_length = 100

[tool.ruff]
extend-include = ["*.ipynb"]
[tool.black]
line-length = 100
target-version = ['py39', 'py310', 'py311', 'py312']
include = '\.pyi?$'
exclude = '''
/(
\.git
| \.__pycache__
| \.tox
| \.venv
| dist
)/
'''

[tool.pytest.ini_options]
addopts = "-ra"
Expand Down
1 change: 1 addition & 0 deletions qbraid_algorithms/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
.. currentmodule:: qbraid_algorithms

"""

from . import datasets, esn, qrc

try:
Expand Down
1 change: 1 addition & 0 deletions qbraid_algorithms/datasets/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@


"""

from .sequences import create_sequences, create_time_series_data

__all__ = ["create_sequences", "create_time_series_data"]
1 change: 1 addition & 0 deletions qbraid_algorithms/datasets/sequences.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
Module defining datasets for reservoir computing tasks.

"""

import numpy as np
import torch
from numpy.lib.stride_tricks import sliding_window_view
Expand Down
1 change: 1 addition & 0 deletions qbraid_algorithms/esn/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@
ReservoirGenerationError

"""

from .exceptions import ReservoirGenerationError
from .model import EchoStateNetwork
from .reservoir import EchoStateReservoir
Expand Down
9 changes: 3 additions & 6 deletions qbraid_algorithms/esn/model.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
Module for classical reservoir computing with Echo State Networks (ESNs).

"""

import torch

from .reservoir import EchoStateReservoir
Expand All @@ -37,9 +38,7 @@ def __init__(self, reservoir: EchoStateReservoir, output_size: int):
"""
super().__init__()
self.reservoir = reservoir
self.fc = torch.nn.Linear(
in_features=reservoir.hidden_size, out_features=output_size
)
self.fc = torch.nn.Linear(in_features=reservoir.hidden_size, out_features=output_size)
self.softmax = torch.nn.Softmax(dim=-1)

def forward(self, input_data: torch.Tensor) -> torch.Tensor:
Expand All @@ -57,9 +56,7 @@ def forward(self, input_data: torch.Tensor) -> torch.Tensor:

self.reservoir.evolve(u) # Pass through reservoir

h = self.fc(
self.reservoir.x.t()
) # Pass transposed output x through the linear layer
h = self.fc(self.reservoir.x.t()) # Pass transposed output x through the linear layer
if len(h[0]) != 1:
h = self.softmax(h) # Apply softmax
return h
8 changes: 3 additions & 5 deletions qbraid_algorithms/esn/reservoir.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
Module for generating classical reservoir for Echo State Networks.

"""

from dataclasses import dataclass, field

import torch
Expand Down Expand Up @@ -41,9 +42,7 @@ def __post_init__(self):

def _generate_w_in(self, mean: float = 0.0) -> torch.Tensor:
"""Generates and returns a random input weight matrix, w_in."""
return torch.randn(self.hidden_size, self.input_size + 1).normal_(
mean=mean, std=self.a
)
return torch.randn(self.hidden_size, self.input_size + 1).normal_(mean=mean, std=self.a)

def _generate_w(self, mean: float = 0.0, max_retries: int = 3) -> torch.Tensor:
"""Generates a sparse internal weight matrix, w, with retries if necessary."""
Expand Down Expand Up @@ -73,8 +72,7 @@ def evolve(self, u: torch.Tensor) -> None:

"""
temp_state = torch.tanh(
torch.mm(self.w_in, torch.cat((torch.tensor([[1.0]]), u), 0))
+ torch.mm(self.w, self.x)
torch.mm(self.w_in, torch.cat((torch.tensor([[1.0]]), u), 0)) + torch.mm(self.w, self.x)
)
new_state = (1 - self.leak) * self.x + self.leak * temp_state
self.x = new_state
23 changes: 4 additions & 19 deletions qbraid_algorithms/qrc/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,25 +17,10 @@
.. autosummary::
:toctree: ../stubs/

QuantumAdapter
DynamicsSimulator
InputHandler
OutputHandler
ReservoirParameters
QuantumReservoir
QRCModel

"""
from .adapter import QuantumAdapter
from .dynamics import DynamicsSimulator
from .io_handler import InputHandler, OutputHandler
from .parameters import ReservoirParameters
from .reservoir import QuantumReservoir

__all__ = [
"QuantumAdapter",
"DynamicsSimulator",
"InputHandler",
"OutputHandler",
"ReservoirParameters",
"QuantumReservoir",
]
from .model import QRCModel

__all__ = ["QRCModel"]
41 changes: 0 additions & 41 deletions qbraid_algorithms/qrc/adapter.py

This file was deleted.

69 changes: 45 additions & 24 deletions qbraid_algorithms/qrc/dynamics.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,36 +13,57 @@

"""

from dataclasses import dataclass, field
from typing import Any

class DynamicsSimulator:
"""Simulate the dynamics of the quantum system.
import numpy as np
from bloqade.emulate.ir.atom_type import AtomType
from bloqade.emulate.ir.emulator import Register

Attributes:
reservoir (QuantumReservoir): The quantum reservoir instance to simulate.

@dataclass
class DetuningLayer:
"""Class representing a detuning layer in a quantum reservoir."""

atoms: list[AtomType] # Atom positions
readouts: list[Any] # Readout observables
omega: float # Rabi frequency
t_start: float # Evolution starting time
t_end: float # Evolution ending time
step: float # Readout time step
reg: Register = field(
default_factory=lambda *args, **kwargs: Register(*args, **kwargs)
) # Quantum state storage


def generate_sites(lattice_type, dimension, scale):
"""
Generate positions for atoms on a specified lattice type with a given scale.

def __init__(self, reservoir):
"""Initialize the DynamicsSimulator with a quantum reservoir.
Args:
lattice_type (Any): Type of the lattice.
dimension (int): Number of principal components.
scale (float): Scale factor for lattice spacing.

Args:
reservoir (QuantumReservoir): The quantum reservoir to simulate.
"""
self.reservoir = reservoir
Returns:
Any: Positions of atoms.

def simulate(self, steps):
"""Perform the simulation for a given number of steps.
TODO: Implement actual site generation based on lattice type.
"""
raise NotImplementedError

Args:
steps (int): The number of simulation steps to execute.
"""
for _ in range(steps):
input_signal = self.generate_input()
self.reservoir.update_state(input_signal)

def generate_input(self):
"""Generate a sample input signal for the simulation.
def apply_layer(layer: DetuningLayer, x: np.ndarray) -> np.ndarray:
"""
Simulate quantum evolution and record output for a given set of PCA values (x).

Args:
layer (DetuningLayer): Configuration and quantum state of the layer.
x (np.ndarray): Vector or matrix of real numbers representing PCA values for each image.

Returns:
Any: The generated input signal.
"""
return 0
Returns:
np.ndarray: Output values from the simulation.

TODO: Implement the actual simulation using suitable quantum simulation libraries.
"""
raise NotImplementedError
33 changes: 33 additions & 0 deletions qbraid_algorithms/qrc/encoding.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
# Copyright (C) 2024 qBraid
#
# This file is part of the qBraid-SDK
#
# The qBraid-SDK is free software released under the GNU General Public License v3
# or later. You can redistribute and/or modify it under the terms of the GPL v3.
# See the LICENSE file in the project root or <https://www.gnu.org/licenses/gpl-3.0.html>.
#
# THERE IS NO WARRANTY for the qBraid-SDK, as per Section 15 of the GPL v3.

"""
Module for encoding of data.

"""

import torch


def one_hot_encoding(labels: torch.Tensor, num_classes: int) -> torch.Tensor:
"""
Convert a tensor of numeric labels into a one-hot encoded matrix using PyTorch.

Args:
labels (torch.Tensor): The tensor of labels to encode.
num_classes (int): The total number of classes.

Returns:
torch.Tensor: The one-hot encoded matrix where each row corresponds to a label.

TODO: Implement the one-hot encoding function.
"""
# Placeholder for actual implementation.
return torch.nn.functional.one_hot(labels, num_classes=num_classes)
44 changes: 0 additions & 44 deletions qbraid_algorithms/qrc/io_handler.py

This file was deleted.

Loading
Loading