Esempio n. 1
0
    def __init__(self, factory):

        # NetQASM Factory, including our connection to the SimulaQron backend
        self.factory = factory

        # Default application ID, typically one connection per application but
        # we will deliberately NOT check for that since this is the task of
        # higher layers or an OS
        self.app_id = 0

        # Define the backend to use.
        self.messageHandler = factory.backend
        self.messageHandler.protocol = self

        # Flag to determine whether we already received _all_ of the NetQASM header
        self.got_netqasm_header = False

        # Header for which we are currently processing a packet
        self.currHeader = None

        # Buffer received data (which may arrive in chunks)
        self.buf = None

        # Convenience
        self.name = self.factory.name

        self._logger = get_netqasm_logger(f"{self.__class__.__name__}({self.name})")
        self._logger.debug("Initialized Protocol")
Esempio n. 2
0
    def __init__(self, host, name, qnodeos_net, backend, network_name="default"):
        """
        Initialize NetQASM Factory.

        lhost	details of the local host (class host)
        """

        self.host = host
        self.name = name
        self.qnodeos_net = qnodeos_net
        self.virtRoot = None
        self.qReg = None
        self.backend = backend(self)
        self.network_name = network_name

        # Dictionary that keeps qubit dictorionaries for each application
        self.qubitList = {}

        # Lock governing access to the qubitList
        self._lock = DeferredLock()

        self._logger = get_netqasm_logger(f"{self.__class__.__name__}({name})")

        # Read in topology, if specified. topology=None means fully connected
        # topology
        self.topology = None
        if simulaqron_settings.network_config_file is not None:
            networks_config = NetworksConfigConstructor(file_path=simulaqron_settings.network_config_file)
            self.topology = networks_config.networks[network_name].topology
Esempio n. 3
0
    def __init__(self, node, register, simNum, num=0):
        # Node where this qubit is located
        self.node = node

        # Register where this qubit is simulated
        self.register = register

        # Number in the register, if known
        self.num = num

        # Number of the simulated qubit, unique at each virtual node
        self.simNum = simNum

        # Lock marshalling access to this qubit
        self._lock = DeferredLock()

        # Mark this qubit as active (still connected to a register)
        self.active = True

        # Time until retry
        self._delay = 1

        # Optional parameters for when the simulation is noise
        self.noisy = settings.simulaqron_settings.noisy_qubits
        self.T1 = settings.simulaqron_settings.t1
        self.last_accessed = time.time()

        self._logger = get_netqasm_logger(
            f"{self.__class__.__name__}(node={node.name}, sim_num={simNum})")
Esempio n. 4
0
    def __init__(
        self,
        app_name,
        remote_app_name,
        socket_id=0,
        timeout=None,
        use_callbacks=False,
        network_name="default",
        log_config=None,
    ):
        assert socket_id == 0, (
            "SimulaQron socket does not support setting socket ID, this is instead done in the config file"
        )
        self._node_name = app_name
        self._remote_node_name = remote_app_name
        self._use_callbacks = use_callbacks
        self._network_name = network_name

        self._logger = get_netqasm_logger(
            f"{self.__class__.__name__}({app_name} <-> {remote_app_name})")
        self._app_socket = None

        self._connect()
Esempio n. 5
0
from netqasm.backend.messages import (ErrorMessage, MessageHeader,
                                      MsgDoneMessage, ReturnArrayMessage,
                                      ReturnRegMessage, deserialize_return_msg)
from netqasm.lang.ir import GenericInstr
from netqasm.lang.operand import Address, Register
from netqasm.logging.glob import get_netqasm_logger
from netqasm.sdk.connection import BaseNetQASMConnection
from netqasm.sdk.network import NetworkInfo
from netqasm.sdk.shared_memory import SharedMemoryManager
from simulaqron.general import SimUnsupportedError
from simulaqron.general.host_config import (SocketsConfig,
                                            get_node_id_from_net_config)
from simulaqron.settings import SimBackend, simulaqron_settings

logger = get_netqasm_logger("SimulaQronConnection")


class SimulaQronConnection(BaseNetQASMConnection):

    NON_STABILIZER_INSTR = [GenericInstr.T]

    def __init__(
        self,
        app_name,
        app_id=None,
        max_qubits=5,
        log_config=None,
        epr_sockets=None,
        compiler=None,
        socket_address=None,
Esempio n. 6
0
from netqasm.logging.glob import get_netqasm_logger
from netqasm.logging.output import (reset_struct_loggers,
                                    save_all_struct_loggers)
from netqasm.runtime import env, process_logs
from netqasm.runtime.app_config import AppConfig
from netqasm.runtime.application import ApplicationInstance
from netqasm.runtime.settings import Formalism
from netqasm.sdk.classical_communication import reset_socket_hub
from netqasm.sdk.config import LogConfig
from netqasm.sdk.shared_memory import SharedMemoryManager
from netqasm.util.yaml import dump_yaml
from simulaqron.network import Network
from simulaqron.settings import SimBackend, simulaqron_settings
from simulaqron.toolbox import has_module

logger = get_netqasm_logger()

# TODO similar code to squidasm.run.run, make base-class and subclasses?

_SIMULAQRON_BACKENDS = {
    Formalism.STAB: SimBackend.STABILIZER,
    Formalism.KET: SimBackend.PROJECTQ,
    Formalism.DM: SimBackend.QUTIP,
}


def as_completed(futures, names=None, sleep_time=0):
    futures = list(futures)
    if names is not None:
        names = list(names)
    while len(futures) > 0:
Esempio n. 7
0
import time
import signal
from timeit import default_timer as timer

from twisted.internet import reactor
from twisted.internet.error import ConnectionRefusedError, CannotListenError
from twisted.spread import pb

from netqasm.logging.glob import get_netqasm_logger, set_log_level

from simulaqron.netqasm_backend.factory import NetQASMFactory
from simulaqron.netqasm_backend.qnodeos import SubroutineHandler
from simulaqron.general.host_config import SocketsConfig
from simulaqron.settings import simulaqron_settings

logger = get_netqasm_logger("start_qnodeos")

_RETRY_TIME = 0.1
_TIMEOUT = 10


def init_register(virtRoot, myName, node):
    """Retrieves the relevant root objects to talk to such remote connections"""
    logger.debug("LOCAL %s: All connections set up.", myName)
    # Set the virtual node
    node.set_virtual_node(virtRoot)
    # Start listening to NetQASM messages
    setup_netqasm_server(myName, node)


def connect_to_virtNode(myName, netqasm_factory, virtual_network):
Esempio n. 8
0
from netqasm.logging.glob import get_netqasm_logger

logger = get_netqasm_logger("sim_util")


def get_qubit_state(qubit, reduced_dm=True):
    """Currenlty we cannot get the qubit in SimulaQron, just return None"""
    logger.warning("Cannot get the qubit state in SimulaQron")
    return None
Esempio n. 9
0
    def __init__(self,
                 name=None,
                 nodes=None,
                 topology=None,
                 network_config_file=None,
                 force=False,
                 new=True):
        """
        Used to spin up a simulated network.

        If new=True then a fresh network with only the specified nodes
        (or the default Alice, Bob, Charlie, David and Eve) are created and overwriting the current network with
        the same name in the network config file. Otherwise only the specified nodes are started without changing
        the config file. Note that if the nodes does not currently exists and new=False, an ValueError is raised.

        If force=False an input to confirm the overwriting is issued.

        :param name: None or str (defualts to "default")
        :param nodes: None or list of str
        :param topology: None or dict
        :param network_config_file: None or str (defaults to simulaqron_settings.network_config_file
        :param force: bool
        :param new: bool
        """
        self._running = False

        if name is None:
            self.name = "default"
        else:
            self.name = name

        self.processes = []
        self._logger = get_netqasm_logger(
            f"{self.__class__.__name__}({self.name})")

        if network_config_file is None:
            self._network_config_file = simulaqron_settings.network_config_file
        else:
            self._network_config_file = network_config_file

        networks_config = NetworksConfigConstructor(
            file_path=self._network_config_file)

        if new:
            if nodes is None:
                if isinstance(topology, dict):
                    self.nodes = list(topology.keys())
                else:
                    self.nodes = ["Alice", "Bob", "Charlie", "David", "Eve"]
            else:
                self.nodes = nodes
            self.topology = construct_topology_config(topology, self.nodes)
            if not force:
                answer = input(
                    "Do you want to add/replace the network {} in the file {}"
                    "with a network constisting of the nodes {}? (yes/no)".
                    format(self.name, self._network_config_file, self.nodes))
                if answer not in ["yes", "y"]:
                    raise RuntimeError(
                        "User did not want to replace network in file")
            networks_config.add_network(node_names=self.nodes,
                                        network_name=self.name,
                                        topology=self.topology)
            networks_config.write_to_file(self._network_config_file)
        else:
            if topology is not None:
                raise ValueError("If new is False a topology cannot be used.")
            if self.name in networks_config.networks:
                node_names = networks_config.get_node_names(self.name)
                self.topology = networks_config.networks[self.name].topology
            else:
                raise ValueError(
                    "Network {} is not in the file {}\n"
                    "If you wish to add this network to the file, use the"
                    "--new flag.".format(self.name, self._network_config_file))
            if nodes is None:
                self.nodes = node_names
            else:
                self.nodes = nodes
                for node_name in self.nodes:
                    if node_name not in node_names:
                        raise ValueError(
                            "Node {} is not in the current network {} in the file {}\n"
                            "If you wish to overwrite the current network in the file, use the"
                            "--new flag.".format(node_name, self.name,
                                                 self._network_config_file))

        self._setup_processes()