def test_create_logger(self, module):
     """Tests that the create_logger function returns a logger with the
     default configuration set for an SF logger"""
     logger = create_logger(module.__name__)
     assert logger.level == logging.INFO
     assert logging_handler_defined(logger)
     assert logger.handlers[0] == default_handler
示例#2
0
    def __init__(self, id_: str, status: JobStatus, connection):
        self._id = id_
        self._status = status
        self._connection = connection
        self._result = None

        self.log = create_logger(__name__)
    def test_default_sf_logger(self, module, capsys):
        """Tests that stderr is set for the SF logger by default as stream if
        there were not other configurations made."""
        level = logging.DEBUG

        logger = create_logger(module.__name__)
        assert len(logger.handlers) == 1
        assert logger.handlers[0].stream.name == "<stderr>"
示例#4
0
    def test_default_sf_logger(self, module):
        """Tests that stderr is set for the SF logger by default as stream if
        there were not other configurations made."""

        logger = create_logger(module.__name__)
        assert len(logger.handlers) == 1
        # checks if stream is stderr (stream name for stderr is 8 or 9, whereas stdout 6 or 7)
        assert logger.handlers[0].stream.fileno() in [8, 9]
示例#5
0
 def __init__(self,
              target: str,
              connection: Connection = None,
              backend_options: dict = None):
     self._target = self.DEFAULT_TARGETS.get(target, target)
     self._spec = None
     self._connection = connection or Connection()
     self._backend_options = backend_options or {}
     self.log = create_logger(__name__)
示例#6
0
 def __init__(
     self,
     target: str,
     connection: Optional[xcc.Connection] = None,
     backend_options: Optional[Dict[str, Any]] = None,
 ):
     self._target = self.DEFAULT_TARGETS.get(target, target)
     self._device = None
     self._connection = connection
     self._backend_options = backend_options or {}
     self.log = create_logger(__name__)
示例#7
0
    def __init__(self, target: str, connection: Connection = None, backend_options: dict = None):
        self._target = self.DEFAULT_TARGETS.get(target, target)

        if self._target not in self.VALID_TARGETS:
            raise ValueError(
                "Invalid engine target: {} (valid targets: {})".format(
                    target, tuple(self.DEFAULT_TARGETS.keys()) + self.VALID_TARGETS
                )
            )

        self._connection = connection or Connection()
        self._backend_options = backend_options or {}
        self.log = create_logger(__name__)
def load_config(filename="config.toml", **kwargs):
    """Load configuration from keyword arguments, configuration file or
    environment variables.

    .. note::

        The configuration dictionary will be created based on the following
        (order defines the importance, going from most important to least
        important):

        1. keyword arguments passed to ``load_config``
        2. data contained in environmental variables (if any)
        3. data contained in a configuration file (if exists)

    Keyword Args:
        filename (str): the name of the configuration file to look for.
            Additional configuration options are detailed in
            :doc:`/code/sf_configuration`

    Returns:
        dict[str, dict[str, Union[str, bool, int]]]: the configuration
    """
    config = create_config()

    filepath = find_config_file(filename=filename)

    if filepath is not None:
        loaded_config = load_config_file(filepath)
        api_config = get_api_config(loaded_config, filepath)

        valid_api_options = keep_valid_options(api_config)
        config["api"].update(valid_api_options)
    else:
        log = create_logger(__name__)
        log.warning("No Strawberry Fields configuration file found.")

    update_from_environment_variables(config)

    valid_kwargs_config = keep_valid_options(kwargs)
    config["api"].update(valid_kwargs_config)

    return config
示例#9
0
    def __init__(
        self,
        token: str = None,
        host: str = None,
        port: int = None,
        use_ssl: bool = None,
        verbose: bool = True,
    ):
        default_config = load_config()

        self._token = token or default_config["api"]["authentication_token"]
        self._host = host or default_config["api"]["hostname"]
        self._port = port or default_config["api"]["port"]
        self._use_ssl = use_ssl or default_config["api"]["use_ssl"]
        self._verbose = verbose

        self._base_url = "http{}://{}:{}".format("s" if self.use_ssl else "", self.host, self.port)
        self._headers = {"Authorization": self.token}

        self.log = create_logger(__name__)
示例#10
0
    def test_custom_logger_before_sf_logger_with_higher_level(self, module):
        """Tests that a custom logger created before an SF logger will define
        the level for logging as expected and the SF logger does not overwrite
        the user configuration.

        The logic of the test goes as follows:
        1. Manually setting the level for logging for DEBUG level
        2. Creating an SF logger with level WARNING, that is higher than DEBUG
        3. Checking that the SF logger did not affect the handlers defined or
           the effective level of the logger
        """
        custom_level = logging.DEBUG
        sf_level = logging.WARNING

        logger = logging.getLogger()
        logging.basicConfig(level=custom_level)

        _ = create_logger(module.__name__, level=sf_level)

        assert logging_handler_defined(logger)
        assert logger.getEffectiveLevel() == custom_level
def get_api_config(loaded_config, filepath):
    """Gets the API section from the loaded configuration.

    Args:
        loaded_config (dict): the configuration that was loaded from the TOML config
            file
        filepath (str): path to the configuration file

    Returns:
        dict[str, Union[str, bool, int]]: the api section of the configuration

    Raises:
        ConfigurationError: if the api section was not defined in the
            configuration
    """
    try:
        return loaded_config["api"]
    except KeyError:
        log = create_logger(__name__)
        log.error('The configuration from the %s file does not contain an "api" section.', filepath)
        raise ConfigurationError
示例#12
0
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
r"""This package provides utility functions for building and running TDM programs"""
from __future__ import annotations

from copy import deepcopy
from typing import Any, Dict, List, Optional, Tuple, Union

import blackbird as bb
import numpy as np

from strawberryfields.logger import create_logger

logger = create_logger(__name__)

pi = np.pi


def get_mode_indices(delays: List[int]) -> Tuple[np.ndarray, int]:
    """Calculates the mode indices for use in a ``TDMProgram``.

    Args:
        delays (list[int]): List of loop delays. E.g. ``delays = [1, 6, 36]`` for Borealis.

    Returns:
        tuple(ndarray, int): the mode indices and number of concurrent (or 'alive')
        modes for the program
    """
    cum_sums = np.cumsum([1] + delays)