Skip to content
This repository has been archived by the owner on Dec 7, 2021. It is now read-only.

Refactor logging methods #803

Merged
merged 11 commits into from
Jan 31, 2020
14 changes: 11 additions & 3 deletions .travis.yml
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ stage_dependencies: &stage_dependencies
- |
if [ "$INSTALL_PSI4" == "yes" ]; then
# Download and install miniconda psi4
wget http://vergil.chemistry.gatech.edu/psicode-download/psi4conda-1.2-py36-Linux-x86_64.sh -O miniconda.sh
wget http://vergil.chemistry.gatech.edu/psicode-download/Psi4conda-1.3.2-py37-Linux-x86_64.sh -O miniconda.sh
bash miniconda.sh -b -p $HOME/miniconda
source "$HOME/miniconda/etc/profile.d/conda.sh"
conda activate
Expand All @@ -58,6 +58,11 @@ stage_dependencies: &stage_dependencies
unzip /tmp/qiskit-ignis.zip -d /tmp/
# Install local Qiskit Ignis
pip install -e /tmp/qiskit-ignis-$DEPENDENCY_BRANCH --progress-bar off
# Download github IBMQ Provider
wget https://codeload.github.com/Qiskit/qiskit-ibmq-provider/zip/$DEPENDENCY_BRANCH -O /tmp/qiskit-ibmq-provider.zip
unzip /tmp/qiskit-ibmq-provider.zip -d /tmp/
# Install local Qiskit IBMQ Provider
pip install -e /tmp/qiskit-ibmq-provider-$DEPENDENCY_BRANCH --progress-bar off
# install Qiskit Aer build dependencies
sudo add-apt-repository -y ppa:ubuntu-toolchain-r/test
sudo apt-get -y update
Expand All @@ -82,6 +87,10 @@ stage_dependencies: &stage_dependencies
# install Aqua and Aqua dev. requirements
- pip install -e $TRAVIS_BUILD_DIR --progress-bar off
- pip install -U -c constraints.txt -r requirements-dev.txt --progress-bar off
- |
if [ "$DEPENDENCY_BRANCH" != "master" ]; then
pip install qiskit-ibmq-provider
fi

stage_test_aqua: &stage_test_aqua
<<: *stage_dependencies
Expand Down Expand Up @@ -159,10 +168,9 @@ jobs:
if: tag IS blank
python: 3.8
script: stestr --test-path test/aqua run --whitelist-file selection.txt
- name: "Test Chemistry Python 3.6"
- name: "Test Chemistry Python 3.7"
<<: *stage_dependencies
if: tag IS blank
python: 3.6
env:
- INSTALL_PSI4=yes
- OPENBLAS_NUM_THREADS=1
Expand Down
8 changes: 6 additions & 2 deletions qiskit/aqua/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

# This code is part of Qiskit.
#
# (C) Copyright IBM 2018, 2019.
# (C) Copyright IBM 2018, 2020.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
Expand Down Expand Up @@ -75,7 +75,9 @@
from .aqua_globals import aqua_globals
from .quantum_instance import QuantumInstance
from .algorithms import QuantumAlgorithm
from ._logging import (get_logging_level,
from ._logging import (QiskitLogDomains,
get_logging_level,
set_logging_level,
build_logging_config,
set_logging_config,
get_qiskit_aqua_logging,
Expand All @@ -86,7 +88,9 @@
'QuantumAlgorithm',
'QuantumInstance',
'aqua_globals',
'QiskitLogDomains',
'get_logging_level',
'set_logging_level',
'build_logging_config',
'set_logging_config',
'get_qiskit_aqua_logging',
Expand Down
111 changes: 69 additions & 42 deletions qiskit/aqua/_logging.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

# This code is part of Qiskit.
#
# (C) Copyright IBM 2018, 2019.
# (C) Copyright IBM 2018, 2020.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
Expand All @@ -11,51 +11,58 @@
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.

"""Utilities for logging."""

from typing import Optional, Dict, List
import os
import copy
import logging
from enum import Enum
from logging.config import dictConfig

_ALGO_LOGGING_CONFIG = {
'version': 1,
'disable_existing_loggers': False,
'formatters': {
'f': {
'format': '%(asctime)s:%(name)s:%(levelname)s: %(message)s'
},
},
'handlers': {
'h': {
'class': 'logging.StreamHandler',
'formatter': 'f'
}
},
'loggers': {}
}

class QiskitLogDomains(Enum):
""" Qiskit available Log Domains """
DOMAIN_AQUA = 'qiskit.aqua'
DOMAIN_CHEMISTRY = 'qiskit.chemistry'
DOMAIN_FINANCE = 'qiskit.finance'
DOMAIN_ML = 'qiskit.ml'
DOMAIN_OPTIMIZATION = 'qiskit.optimization'

def _get_logging_names():
return ['qiskit.aqua']


def build_logging_config(level, filepath=None):
def build_logging_config(level: int,
domains: List[QiskitLogDomains],
filepath: Optional[str] = None) -> Dict:
"""
Creates a the configuration dict of the named loggers using the default SDK
configuration provided by `_ALGO_LOGGING_CONFIG`:
Creates a configuration dict for the given domains

* console logging using a custom format for levels != level parameter.
* console logging with simple format for level parameter.
* set logger level to level parameter.

Args:
level (number): logging level
filepath (str): file to receive logging data
level: logging level
domains: Qiskit domains to be logged
filepath: file to receive logging data
Returns:
dict: New configuration dictionary
"""
dict_conf = copy.deepcopy(_ALGO_LOGGING_CONFIG)
dict_conf = {
'version': 1,
'disable_existing_loggers': False,
'formatters': {
'f': {
'format': '%(asctime)s:%(name)s:%(levelname)s: %(message)s'
},
},
'handlers': {
'h': {
'class': 'logging.StreamHandler',
'formatter': 'f'
}
},
'loggers': {}
}
if filepath is not None:
filepath = os.path.expanduser(filepath)
dict_conf['handlers']['f'] = {
Expand All @@ -66,47 +73,67 @@ def build_logging_config(level, filepath=None):
}

handlers = list(dict_conf['handlers'].keys())
for name in _get_logging_names():
dict_conf['loggers'][name] = {
for domain in domains:
dict_conf['loggers'][domain.value] = {
'handlers': handlers,
'propagate': False,
'level': level
}
return dict_conf


def get_logging_level():
"""get level for the named logger."""
return logging.getLogger('qiskit.aqua').getEffectiveLevel()
def get_logging_level(domain: QiskitLogDomains) -> int:
"""
Get level for the named logger.
Args:
domain: Qiskit domain.
Returns:
int: logging level
"""
return logging.getLogger(domain.value).getEffectiveLevel()


def set_logging_level(level: int,
domains: Optional[List[QiskitLogDomains]],
filepath: Optional[str] = None) -> None:
"""
Updates given domains with the appropriate logging level

Args:
level: logging level
domains: Qiskit domains to be logged.
filepath: file to receive logging data
"""
set_logging_config(build_logging_config(level, domains, filepath))


def set_logging_config(logging_config):
"""Update logger configurations using a SDK default one.
def set_logging_config(logging_config: Dict) -> None:
"""Update logger configurations.

Warning:
This function modifies the configuration of the standard logging system
for the loggers, and might interfere with custom logger
for all loggers, and might interfere with custom logger
configurations.
"""
dictConfig(logging_config)


def get_qiskit_aqua_logging():
def get_qiskit_aqua_logging() -> int:
"""
Returns the current Aqua logging level

Returns:
int: logging level
"""
return get_logging_level()
return get_logging_level(QiskitLogDomains.DOMAIN_AQUA)


def set_qiskit_aqua_logging(level, filepath=None):
def set_qiskit_aqua_logging(level: int, filepath: Optional[str] = None) -> None:
"""
Updates the Aqua logging with the appropriate logging level
Updates the Qiskit Aqua logging with the appropriate logging level

Args:
level (number): logging level
filepath (str): file to receive logging data
level: logging level
filepath: file to receive logging data
"""
set_logging_config(build_logging_config(level, filepath))
set_logging_level(level, [QiskitLogDomains.DOMAIN_AQUA], filepath)
6 changes: 3 additions & 3 deletions qiskit/aqua/utils/subsystem.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@
import numpy as np
from scipy.linalg import sqrtm

from qiskit.tools.qi.qi import partial_trace
from qiskit.quantum_info.states import partial_trace


def get_subsystem_density_matrix(statevector, trace_systems):
Expand All @@ -33,7 +33,7 @@ def get_subsystem_density_matrix(statevector, trace_systems):
numpy.ndarray: The reduced density matrix for the desired subsystem
"""
rho = np.outer(statevector, np.conj(statevector))
rho_sub = partial_trace(rho, trace_systems)
rho_sub = partial_trace(rho, trace_systems).data
return rho_sub


Expand All @@ -51,7 +51,7 @@ def get_subsystem_fidelity(statevector, trace_systems, subsystem_state):
numpy.ndarray: The subsystem fidelity
"""
rho = np.outer(np.conj(statevector), statevector)
rho_sub = partial_trace(rho, trace_systems)
rho_sub = partial_trace(rho, trace_systems).data
rho_sub_in = np.outer(np.conj(subsystem_state), subsystem_state)
fidelity = np.trace(
sqrtm(
Expand Down
10 changes: 2 additions & 8 deletions qiskit/chemistry/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

# This code is part of Qiskit.
#
# (C) Copyright IBM 2018, 2019.
# (C) Copyright IBM 2018, 2020.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
Expand Down Expand Up @@ -56,18 +56,12 @@
from .qmolecule import QMolecule
from .fermionic_operator import FermionicOperator
from .mp2info import MP2Info
from ._logging import (get_logging_level,
build_logging_config,
set_logging_config,
get_qiskit_chemistry_logging,
from ._logging import (get_qiskit_chemistry_logging,
set_qiskit_chemistry_logging)

__all__ = ['QiskitChemistryError',
'QMolecule',
'FermionicOperator',
'MP2Info',
'get_logging_level',
'build_logging_config',
'set_logging_config',
'get_qiskit_chemistry_logging',
'set_qiskit_chemistry_logging']
Loading