<commit_before>#!/usr/bin/env python

"""Test that check config script handles various broken configs."""

# Copyright (C) 2015 Brad Cowie, Christopher Lorier and Joe Stringer.
# Copyright (C) 2015 Research and Innovation Advanced Network New Zealand Ltd.
# Copyright (C) 2015--2019 The Contributors
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#    http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# 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.

import logging
import os
import shutil
import tempfile
import unittest
import re

from faucet.check_faucet_config import check_config

class CheckConfigTestCase(unittest.TestCase): # pytype: disable=module-attr
    """Test that check config script handles various broken configs."""

    tmpdir = None

    def setUp(self):
        self.tmpdir = tempfile.mkdtemp()

    def tearDown(self):
        shutil.rmtree(self.tmpdir)

    def run_check_config(self, config, expected_ok):
        """Try to parse config and return True if result fails or succeeds as expected."""
        conf_files = []
        if config is not None:
            conf_file_name = os.path.join(self.tmpdir, 'faucet.yaml')
            with open(conf_file_name, 'w') as conf_file:
                conf_file.write(config)
            conf_files = [conf_file_name]
        with open(os.devnull, 'w') as check_output_file:
            result_ok = check_config( # pylint: disable=unexpected-keyword-arg
                conf_files, logging.FATAL, check_output_file)
        return expected_ok == result_ok

    def _deprecated_acl_check(self, config, success):
        # TODO: Check acls_in work now acl_in is deprecated, remove in future
        if config and 'acl_in' in config and not 'acls_in' in config:
            acls_cfg = re.sub('(acl_in: )(.*)', 'acls_in: [\\2]', config)
            self.assertTrue(self.run_check_config(acls_cfg, success))

    def check_config_success(self, config):
        """Try to parse config and expect success."""
        self.assertTrue(self.run_check_config(config, True))
        self._deprecated_acl_check(config, True)

    def check_config_failure(self, config):
        """Try to parse config and expect failure."""
        self.assertTrue(self.run_check_config(config, False))
        self._deprecated_acl_check(config, False)

    def test_no_dps(self):
        """Test bad config with no DPs."""
        no_dps_conf = """
vlans:
    100:
        description: "100"
"""
        self.check_config_failure(no_dps_conf)

    def test_minimal(self):
        """Test minimal correct config."""
        minimal_conf = """
vlans:
    100:
        description: "100"
dps:
    switch1:
        dp_id: 0xcafef00d
        hardware: 'Open vSwitch'
        interfaces:
            1:
                native_vlan: 100
"""
        self.check_config_success(minimal_conf)

    def test_include_optional(self):
        """Test minimal include optional correct config."""
        minimal_conf = """
include-optional: ['/nonexistant']
vlans:
    100:
        description: "100"
dps:
    switch1:
        dp_id: 0xcafef00d
        hardware: 'Open vSwitch'
        interfaces:
            1:
                native_vlan: 100
"""
        self.check_config_success(minimal_conf)

    def test_include_required(self):
        """Test minimal include optional correct config."""
        minimal_conf = """
include: ['/nonexistant']
vlans:
    100:
        description: "100"
dps:
    switch1:
        dp_id: 0xcafef00d
        hardware: 'Open vSwitch'
        interfaces:
            1:
                native_vlan: 100
"""
        self.check_config_failure(minimal_conf)

    def test_invalid_vid(self):
        """Test invalid VID."""
        invalid_vid_conf = """
vlans:
    100:
        description: "100"
dps:
    switch1:
        dp_id: 0xcafef00d
        hardware: 'Open vSwitch'
        interfaces:
            1:
                native_vlan: 4097
"""
        self.check_config_failure(invalid_vid_conf)

    def test_vlan_name(self):
        """Test vlan referred by its name."""
        vlan_name_conf = """
vlans:
    finance:
        description: "FINANCE VLAN"
        vid: 100
dps:
    switch1:
        dp_id: 0xcafef00d
        hardware: 'Open vSwitch'
        interfaces:
            1:
                native_vlan: finance
"""
        self.check_config_success(vlan_name_conf)

    def test_no_interfaces(self):
        """Test DP has no interfaces."""
        no_interfaces_conf = """
vlans:
    100:
        description: "100"
dps:
    switch1:
        dp_id: 0xcafef00d
        hardware: 'Open vSwitch'
"""
        self.check_config_failure(no_interfaces_conf)

    def test_tabs(self):
        """Test that config with tabs is rejected."""
        tab_conf = """
vlans:
    100:
        	description: "100"
dps:
    switch1:
        dp_id: 0xcafef00d
        hardware: 'Open vSwitch'
        interfaces:
            1:
                native_vlan: 100
"""
        self.check_config_failure(tab_conf)

    def test_no_vlan(self):
        """Test port without a VLAN rejected."""
        no_vlan_config = """
dps:
    switch1:
        dp_id: 0xcafef00d
        hardware: 'NOTSUPPORTED'
        interfaces:
            1:
                description: 'vlanless'
"""
        self.check_config_failure(no_vlan_config)

    def test_unknown_dp_config_item(self):
        """Test that an unknown DP field is rejected."""
        unknown_dp_config_item = """
vlans:
    100:
        description: "100"
dps:
    switch1:
        dp_id: 0xcafef00d
        hardware: 'Open vSwitch'
        broken: something
        interfaces:
            1:
                native_vlan: 100
"""
        self.check_config_failure(unknown_dp_config_item)

    def test_toplevel_unknown_config(self):
        """Test that an unknown toplevel config section is rejected."""
        toplevel_unknown_config = """
vlans:
    100:
        description: "100"
dps:
    switch1:
        dp_id: 0xcafef00d
        hardware: 'Open vSwitch'
        interfaces:
            1:
                native_vlan: 100
unknown_thing: 1
"""
        self.check_config_failure(toplevel_unknown_config)

    def test_toplevel_unknown_hardware(self):
        """Test that unknown hardware is rejected."""
        unknown_hardware_config = """
vlans:
    100:
        description: "100"
dps:
    switch1:
        dp_id: 0xcafef00d
        hardware: 'NOTSUPPORTED'
        interfaces:
            1:
                native_vlan: 100
"""
        self.check_config_failure(unknown_hardware_config)

    def test_stacking_noroot(self):
        """Test that a stacking root is defined."""
        stacking_config = """
vlans:
    100:
        description: "100"
dps:
    switch1:
        dp_id: 0xcafef00d
        hardware: 'Open vSwitch'
        stack:
            priority: 0
        interfaces:
            1:
                native_vlan: 100
"""
        self.check_config_failure(stacking_config)

    def test_bad_acl_action(self):
        """Test that an ACL with a bad match field is rejected."""
        acl_config = """
vlans:
    100:
        description: "100"
acls:
    101:
        - rule:
            nogood: '0e:00:00:00:02:02'
            actions:
                output:
                    port: 1
dps:
    switch1:
        dp_id: 0xcafef00d
        hardware: 'Open vSwitch'
        interfaces:
            1:
                native_vlan: 100
                acl_in: 101
"""
        self.check_config_failure(acl_config)

    def test_bad_acl_vlan(self):
        """Test that an ACL with a bad match field is rejected."""
        acl_config = """
vlans:
    100:
        description: "100"
        acl_in: 101
acls:
    101:
        - rule:
            nogood: "0e:00:00:00:02:02"
            actions:
                output:
                    port: 1
dps:
    switch1:
        dp_id: 0xcafef00d
        hardware: 'Open vSwitch'
        interfaces:
            1:
                native_vlan: 100
"""
        self.check_config_failure(acl_config)

    def test_good_acl(self):
        """Test that an ACL with good match field is accepted."""
        acl_config = """
vlans:
    100:
        description: "100"
acls:
    101:
        - rule:
            dl_dst: "0e:00:00:00:02:02"
            actions:
                output:
                    port: 1
dps:
    switch1:
        dp_id: 0xcafef00d
        hardware: 'Open vSwitch'
        interfaces:
            1:
                native_vlan: 100
                acl_in: 101
"""
        self.check_config_success(acl_config)

    def test_ports_good_acl(self):
        """Test that an ACL with good match field is accepted."""
        acl_config = """
vlans:
    100:
        description: "100"
acls:
    101:
        - rule:
            dl_dst: "0e:00:00:00:02:02"
            actions:
                output:
                    ports: [1, 2]
dps:
    switch1:
        dp_id: 0xcafef00d
        hardware: 'Open vSwitch'
        interfaces:
            1:
                native_vlan: 100
                acl_in: 101
            2:
                native_vlan: 100
                acl_in: 101
"""
        self.check_config_success(acl_config)

    def test_multiple_dps(self):
        """Test multiple DPs."""
        acl_config = """
vlans:
    100:
        description: "100"
dps:
    switch1:
        dp_id: 0xcafef00d
        hardware: 'Open vSwitch'
        interfaces:
            1:
                native_vlan: 100
    switch2:
        dp_id: 0xcafef00e
        hardware: 'Open vSwitch'
        interfaces:
            1:
                native_vlan: 100
"""
        self.check_config_success(acl_config)

    def test_router_resolved_vlans(self):
        """Test that VLANs get resolved by routers."""
        vlan_config = """
vlans:
    100:
        description: "100"
    200:
        description: "200"
routers:
    router1:
        vlans: [100, 200]
dps:
    switch1:
        dp_id: 0xcafef00d
        hardware: 'Open vSwitch'
        interfaces:
            1:
                native_vlan: 100
            2:
                native_vlan: 200
    switch2:
        dp_id: 0xdeadbeef
        hardware: 'Open vSwitch'
        interfaces:
            1:
                native_vlan: 200
"""
        self.check_config_success(vlan_config)

    def test_no_config_file(self):
        """Test no config file handled."""
        self.check_config_failure(None)

if __name__ == "__main__":
    unittest.main() # pytype: disable=module-attr
<commit_msg>Obsolete test.<commit_after>#!/usr/bin/env python

"""Test that check config script handles various broken configs."""

# Copyright (C) 2015 Brad Cowie, Christopher Lorier and Joe Stringer.
# Copyright (C) 2015 Research and Innovation Advanced Network New Zealand Ltd.
# Copyright (C) 2015--2019 The Contributors
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#    http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# 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.

import logging
import os
import shutil
import tempfile
import unittest
import re

from faucet.check_faucet_config import check_config

class CheckConfigTestCase(unittest.TestCase): # pytype: disable=module-attr
    """Test that check config script handles various broken configs."""

    tmpdir = None

    def setUp(self):
        self.tmpdir = tempfile.mkdtemp()

    def tearDown(self):
        shutil.rmtree(self.tmpdir)

    def run_check_config(self, config, expected_ok):
        """Try to parse config and return True if result fails or succeeds as expected."""
        conf_files = []
        if config is not None:
            conf_file_name = os.path.join(self.tmpdir, 'faucet.yaml')
            with open(conf_file_name, 'w') as conf_file:
                conf_file.write(config)
            conf_files = [conf_file_name]
        with open(os.devnull, 'w') as check_output_file:
            result_ok = check_config( # pylint: disable=unexpected-keyword-arg
                conf_files, logging.FATAL, check_output_file)
        return expected_ok == result_ok

    def _deprecated_acl_check(self, config, success):
        # TODO: Check acls_in work now acl_in is deprecated, remove in future
        if config and 'acl_in' in config and not 'acls_in' in config:
            acls_cfg = re.sub('(acl_in: )(.*)', 'acls_in: [\\2]', config)
            self.assertTrue(self.run_check_config(acls_cfg, success))

    def check_config_success(self, config):
        """Try to parse config and expect success."""
        self.assertTrue(self.run_check_config(config, True))
        self._deprecated_acl_check(config, True)

    def check_config_failure(self, config):
        """Try to parse config and expect failure."""
        self.assertTrue(self.run_check_config(config, False))
        self._deprecated_acl_check(config, False)

    def test_no_dps(self):
        """Test bad config with no DPs."""
        no_dps_conf = """
vlans:
    100:
        description: "100"
"""
        self.check_config_failure(no_dps_conf)

    def test_minimal(self):
        """Test minimal correct config."""
        minimal_conf = """
vlans:
    100:
        description: "100"
dps:
    switch1:
        dp_id: 0xcafef00d
        hardware: 'Open vSwitch'
        interfaces:
            1:
                native_vlan: 100
"""
        self.check_config_success(minimal_conf)

    def test_include_optional(self):
        """Test minimal include optional correct config."""
        minimal_conf = """
include-optional: ['/nonexistant']
vlans:
    100:
        description: "100"
dps:
    switch1:
        dp_id: 0xcafef00d
        hardware: 'Open vSwitch'
        interfaces:
            1:
                native_vlan: 100
"""
        self.check_config_success(minimal_conf)

    def test_include_required(self):
        """Test minimal include optional correct config."""
        minimal_conf = """
include: ['/nonexistant']
vlans:
    100:
        description: "100"
dps:
    switch1:
        dp_id: 0xcafef00d
        hardware: 'Open vSwitch'
        interfaces:
            1:
                native_vlan: 100
"""
        self.check_config_failure(minimal_conf)

    def test_invalid_vid(self):
        """Test invalid VID."""
        invalid_vid_conf = """
vlans:
    100:
        description: "100"
dps:
    switch1:
        dp_id: 0xcafef00d
        hardware: 'Open vSwitch'
        interfaces:
            1:
                native_vlan: 4097
"""
        self.check_config_failure(invalid_vid_conf)

    def test_vlan_name(self):
        """Test vlan referred by its name."""
        vlan_name_conf = """
vlans:
    finance:
        description: "FINANCE VLAN"
        vid: 100
dps:
    switch1:
        dp_id: 0xcafef00d
        hardware: 'Open vSwitch'
        interfaces:
            1:
                native_vlan: finance
"""
        self.check_config_success(vlan_name_conf)

    def test_no_interfaces(self):
        """Test DP has no interfaces."""
        no_interfaces_conf = """
vlans:
    100:
        description: "100"
dps:
    switch1:
        dp_id: 0xcafef00d
        hardware: 'Open vSwitch'
"""
        self.check_config_failure(no_interfaces_conf)

    def test_tabs(self):
        """Test that config with tabs is rejected."""
        tab_conf = """
vlans:
    100:
        	description: "100"
dps:
    switch1:
        dp_id: 0xcafef00d
        hardware: 'Open vSwitch'
        interfaces:
            1:
                native_vlan: 100
"""
        self.check_config_failure(tab_conf)

    def test_no_vlan(self):
        """Test port without a VLAN rejected."""
        no_vlan_config = """
dps:
    switch1:
        dp_id: 0xcafef00d
        hardware: 'NOTSUPPORTED'
        interfaces:
            1:
                description: 'vlanless'
"""
        self.check_config_failure(no_vlan_config)

    def test_unknown_dp_config_item(self):
        """Test that an unknown DP field is rejected."""
        unknown_dp_config_item = """
vlans:
    100:
        description: "100"
dps:
    switch1:
        dp_id: 0xcafef00d
        hardware: 'Open vSwitch'
        broken: something
        interfaces:
            1:
                native_vlan: 100
"""
        self.check_config_failure(unknown_dp_config_item)

    def test_toplevel_unknown_config(self):
        """Test that an unknown toplevel config section is rejected."""
        toplevel_unknown_config = """
vlans:
    100:
        description: "100"
dps:
    switch1:
        dp_id: 0xcafef00d
        hardware: 'Open vSwitch'
        interfaces:
            1:
                native_vlan: 100
unknown_thing: 1
"""
        self.check_config_failure(toplevel_unknown_config)

    def test_toplevel_unknown_hardware(self):
        """Test that unknown hardware is rejected."""
        unknown_hardware_config = """
vlans:
    100:
        description: "100"
dps:
    switch1:
        dp_id: 0xcafef00d
        hardware: 'NOTSUPPORTED'
        interfaces:
            1:
                native_vlan: 100
"""
        self.check_config_failure(unknown_hardware_config)

    def test_bad_acl_action(self):
        """Test that an ACL with a bad match field is rejected."""
        acl_config = """
vlans:
    100:
        description: "100"
acls:
    101:
        - rule:
            nogood: '0e:00:00:00:02:02'
            actions:
                output:
                    port: 1
dps:
    switch1:
        dp_id: 0xcafef00d
        hardware: 'Open vSwitch'
        interfaces:
            1:
                native_vlan: 100
                acl_in: 101
"""
        self.check_config_failure(acl_config)

    def test_bad_acl_vlan(self):
        """Test that an ACL with a bad match field is rejected."""
        acl_config = """
vlans:
    100:
        description: "100"
        acl_in: 101
acls:
    101:
        - rule:
            nogood: "0e:00:00:00:02:02"
            actions:
                output:
                    port: 1
dps:
    switch1:
        dp_id: 0xcafef00d
        hardware: 'Open vSwitch'
        interfaces:
            1:
                native_vlan: 100
"""
        self.check_config_failure(acl_config)

    def test_good_acl(self):
        """Test that an ACL with good match field is accepted."""
        acl_config = """
vlans:
    100:
        description: "100"
acls:
    101:
        - rule:
            dl_dst: "0e:00:00:00:02:02"
            actions:
                output:
                    port: 1
dps:
    switch1:
        dp_id: 0xcafef00d
        hardware: 'Open vSwitch'
        interfaces:
            1:
                native_vlan: 100
                acl_in: 101
"""
        self.check_config_success(acl_config)

    def test_ports_good_acl(self):
        """Test that an ACL with good match field is accepted."""
        acl_config = """
vlans:
    100:
        description: "100"
acls:
    101:
        - rule:
            dl_dst: "0e:00:00:00:02:02"
            actions:
                output:
                    ports: [1, 2]
dps:
    switch1:
        dp_id: 0xcafef00d
        hardware: 'Open vSwitch'
        interfaces:
            1:
                native_vlan: 100
                acl_in: 101
            2:
                native_vlan: 100
                acl_in: 101
"""
        self.check_config_success(acl_config)

    def test_multiple_dps(self):
        """Test multiple DPs."""
        acl_config = """
vlans:
    100:
        description: "100"
dps:
    switch1:
        dp_id: 0xcafef00d
        hardware: 'Open vSwitch'
        interfaces:
            1:
                native_vlan: 100
    switch2:
        dp_id: 0xcafef00e
        hardware: 'Open vSwitch'
        interfaces:
            1:
                native_vlan: 100
"""
        self.check_config_success(acl_config)

    def test_router_resolved_vlans(self):
        """Test that VLANs get resolved by routers."""
        vlan_config = """
vlans:
    100:
        description: "100"
    200:
        description: "200"
routers:
    router1:
        vlans: [100, 200]
dps:
    switch1:
        dp_id: 0xcafef00d
        hardware: 'Open vSwitch'
        interfaces:
            1:
                native_vlan: 100
            2:
                native_vlan: 200
    switch2:
        dp_id: 0xdeadbeef
        hardware: 'Open vSwitch'
        interfaces:
            1:
                native_vlan: 200
"""
        self.check_config_success(vlan_config)

    def test_no_config_file(self):
        """Test no config file handled."""
        self.check_config_failure(None)

if __name__ == "__main__":
    unittest.main() # pytype: disable=module-attr
<|endoftext|>


<commit_before>import os
import signal
import sys
import socket, time
import cv
#from PIL import Image

# This makes sure the path which python uses to find things when using import
# can find all our code.
sys.path.insert(0, os.path.abspath('..'))
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))

# Import qt modules (platform independant)
import ardrone.util.qtcompat as qt
QtCore = qt.import_module('QtCore')
QtNetwork = qt.import_module('QtNetwork')

# Import the actual drone control stuff.
from ardrone.core.controlloop import ControlLoop
from ardrone.platform import qt as platform

# Import video decoder
import ardrone.core.videopacket as videopacket

class imageViewer(object):

	win_title = "Drone Video Feed"

	def __init__(self):
		# Create a QtCoreApplication loop (NB remember to use QApplication instead if wanting GUI features)
		self.app = QtCore.QCoreApplication(sys.argv)

		# Wire up Ctrl-C to call QApplication.quit()
		signal.signal(signal.SIGINT, lambda *args: self.app.quit())

		# Initialise the drone control loop and attempt to open a connection.
		connection = platform.Connection()
		self._control = ControlLoop(connection, video_cb=None, navdata_cb=None)

		# Create a window in which to place frames
		cv.NamedWindow(self.win_title, cv.CV_WINDOW_AUTOSIZE) #probably no need to autosize

		# Set up a UDP listening socket on port 5562 which calls readData upon socket activity
		self.socket = QtNetwork.QUdpSocket()
		if not self.socket.bind(QtNetwork.QHostAddress.Any, 5562):
			raise RuntimeError('Error binding to port: %s' % (self.socket.errorString()))
		self.socket.readyRead.connect(self.readData)

		# Start video on drone
		self._control.start_video()

	def run(self):
		self.app.exec_()

	def readData(self):
		"""Called when there is some interesting data to read on the video socket."""
		while self.socket.hasPendingDatagrams():
			sz = self.socket.pendingDatagramSize()
			(data, host, port) = self.socket.readDatagram(sz)

		# Some hack to account for PySide vs. PyQt differences
		if qt.USES_PYSIDE:
			data = data.data()

		# Decode video data and pass result to showImage
		videopacket.Decoder(self.showImage).decode(data)

	def showImage(self, data):
		"""
		Displays argument image in window using openCV.
		data argument must be a string containing a 16 bit unsigned RGB image (RGB16 == RGB565).
		"""

		iplimage = cv.CreateImageHeader((320,240), cv.IPL_DEPTH_16U, 1)
		cv.SetData(iplimage, data)
		cv.ShowImage(self.win_title, iplimage)

if (__name__ == '__main__'):
  image_app = imageViewer()
  image_app.run()
<commit_msg>qtdronevideo: Stopped creating a new instance of decoder for every data packet, image conversion now working correctly<commit_after>import os
import signal
import sys
import socket, time
import cv
from PIL import Image
from numpy import array

# This makes sure the path which python uses to find things when using import
# can find all our code.
sys.path.insert(0, os.path.abspath('..'))
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))

# Import qt modules (platform independant)
import ardrone.util.qtcompat as qt
QtCore = qt.import_module('QtCore')
QtNetwork = qt.import_module('QtNetwork')

# Import the actual drone control stuff.
from ardrone.core.controlloop import ControlLoop
from ardrone.platform import qt as platform

# Import video decoder
import ardrone.core.videopacket as videopacket

class imageViewer(object):

	win_title = "Drone Video Feed"

	def __init__(self):
		# Create a QtCoreApplication loop (NB remember to use QApplication instead if wanting GUI features)
		self.app = QtCore.QCoreApplication(sys.argv)

		# Wire up Ctrl-C to call QApplication.quit()
		signal.signal(signal.SIGINT, lambda *args: self.app.quit())

		# Initialise the drone control loop and attempt to open a connection.
		connection = platform.Connection()
		self._control = ControlLoop(connection, video_cb=None, navdata_cb=None)

		# Create a window in which to place frames
		cv.NamedWindow(self.win_title, cv.CV_WINDOW_AUTOSIZE) #probably no need to autosize

		# Set up a UDP listening socket on port 5562 which calls readData upon socket activity
		self.socket = QtNetwork.QUdpSocket()
		if not self.socket.bind(QtNetwork.QHostAddress.Any, 5562):
			raise RuntimeError('Error binding to port: %s' % (self.socket.errorString()))
		self.socket.readyRead.connect(self.readData)

		# Create decoder object
		self._vid_decoder = videopacket.Decoder(self.showImage)

		# Start video on drone
		self._control.start_video()

	def run(self):
		self.app.exec_()

	def readData(self):
		"""Called when there is some interesting data to read on the video socket."""
		while self.socket.hasPendingDatagrams():
			sz = self.socket.pendingDatagramSize()
			(data, host, port) = self.socket.readDatagram(sz)

		# Some hack to account for PySide vs. PyQt differences
		if qt.USES_PYSIDE:
			data = data.data()

		# Decode video data and pass result to showImage
		self._vid_decoder.decode(data)

	def showImage(self, data):
		"""
		Displays argument image in window using openCV.
		data argument must be a string containing a 16 bit unsigned RGB image (RGB16 == RGB565).
		"""

		iplimage = cv.CreateImageHeader((320,240), cv.IPL_DEPTH_8U, 2)
		RGBimage = cv.CreateImage((320,240), cv.IPL_DEPTH_8U, 3)
		cv.SetData(iplimage, data)
		cv.CvtColor(iplimage, RGBimage, cv.CV_BGR5652BGR)
		cv.ShowImage(self.win_title, RGBimage)

if (__name__ == '__main__'):
  image_app = imageViewer()
  image_app.run()
<|endoftext|>


<commit_before># -*- coding: utf-8 -*-
# This file is part of Quantum.
#
#    Copyright (c) 2017, Diego Nicolás Bernal-García
#    All rights reserved.
#
#    Redistribution and use in source and binary forms, with or without
#    modification, are permitted provided that the following conditions are
#    met:
#
#    * Redistributions of source code must retain the above copyright notice,
#      this list of conditions and the following disclaimer.
#
#    * Redistributions in binary form must reproduce the above copyright
#      notice, this list of conditions and the following disclaimer in the
#      documentation and/or other materials provided with the distribution.
#
#    THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
#    "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
#    LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
#    PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
#    HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
#    SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
#    LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
#    DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
#    THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
#    (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
#    OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
###############################################################################
#
# The functions in these module were inspired by:
# QuTiP: Quantum Toolbox in Python.
#
#    Copyright (c) 2011 and later, Paul D. Nation and Robert J. Johansson.
#    All rights reserved.
#
#    Redistribution and use in source and binary forms, with or without
#    modification, are permitted provided that the following conditions are
#    met:
#
#    1. Redistributions of source code must retain the above copyright notice,
#       this list of conditions and the following disclaimer.
#
#    2. Redistributions in binary form must reproduce the above copyright
#       notice, this list of conditions and the following disclaimer in the
#       documentation and/or other materials provided with the distribution.
#
#    3. Neither the name of the QuTiP: Quantum Toolbox in Python nor the names
#       of its contributors may be used to endorse or promote products derived
#       from this software without specific prior written permission.
#
#    THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
#    "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
#    LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
#    PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
#    HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
#    SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
#    LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
#    DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
#    THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
#    (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
#    OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
###############################################################################
"""
This module contains a collection of operations commonly used in quantum
mechanics.
"""

__all__ = ['dag', 'isherm', 'expm']

from qutip.sparse import sp_expm
from qutip.qobj import Qobj
import qutip.settings as settings

def dag(A):
    """Adjont operator (dagger) of a quantum object.

    Parameters
    ----------
    A : qobj
        Input quantum object.

    Returns
    -------
    oper : qobj
        Adjoint of input operator

    Notes
    -----
    This function is for legacy compatibility only. It is recommended to use
    the ``dag()`` Qobj method.

    """
    if not isinstance(A, Qobj):
        raise TypeError("Input is not a quantum object")

    return A.dag()

def isherm(Q):
    """Determines if given operator is Hermitian.

    Parameters
    ----------
    Q : qobj
        Quantum object

    Returns
    -------
    isherm : bool
        True if operator is Hermitian, False otherwise.

    Examples
    --------
    >>> a = destroy(4)
    >>> isherm(a)
    False

    Notes
    -----
    This function is for legacy compatibility only. Using the `Qobj.isherm`
    attribute is recommended.

    """
    return True if isinstance(Q, Qobj) and Q.isherm else False

def expm(Q, method='sparse'):
    """Matrix exponential of quantum operator.

    Input operator must be square.

    Parameters
    ----------
    method : str {'dense', 'sparse'}
        Use set method to use to calculate the matrix exponentiation. The
        available choices includes 'dense' and 'sparse'.  Since the
        exponential of a matrix is nearly always dense, method='dense'
        is set as default.s

    Returns
    -------
    oper : qobj
        Exponentiated quantum operator.

    Raises
    ------
    TypeError
        Quantum operator is not square.

    """
    if not isinstance(Q, Qobj):
        raise TypeError('Input is not a quantum object')

    if Q.dims[0][0] != Q.dims[1][0]:
        raise TypeError('Invalid operand for matrix exponential')

    if method == 'sparse':
        F = sp_expm(Q.data, sparse=True)

    elif method == 'dense':
        F = sp_expm(Q.data, sparse=False)

    else:
        raise ValueError("method must be 'dense' or 'sparse'.")

    out = Qobj(F, dims=Q.dims)
    return out.tidyup() if settings.auto_tidyup else out
<commit_msg>Update qobj.py<commit_after># -*- coding: utf-8 -*-
# This file is part of Quantum.
#
#    Copyright (c) 2017, Diego Nicolás Bernal-García
#    All rights reserved.
#
#    Redistribution and use in source and binary forms, with or without
#    modification, are permitted provided that the following conditions are
#    met:
#
#    * Redistributions of source code must retain the above copyright notice,
#      this list of conditions and the following disclaimer.
#
#    * Redistributions in binary form must reproduce the above copyright
#      notice, this list of conditions and the following disclaimer in the
#      documentation and/or other materials provided with the distribution.
#
#    THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
#    "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
#    LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
#    PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
#    HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
#    SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
#    LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
#    DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
#    THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
#    (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
#    OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
###############################################################################
#
# The functions in this module were inspired by:
# QuTiP: Quantum Toolbox in Python.
#
#    Copyright (c) 2011 and later, Paul D. Nation and Robert J. Johansson.
#    All rights reserved.
#
#    Redistribution and use in source and binary forms, with or without
#    modification, are permitted provided that the following conditions are
#    met:
#
#    1. Redistributions of source code must retain the above copyright notice,
#       this list of conditions and the following disclaimer.
#
#    2. Redistributions in binary form must reproduce the above copyright
#       notice, this list of conditions and the following disclaimer in the
#       documentation and/or other materials provided with the distribution.
#
#    3. Neither the name of the QuTiP: Quantum Toolbox in Python nor the names
#       of its contributors may be used to endorse or promote products derived
#       from this software without specific prior written permission.
#
#    THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
#    "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
#    LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
#    PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
#    HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
#    SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
#    LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
#    DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
#    THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
#    (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
#    OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
###############################################################################
"""
This module contains a collection of operations commonly used in quantum
mechanics.
"""

__all__ = ['dag', 'isherm', 'expm']

from qutip.sparse import sp_expm
from qutip.qobj import Qobj
import qutip.settings as settings

def dag(A):
    """Adjont operator (dagger) of a quantum object.

    Parameters
    ----------
    A : qobj
        Input quantum object.

    Returns
    -------
    oper : qobj
        Adjoint of input operator

    Notes
    -----
    This function is for legacy compatibility only. It is recommended to use
    the ``dag()`` Qobj method.

    """
    if not isinstance(A, Qobj):
        raise TypeError("Input is not a quantum object")

    return A.dag()

def isherm(Q):
    """Determines if given operator is Hermitian.

    Parameters
    ----------
    Q : qobj
        Quantum object

    Returns
    -------
    isherm : bool
        True if operator is Hermitian, False otherwise.

    Examples
    --------
    >>> a = destroy(4)
    >>> isherm(a)
    False

    Notes
    -----
    This function is for legacy compatibility only. Using the `Qobj.isherm`
    attribute is recommended.

    """
    return True if isinstance(Q, Qobj) and Q.isherm else False

def expm(Q, method='sparse'):
    """Matrix exponential of quantum operator.

    Input operator must be square.

    Parameters
    ----------
    method : str {'dense', 'sparse'}
        Use set method to use to calculate the matrix exponentiation. The
        available choices includes 'dense' and 'sparse'.  Since the
        exponential of a matrix is nearly always dense, method='dense'
        is set as default.s

    Returns
    -------
    oper : qobj
        Exponentiated quantum operator.

    Raises
    ------
    TypeError
        Quantum operator is not square.

    """
    if not isinstance(Q, Qobj):
        raise TypeError('Input is not a quantum object')

    if Q.dims[0][0] != Q.dims[1][0]:
        raise TypeError('Invalid operand for matrix exponential')

    if method == 'sparse':
        F = sp_expm(Q.data, sparse=True)

    elif method == 'dense':
        F = sp_expm(Q.data, sparse=False)

    else:
        raise ValueError("method must be 'dense' or 'sparse'.")

    out = Qobj(F, dims=Q.dims)
    return out.tidyup() if settings.auto_tidyup else out
<|endoftext|>


<commit_before>import pytest
from django.core.urlresolvers import reverse

from thclient import TreeherderResultSetCollection
from tests import test_utils

from treeherder.webapp.api import utils

def test_resultset_list(webapp, eleven_jobs_processed, jm):
    """
    test retrieving a list of ten json blobs from the jobs-list
    endpoint.
    """
    resp = webapp.get(
        reverse("resultset-list", kwargs={"project": jm.project})
    )

    assert resp.status_int == 200
    assert isinstance(resp.json, list)
    rs_list = resp.json

    assert len(rs_list) == 10
    exp_keys = set([
        u'id',
        u'repository_id',
        u'push_timestamp',
        u'author',
        u'comments',
        u'revision_hash',
        u'revision',
        u'revision_list',
        u'revision_count',
        u'revisions_uri',
        u'job_counts',
        u'platforms'
    ])
    for rs in rs_list:
        assert set(rs.keys()) == exp_keys

def test_resultset_list_bad_project(webapp, jm):
    """
    test retrieving a list of ten json blobs from the jobs-list
    endpoint.
    """
    resp = webapp.get(
        reverse("resultset-list", kwargs={"project": "foo"}),
        expect_errors=True
    )

    assert resp.status_int == 404
    assert resp.json == {"message": "No project with name foo"}

def test_resultset_list_empty_rs_still_show(webapp, initial_data,
                                            sample_resultset, jm):
    """
    test retrieving a resultset list, when the resultset has no jobs.
    should show.
    """
    jm.store_result_set_data(sample_resultset)

    resp = webapp.get(
        reverse("resultset-list", kwargs={"project": jm.project}),
    )
    assert resp.status_int == 200
    assert len(resp.json) == 10

def test_resultset_list_filter_by_revision(webapp, eleven_jobs_processed, jm):
    """
    test retrieving a resultset list, filtered by a date range
    """

    resp = webapp.get(
        reverse("resultset-list", kwargs={"project": jm.project}),
        {"fromchange": "21fb3eed1b5f", "tochange": "909f55c626a8"}
    )
    assert resp.status_int == 200
    assert len(resp.json) == 4
    assert set([rs["revision"] for rs in resp.json]) == set(
        ["909f55c626a8","71d49fee325a","bb57e9f67223","21fb3eed1b5f"]
        )

def test_resultset_list_filter_by_date(webapp, initial_data,
                                       sample_resultset, jm):
    """
    test retrieving a resultset list, filtered by a date range
    """
    sample_resultset[3]["push_timestamp"] = utils.to_timestamp("2013-08-09")
    sample_resultset[4]["push_timestamp"] = utils.to_timestamp("2013-08-10")
    sample_resultset[5]["push_timestamp"] = utils.to_timestamp("2013-08-11")
    sample_resultset[6]["push_timestamp"] = utils.to_timestamp("2013-08-12")
    sample_resultset[7]["push_timestamp"] = utils.to_timestamp("2013-08-13")

    jm.store_result_set_data(sample_resultset)

    resp = webapp.get(
        reverse("resultset-list", kwargs={"project": jm.project}),
        {"startdate": "2013-08-10", "enddate": "2013-08-13"}
    )
    assert resp.status_int == 200
    assert len(resp.json) == 4
    assert set([rs["revision"] for rs in resp.json]) == set(
        ["909f55c626a8","71d49fee325a","bb57e9f67223","668424578a0d"]
        )

def test_resultset_detail(webapp, eleven_jobs_processed, jm):
    """
    test retrieving a resultset from the resultset-detail
    endpoint.
    """

    rs_list = jm.get_result_set_list(0, 10)
    rs = rs_list[0]

    resp = webapp.get(
        reverse("resultset-detail",
                kwargs={"project": jm.project, "pk": int(rs["id"])})
    )
    assert resp.status_int == 200
    assert isinstance(resp.json, dict)
    assert resp.json["id"] == rs["id"]

def test_result_set_detail_not_found(webapp, jm):
    """
    test retrieving a HTTP 404 from the resultset-detail
    endpoint.
    """
    resp = webapp.get(
        reverse("resultset-detail",
                kwargs={"project": jm.project, "pk": -32767}),
        expect_errors=True
    )
    assert resp.status_int == 404

def test_result_set_detail_bad_project(webapp, jm):
    """
    test retrieving a HTTP 404 from the resultset-detail
    endpoint.
    """
    resp = webapp.get(
        reverse("resultset-detail",
                kwargs={"project": "foo", "pk": -32767}),
        expect_errors=True
    )
    assert resp.status_int == 404
    assert resp.json == {"message": "No project with name foo"}

def test_resultset_create(sample_resultset, jm, initial_data):
    """
    test posting data to the resultset endpoint via webtest.
    extected result are:
    - return code 200
    - return message successful
    - 1 resultset stored in the jobs schema
    """

    trsc = TreeherderResultSetCollection()

    for rs in sample_resultset:
        rs = trsc.get_resultset(rs)
        trsc.add(rs)

    resp = test_utils.post_collection(jm.project, trsc)

    assert resp.status_int == 200
    assert resp.json['message'] == 'well-formed JSON stored'

    stored_objs = jm.get_jobs_dhub().execute(
        proc="jobs_test.selects.resultset_by_rev_hash",
        placeholders=[sample_resultset[0]['revision_hash']]
    )

    assert len(stored_objs) == 1
    assert stored_objs[0]['revision_hash'] == sample_resultset[0]['revision_hash']

def test_resultset_with_bad_secret(sample_resultset, jm, initial_data):

    trsc = TreeherderResultSetCollection()
    for rs in sample_resultset:
        rs = trsc.get_resultset(rs)
        trsc.add(rs)

    resp = test_utils.post_collection(
        jm.project, trsc, status=403, consumer_secret="horrible secret"
        )

    assert resp.status_int == 403
    assert resp.json['message'] == "Client authentication failed for project, {0}".format(jm.project)
    assert resp.json['response'] == "invalid_client"

def test_resultset_with_bad_key(sample_resultset, jm, initial_data):

    trsc = TreeherderResultSetCollection()
    for rs in sample_resultset:
        rs = trsc.get_resultset(rs)
        trsc.add(rs)

    resp = test_utils.post_collection(
        jm.project, trsc, status=403, consumer_key="horrible key"
        )

    assert resp.status_int == 403
    assert resp.json['response'] == "access_denied"
    assert resp.json['message'] == "oauth_consumer_key does not match project, {0}, credentials".format(jm.project)
<commit_msg>fix unit tests for change in /resultsets/ api<commit_after>import pytest
from django.core.urlresolvers import reverse

from thclient import TreeherderResultSetCollection
from tests import test_utils

from treeherder.webapp.api import utils

def test_resultset_list(webapp, eleven_jobs_processed, jm):
    """
    test retrieving a list of ten json blobs from the jobs-list
    endpoint.
    """
    resp = webapp.get(
        reverse("resultset-list", kwargs={"project": jm.project})
    )

    results = resp.json['results']
    meta = resp.json['meta']

    assert resp.status_int == 200
    assert isinstance(results, list)

    assert len(results) == 10
    exp_keys = set([
        u'id',
        u'repository_id',
        u'push_timestamp',
        u'author',
        u'comments',
        u'revision_hash',
        u'revision',
        u'revision_list',
        u'revision_count',
        u'revisions_uri',
        u'job_counts',
        u'platforms'
    ])
    for rs in results:
        assert set(rs.keys()) == exp_keys

    assert(meta == {
        u'count': 10,
        u'filter_params': {},
        u'repository':
        u'test_treeherder'
    })

def test_resultset_list_bad_project(webapp, jm):
    """
    test retrieving a list of ten json blobs from the jobs-list
    endpoint.
    """
    resp = webapp.get(
        reverse("resultset-list", kwargs={"project": "foo"}),
        expect_errors=True
    )

    assert resp.status_int == 404
    assert resp.json == {"message": "No project with name foo"}

def test_resultset_list_empty_rs_still_show(webapp, initial_data,
                                            sample_resultset, jm):
    """
    test retrieving a resultset list, when the resultset has no jobs.
    should show.
    """
    jm.store_result_set_data(sample_resultset)

    resp = webapp.get(
        reverse("resultset-list", kwargs={"project": jm.project}),
    )
    assert resp.status_int == 200
    assert len(resp.json['results']) == 10

def test_resultset_list_filter_by_revision(webapp, eleven_jobs_processed, jm):
    """
    test retrieving a resultset list, filtered by a date range
    """

    resp = webapp.get(
        reverse("resultset-list", kwargs={"project": jm.project}),
        {"fromchange": "21fb3eed1b5f", "tochange": "909f55c626a8"}
    )
    assert resp.status_int == 200
    results = resp.json['results']
    meta = resp.json['meta']
    assert len(results) == 4
    assert set([rs["revision"] for rs in results]) == set(
        ["909f55c626a8","71d49fee325a","bb57e9f67223","21fb3eed1b5f"]
        )
    assert(meta == {
        u'count': 4,
        u'fromchange': u'21fb3eed1b5f',
        u'filter_params': {
            u'push_timestamp__gte': 1384363842,
            u'push_timestamp__lte': 1384365942
        },
        u'repository': u'test_treeherder',
        u'tochange': u'909f55c626a8'}
    )

def test_resultset_list_filter_by_date(webapp, initial_data,
                                       sample_resultset, jm):
    """
    test retrieving a resultset list, filtered by a date range
    """
    sample_resultset[3]["push_timestamp"] = utils.to_timestamp("2013-08-09")
    sample_resultset[4]["push_timestamp"] = utils.to_timestamp("2013-08-10")
    sample_resultset[5]["push_timestamp"] = utils.to_timestamp("2013-08-11")
    sample_resultset[6]["push_timestamp"] = utils.to_timestamp("2013-08-12")
    sample_resultset[7]["push_timestamp"] = utils.to_timestamp("2013-08-13")

    jm.store_result_set_data(sample_resultset)

    resp = webapp.get(
        reverse("resultset-list", kwargs={"project": jm.project}),
        {"startdate": "2013-08-10", "enddate": "2013-08-13"}
    )
    assert resp.status_int == 200
    results = resp.json['results']
    meta = resp.json['meta']
    assert len(results) == 4
    assert set([rs["revision"] for rs in results]) == set(
        ["909f55c626a8","71d49fee325a","bb57e9f67223","668424578a0d"]
        )
    assert(meta == {
        u'count': 4,
        u'enddate': u'2013-08-13',
        u'filter_params': {
            u'push_timestamp__gte': 1376118000.0,
            u'push_timestamp__lt': 1376463600.0
        },
        u'repository': u'test_treeherder',
        u'startdate': u'2013-08-10'}
    )

def test_resultset_detail(webapp, eleven_jobs_processed, jm):
    """
    test retrieving a resultset from the resultset-detail
    endpoint.
    """

    rs_list = jm.get_result_set_list(0, 10)
    rs = rs_list[0]

    resp = webapp.get(
        reverse("resultset-detail",
                kwargs={"project": jm.project, "pk": int(rs["id"])})
    )
    assert resp.status_int == 200
    assert isinstance(resp.json, dict)
    assert resp.json["id"] == rs["id"]

def test_result_set_detail_not_found(webapp, jm):
    """
    test retrieving a HTTP 404 from the resultset-detail
    endpoint.
    """
    resp = webapp.get(
        reverse("resultset-detail",
                kwargs={"project": jm.project, "pk": -32767}),
        expect_errors=True
    )
    assert resp.status_int == 404

def test_result_set_detail_bad_project(webapp, jm):
    """
    test retrieving a HTTP 404 from the resultset-detail
    endpoint.
    """
    resp = webapp.get(
        reverse("resultset-detail",
                kwargs={"project": "foo", "pk": -32767}),
        expect_errors=True
    )
    assert resp.status_int == 404
    assert resp.json == {"message": "No project with name foo"}

def test_resultset_create(sample_resultset, jm, initial_data):
    """
    test posting data to the resultset endpoint via webtest.
    extected result are:
    - return code 200
    - return message successful
    - 1 resultset stored in the jobs schema
    """

    trsc = TreeherderResultSetCollection()

    for rs in sample_resultset:
        rs = trsc.get_resultset(rs)
        trsc.add(rs)

    resp = test_utils.post_collection(jm.project, trsc)

    assert resp.status_int == 200
    assert resp.json['message'] == 'well-formed JSON stored'

    stored_objs = jm.get_jobs_dhub().execute(
        proc="jobs_test.selects.resultset_by_rev_hash",
        placeholders=[sample_resultset[0]['revision_hash']]
    )

    assert len(stored_objs) == 1
    assert stored_objs[0]['revision_hash'] == sample_resultset[0]['revision_hash']

def test_resultset_with_bad_secret(sample_resultset, jm, initial_data):

    trsc = TreeherderResultSetCollection()
    for rs in sample_resultset:
        rs = trsc.get_resultset(rs)
        trsc.add(rs)

    resp = test_utils.post_collection(
        jm.project, trsc, status=403, consumer_secret="horrible secret"
        )

    assert resp.status_int == 403
    assert resp.json['message'] == "Client authentication failed for project, {0}".format(jm.project)
    assert resp.json['response'] == "invalid_client"

def test_resultset_with_bad_key(sample_resultset, jm, initial_data):

    trsc = TreeherderResultSetCollection()
    for rs in sample_resultset:
        rs = trsc.get_resultset(rs)
        trsc.add(rs)

    resp = test_utils.post_collection(
        jm.project, trsc, status=403, consumer_key="horrible key"
        )

    assert resp.status_int == 403
    assert resp.json['response'] == "access_denied"
    assert resp.json['message'] == "oauth_consumer_key does not match project, {0}, credentials".format(jm.project)
<|endoftext|>


<commit_before>#!/usr/bin/env python

"""
This module defines filters for Transmuter object.
"""

from __future__ import division

__author__ = "Will Richards, Shyue Ping Ong, Stephen Dacek"
__copyright__ = "Copyright 2011, The Materials Project"
__version__ = "1.0"
__maintainer__ = "Will Richards"
__email__ = "wrichards@mit.edu"
__date__ = "Sep 25, 2012"

from pymatgen.core.periodic_table import smart_element_or_specie
from pymatgen.serializers.json_coders import MSONable
from pymatgen.analysis.structure_matcher import StructureMatcher,\
    ElementComparator
import abc

class AbstractStructureFilter(MSONable):
    """
    Abstract structure filter class.
    """
    __metaclass__ = abc.ABCMeta

    @abc.abstractmethod
    def test(self, structure):
        """
        Returns a boolean for any structure. Structures that return true are
        kept in the Transmuter object during filtering.
        """
        return

    @staticmethod
    def from_dict(d):
        for trans_modules in ['filters']:
            mod = __import__('pymatgen.alchemy.' + trans_modules,
                             globals(), locals(), [d['@class']], -1)
            if hasattr(mod, d['@class']):
                trans = getattr(mod, d['@class'])
                return trans(**d['init_args'])
        raise ValueError("Invalid filter dict")

class ContainsSpecieFilter(AbstractStructureFilter):
    """
    Filter for structures containing certain elements or species.
    By default compares by atomic number
    """

    def __init__(self, species, strict_compare=False, AND=True, exclude=False):
        """
        Args:
            species:
                list of species to look for
            AND:
                whether all species must be present to pass (or fail)
                filter.
            strict_compare:
                if true, compares objects by specie or element object
                if false, compares atomic number
            exclude:
                if true, returns false for any structures with the specie
                (excludes them from the Transmuter)
        """
        self._species = map(smart_element_or_specie, species)
        self._strict = strict_compare
        self._AND = AND
        self._exclude = exclude

    def test(self, structure):
        #set up lists to compare
        if not self._strict:
            #compare by atomic number
            atomic_number = lambda x: x.Z
            filter_set = set(map(atomic_number, self._species))
            structure_set = set(map(atomic_number,
                                structure.composition.elements))
        else:
            #compare by specie or element object
            filter_set = set(self._species)
            structure_set = set(structure.composition.elements)

        if self._AND and filter_set <= structure_set:
            #return true if we aren't excluding since all are in structure
            return not self._exclude
        elif (not self._AND) and filter_set & structure_set:
            #return true if we aren't excluding since one is in structure
            return not self._exclude
        else:
            #return false if we aren't excluding otherwise
            return self._exclude

    def __repr__(self):
        return "\n".join(["ContainsSpecieFilter with parameters:",
                          "species = {}".format(self._species),
                          "strict_compare = {}".format(self._strict),
                          "AND = {}".format(self._AND),
                          "exclude = {}".format(self._exclude)])

    @property
    def to_dict(self):
        return {"version": __version__, "@module": self.__class__.__module__,
                "@class": self.__class__.__name__,
                "init_args": {"species": [str(sp) for sp in self._species],
                              "strict_compare": self._strict,
                              "AND": self._AND,
                              "exclude": self._exclude}}

class SpecieProximityFilter(AbstractStructureFilter):
    """
    This filter removes structures that have certain species that are too close
    together.
    """

    def __init__(self, specie_and_min_dist_dict):
        """
        Args:
            specie_and_min_dist_dict:
                A species string to float mapping. For example, {"Na+": 1}
                means that all Na+ ions must be at least 1 Angstrom away from
                each other. Multiple species criteria can be applied. Note that
                the testing is done based on the actual object. If you have a
                structure with Element, you must use {"Na":1} instead to filter
                based on Element and not Specie.
        """
        self.specie_and_min_dist = {smart_element_or_specie(k): v
                                    for k, v
                                    in specie_and_min_dist_dict.items()}

    def test(self, structure):
        all_species = set(self.specie_and_min_dist.keys())
        for site in structure:
            species = site.species_and_occu.keys()
            sp_to_test = set(species).intersection(all_species)
            if sp_to_test:
                max_r = max([self.specie_and_min_dist[sp]
                             for sp in sp_to_test])
                nn = structure.get_neighbors(site, max_r)
                for sp in sp_to_test:
                    for (nnsite, dist) in nn:
                        if sp in nnsite.species_and_occu.keys():
                            if dist < self.specie_and_min_dist[sp]:
                                return False
        return True

    @property
    def to_dict(self):
        return {"version": __version__, "@module": self.__class__.__module__,
                "@class": self.__class__.__name__,
                "init_args": {"specie_and_min_dist_dict":
                              {str(sp): v
                              for sp, v in self.specie_and_min_dist.items()}}}

class RemoveDuplicatesFilter(AbstractStructureFilter):
    """
    This filter removes exact duplicate structures from the transmuter.
    """

    def __init__(self,
                 structure_matcher=StructureMatcher(
                     comparator=ElementComparator())):
        """
        Args:
            comparator:
                The comparator to be used in the matching
        """
        self._structure_list = []
        if isinstance(structure_matcher, dict):
            self._sm = StructureMatcher.from_dict(structure_matcher)
        else:
            self._sm = structure_matcher

    def test(self, structure):
        if not self._structure_list:
            self._structure_list.append(structure)
            return True

        for s in self._structure_list:
            if self._sm._comparator.get_structure_hash(structure) ==\
                    self._sm._comparator.get_structure_hash(s):
                if self._sm.fit(s, structure):
                    return False

        self._structure_list.append(structure)
        return True

    @property
    def to_dict(self):
        return {"version": __version__, "@module": self.__class__.__module__,
                "@class": self.__class__.__name__,
                "init_args": {"structure_matcher": self._sm.to_dict}}
<commit_msg>added filter to check charge balance for structures in the transmuter. Makes doing substitutions easier<commit_after>#!/usr/bin/env python

"""
This module defines filters for Transmuter object.
"""

from __future__ import division

__author__ = "Will Richards, Shyue Ping Ong, Stephen Dacek"
__copyright__ = "Copyright 2011, The Materials Project"
__version__ = "1.0"
__maintainer__ = "Will Richards"
__email__ = "wrichards@mit.edu"
__date__ = "Sep 25, 2012"

from pymatgen.core.periodic_table import smart_element_or_specie
from pymatgen.serializers.json_coders import MSONable
from pymatgen.analysis.structure_matcher import StructureMatcher,\
    ElementComparator
import abc

class AbstractStructureFilter(MSONable):
    """
    Abstract structure filter class.
    """
    __metaclass__ = abc.ABCMeta

    @abc.abstractmethod
    def test(self, structure):
        """
        Returns a boolean for any structure. Structures that return true are
        kept in the Transmuter object during filtering.
        """
        return

    @staticmethod
    def from_dict(d):
        for trans_modules in ['filters']:
            mod = __import__('pymatgen.alchemy.' + trans_modules,
                             globals(), locals(), [d['@class']], -1)
            if hasattr(mod, d['@class']):
                trans = getattr(mod, d['@class'])
                return trans(**d['init_args'])
        raise ValueError("Invalid filter dict")

class ContainsSpecieFilter(AbstractStructureFilter):
    """
    Filter for structures containing certain elements or species.
    By default compares by atomic number
    """

    def __init__(self, species, strict_compare=False, AND=True, exclude=False):
        """
        Args:
            species:
                list of species to look for
            AND:
                whether all species must be present to pass (or fail)
                filter.
            strict_compare:
                if true, compares objects by specie or element object
                if false, compares atomic number
            exclude:
                if true, returns false for any structures with the specie
                (excludes them from the Transmuter)
        """
        self._species = map(smart_element_or_specie, species)
        self._strict = strict_compare
        self._AND = AND
        self._exclude = exclude

    def test(self, structure):
        #set up lists to compare
        if not self._strict:
            #compare by atomic number
            atomic_number = lambda x: x.Z
            filter_set = set(map(atomic_number, self._species))
            structure_set = set(map(atomic_number,
                                structure.composition.elements))
        else:
            #compare by specie or element object
            filter_set = set(self._species)
            structure_set = set(structure.composition.elements)

        if self._AND and filter_set <= structure_set:
            #return true if we aren't excluding since all are in structure
            return not self._exclude
        elif (not self._AND) and filter_set & structure_set:
            #return true if we aren't excluding since one is in structure
            return not self._exclude
        else:
            #return false if we aren't excluding otherwise
            return self._exclude

    def __repr__(self):
        return "\n".join(["ContainsSpecieFilter with parameters:",
                          "species = {}".format(self._species),
                          "strict_compare = {}".format(self._strict),
                          "AND = {}".format(self._AND),
                          "exclude = {}".format(self._exclude)])

    @property
    def to_dict(self):
        return {"version": __version__, "@module": self.__class__.__module__,
                "@class": self.__class__.__name__,
                "init_args": {"species": [str(sp) for sp in self._species],
                              "strict_compare": self._strict,
                              "AND": self._AND,
                              "exclude": self._exclude}}

class SpecieProximityFilter(AbstractStructureFilter):
    """
    This filter removes structures that have certain species that are too close
    together.
    """

    def __init__(self, specie_and_min_dist_dict):
        """
        Args:
            specie_and_min_dist_dict:
                A species string to float mapping. For example, {"Na+": 1}
                means that all Na+ ions must be at least 1 Angstrom away from
                each other. Multiple species criteria can be applied. Note that
                the testing is done based on the actual object. If you have a
                structure with Element, you must use {"Na":1} instead to filter
                based on Element and not Specie.
        """
        self.specie_and_min_dist = {smart_element_or_specie(k): v
                                    for k, v
                                    in specie_and_min_dist_dict.items()}

    def test(self, structure):
        all_species = set(self.specie_and_min_dist.keys())
        for site in structure:
            species = site.species_and_occu.keys()
            sp_to_test = set(species).intersection(all_species)
            if sp_to_test:
                max_r = max([self.specie_and_min_dist[sp]
                             for sp in sp_to_test])
                nn = structure.get_neighbors(site, max_r)
                for sp in sp_to_test:
                    for (nnsite, dist) in nn:
                        if sp in nnsite.species_and_occu.keys():
                            if dist < self.specie_and_min_dist[sp]:
                                return False
        return True

    @property
    def to_dict(self):
        return {"version": __version__, "@module": self.__class__.__module__,
                "@class": self.__class__.__name__,
                "init_args": {"specie_and_min_dist_dict":
                              {str(sp): v
                              for sp, v in self.specie_and_min_dist.items()}}}

class RemoveDuplicatesFilter(AbstractStructureFilter):
    """
    This filter removes exact duplicate structures from the transmuter.
    """

    def __init__(self,
                 structure_matcher=StructureMatcher(
                     comparator=ElementComparator())):
        """
        Args:
            comparator:
                The comparator to be used in the matching
        """
        self._structure_list = []
        if isinstance(structure_matcher, dict):
            self._sm = StructureMatcher.from_dict(structure_matcher)
        else:
            self._sm = structure_matcher

    def test(self, structure):
        if not self._structure_list:
            self._structure_list.append(structure)
            return True

        for s in self._structure_list:
            if self._sm._comparator.get_structure_hash(structure) ==\
                    self._sm._comparator.get_structure_hash(s):
                if self._sm.fit(s, structure):
                    return False

        self._structure_list.append(structure)
        return True

    @property
    def to_dict(self):
        return {"version": __version__, "@module": self.__class__.__module__,
                "@class": self.__class__.__name__,
                "init_args": {"structure_matcher": self._sm.to_dict}}

class ChargeBalanceFilter(AbstractStructureFilter):
    """
     This filter removes structures that are not
     charge balanced from the transmuter.
     This only works if the structure is
     oxidation state decorated, as structures
     with only elemental sites are automatically
     assumed to have net charge of 0
    """
    def test(self, structure):
        if structure.charge == 0.0:
            return True
        else:
            return False

    @property
    def to_dict(self):
        return {"@module": self.__class__.__module__,
                "@class": self.__class__.__name__}
<|endoftext|>


<commit_before>#!/usr/bin/env python

# Collect per-device btrfs filesystem errors.
# Designed to work on Debian and Centos 6 (with python2.6).

import collections
import glob
import os
import re
import subprocess

def get_btrfs_mount_points():
    """List all btrfs mount points.

    Yields:
        (string) filesystem mount points.
    """
    with open("/proc/mounts") as f:
        for line in f:
            parts = line.split()
            if parts[2] == "btrfs":
                yield parts[1]

def get_btrfs_errors(mountpoint):
    """Get per-device errors for a btrfs mount point.

    Args:
        mountpoint: (string) path to a mount point.

    Yields:
        (device, error_type, error_count) tuples, where:
            device: (string) path to block device.
            error_type: (string) type of btrfs error.
            error_count: (int) number of btrfs errors of a given type.
    """
    p = subprocess.Popen(["btrfs", "device", "stats", mountpoint],
                         stdout=subprocess.PIPE)
    (stdout, stderr) = p.communicate()
    if p.returncode != 0:
        raise RuntimeError("btrfs returned exit code %d" % p.returncode)
    for line in stdout.splitlines():
        if line == '':
            continue
        # Sample line:
        # [/dev/vdb1].flush_io_errs   0
        m = re.search(r"^\[([^\]]+)\]\.(\S+)\s+(\d+)$", line.decode("utf-8"))
        if not m:
            raise RuntimeError("unexpected output from btrfs: '%s'" % line)
        yield m.group(1), m.group(2), int(m.group(3))

def btrfs_error_metrics():
    """Collect btrfs error metrics.

    Returns:
        a list of strings to be exposed as Prometheus metrics.
    """
    metric = "node_btrfs_errors_total"
    contents = [
        "# TYPE %s counter" % metric,
        "# HELP %s number of btrfs errors" % metric,
    ]
    errors_by_device = collections.defaultdict(dict)
    for mountpoint in get_btrfs_mount_points():
        for device, error_type, error_count in get_btrfs_errors(mountpoint):
            contents.append(
                '%s{mountpoint="%s",device="%s",type="%s"} %d' %
                (metric, mountpoint, device, error_type, error_count))

    if len(contents) > 2:
        # return metrics if there are actual btrfs filesystems found
        # (i.e. `contents` contains more than just TYPE and HELP).
        return contents

def btrfs_allocation_metrics():
    """Collect btrfs allocation metrics.

    Returns:
        a list of strings to be exposed as Prometheus metrics.
    """
    prefix = 'node_btrfs_allocation'
    metric_to_filename = {
        'size_bytes': 'total_bytes',
        'used_bytes': 'bytes_used',
        'reserved_bytes': 'bytes_reserved',
        'pinned_bytes': 'bytes_pinned',
        'disk_size_bytes': 'disk_total',
        'disk_used_bytes': 'disk_used',
    }
    contents = []
    for m, f in metric_to_filename.items():
        contents += [
            "# TYPE %s_%s gauge" % (prefix, m),
            "# HELP %s_%s btrfs allocation data (%s)" % (prefix, m, f),
        ]

    for alloc in glob.glob("/sys/fs/btrfs/*/allocation"):
        fs = alloc.split('/')[4]
        for type_ in ('data', 'metadata', 'system'):
            for m, f in metric_to_filename.items():
                filename = os.path.join(alloc, type_, f)
                with open(filename) as f:
                    value = int(f.read().strip())
                    contents.append('%s_%s{fs="%s",type="%s"} %d' % (
                        prefix, m, fs, type_, value))
    if len(contents) > 2*len(metric_to_filename):
        return contents

if __name__ == "__main__":
    contents = ((btrfs_error_metrics() or []) +
                (btrfs_allocation_metrics() or []))

    print("\n".join(contents))
<commit_msg>btrfs_stats: Upgrade to Python 3 (#1359)<commit_after>#!/usr/bin/env python3

# Collect per-device btrfs filesystem errors.
# Designed to work on Debian and Centos 6 (with python2.6).

import collections
import glob
import os
import re
import subprocess

def get_btrfs_mount_points():
    """List all btrfs mount points.

    Yields:
        (string) filesystem mount points.
    """
    with open("/proc/mounts") as f:
        for line in f:
            parts = line.split()
            if parts[2] == "btrfs":
                yield parts[1]

def get_btrfs_errors(mountpoint):
    """Get per-device errors for a btrfs mount point.

    Args:
        mountpoint: (string) path to a mount point.

    Yields:
        (device, error_type, error_count) tuples, where:
            device: (string) path to block device.
            error_type: (string) type of btrfs error.
            error_count: (int) number of btrfs errors of a given type.
    """
    p = subprocess.Popen(["btrfs", "device", "stats", mountpoint],
                         stdout=subprocess.PIPE)
    (stdout, stderr) = p.communicate()
    if p.returncode != 0:
        raise RuntimeError("btrfs returned exit code %d" % p.returncode)
    for line in stdout.splitlines():
        if line == '':
            continue
        # Sample line:
        # [/dev/vdb1].flush_io_errs   0
        m = re.search(r"^\[([^\]]+)\]\.(\S+)\s+(\d+)$", line.decode("utf-8"))
        if not m:
            raise RuntimeError("unexpected output from btrfs: '%s'" % line)
        yield m.group(1), m.group(2), int(m.group(3))

def btrfs_error_metrics():
    """Collect btrfs error metrics.

    Returns:
        a list of strings to be exposed as Prometheus metrics.
    """
    metric = "node_btrfs_errors_total"
    contents = [
        "# TYPE %s counter" % metric,
        "# HELP %s number of btrfs errors" % metric,
    ]
    errors_by_device = collections.defaultdict(dict)
    for mountpoint in get_btrfs_mount_points():
        for device, error_type, error_count in get_btrfs_errors(mountpoint):
            contents.append(
                '%s{mountpoint="%s",device="%s",type="%s"} %d' %
                (metric, mountpoint, device, error_type, error_count))

    if len(contents) > 2:
        # return metrics if there are actual btrfs filesystems found
        # (i.e. `contents` contains more than just TYPE and HELP).
        return contents

def btrfs_allocation_metrics():
    """Collect btrfs allocation metrics.

    Returns:
        a list of strings to be exposed as Prometheus metrics.
    """
    prefix = 'node_btrfs_allocation'
    metric_to_filename = {
        'size_bytes': 'total_bytes',
        'used_bytes': 'bytes_used',
        'reserved_bytes': 'bytes_reserved',
        'pinned_bytes': 'bytes_pinned',
        'disk_size_bytes': 'disk_total',
        'disk_used_bytes': 'disk_used',
    }
    contents = []
    for m, f in metric_to_filename.items():
        contents += [
            "# TYPE %s_%s gauge" % (prefix, m),
            "# HELP %s_%s btrfs allocation data (%s)" % (prefix, m, f),
        ]

    for alloc in glob.glob("/sys/fs/btrfs/*/allocation"):
        fs = alloc.split('/')[4]
        for type_ in ('data', 'metadata', 'system'):
            for m, f in metric_to_filename.items():
                filename = os.path.join(alloc, type_, f)
                with open(filename) as f:
                    value = int(f.read().strip())
                    contents.append('%s_%s{fs="%s",type="%s"} %d' % (
                        prefix, m, fs, type_, value))
    if len(contents) > 2*len(metric_to_filename):
        return contents

if __name__ == "__main__":
    contents = ((btrfs_error_metrics() or []) +
                (btrfs_allocation_metrics() or []))

    print("\n".join(contents))
<|endoftext|>


<commit_before>import numpy as np
import qutip
from qutip import qip

class qasm:
    def __init__(self,filename):  # The function used when the object is created.
        self.filename=filename
        self.qasm_file=[]
        self.qasm_instructions=[]
        self.qasm_instruction_line=[]
        self.last_qubit_line_index=int(0)
        self.number_of_qubits=1
        self.state=np.array([0,1])
        self.gate_dict=self.operator_dict_default()
        pass

    def load_qasm_file(self):
        '''
        Reads in a .qasm file. filename a string with the filename, eg. 'test1.qasm'
        ---
        Return: List of strings with all characters in the file
        '''
        qasm_file=[]
        f=open(self.filename,'r')
        for line in f:
            qasm_file.append(line)
        self.qasm_file=qasm_file

    def get_filtered_qasm(self):
        '''
        In: List of strings with comments
        ---
        Return: list of strings without comments
        '''
        qasm_instructions=[]
        m=0
        for tt, line in enumerate(self.qasm_file):
            if line[0]=='#' or line.split()==[]:
                m+=1
                pass
            else:
                qasm_instructions.append('')
                for char in line:
                    if not char=='#':
                        qasm_instructions[tt-m]+=char
                    else:
                        break
        self.qasm_instructions=qasm_instructions

    def read_instruction_line(self,line_index):
        """
        In: instructions
        read the first line
        recognize the operation and qubit
        ---
        Out: list with operation as first entry and list of qubit(s) as second entry
        """
        instructions=self.qasm_instructions
        if instructions!=[]:
            instruction_line=str(instructions[line_index])
            instruction = instruction_line.split()
            operator = instruction[0]
            qubits = instruction[1].split(",")
        self.qasm_instruction_line=[operator, qubits]

    def read_qubits_string(self,qubits):
        """
        In: list with qubit names
        ----
        Out: returns a list with qubit numbers starting at 0.
        """
        qubit_numbers=[]
        for i in range(len(qubits)):
            name=qubits[i]
            number=name[1::]
            qubit_numbers.append(int(number))
        self.qubit_numbers=qubit_numbers
        #return qubit_numbers

    def run_algorithm(self):
        """
        load the file, filter the instructions
        run the instructions line by line
        Out: final qubit state.
        """
        self.load_qasm_file()
        self.get_filtered_qasm()
        self.get_number_of_qubits()
        self.create_qubits()
        for line_index,line in enumerate(self.qasm_instructions[self.last_qubit_line_index::]):
            self.read_instruction_line(line_index+self.last_qubit_line_index)
            self.run_instruction_line()
        return(self.state)

    def run_instruction_line(self):
        instruction=self.qasm_instruction_line
        self.read_qubits_string(instruction[1])
        qubits=self.qubit_numbers
        gate_matrix=self.gate_dict.get(instruction[0])
        matrix=[]
        if gate_matrix==None:
            if instruction[0]=='cnot':
                control=qubits[0]
                target=qubits[1]
                matrix=self.create_cnot_gate(control,target)
                self.act_gate_on_state(matrix)
            else:
                raise NameError ('Gate ' + instruction[0] + ' not defined')
        else:
            for qubit_number in range(len(qubits)):
                matrix=self.create_single_qubit_gate(instruction[0],qubit_number)
                print(matrix)
                self.act_gate_on_state(matrix)

    def get_number_of_qubits(self):
        '''
        In: filtered quasm instructions
        ---
        Out: integer with number of needed qubits
        '''
        num_qubits=0
        last_qubit_line_index=0
        for line_index, line in enumerate(self.qasm_instructions):
            if 'qubit' in line:
                num_qubits+=1
                last_qubit_line_index=line_index
        self.number_of_qubits=num_qubits
        self.last_qubit_line_index=last_qubit_line_index+1

    def create_qubits(self):
        self.state=np.zeros(2**self.number_of_qubits) # construct the state vector
        self.state[0]=1 #start in the ground state

    def create_single_qubit_gate(self,gate,qubit_number):
        '''
        In: which gate is to be applied, qubit_number: which qubit is acted on (first qubit is 0), number_of_qubits: total number of qubits
        ---
        Out: Process matrix with dimension 2**number_of_qubits x 2**number_of_qubits
        '''
        single_qubit_gate=self.gate_dict[gate]
        if qubit_number==0:
            matrix=single_qubit_gate
        else:
            matrix=self.gate_dict['i']
        for tt in range(1,self.number_of_qubits):
            if tt==qubit_number:
                matrix=np.kron(matrix,single_qubit_gate)
            else:
                matrix=np.kron(matrix,self.gate_dict['i'])
        return matrix

    def create_cnot_gate(self,control,target):
        '''
        In: control qubit, starting with 0, target qubit, starting with 0, number of qubits
        ---
        Out: Matrix for the gate
        '''
        return qip.cnot(N=self.number_of_qubits, control=control, target=target).full()

    def act_gate_on_state(self,matrix):
        '''
        In: Matrix that should be acted on the qubits
        ---
        Out: -    updates the state of the qubit
        '''
        old_state=self.state
        new_state=np.dot(matrix,old_state)
        self.state=new_state

    def operator_dict_default(self):
        """
        In: none
        Creates a dictionary with default operations
        Out: none
        """
        operator_dict={}
        # add hadamard
        operator_dict.update({'h':1/np.sqrt(2)*np.array([[1,1],[1,-1]])})
        # add identity
        operator_dict.update({'i':np.array([[1,0],[0,1]])})
        # add Pauli X
        operator_dict.update({'x':np.array([[0,1],[1,0]])})
        # add Pauli Y
        operator_dict.update({'y':np.array([[0,-1j],[1j,0]])})
        # add Pauli Z
        operator_dict.update({'z':np.array([[1,0],[0,-1]])})
        return operator_dict

<commit_msg>started on measurment<commit_after>import numpy as np
import qutip
from qutip import qip

class qasm:
    def __init__(self,filename):  # The function used when the object is created.
        self.filename=filename
        self.qasm_file=[]
        self.qasm_instructions=[]
        self.qasm_instruction_line=[]
        self.last_qubit_line_index=int(0)
        self.number_of_qubits=1
        self.state=np.array([0,1])
        self.gate_dict=self.operator_dict_default()
        pass

    def load_qasm_file(self):
        '''
        Reads in a .qasm file. filename a string with the filename, eg. 'test1.qasm'
        ---
        Return: List of strings with all characters in the file
        '''
        qasm_file=[]
        f=open(self.filename,'r')
        for line in f:
            qasm_file.append(line)
        self.qasm_file=qasm_file

    def get_filtered_qasm(self):
        '''
        In: List of strings with comments
        ---
        Return: list of strings without comments
        '''
        qasm_instructions=[]
        m=0
        for tt, line in enumerate(self.qasm_file):
            if line[0]=='#' or line.split()==[]:
                m+=1
                pass
            else:
                qasm_instructions.append('')
                for char in line:
                    if not char=='#':
                        qasm_instructions[tt-m]+=char
                    else:
                        break
        self.qasm_instructions=qasm_instructions

    def read_instruction_line(self,line_index):
        """
        In: instructions
        read the first line
        recognize the operation and qubit
        ---
        Out: list with operation as first entry and list of qubit(s) as second entry
        """
        instructions=self.qasm_instructions
        if instructions!=[]:
            instruction_line=str(instructions[line_index])
            instruction = instruction_line.split()
            operator = instruction[0]
            qubits = instruction[1].split(",")
        self.qasm_instruction_line=[operator, qubits]

    def read_qubits_string(self,qubits):
        """
        In: list with qubit names
        ----
        Out: returns a list with qubit numbers starting at 0.
        """
        qubit_numbers=[]
        for i in range(len(qubits)):
            name=qubits[i]
            number=name[1::]
            qubit_numbers.append(int(number))
        self.qubit_numbers=qubit_numbers
        #return qubit_numbers

    def run_algorithm(self):
        """
        load the file, filter the instructions
        run the instructions line by line
        Out: final qubit state.
        """
        self.load_qasm_file()
        self.get_filtered_qasm()
        self.get_number_of_qubits()
        self.create_qubits()
        for line_index,line in enumerate(self.qasm_instructions[self.last_qubit_line_index::]):
            self.read_instruction_line(line_index+self.last_qubit_line_index)
            self.run_instruction_line()
        return(self.state)

    def run_instruction_line(self):
        instruction=self.qasm_instruction_line
        self.read_qubits_string(instruction[1])
        qubits=self.qubit_numbers
        gate_matrix=self.gate_dict.get(instruction[0])
        matrix=[]
        if gate_matrix==None:
            if instruction[0]=='cnot':
                control=qubits[0]
                target=qubits[1]
                matrix=self.create_cnot_gate(control,target)
                self.act_gate_on_state(matrix)
            elif instruction[0]=='measure':
                self.do_measurement()
            else:
                raise NameError ('Gate ' + instruction[0] + ' not defined')
        else:
            for qubit_number in range(len(qubits)):
                matrix=self.create_single_qubit_gate(instruction[0],qubit_number)
                print(matrix)
                self.act_gate_on_state(matrix)

    def get_number_of_qubits(self):
        '''
        In: filtered quasm instructions
        ---
        Out: integer with number of needed qubits
        '''
        num_qubits=0
        last_qubit_line_index=0
        for line_index, line in enumerate(self.qasm_instructions):
            if 'qubit' in line:
                num_qubits+=1
                last_qubit_line_index=line_index
        self.number_of_qubits=num_qubits
        self.last_qubit_line_index=last_qubit_line_index+1

    def create_qubits(self):
        self.state=np.zeros(2**self.number_of_qubits) # construct the state vector
        self.state[0]=1 #start in the ground state

    def create_single_qubit_gate(self,gate,qubit_number):
        '''
        In: which gate is to be applied, qubit_number: which qubit is acted on (first qubit is 0), number_of_qubits: total number of qubits
        ---
        Out: Process matrix with dimension 2**number_of_qubits x 2**number_of_qubits
        '''
        single_qubit_gate=self.gate_dict[gate]
        if qubit_number==0:
            matrix=single_qubit_gate
        else:
            matrix=self.gate_dict['i']
        for tt in range(1,self.number_of_qubits):
            if tt==qubit_number:
                matrix=np.kron(matrix,single_qubit_gate)
            else:
                matrix=np.kron(matrix,self.gate_dict['i'])
        return matrix

    def create_cnot_gate(self,control,target):
        '''
        In: control qubit, starting with 0, target qubit, starting with 0, number of qubits
        ---
        Out: Matrix for the gate
        '''
        return qip.cnot(N=self.number_of_qubits, control=control, target=target).full()

    def do_measurement(self,number_of_measurements=10000):
        self.get_probability_vector()
        prob_vector=self.probability vector
        result=0
        hist=np.array(len(prob_vector))
        for i in range(number_of_measurements):
            result=self.measure()
            #add a count to the histogram
            hist(result)+=1
        return hist

    def act_gate_on_state(self,matrix):
        '''
        In: Matrix that should be acted on the qubits
        ---
        Out: -    updates the state of the qubit
        '''
        old_state=self.state
        new_state=np.dot(matrix,old_state)
        self.state=new_state

    def operator_dict_default(self):
        """
        In: none
        Creates a dictionary with default operations
        Out: none
        """
        operator_dict={}
        # add hadamard
        operator_dict.update({'h':1/np.sqrt(2)*np.array([[1,1],[1,-1]])})
        # add identity
        operator_dict.update({'i':np.array([[1,0],[0,1]])})
        # add identity
        operator_dict.update({'nop':np.array([[1,0],[0,1]])})
        # add Pauli X
        operator_dict.update({'x':np.array([[0,1],[1,0]])})
        # add Pauli Y
        operator_dict.update({'y':np.array([[0,-1j],[1j,0]])})
        # add Pauli Z
        operator_dict.update({'z':np.array([[1,0],[0,-1]])})
        return operator_dict

    def measure(self,prob_vector):
        self.probability_vector
        return measurement_outcome<|endoftext|>