<commit_before># Copyright 2013-2020 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)

from spack import *

class Ape(Package):
    """A tool for generating atomic pseudopotentials within a Density-Functional
    Theory framework"""

    homepage = "http://www.tddft.org/programs/APE/"
    url      = "http://www.tddft.org/programs/APE/sites/default/files/ape-2.2.1.tar.gz"

    version('2.2.1', sha256='1bdb7f987fde81f8a5f335da6b59fa884e6d185d4a0995c90fde7c04376ce9e3')

    depends_on('gsl')
    depends_on('libxc@:2.2.2')

    def install(self, spec, prefix):
        args = []
        args.extend([
            '--prefix=%s' % prefix,
            '--with-gsl-prefix=%s'   % spec['gsl'].prefix,
            '--with-libxc-prefix=%s' % spec['libxc'].prefix
        ])

        # When preprocessor expands macros (i.e. CFLAGS) defined as quoted
        # strings the result may be > 132 chars and is terminated.
        # This will look to a compiler as an Unterminated character constant
        # and produce Line truncated errors. To overcome this, add flags to
        # let compiler know that the entire line is meaningful.
        # TODO: For the lack of better approach, assume that clang is mixed
        # TODO: with GNU fortran.
        if (spec.satisfies('%apple-clang') or
                spec.satisfies('%clang') or
                spec.satisfies('%gcc')):
            args.extend([
                'FCFLAGS=-O2 -ffree-line-length-none'
            ])

        configure(*args)
        make()
        make('install')
<commit_msg>ape: fix build error and update version (#17952)<commit_after># Copyright 2013-2020 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)

from spack import *

class Ape(Package):
    """A tool for generating atomic pseudopotentials within a Density-Functional
    Theory framework"""

    homepage = "http://www.tddft.org/programs/APE/"
    url      = "http://www.tddft.org/programs/APE/sites/default/files/ape-2.2.1.tar.gz"

    version('2.2.1', sha256='1bdb7f987fde81f8a5f335da6b59fa884e6d185d4a0995c90fde7c04376ce9e3')

    depends_on('gsl')
    depends_on('libxc@:4.999', when='@2.3.0:')
    depends_on('libxc@:2.2.2', when='@:2.2.1')

    def install(self, spec, prefix):
        args = []
        args.extend([
            '--prefix=%s' % prefix,
            '--with-gsl-prefix=%s'   % spec['gsl'].prefix,
            '--with-libxc-prefix=%s' % spec['libxc'].prefix
        ])

        # When preprocessor expands macros (i.e. CFLAGS) defined as quoted
        # strings the result may be > 132 chars and is terminated.
        # This will look to a compiler as an Unterminated character constant
        # and produce Line truncated errors. To overcome this, add flags to
        # let compiler know that the entire line is meaningful.
        # TODO: For the lack of better approach, assume that clang is mixed
        # TODO: with GNU fortran.
        if (spec.satisfies('%apple-clang') or
                spec.satisfies('%clang') or
                spec.satisfies('%gcc')):
            args.extend([
                'FCFLAGS=-O2 -ffree-line-length-none'
            ])

        configure(*args)
        make()
        make('install')
<|endoftext|>


<commit_before># Licensed to the Software Freedom Conservancy (SFC) under one
# or more contributor license agreements.  See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership.  The SFC licenses this file
# to you 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 pytest

from selenium.common.exceptions import (
    ElementNotInteractableException,
    MoveTargetOutOfBoundsException,
    WebDriverException)
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import WebDriverWait

def testClickingOnAnchorScrollsPage(driver, pages):
    scrollScript = """var pageY;
    if (typeof(window.pageYOffset) == 'number') {
      pageY = window.pageYOffset;
    } else {
      pageY = document.documentElement.scrollTop;
    }
    return pageY;"""

    pages.load("macbeth.html")

    driver.find_element(By.PARTIAL_LINK_TEXT, "last speech").click()

    yOffset = driver.execute_script(scrollScript)

    # Focusing on to click, but not actually following,
    # the link will scroll it in to view, which is a few pixels further than 0
    assert yOffset > 300

def testShouldScrollToClickOnAnElementHiddenByOverflow(driver, pages):
    pages.load("click_out_of_bounds_overflow.html")

    link = driver.find_element(By.ID, "link")
    try:
        link.click()
    except MoveTargetOutOfBoundsException as e:
        AssertionError("Should not be out of bounds: %s" % e.msg)

def testShouldBeAbleToClickOnAnElementHiddenByOverflow(driver, pages):
    pages.load("scroll.html")

    link = driver.find_element(By.ID, "line8")
    # This used to throw a MoveTargetOutOfBoundsException - we don't expect it to
    link.click()
    assert "line8" == driver.find_element(By.ID, "clicked").text

def testShouldBeAbleToClickOnAnElementHiddenByDoubleOverflow(driver, pages):
    pages.load("scrolling_tests/page_with_double_overflow_auto.html")

    driver.find_element(By.ID, "link").click()
    WebDriverWait(driver, 3).until(EC.title_is("Clicked Successfully!"))

def testShouldBeAbleToClickOnAnElementHiddenByYOverflow(driver, pages):
    pages.load("scrolling_tests/page_with_y_overflow_auto.html")

    driver.find_element(By.ID, "link").click()
    WebDriverWait(driver, 3).until(EC.title_is("Clicked Successfully!"))

def testShouldNotScrollOverflowElementsWhichAreVisible(driver, pages):
    pages.load("scroll2.html")
    list = driver.find_element(By.TAG_NAME, "ul")
    item = list.find_element(By.ID, "desired")
    item.click()
    yOffset = driver.execute_script("return arguments[0].scrollTop", list)
    assert 0 == yOffset, "Should not have scrolled"

@pytest.mark.xfail_chrome(
    reason='https://bugs.chromium.org/p/chromedriver/issues/detail?id=1542')
@pytest.mark.xfail_marionette
def testShouldNotScrollIfAlreadyScrolledAndElementIsInView(driver, pages):
    pages.load("scroll3.html")
    driver.find_element(By.ID, "button1").click()
    scrollTop = getScrollTop(driver)
    driver.find_element(By.ID, "button2").click()
    assert scrollTop == getScrollTop(driver)

def testShouldBeAbleToClickRadioButtonScrolledIntoView(driver, pages):
    pages.load("scroll4.html")
    driver.find_element(By.ID, "radio").click()
    # If we don't throw, we're good

def testShouldScrollOverflowElementsIfClickPointIsOutOfViewButElementIsInView(driver, pages):
    pages.load("scroll5.html")
    driver.find_element(By.ID, "inner").click()
    assert "clicked" == driver.find_element(By.ID, "clicked").text

@pytest.mark.xfail_marionette(
    reason='https://github.com/w3c/webdriver/issues/408')
def testShouldBeAbleToClickElementInAFrameThatIsOutOfView(driver, pages):
    pages.load("scrolling_tests/page_with_frame_out_of_view.html")
    driver.switch_to.frame(driver.find_element_by_name("frame"))
    element = driver.find_element(By.NAME, "checkbox")
    element.click()
    assert element.is_selected()

def testShouldBeAbleToClickElementThatIsOutOfViewInAFrame(driver, pages):
    pages.load("scrolling_tests/page_with_scrolling_frame.html")
    driver.switch_to.frame(driver.find_element_by_name("scrolling_frame"))
    element = driver.find_element(By.NAME, "scroll_checkbox")
    element.click()
    assert element.is_selected()

def testShouldNotBeAbleToClickElementThatIsOutOfViewInANonScrollableFrame(driver, pages):
    pages.load("scrolling_tests/page_with_non_scrolling_frame.html")
    driver.switch_to.frame("scrolling_frame")
    element = driver.find_element(By.NAME, "scroll_checkbox")
    element.click()
    # TODO we should assert that the click was unsuccessful

def testShouldBeAbleToClickElementThatIsOutOfViewInAFrameThatIsOutOfView(driver, pages):
    pages.load("scrolling_tests/page_with_scrolling_frame_out_of_view.html")
    driver.switch_to.frame(driver.find_element_by_name("scrolling_frame"))
    element = driver.find_element(By.NAME, "scroll_checkbox")
    element.click()
    assert element.is_selected()

def testShouldBeAbleToClickElementThatIsOutOfViewInANestedFrame(driver, pages):
    pages.load("scrolling_tests/page_with_nested_scrolling_frames.html")
    driver.switch_to.frame(driver.find_element_by_name("scrolling_frame"))
    driver.switch_to.frame(driver.find_element_by_name("nested_scrolling_frame"))
    element = driver.find_element(By.NAME, "scroll_checkbox")
    element.click()
    assert element.is_selected()

def testShouldBeAbleToClickElementThatIsOutOfViewInANestedFrameThatIsOutOfView(driver, pages):
    pages.load("scrolling_tests/page_with_nested_scrolling_frames_out_of_view.html")
    driver.switch_to.frame(driver.find_element_by_name("scrolling_frame"))
    driver.switch_to.frame(driver.find_element_by_name("nested_scrolling_frame"))
    element = driver.find_element(By.NAME, "scroll_checkbox")
    element.click()
    assert element.is_selected()

def testShouldNotScrollWhenGettingElementSize(driver, pages):
    pages.load("scroll3.html")
    scrollTop = getScrollTop(driver)
    driver.find_element(By.ID, "button1").size
    assert scrollTop == getScrollTop(driver)

def getScrollTop(driver):
    return driver.execute_script("return document.body.scrollTop")

@pytest.mark.xfail_marionette(
    reason='https://github.com/w3c/webdriver/issues/408')
def testShouldBeAbleToClickElementInATallFrame(driver, pages):
    pages.load("scrolling_tests/page_with_tall_frame.html")
    driver.switch_to.frame(driver.find_element_by_name("tall_frame"))
    element = driver.find_element(By.NAME, "checkbox")
    element.click()
    assert element.is_selected()
<commit_msg>[py] Deleting unused imports<commit_after># Licensed to the Software Freedom Conservancy (SFC) under one
# or more contributor license agreements.  See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership.  The SFC licenses this file
# to you 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 pytest

from selenium.common.exceptions import MoveTargetOutOfBoundsException
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import WebDriverWait

def testClickingOnAnchorScrollsPage(driver, pages):
    scrollScript = """var pageY;
    if (typeof(window.pageYOffset) == 'number') {
      pageY = window.pageYOffset;
    } else {
      pageY = document.documentElement.scrollTop;
    }
    return pageY;"""

    pages.load("macbeth.html")

    driver.find_element(By.PARTIAL_LINK_TEXT, "last speech").click()

    yOffset = driver.execute_script(scrollScript)

    # Focusing on to click, but not actually following,
    # the link will scroll it in to view, which is a few pixels further than 0
    assert yOffset > 300

def testShouldScrollToClickOnAnElementHiddenByOverflow(driver, pages):
    pages.load("click_out_of_bounds_overflow.html")

    link = driver.find_element(By.ID, "link")
    try:
        link.click()
    except MoveTargetOutOfBoundsException as e:
        AssertionError("Should not be out of bounds: %s" % e.msg)

def testShouldBeAbleToClickOnAnElementHiddenByOverflow(driver, pages):
    pages.load("scroll.html")

    link = driver.find_element(By.ID, "line8")
    # This used to throw a MoveTargetOutOfBoundsException - we don't expect it to
    link.click()
    assert "line8" == driver.find_element(By.ID, "clicked").text

def testShouldBeAbleToClickOnAnElementHiddenByDoubleOverflow(driver, pages):
    pages.load("scrolling_tests/page_with_double_overflow_auto.html")

    driver.find_element(By.ID, "link").click()
    WebDriverWait(driver, 3).until(EC.title_is("Clicked Successfully!"))

def testShouldBeAbleToClickOnAnElementHiddenByYOverflow(driver, pages):
    pages.load("scrolling_tests/page_with_y_overflow_auto.html")

    driver.find_element(By.ID, "link").click()
    WebDriverWait(driver, 3).until(EC.title_is("Clicked Successfully!"))

def testShouldNotScrollOverflowElementsWhichAreVisible(driver, pages):
    pages.load("scroll2.html")
    list = driver.find_element(By.TAG_NAME, "ul")
    item = list.find_element(By.ID, "desired")
    item.click()
    yOffset = driver.execute_script("return arguments[0].scrollTop", list)
    assert 0 == yOffset, "Should not have scrolled"

@pytest.mark.xfail_chrome(
    reason='https://bugs.chromium.org/p/chromedriver/issues/detail?id=1542')
@pytest.mark.xfail_marionette
def testShouldNotScrollIfAlreadyScrolledAndElementIsInView(driver, pages):
    pages.load("scroll3.html")
    driver.find_element(By.ID, "button1").click()
    scrollTop = getScrollTop(driver)
    driver.find_element(By.ID, "button2").click()
    assert scrollTop == getScrollTop(driver)

def testShouldBeAbleToClickRadioButtonScrolledIntoView(driver, pages):
    pages.load("scroll4.html")
    driver.find_element(By.ID, "radio").click()
    # If we don't throw, we're good

def testShouldScrollOverflowElementsIfClickPointIsOutOfViewButElementIsInView(driver, pages):
    pages.load("scroll5.html")
    driver.find_element(By.ID, "inner").click()
    assert "clicked" == driver.find_element(By.ID, "clicked").text

@pytest.mark.xfail_marionette(
    reason='https://github.com/w3c/webdriver/issues/408')
def testShouldBeAbleToClickElementInAFrameThatIsOutOfView(driver, pages):
    pages.load("scrolling_tests/page_with_frame_out_of_view.html")
    driver.switch_to.frame(driver.find_element_by_name("frame"))
    element = driver.find_element(By.NAME, "checkbox")
    element.click()
    assert element.is_selected()

def testShouldBeAbleToClickElementThatIsOutOfViewInAFrame(driver, pages):
    pages.load("scrolling_tests/page_with_scrolling_frame.html")
    driver.switch_to.frame(driver.find_element_by_name("scrolling_frame"))
    element = driver.find_element(By.NAME, "scroll_checkbox")
    element.click()
    assert element.is_selected()

def testShouldNotBeAbleToClickElementThatIsOutOfViewInANonScrollableFrame(driver, pages):
    pages.load("scrolling_tests/page_with_non_scrolling_frame.html")
    driver.switch_to.frame("scrolling_frame")
    element = driver.find_element(By.NAME, "scroll_checkbox")
    element.click()
    # TODO we should assert that the click was unsuccessful

def testShouldBeAbleToClickElementThatIsOutOfViewInAFrameThatIsOutOfView(driver, pages):
    pages.load("scrolling_tests/page_with_scrolling_frame_out_of_view.html")
    driver.switch_to.frame(driver.find_element_by_name("scrolling_frame"))
    element = driver.find_element(By.NAME, "scroll_checkbox")
    element.click()
    assert element.is_selected()

def testShouldBeAbleToClickElementThatIsOutOfViewInANestedFrame(driver, pages):
    pages.load("scrolling_tests/page_with_nested_scrolling_frames.html")
    driver.switch_to.frame(driver.find_element_by_name("scrolling_frame"))
    driver.switch_to.frame(driver.find_element_by_name("nested_scrolling_frame"))
    element = driver.find_element(By.NAME, "scroll_checkbox")
    element.click()
    assert element.is_selected()

def testShouldBeAbleToClickElementThatIsOutOfViewInANestedFrameThatIsOutOfView(driver, pages):
    pages.load("scrolling_tests/page_with_nested_scrolling_frames_out_of_view.html")
    driver.switch_to.frame(driver.find_element_by_name("scrolling_frame"))
    driver.switch_to.frame(driver.find_element_by_name("nested_scrolling_frame"))
    element = driver.find_element(By.NAME, "scroll_checkbox")
    element.click()
    assert element.is_selected()

def testShouldNotScrollWhenGettingElementSize(driver, pages):
    pages.load("scroll3.html")
    scrollTop = getScrollTop(driver)
    driver.find_element(By.ID, "button1").size
    assert scrollTop == getScrollTop(driver)

def getScrollTop(driver):
    return driver.execute_script("return document.body.scrollTop")

@pytest.mark.xfail_marionette(
    reason='https://github.com/w3c/webdriver/issues/408')
def testShouldBeAbleToClickElementInATallFrame(driver, pages):
    pages.load("scrolling_tests/page_with_tall_frame.html")
    driver.switch_to.frame(driver.find_element_by_name("tall_frame"))
    element = driver.find_element(By.NAME, "checkbox")
    element.click()
    assert element.is_selected()
<|endoftext|>


<commit_before># Copyright 2013-2019 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
import os
from spack import *

class Gdl(CMakePackage):
    """A free and open-source IDL/PV-WAVE compiler.

    GNU Data Language (GDL) is a free/libre/open source incremental compiler
    compatible with IDL and to some extent with PV-WAVE.
    """

    homepage = "https://github.com/gnudatalanguage/gdl"
    url      = "https://github.com/gnudatalanguage/gdl/archive/v0.9.8.tar.gz"

    version('0.9.8', '447b0362e1df5ea8af814a969e89d3ec')

    variant(
            'graphicsmagick',
            default=False,
            description='Enable GraphicsMagick'
           )
    variant('hdf4', default=False, description='Enable HDF4')
    variant('hdf5', default=True, description='Enable HDF5')
    variant('openmp', default=True, description='Enable OpenMP')
    variant('proj', default=True, description='Enable LIBPROJ4')
    variant('embed_python', default=False, description='Ability to embed Python within GDL')
    variant('python', default=False, description='Build the GDL Python module')
    variant('wx', default=False, description='Enable WxWidgets')
    variant('x11', default=False, description='Enable X11')

    extends('python', when='+python')

    depends_on('graphicsmagick', when='+graphicsmagick')
    depends_on('hdf', when='+hdf4')
    depends_on('hdf5', when='+hdf5')
    depends_on('libx11', when='+x11')
    depends_on('plplot+wx', when='+wx@:5.11')
    depends_on('plplot+wx+wxold', when='+wx@5.12:')
    depends_on('plplot~wx', when='~wx')
    depends_on('proj', when='+proj')
    depends_on('py-numpy', type=('build', 'run'), when='+embed_python')
    depends_on('python@2.7:2.8', type=('build', 'run'), when='+embed_python')
    depends_on('wx', when='+wx')

    depends_on('eigen')
    depends_on('fftw')
    depends_on('gsl')
    depends_on('jpeg')
    depends_on('libice')
    depends_on('libsm')
    depends_on('libxinerama')
    depends_on('libxxf86vm')
    depends_on('netcdf')
    depends_on('pslib')
    depends_on('readline')

    conflicts('+python', when='~embed_python')

    # Building the Python module requires patches currently targetting 0.9.8
    # othwerwise asking for the Python module *only* builds the Python module
    conflicts('+python', when='@:0.9.7,0.9.9:')

    # Allows building gdl as a shared library to in turn allow building
    # both the executable and the Python module
    patch('https://sources.debian.org/data/main/g/gnudatalanguage/0.9.8-7/debian/patches/Create-a-shared-library.patch',
          sha256='bb380394c8ea2602404d8cd18047b93cf00fdb73b83d389f30100dd4b0e1a05c',
          when='@0.9.8')
    patch('Always-build-antlr-as-shared-library.patch',
          sha256='f40c06e8a8f1977780787f58885590affd7e382007cb677d2fb4723aaadd415c',
          when='@0.9.8')

    def cmake_args(self):
        args = []

        # GraphicsMagick covers the same features as ImageMagick and
        # only version 6 of ImageMagick is supported (version 7 is packaged)
        args += ['-DMAGICK=OFF']

        if '+graphicsmagick' in self.spec:
            args += ['-DGRAPHICSMAGICK=ON']
        else:
            args += ['-DGRAPHICSMAGICK=OFF']

        if '+hdf4' in self.spec:
            args += ['-DHDF=ON']
        else:
            args += ['-DHDF=OFF']

        if '+hdf5' in self.spec:
            args += ['-DHDF5=ON']
        else:
            args += ['-DHDF5=OFF']

        if '+openmp' in self.spec:
            args += ['-DOPENMP=ON']
        else:
            args += ['-DOPENMP=OFF']

        if '+proj' in self.spec:
            args += [
                '-DLIBPROJ4=ON',
                '-DLIBPROJ4DIR={0}'.format(self.spec['proj'].prefix)
            ]
        else:
            args += ['-DLIBPROJ4=OFF']

        if '+embed_python' in self.spec:
            args += ['-DPYTHON=ON']
        else:
            args += ['-DPYTHON=OFF']

        if '+python' in self.spec:
            args += ['-DPYTHON_MODULE=ON']
        else:
            args += ['-DPYTHON_MODULE=OFF']

        if '+wx' in self.spec:
            args += ['-DWXWIDGETS=ON']
        else:
            args += ['-DWXWIDGETS=OFF']

        if '+x11' in self.spec:
            args += ['-DX11=ON']
        else:
            args += ['-DX11=OFF']

        return args

    @run_after('install')
    def post_install(self):
        if '+python' in self.spec:
            # gdl installs the python module into prefix/lib/site-python
            # move it to the standard location
            src = os.path.join(
                self.spec.prefix.lib,
                'site-python')
            dst = site_packages_dir
            if os.path.isdir(src):
                if not os.path.isdir(dst):
                    mkdirp(dst)
                for f in os.listdir(src):
                    os.rename(os.path.join(src, f),
                              os.path.join(dst, f))
<commit_msg>Add GDL 0.9.9 (#11760)<commit_after># Copyright 2013-2019 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
import os
from spack import *

class Gdl(CMakePackage):
    """A free and open-source IDL/PV-WAVE compiler.

    GNU Data Language (GDL) is a free/libre/open source incremental compiler
    compatible with IDL and to some extent with PV-WAVE.
    """

    homepage = "https://github.com/gnudatalanguage/gdl"
    url      = "https://github.com/gnudatalanguage/gdl/archive/v0.9.9.tar.gz"

    version('0.9.9', sha256='ad5de3fec095a5c58b46338dcc7367d2565c093794ab1bbcf180bba1a712cf14')
    version('0.9.8', '447b0362e1df5ea8af814a969e89d3ec')

    variant(
            'graphicsmagick',
            default=False,
            description='Enable GraphicsMagick'
           )
    variant('hdf4', default=False, description='Enable HDF4')
    variant('hdf5', default=True, description='Enable HDF5')
    variant('openmp', default=True, description='Enable OpenMP')
    variant('proj', default=True, description='Enable LIBPROJ4')
    variant('embed_python', default=False, description='Ability to embed Python within GDL')
    variant('python', default=False, description='Build the GDL Python module')
    variant('wx', default=False, description='Enable WxWidgets')
    variant('x11', default=False, description='Enable X11')

    extends('python', when='+python')

    depends_on('cmake@3:', type='build')
    depends_on('graphicsmagick', when='+graphicsmagick')
    depends_on('hdf', when='+hdf4')
    depends_on('hdf5', when='+hdf5')
    depends_on('libx11', when='+x11')
    depends_on('plplot+wx', when='+wx@:5.11')
    depends_on('plplot+wx+wxold', when='+wx@5.12:')
    depends_on('plplot~wx', when='~wx')
    # Too many dependencies to test if GDL supports PROJ.6,
    # so restricting to old API
    depends_on('proj@:5', when='+proj')
    depends_on('py-numpy', type=('build', 'run'), when='+embed_python')
    depends_on('python@2.7:2.8', type=('build', 'run'), when='+embed_python')
    depends_on('wx', when='+wx')

    depends_on('eigen')
    depends_on('fftw')
    depends_on('gsl')
    depends_on('jpeg')
    depends_on('libice')
    depends_on('libsm')
    depends_on('libxinerama')
    depends_on('libxxf86vm')
    depends_on('netcdf')
    depends_on('pslib')
    depends_on('readline')

    conflicts('+python', when='~embed_python')

    # Building the Python module requires patches currently targetting 0.9.8
    # othwerwise asking for the Python module *only* builds the Python module
    conflicts('+python', when='@:0.9.7,0.9.9:')

    # Allows building gdl as a shared library to in turn allow building
    # both the executable and the Python module
    patch('https://sources.debian.org/data/main/g/gnudatalanguage/0.9.8-7/debian/patches/Create-a-shared-library.patch',
          sha256='bb380394c8ea2602404d8cd18047b93cf00fdb73b83d389f30100dd4b0e1a05c',
          when='@0.9.8')
    patch('Always-build-antlr-as-shared-library.patch',
          sha256='f40c06e8a8f1977780787f58885590affd7e382007cb677d2fb4723aaadd415c',
          when='@0.9.8')

    def cmake_args(self):
        args = []

        # GraphicsMagick covers the same features as ImageMagick and
        # only version 6 of ImageMagick is supported (version 7 is packaged)
        args += ['-DMAGICK=OFF']

        if '+graphicsmagick' in self.spec:
            args += ['-DGRAPHICSMAGICK=ON']
        else:
            args += ['-DGRAPHICSMAGICK=OFF']

        if '+hdf4' in self.spec:
            args += ['-DHDF=ON']
        else:
            args += ['-DHDF=OFF']

        if '+hdf5' in self.spec:
            args += ['-DHDF5=ON']
        else:
            args += ['-DHDF5=OFF']

        if '+openmp' in self.spec:
            args += ['-DOPENMP=ON']
        else:
            args += ['-DOPENMP=OFF']

        if '+proj' in self.spec:
            args += [
                '-DLIBPROJ4=ON',
                '-DLIBPROJ4DIR={0}'.format(self.spec['proj'].prefix)
            ]
        else:
            args += ['-DLIBPROJ4=OFF']

        if '+embed_python' in self.spec:
            args += ['-DPYTHON=ON']
        else:
            args += ['-DPYTHON=OFF']

        if '+python' in self.spec:
            args += ['-DPYTHON_MODULE=ON']
        else:
            args += ['-DPYTHON_MODULE=OFF']

        if '+wx' in self.spec:
            args += ['-DWXWIDGETS=ON']
        else:
            args += ['-DWXWIDGETS=OFF']

        if '+x11' in self.spec:
            args += ['-DX11=ON']
        else:
            args += ['-DX11=OFF']

        return args

    @run_after('install')
    def post_install(self):
        if '+python' in self.spec:
            # gdl installs the python module into prefix/lib/site-python
            # move it to the standard location
            src = os.path.join(
                self.spec.prefix.lib,
                'site-python')
            dst = site_packages_dir
            if os.path.isdir(src):
                if not os.path.isdir(dst):
                    mkdirp(dst)
                for f in os.listdir(src):
                    os.rename(os.path.join(src, f),
                              os.path.join(dst, f))
<|endoftext|>


<commit_before>import numpy as np
import traceback
from copy import deepcopy
from pycqed.analysis_v3.processing_pipeline import ProcessingPipeline
from pycqed.measurement.calibration.two_qubit_gates import MultiTaskingExperiment
from pycqed.measurement.sweep_points import SweepPoints
from pycqed.measurement.randomized_benchmarking import \
    randomized_benchmarking as rb
import pycqed.measurement.randomized_benchmarking.two_qubit_clifford_group as tqc
from pycqed.analysis_v3 import pipeline_analysis as pla
import logging
log = logging.getLogger(__name__)

class RandomizedBenchmarking(MultiTaskingExperiment):

    kw_for_sweep_points = {
        'nr_seeds': dict(param_name='seeds', unit='',
                         label='Seeds', dimension=0,
                         values_func=lambda ns: np.random.randint(0, 1e8, ns)),
        'cliffords': dict(param_name='cliffords', unit='',
                          label='Nr. Cliffords',
                          dimension=1),
    }

    def __init__(self, task_list=None, sweep_points=None, qubits=None,
                 nr_seeds=None, cliffords=None,
                 interleaved_gate=None, gate_decomposition='HZ', **kw):
        """
        Class to run and analyze the randomized benchmarking experiment on
        one or several qubits in parallel, using the single-qubit Clifford group
        :param task_list: list of dicts; see CalibBuilder docstring
        :param sweep_points: SweepPoints class instance with first sweep
            dimension describing the seeds and second dimension the cliffords
            Ex: [{'seeds': (array([0, 1, 2, 3]), '', 'Nr. Seeds')},
                 {'cliffords': ([0, 4, 10], '', 'Nr. Cliffords')}]
            If it contains only one sweep dimension, this must be the
            cliffords. The seeds will be added automatically.
            If this parameter is provided it will be used for all qubits.
        :param qubits: list of QuDev_transmon class instances
        :param nr_seeds: int specifying the number of times the Clifford
            group should be sampled for each Clifford sequence length.
            If nr_seeds is specified and it does not exist in the SweepPoints
            of each task in task_list, THEN ALL TASKS WILL RECEIVE THE SAME
            PULSES!!!
        :param interleaved_gate: string specifying the interleaved gate in
            pycqed notation (ex: X90, Y180 etc). Gate must be part of the
            Clifford group.
        :param gate_decomposition: string specifying what decomposition to use
            to translate the Clifford elements into applicable pulses.
            Possible choices are 'HZ' or 'XY'.
            See HZ_gate_decomposition and XY_gate_decomposition in
            pycqed\measurement\randomized_benchmarking\clifford_decompositions.py
        :param kw: keyword arguments
            passed to CalibBuilder; see docstring there

        Assumptions:
         - assumes there is one task for each qubit. If task_list is None, it
          will internally create it.
         - in rb_block, it assumes only one parameter is being swept in the
         second sweep dimension (cliffords)
         - interleaved_gate and gate_decomposition should be the same for
         all qubits since otherwise the segments will have very different
         lengths for different qubits
        """
        try:
            self.interleaved_gate = interleaved_gate
            if self.interleaved_gate is not None:
                self.kw_for_sweep_points['nr_seeds'] = [
                    dict(param_name='seeds', unit='',
                         label='Seeds', dimension=0,
                         values_func=lambda ns: np.random.randint(0, 1e8, ns)),
                    dict(param_name='seeds_irb', unit='',
                         label='Seeds', dimension=0,
                         values_func=lambda ns: np.random.randint(0, 1e8, ns))]
            kw['cal_states'] = kw.get('cal_states', '')

            super().__init__(task_list, qubits=qubits,
                             sweep_points=sweep_points,
                             nr_seeds=nr_seeds,
                             cliffords=cliffords, **kw)
            if self.experiment_name is None:
                self.experiment_name = f'RB_{gate_decomposition}' if \
                    interleaved_gate is None else f'IRB_{gate_decomposition}'
            self.identical_pulses = nr_seeds is not None
            self.gate_decomposition = gate_decomposition
            self.preprocessed_task_list = self.preprocess_task_list(**kw)

            # Check if we can apply identical pulses on all qubits in task_list
            # Can only do this if they have identical cliffords array
            if self.identical_pulses:
                unique_clf_sets = np.unique([
                    self.sweep_points.get_sweep_params_property('values', 1, k)
                    for k in self.sweep_points.get_sweep_dimension(1) if
                    k.endswith('cliffords')], axis=0)
                if unique_clf_sets.shape[0] > 1:
                    raise ValueError('Cannot apply identical pulses. '
                                     'Not all qubits have the same Cliffords.'
                                     'To use non-identical pulses, '
                                     'move nr_seeds from keyword arguments '
                                     'into the tasks.')

            self.sequences, self.mc_points = self.sweep_n_dim(
                self.sweep_points, body_block=None,
                body_block_func=self.rb_block, cal_points=self.cal_points,
                ro_qubits=self.meas_obj_names, **kw)
            if self.interleaved_gate is not None:
                seqs_irb, _ = self.sweep_n_dim(
                    self.sweep_points, body_block=None,
                    body_block_func_kw={'interleaved_gate':
                                            self.interleaved_gate},
                    body_block_func=self.rb_block, cal_points=self.cal_points,
                    ro_qubits=self.meas_obj_names, **kw)
                # interleave sequences
                self.sequences, self.mc_points = \
                    self.sequences[0].interleave_sequences(
                        [self.sequences, seqs_irb])
                self.exp_metadata['interleaved_gate'] = self.interleaved_gate
            self.exp_metadata['gate_decomposition'] = self.gate_decomposition
            self.exp_metadata['identical_pulses'] = self.identical_pulses

            self.add_processing_pipeline()
            self.autorun(**kw)

        except Exception as x:
            self.exception = x
            traceback.print_exc()

    def rb_block(self, sp1d_idx, sp2d_idx, **kw):
        pass

    def add_processing_pipeline(self):
        pass

    def run_analysis(self, **kw):
        """
        Runs analysis and stores analysis instance in self.analysis.
        :param kw: keyword_arguments passed to analysis functions;
            see docstrings there
        """
        self.analysis = pla.extract_data_hdf()  # returns a dict
        pla.process_pipeline(self.analysis)

class SingleQubitRandomizedBenchmarking(RandomizedBenchmarking):

    def __init__(self, task_list, sweep_points=None, **kw):
        """
        See docstring for RandomizedBenchmarking.
        """
        self.experiment_name = f'SingleQubitRB' if \
            kw.get('interleaved_gate', None) is None else f'SingleQubitIRB'

        for task in task_list:
            if 'qb' not in task:
                raise ValueError('Please specify "qb" in each task in '
                                 '"task_list."')
            if not isinstance(task['qb'], str):
                task['qb'] = task['qb'].name
            if 'prefix' not in task:
                task['prefix'] = f"{task['qb']}_"

        super().__init__(task_list, sweep_points=sweep_points, **kw)

    def rb_block(self, sp1d_idx, sp2d_idx, **kw):
        interleaved_gate = kw.get('interleaved_gate', None)
        pulse_op_codes_list = []
        tl = [self.preprocessed_task_list[0]] if self.identical_pulses else \
            self.preprocessed_task_list
        for i, task in enumerate(tl):
            param_name = 'seeds' if interleaved_gate is None else 'seeds_irb'
            seed = task['sweep_points'].get_sweep_params_property(
                'values', 0, param_name)[sp1d_idx]
            clifford = task['sweep_points'].get_sweep_params_property(
                'values', 1, 'cliffords')[sp2d_idx]
            cl_seq = rb.randomized_benchmarking_sequence(
                clifford, seed=seed, interleaved_gate=interleaved_gate)
            pulse_op_codes_list += [rb.decompose_clifford_seq(
                cl_seq, gate_decomp=self.gate_decomposition)]
        rb_block_list = [self.block_from_ops(
            f"rb_{task['qb']}", [f"{p} {task['qb']}" for p in
                                 pulse_op_codes_list[0 if self.identical_pulses
                                 else i]])
            for i, task in enumerate(self.preprocessed_task_list)]

        return self.simultaneous_blocks(f'sim_rb_{clifford}{sp1d_idx}',
                                        rb_block_list, block_align='end')

    def add_processing_pipeline(self):
        """
        Creates and adds the analysis processing pipeline to exp_metadata.
        """
        pp = ProcessingPipeline()
        for task in self.preprocessed_task_list:
            cliffords = task['sweep_points'].get_sweep_params_property(
                'values', 1)
            seeds = task['sweep_points'].get_sweep_params_property(
                'values', 0)
            if len(self.cal_points.states) != 0:
                pp.add_node('rotate_iq', keys_in='raw',
                            meas_obj_names=task['qb'],
                            num_keys_out=1)
            pp.add_node('average_data',
                        keys_in='raw' if not self.classified else
                        'previous rotate_iq',
                        shape=(len(cliffords), len(seeds)),
                        meas_obj_names=task['qb'])
            pp.add_node('get_std_deviation',
                        keys_in='raw' if not self.classified else
                        'previous rotate_iq',
                        shape=(len(cliffords), len(seeds)),
                        meas_obj_names=task['qb'])
            pp.add_node('rb_analysis', meas_obj_names=task['qb'],
                        keys_out=None, d=2,
                        keys_in=f'previous average_data',
                        keys_in_std=f'previous get_std_deviation')
        self.exp_metadata.update({'processing_pipeline': pp})

class TwoQubitRandomizedBenchmarking(RandomizedBenchmarking):

    def __init__(self, task_list, sweep_points=None,
                 max_clifford_idx=11520, **kw):
        """
        See docstring for RandomizedBenchmarking.

        :param max_clifford_idx: int that allows to restrict the two qubit
            Clifford that is sampled. Set to 24**2 to only sample the tensor
            product of 2 single qubit Clifford groups.
        """
        self.max_clifford_idx = max_clifford_idx
        tqc.gate_decomposition = rb.get_clifford_decomposition(
            kw.get('gate_decomposition', 'HZ'))

        for task in task_list:
            for k in ['qb_1', 'qb_2']:
                if not isinstance(task[k], str):
                    task[k] = task[k].name
            if 'prefix' not in task:
                task['prefix'] = f"{task['qb_1']}{task['qb_2']}_"
        kw['for_ef'] = kw.get('for_ef', True)
        self.experiment_name = 'TwoQubitRB' if \
            kw.get('interleaved_gate', None) is None else 'TwoQubitIRB'
        super().__init__(task_list, sweep_points=sweep_points, **kw)

    def guess_label(self, **kw):
        """
        Default measurement label.
        """
        suffix = [''.join([task['qb_1'], task['qb_2']])
                  for task in self.task_list]
        suffix = '_'.join(suffix)
        if self.label is None:
            if self.interleaved_gate is None:
                self.label = f'{self.experiment_name}_' \
                             f'{self.gate_decomposition}_{suffix}'
            else:
                self.label = f'{self.experiment_name}_{self.interleaved_gate}_' \
                             f'{self.gate_decomposition}_{suffix}'

    def rb_block(self, sp1d_idx, sp2d_idx, **kw):
        interleaved_gate = kw.get('interleaved_gate', None)
        rb_block_list = []
        for i, task in enumerate(self.preprocessed_task_list):
            param_name = 'seeds' if interleaved_gate is None else 'seeds_irb'
            seed = task['sweep_points'].get_sweep_params_property(
                'values', 0, param_name)[sp1d_idx]
            clifford = task['sweep_points'].get_sweep_params_property(
                'values', 1, 'cliffords')[sp2d_idx]

            cl_seq = rb.randomized_benchmarking_sequence_new(
                clifford, number_of_qubits=2, seed=seed,
                max_clifford_idx=kw.get('max_clifford_idx',
                                        self.max_clifford_idx),
                interleaving_cl=interleaved_gate)

            qb_1 = task['qb_1']
            qb_2 = task['qb_2']
            seq_blocks = []
            single_qb_gates = {qb_1: [], qb_2: []}
            for k, idx in enumerate(cl_seq):
                pulse_tuples_list = tqc.TwoQubitClifford(idx).gate_decomposition
                for j, pulse_tuple in enumerate(pulse_tuples_list):
                    if isinstance(pulse_tuple[1], list):
                        seq_blocks.append(
                            self.simultaneous_blocks(
                                f'blk{k}_{j}', [
                            self.block_from_ops(f'blk{k}_{j}_{qbn}', gates)
                                    for qbn, gates in single_qb_gates.items()]))
                        single_qb_gates = {qb_1: [], qb_2: []}
                        seq_blocks.append(self.block_from_ops(
                            f'blk{k}_{j}_cz',
                            f'{kw.get("cz_pulse_name", "CZ")} {qb_1} {qb_2}'))
                    else:
                        qb_name = qb_1 if '0' in pulse_tuple[1] else qb_2
                        pulse_name = pulse_tuple[0]
                        single_qb_gates[qb_name].append(
                            pulse_name + ' ' + qb_name)

            seq_blocks.append(
                self.simultaneous_blocks(
                    f'blk{i}', [
                        self.block_from_ops(f'blk{i}{qbn}', gates)
                        for qbn, gates in single_qb_gates.items()]))
            rb_block_list += [self.sequential_blocks(f'rb_block{i}', seq_blocks)]

        return self.simultaneous_blocks(
            f'sim_rb_{sp2d_idx}_{sp1d_idx}', rb_block_list, block_align='end')

    def add_processing_pipeline(self):
        """
        Creates and adds the analysis processing pipeline to exp_metadata.
        """
        pp = ProcessingPipeline()
        for task in self.preprocessed_task_list:
            cliffords = task['sweep_points'].get_sweep_params_property(
                'values', 1)
            seeds = task['sweep_points'].get_sweep_params_property(
                'values', 0)
            if len(self.cal_points.states) != 0:
                pp.add_node('rotate_iq', keys_in='raw',
                            meas_obj_names=[task['qb_1'], task['qb_2']],
                            num_keys_out=1)
            pp.add_node('average_data',
                        keys_in='raw' if not self.classified else
                        'previous rotate_iq',
                        shape=(len(cliffords), len(seeds)),
                        meas_obj_names=[task['qb_1'], task['qb_2']],)
            pp.add_node('get_std_deviation',
                        keys_in='raw' if not self.classified else
                        'previous rotate_iq',
                        shape=(len(cliffords), len(seeds)),
                        meas_obj_names=[task['qb_1'], task['qb_2']],)
            pp.add_node('rb_analysis',
                        meas_obj_names=[task['qb_1'], task['qb_2']],
                        keys_out=None, d=4,
                        keys_in=f'previous average_data',
                        keys_in_std=f'previous get_std_deviation')
        self.exp_metadata.update({'processing_pipeline': pp})<commit_msg>Switches the sweep dimensions in RandomizedBenchmarking and SingleQubitRandomizedBenchmarking (1D = cliffords, 2D = seeds)<commit_after>import numpy as np
import traceback
from copy import deepcopy
from pycqed.analysis_v3.processing_pipeline import ProcessingPipeline
from pycqed.measurement.calibration.two_qubit_gates import MultiTaskingExperiment
from pycqed.measurement.sweep_points import SweepPoints
from pycqed.measurement.randomized_benchmarking import \
    randomized_benchmarking as rb
import pycqed.measurement.randomized_benchmarking.two_qubit_clifford_group as tqc
from pycqed.analysis_v3 import pipeline_analysis as pla
import logging
log = logging.getLogger(__name__)

class RandomizedBenchmarking(MultiTaskingExperiment):

    kw_for_sweep_points = {
        'nr_seeds': dict(param_name='seeds', unit='',
                         label='Seeds', dimension=1,
                         values_func=lambda ns: np.random.randint(0, 1e8, ns)),
        'cliffords': dict(param_name='cliffords', unit='',
                          label='Nr. Cliffords',
                          dimension=0),
    }

    def __init__(self, task_list=None, sweep_points=None, qubits=None,
                 nr_seeds=None, cliffords=None,
                 interleaved_gate=None, gate_decomposition='HZ', **kw):
        """
        Class to run and analyze the randomized benchmarking experiment on
        one or several qubits in parallel, using the single-qubit Clifford group
        :param task_list: list of dicts; see CalibBuilder docstring
        :param sweep_points: SweepPoints class instance with first sweep
            dimension describing the seeds and second dimension the cliffords
            Ex: [{'seeds': (array([0, 1, 2, 3]), '', 'Nr. Seeds')},
                 {'cliffords': ([0, 4, 10], '', 'Nr. Cliffords')}]
            If it contains only one sweep dimension, this must be the
            cliffords. The seeds will be added automatically.
            If this parameter is provided it will be used for all qubits.
        :param qubits: list of QuDev_transmon class instances
        :param nr_seeds: int specifying the number of times the Clifford
            group should be sampled for each Clifford sequence length.
            If nr_seeds is specified and it does not exist in the SweepPoints
            of each task in task_list, THEN ALL TASKS WILL RECEIVE THE SAME
            PULSES!!!
        :param interleaved_gate: string specifying the interleaved gate in
            pycqed notation (ex: X90, Y180 etc). Gate must be part of the
            Clifford group.
        :param gate_decomposition: string specifying what decomposition to use
            to translate the Clifford elements into applicable pulses.
            Possible choices are 'HZ' or 'XY'.
            See HZ_gate_decomposition and XY_gate_decomposition in
            pycqed\measurement\randomized_benchmarking\clifford_decompositions.py
        :param kw: keyword arguments
            passed to CalibBuilder; see docstring there

        Assumptions:
         - assumes there is one task for each qubit. If task_list is None, it
          will internally create it.
         - in rb_block, it assumes only one parameter is being swept in the
         second sweep dimension (cliffords)
         - interleaved_gate and gate_decomposition should be the same for
         all qubits since otherwise the segments will have very different
         lengths for different qubits
        """
        try:
            self.interleaved_gate = interleaved_gate
            if self.interleaved_gate is not None:
                self.kw_for_sweep_points['nr_seeds'] = [
                    dict(param_name='seeds', unit='',
                         label='Seeds', dimension=0,
                         values_func=lambda ns: np.random.randint(0, 1e8, ns)),
                    dict(param_name='seeds_irb', unit='',
                         label='Seeds', dimension=0,
                         values_func=lambda ns: np.random.randint(0, 1e8, ns))]
            kw['cal_states'] = kw.get('cal_states', '')

            super().__init__(task_list, qubits=qubits,
                             sweep_points=sweep_points,
                             nr_seeds=nr_seeds,
                             cliffords=cliffords, **kw)
            if self.experiment_name is None:
                self.experiment_name = f'RB_{gate_decomposition}' if \
                    interleaved_gate is None else f'IRB_{gate_decomposition}'
            self.identical_pulses = nr_seeds is not None
            self.gate_decomposition = gate_decomposition
            self.preprocessed_task_list = self.preprocess_task_list(**kw)

            # Check if we can apply identical pulses on all qubits in task_list
            # Can only do this if they have identical cliffords array
            if self.identical_pulses:
                unique_clf_sets = np.unique([
                    self.sweep_points.get_sweep_params_property('values', 1, k)
                    for k in self.sweep_points.get_sweep_dimension(1) if
                    k.endswith('cliffords')], axis=0)
                if unique_clf_sets.shape[0] > 1:
                    raise ValueError('Cannot apply identical pulses. '
                                     'Not all qubits have the same Cliffords.'
                                     'To use non-identical pulses, '
                                     'move nr_seeds from keyword arguments '
                                     'into the tasks.')

            self.sequences, self.mc_points = self.sweep_n_dim(
                self.sweep_points, body_block=None,
                body_block_func=self.rb_block, cal_points=self.cal_points,
                ro_qubits=self.meas_obj_names, **kw)
            if self.interleaved_gate is not None:
                seqs_irb, _ = self.sweep_n_dim(
                    self.sweep_points, body_block=None,
                    body_block_func_kw={'interleaved_gate':
                                            self.interleaved_gate},
                    body_block_func=self.rb_block, cal_points=self.cal_points,
                    ro_qubits=self.meas_obj_names, **kw)
                # interleave sequences
                self.sequences, self.mc_points = \
                    self.sequences[0].interleave_sequences(
                        [self.sequences, seqs_irb])
                self.exp_metadata['interleaved_gate'] = self.interleaved_gate
            self.exp_metadata['gate_decomposition'] = self.gate_decomposition
            self.exp_metadata['identical_pulses'] = self.identical_pulses

            self.add_processing_pipeline()
            self.autorun(**kw)

        except Exception as x:
            self.exception = x
            traceback.print_exc()

    def rb_block(self, sp1d_idx, sp2d_idx, **kw):
        pass

    def add_processing_pipeline(self):
        pass

    def run_analysis(self, **kw):
        """
        Runs analysis and stores analysis instance in self.analysis.
        :param kw: keyword_arguments passed to analysis functions;
            see docstrings there
        """
        self.analysis = pla.extract_data_hdf()  # returns a dict
        pla.process_pipeline(self.analysis)

class SingleQubitRandomizedBenchmarking(RandomizedBenchmarking):

    def __init__(self, task_list, sweep_points=None, **kw):
        """
        See docstring for RandomizedBenchmarking.
        """
        self.experiment_name = f'SingleQubitRB' if \
            kw.get('interleaved_gate', None) is None else f'SingleQubitIRB'

        for task in task_list:
            if 'qb' not in task:
                raise ValueError('Please specify "qb" in each task in '
                                 '"task_list."')
            if not isinstance(task['qb'], str):
                task['qb'] = task['qb'].name
            if 'prefix' not in task:
                task['prefix'] = f"{task['qb']}_"

        super().__init__(task_list, sweep_points=sweep_points, **kw)

    def rb_block(self, sp1d_idx, sp2d_idx, **kw):
        interleaved_gate = kw.get('interleaved_gate', None)
        pulse_op_codes_list = []
        tl = [self.preprocessed_task_list[0]] if self.identical_pulses else \
            self.preprocessed_task_list
        for i, task in enumerate(tl):
            param_name = 'seeds' if interleaved_gate is None else 'seeds_irb'
            seed = task['sweep_points'].get_sweep_params_property(
                'values', 1, param_name)[sp2d_idx]
            clifford = task['sweep_points'].get_sweep_params_property(
                'values', 0, 'cliffords')[sp1d_idx]
            cl_seq = rb.randomized_benchmarking_sequence(
                clifford, seed=seed, interleaved_gate=interleaved_gate)
            pulse_op_codes_list += [rb.decompose_clifford_seq(
                cl_seq, gate_decomp=self.gate_decomposition)]
        rb_block_list = [self.block_from_ops(
            f"rb_{task['qb']}", [f"{p} {task['qb']}" for p in
                                 pulse_op_codes_list[0 if self.identical_pulses
                                 else i]])
            for i, task in enumerate(self.preprocessed_task_list)]

        return self.simultaneous_blocks(f'sim_rb_{clifford}{sp1d_idx}',
                                        rb_block_list, block_align='end')

    def add_processing_pipeline(self):
        """
        Creates and adds the analysis processing pipeline to exp_metadata.
        """
        pp = ProcessingPipeline()
        for task in self.preprocessed_task_list:
            cliffords = task['sweep_points'].get_sweep_params_property(
                'values', 1)
            seeds = task['sweep_points'].get_sweep_params_property(
                'values', 0)
            if len(self.cal_points.states) != 0:
                pp.add_node('rotate_iq', keys_in='raw',
                            meas_obj_names=task['qb'],
                            num_keys_out=1)
            pp.add_node('average_data',
                        keys_in='raw' if not self.classified else
                        'previous rotate_iq',
                        shape=(len(cliffords), len(seeds)),
                        meas_obj_names=task['qb'])
            pp.add_node('get_std_deviation',
                        keys_in='raw' if not self.classified else
                        'previous rotate_iq',
                        shape=(len(cliffords), len(seeds)),
                        meas_obj_names=task['qb'])
            pp.add_node('rb_analysis', meas_obj_names=task['qb'],
                        keys_out=None, d=2,
                        keys_in=f'previous average_data',
                        keys_in_std=f'previous get_std_deviation')
        self.exp_metadata.update({'processing_pipeline': pp})

class TwoQubitRandomizedBenchmarking(RandomizedBenchmarking):

    def __init__(self, task_list, sweep_points=None,
                 max_clifford_idx=11520, **kw):
        """
        See docstring for RandomizedBenchmarking.

        :param max_clifford_idx: int that allows to restrict the two qubit
            Clifford that is sampled. Set to 24**2 to only sample the tensor
            product of 2 single qubit Clifford groups.
        """
        self.max_clifford_idx = max_clifford_idx
        tqc.gate_decomposition = rb.get_clifford_decomposition(
            kw.get('gate_decomposition', 'HZ'))

        for task in task_list:
            for k in ['qb_1', 'qb_2']:
                if not isinstance(task[k], str):
                    task[k] = task[k].name
            if 'prefix' not in task:
                task['prefix'] = f"{task['qb_1']}{task['qb_2']}_"
        kw['for_ef'] = kw.get('for_ef', True)
        self.experiment_name = 'TwoQubitRB' if \
            kw.get('interleaved_gate', None) is None else 'TwoQubitIRB'
        super().__init__(task_list, sweep_points=sweep_points, **kw)

    def guess_label(self, **kw):
        """
        Default measurement label.
        """
        suffix = [''.join([task['qb_1'], task['qb_2']])
                  for task in self.task_list]
        suffix = '_'.join(suffix)
        if self.label is None:
            if self.interleaved_gate is None:
                self.label = f'{self.experiment_name}_' \
                             f'{self.gate_decomposition}_{suffix}'
            else:
                self.label = f'{self.experiment_name}_{self.interleaved_gate}_' \
                             f'{self.gate_decomposition}_{suffix}'

    def rb_block(self, sp1d_idx, sp2d_idx, **kw):
        interleaved_gate = kw.get('interleaved_gate', None)
        rb_block_list = []
        for i, task in enumerate(self.preprocessed_task_list):
            param_name = 'seeds' if interleaved_gate is None else 'seeds_irb'
            seed = task['sweep_points'].get_sweep_params_property(
                'values', 0, param_name)[sp1d_idx]
            clifford = task['sweep_points'].get_sweep_params_property(
                'values', 1, 'cliffords')[sp2d_idx]

            cl_seq = rb.randomized_benchmarking_sequence_new(
                clifford, number_of_qubits=2, seed=seed,
                max_clifford_idx=kw.get('max_clifford_idx',
                                        self.max_clifford_idx),
                interleaving_cl=interleaved_gate)

            qb_1 = task['qb_1']
            qb_2 = task['qb_2']
            seq_blocks = []
            single_qb_gates = {qb_1: [], qb_2: []}
            for k, idx in enumerate(cl_seq):
                pulse_tuples_list = tqc.TwoQubitClifford(idx).gate_decomposition
                for j, pulse_tuple in enumerate(pulse_tuples_list):
                    if isinstance(pulse_tuple[1], list):
                        seq_blocks.append(
                            self.simultaneous_blocks(
                                f'blk{k}_{j}', [
                            self.block_from_ops(f'blk{k}_{j}_{qbn}', gates)
                                    for qbn, gates in single_qb_gates.items()]))
                        single_qb_gates = {qb_1: [], qb_2: []}
                        seq_blocks.append(self.block_from_ops(
                            f'blk{k}_{j}_cz',
                            f'{kw.get("cz_pulse_name", "CZ")} {qb_1} {qb_2}'))
                    else:
                        qb_name = qb_1 if '0' in pulse_tuple[1] else qb_2
                        pulse_name = pulse_tuple[0]
                        single_qb_gates[qb_name].append(
                            pulse_name + ' ' + qb_name)

            seq_blocks.append(
                self.simultaneous_blocks(
                    f'blk{i}', [
                        self.block_from_ops(f'blk{i}{qbn}', gates)
                        for qbn, gates in single_qb_gates.items()]))
            rb_block_list += [self.sequential_blocks(f'rb_block{i}', seq_blocks)]

        return self.simultaneous_blocks(
            f'sim_rb_{sp2d_idx}_{sp1d_idx}', rb_block_list, block_align='end')

    def add_processing_pipeline(self):
        """
        Creates and adds the analysis processing pipeline to exp_metadata.
        """
        pp = ProcessingPipeline()
        for task in self.preprocessed_task_list:
            cliffords = task['sweep_points'].get_sweep_params_property(
                'values', 1)
            seeds = task['sweep_points'].get_sweep_params_property(
                'values', 0)
            if len(self.cal_points.states) != 0:
                pp.add_node('rotate_iq', keys_in='raw',
                            meas_obj_names=[task['qb_1'], task['qb_2']],
                            num_keys_out=1)
            pp.add_node('average_data',
                        keys_in='raw' if not self.classified else
                        'previous rotate_iq',
                        shape=(len(cliffords), len(seeds)),
                        meas_obj_names=[task['qb_1'], task['qb_2']],)
            pp.add_node('get_std_deviation',
                        keys_in='raw' if not self.classified else
                        'previous rotate_iq',
                        shape=(len(cliffords), len(seeds)),
                        meas_obj_names=[task['qb_1'], task['qb_2']],)
            pp.add_node('rb_analysis',
                        meas_obj_names=[task['qb_1'], task['qb_2']],
                        keys_out=None, d=4,
                        keys_in=f'previous average_data',
                        keys_in_std=f'previous get_std_deviation')
        self.exp_metadata.update({'processing_pipeline': pp})<|endoftext|>


<commit_before># Copyright 2013-2020 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)

from spack import *

class Hip(CMakePackage):
    """HIP is a C++ Runtime API and Kernel Language that allows developers to
       create portable applications for AMD and NVIDIA GPUs from
       single source code."""

    homepage = "https://github.com/ROCm-Developer-Tools/HIP"
    url      = "https://github.com/ROCm-Developer-Tools/HIP/archive/rocm-3.8.0.tar.gz"

    maintainers = ['srekolam', 'arjun-raj-kuppala']

    version('3.8.0', sha256='6450baffe9606b358a4473d5f3e57477ca67cff5843a84ee644bcf685e75d839')
    version('3.7.0', sha256='757b392c3beb29beea27640832fbad86681dbd585284c19a4c2053891673babd')
    version('3.5.0', sha256='ae8384362986b392288181bcfbe5e3a0ec91af4320c189bd83c844ed384161b3')

    depends_on('cmake@3:', type='build')
    depends_on('perl@5.10:', type=('build', 'run'))
    depends_on('mesa~llvm@18.3:')

    for ver in ['3.5.0', '3.7.0', '3.8.0']:
        depends_on('hip-rocclr@' + ver,  type='build', when='@' + ver)
        depends_on('hsakmt-roct@' + ver, type='build', when='@' + ver)
        depends_on('hsa-rocr-dev@' + ver, type='link', when='@' + ver)
        depends_on('comgr@' + ver, type='build', when='@' + ver)
        depends_on('llvm-amdgpu@' + ver, type='build', when='@' + ver)
        depends_on('rocm-device-libs@' + ver, type='build', when='@' + ver)
        depends_on('rocminfo@' + ver, type='build', when='@' + ver)

    # Notice: most likely this will only be a hard dependency on 3.7.0
    depends_on('numactl', when='@3.7.0:')

    # Note: the ROCm ecosystem expects `lib/` and `bin/` folders with symlinks
    # in the parent directory of the package, which is incompatible with spack.
    # In hipcc the ROCM_PATH variable is used to point to the parent directory
    # of the package. With the following patch we should never hit code that
    # uses the ROCM_PATH variable again; just to be sure we set it to an empty
    # string.
    patch('0001-Make-it-possible-to-specify-the-package-folder-of-ro.patch', when='@3.5.0:')

    # See https://github.com/ROCm-Developer-Tools/HIP/pull/2141
    patch('0002-Fix-detection-of-HIP_CLANG_ROOT.patch', when='@3.5.0:')

    def setup_dependent_build_environment(self, env, dependent_spec):
        env.set('ROCM_PATH', '')
        env.set('HIP_COMPILER', 'clang')
        env.set('HIP_PLATFORM', 'hcc')
        env.set('HIP_CLANG_PATH', self.spec['llvm-amdgpu'].prefix.bin)
        env.set('HSA_PATH', self.spec['hsa-rocr-dev'].prefix)
        env.set('ROCMINFO_PATH', self.spec['rocminfo'].prefix)
        env.set('DEVICE_LIB_PATH', self.spec['rocm-device-libs'].prefix.lib)

    def setup_dependent_package(self, module, dependent_spec):
        self.spec.hipcc = join_path(self.prefix.bin, 'hipcc')

    def patch(self):
        filter_file(
            'INTERFACE_INCLUDE_DIRECTORIES "${_IMPORT_PREFIX}/../include"',
            'INTERFACE_INCLUDE_DIRECTORIES "${_IMPORT_PREFIX}/include"',
            'hip-config.cmake.in', string=True)

    def flag_handler(self, name, flags):
        if name == 'cxxflags' and '@3.7.0:' in self.spec:
            incl = self.spec['hip-rocclr'].prefix.include
            flags.append('-I {0}/compiler/lib/include'.format(incl))

        return (flags, None, None)

    @run_before('install')
    def filter_sbang(self):
        perl = self.spec['perl'].command
        kwargs = {'ignore_absent': False, 'backup': False, 'string': False}

        with working_dir('bin'):
            match = '^#!/usr/bin/perl'
            substitute = "#!{perl}".format(perl=perl)
            files = [
                'hipify-perl', 'hipcc', 'extractkernel',
                'hipconfig', 'hipify-cmakefile'
            ]
            filter_file(match, substitute, *files, **kwargs)

    def cmake_args(self):
        args = [
            '-DHIP_COMPILER=clang',
            '-DHIP_PLATFORM=rocclr',
            '-DHSA_PATH={0}'.format(self.spec['hsa-rocr-dev'].prefix),
            '-DLIBROCclr_STATIC_DIR={0}/lib'.format
            (self.spec['hip-rocclr'].prefix)
        ]
        return args
<commit_msg>libamd_comgr.so.1 is linked to by libamdhip64.so.3, so it should be a link dep (#19025)<commit_after># Copyright 2013-2020 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)

from spack import *

class Hip(CMakePackage):
    """HIP is a C++ Runtime API and Kernel Language that allows developers to
       create portable applications for AMD and NVIDIA GPUs from
       single source code."""

    homepage = "https://github.com/ROCm-Developer-Tools/HIP"
    url      = "https://github.com/ROCm-Developer-Tools/HIP/archive/rocm-3.8.0.tar.gz"

    maintainers = ['srekolam', 'arjun-raj-kuppala']

    version('3.8.0', sha256='6450baffe9606b358a4473d5f3e57477ca67cff5843a84ee644bcf685e75d839')
    version('3.7.0', sha256='757b392c3beb29beea27640832fbad86681dbd585284c19a4c2053891673babd')
    version('3.5.0', sha256='ae8384362986b392288181bcfbe5e3a0ec91af4320c189bd83c844ed384161b3')

    depends_on('cmake@3:', type='build')
    depends_on('perl@5.10:', type=('build', 'run'))
    depends_on('mesa~llvm@18.3:')

    for ver in ['3.5.0', '3.7.0', '3.8.0']:
        depends_on('hip-rocclr@' + ver,  type='build', when='@' + ver)
        depends_on('hsakmt-roct@' + ver, type='build', when='@' + ver)
        depends_on('hsa-rocr-dev@' + ver, type='link', when='@' + ver)
        depends_on('comgr@' + ver, when='@' + ver)
        depends_on('llvm-amdgpu@' + ver, type='build', when='@' + ver)
        depends_on('rocm-device-libs@' + ver, type='build', when='@' + ver)
        depends_on('rocminfo@' + ver, type='build', when='@' + ver)

    # Notice: most likely this will only be a hard dependency on 3.7.0
    depends_on('numactl', when='@3.7.0:')

    # Note: the ROCm ecosystem expects `lib/` and `bin/` folders with symlinks
    # in the parent directory of the package, which is incompatible with spack.
    # In hipcc the ROCM_PATH variable is used to point to the parent directory
    # of the package. With the following patch we should never hit code that
    # uses the ROCM_PATH variable again; just to be sure we set it to an empty
    # string.
    patch('0001-Make-it-possible-to-specify-the-package-folder-of-ro.patch', when='@3.5.0:')

    # See https://github.com/ROCm-Developer-Tools/HIP/pull/2141
    patch('0002-Fix-detection-of-HIP_CLANG_ROOT.patch', when='@3.5.0:')

    def setup_dependent_build_environment(self, env, dependent_spec):
        env.set('ROCM_PATH', '')
        env.set('HIP_COMPILER', 'clang')
        env.set('HIP_PLATFORM', 'hcc')
        env.set('HIP_CLANG_PATH', self.spec['llvm-amdgpu'].prefix.bin)
        env.set('HSA_PATH', self.spec['hsa-rocr-dev'].prefix)
        env.set('ROCMINFO_PATH', self.spec['rocminfo'].prefix)
        env.set('DEVICE_LIB_PATH', self.spec['rocm-device-libs'].prefix.lib)

    def setup_dependent_package(self, module, dependent_spec):
        self.spec.hipcc = join_path(self.prefix.bin, 'hipcc')

    def patch(self):
        filter_file(
            'INTERFACE_INCLUDE_DIRECTORIES "${_IMPORT_PREFIX}/../include"',
            'INTERFACE_INCLUDE_DIRECTORIES "${_IMPORT_PREFIX}/include"',
            'hip-config.cmake.in', string=True)

    def flag_handler(self, name, flags):
        if name == 'cxxflags' and '@3.7.0:' in self.spec:
            incl = self.spec['hip-rocclr'].prefix.include
            flags.append('-I {0}/compiler/lib/include'.format(incl))

        return (flags, None, None)

    @run_before('install')
    def filter_sbang(self):
        perl = self.spec['perl'].command
        kwargs = {'ignore_absent': False, 'backup': False, 'string': False}

        with working_dir('bin'):
            match = '^#!/usr/bin/perl'
            substitute = "#!{perl}".format(perl=perl)
            files = [
                'hipify-perl', 'hipcc', 'extractkernel',
                'hipconfig', 'hipify-cmakefile'
            ]
            filter_file(match, substitute, *files, **kwargs)

    def cmake_args(self):
        args = [
            '-DHIP_COMPILER=clang',
            '-DHIP_PLATFORM=rocclr',
            '-DHSA_PATH={0}'.format(self.spec['hsa-rocr-dev'].prefix),
            '-DLIBROCclr_STATIC_DIR={0}/lib'.format
            (self.spec['hip-rocclr'].prefix)
        ]
        return args
<|endoftext|>


<commit_before>#!/usr/bin/python
# -*- coding: utf-8 -*-

""" pyforms.gui.Controls.ControlEventTimeline.TimelineChart

"""

from PyQt4 import QtGui

__author__ = ["Ricardo Ribeiro", "Hugo Cachitas"]
__credits__ = ["Ricardo Ribeiro", "Hugo Cachitas"]
__license__ = "MIT"
__version__ = "0.0"
__maintainer__ = "Ricardo Ribeiro"
__email__ = "ricardojvr@gmail.com"
__status__ = "Development"

class TimelineChart(object):

    def __init__(self, timeLineWidget, csvfileobject, color=QtGui.QColor(255, 0, 0)):
        self._data = []
        self._firstFrame = None
        self._graphMax = None
        self._graphMin = None
        self._widget = timeLineWidget
        self._color = color

        for row in csvfileobject:
            print row
        data = [map(float, row) for row in csvfileobject]

        self._graphMax = 0
        self._graphMin = 100000000000
        self._data = []
        lastX = 0
        for x, y in data:
            if y > self._graphMax:
                self._graphMax = y
            if y < self._graphMin:
                self._graphMin = y

            if int(x - lastX) > 1:
                for i in range(0, int(x - lastX) + 1):
                    self._data.append((lastX + i, y))
                    # self._data.append( None )
            self._data.append((x, y))
            lastX = x

        if self._graphMin < 0:
            min2Zero = 0 - self._graphMin
            self._graphMin += min2Zero
            self._graphMax += min2Zero
            newData = []
            for f, y in self._data:
                newData.append((f, y + min2Zero))

            self._data = newData

    def draw(self,  painter, left, right, top, bottom):
        painter.setPen(self._color)
        painter.setOpacity(0.7)

        maxPixelsHeight = (bottom - top)
        start = self._widget.x2frame(left)
        end = self._widget.x2frame(right)
        end = len(self._data) if end > len(self._data) else end

        diffMinMaxValue = self._graphMax - self._graphMin
        if diffMinMaxValue <= 0:
            diffMinMaxValue = 1

        for pos1, pos2 in zip(self._data[start + 1:end], self._data[start:end]):
            if pos1 and pos2:
                x, y = pos1
                xx, yy = pos2

                # y -= self._graphMin
                # yy -= self._graphMin

                y = (y * maxPixelsHeight) // diffMinMaxValue  # + yMiddle
                yy = (yy * maxPixelsHeight) // diffMinMaxValue  # + yMiddle

                painter.drawLine(
                    self._widget.frame2x(xx), yy, self._widget.frame2x(x), y)

        painter.setOpacity(1.0)
<commit_msg>compliance to python3<commit_after>#!/usr/bin/python
# -*- coding: utf-8 -*-

""" pyforms.gui.Controls.ControlEventTimeline.TimelineChart

"""

from PyQt4 import QtGui

__author__ = ["Ricardo Ribeiro", "Hugo Cachitas"]
__credits__ = ["Ricardo Ribeiro", "Hugo Cachitas"]
__license__ = "MIT"
__version__ = "0.0"
__maintainer__ = "Ricardo Ribeiro"
__email__ = "ricardojvr@gmail.com"
__status__ = "Development"

class TimelineChart(object):

    def __init__(self, timeLineWidget, csvfileobject, color=QtGui.QColor(255, 0, 0)):
        self._data = []
        self._firstFrame = None
        self._graphMax = None
        self._graphMin = None
        self._widget = timeLineWidget
        self._color = color

        for row in csvfileobject:
            print(row)
        data = [map(float, row) for row in csvfileobject]

        self._graphMax = 0
        self._graphMin = 100000000000
        self._data = []
        lastX = 0
        for x, y in data:
            if y > self._graphMax:
                self._graphMax = y
            if y < self._graphMin:
                self._graphMin = y

            if int(x - lastX) > 1:
                for i in range(0, int(x - lastX) + 1):
                    self._data.append((lastX + i, y))
                    # self._data.append( None )
            self._data.append((x, y))
            lastX = x

        if self._graphMin < 0:
            min2Zero = 0 - self._graphMin
            self._graphMin += min2Zero
            self._graphMax += min2Zero
            newData = []
            for f, y in self._data:
                newData.append((f, y + min2Zero))

            self._data = newData

    def draw(self, painter, left, right, top, bottom):
        painter.setPen(self._color)
        painter.setOpacity(0.7)

        maxPixelsHeight = (bottom - top)
        start = self._widget.x2frame(left)
        end = self._widget.x2frame(right)
        end = len(self._data) if end > len(self._data) else end

        diffMinMaxValue = self._graphMax - self._graphMin
        if diffMinMaxValue <= 0:
            diffMinMaxValue = 1

        for pos1, pos2 in zip(self._data[start + 1:end], self._data[start:end]):
            if pos1 and pos2:
                x, y = pos1
                xx, yy = pos2

                # y -= self._graphMin
                # yy -= self._graphMin

                y = (y * maxPixelsHeight) // diffMinMaxValue  # + yMiddle
                yy = (yy * maxPixelsHeight) // diffMinMaxValue  # + yMiddle

                painter.drawLine(
                    self._widget.frame2x(xx), yy, self._widget.frame2x(x), y)

        painter.setOpacity(1.0)
<|endoftext|>


<commit_before>from flask import Flask, render_template, request, session, url_for, redirect, abort, json

import requests
import os

app = Flask(__name__)
app.secret_key = os.environ['secret_key']

client_id = os.environ['client_id']
client_secret = os.environ['client_secret']

# Required Parameters: - Access Code  - Client ID  - Client secret
# Output: - A JSON object containing a valid access token
def getAccessToken(code):
    url = "https://api.ciscospark.com/v1/access_token"
    data = {
        'grant_type': 'authorization_code',
        'client_id': client_id,
        'client_secret': client_secret,
        'code': code,
        'redirect_uri': 'http://localhost:8080/oauth'
    }
    accessData = requests.post(url, data)
    return accessData.json()

# Required Data: - Access Token
# Output: - An array of all rooms
def listRooms():
    url = "https://api.ciscospark.com/v1/rooms"
    headers = {
        'Content-type': 'application/json; charset=utf-8',
        'Authorization': 'Bearer ' + session['access_token']
    }
    roomData = (requests.get(url, headers=headers)).json()

    rooms = []
    rooms.append([item["title"] for item in roomData["items"]])
    return rooms

# Required Parameters: - Access Token
# Output: - A JSON object containing the user's Cisco Spark details
def getUserProfile():
    url = "https://api.ciscospark.com/v1/people/me"
    headers = {
        'Content-type': 'application/json; charset=utf-8',
        'Authorization': 'Bearer ' + session['access_token']
    }
    userDetails = requests.get(url, headers=headers)
    return userDetails.json()

# 'Main' page with a list of all the rooms the user is part of
@app.route('/main')
def main():
    rooms = listRooms()

    # with open('roomList.txt', 'w') as f:
    #     for room in rooms:
    #         f.write("%s\n" %room)

    # with open('rooms.txt', 'w') as f:
    #         json.dump(rooms,f, ensure_ascii = False)

    userDetails = getUserProfile()
    session['displayName'] = userDetails['displayName']

    return render_template("main.html", key = session['displayName'])

# 'Authorised' page which redirects the user if the login was valid
@app.route('/oauth')
def oauth():
    code = request.args.get("code")

    data = getAccessToken(code)
    session['access_token'] = data['access_token']

    return render_template("authorise.html")

# Redirect to authorisation URL (Cisco Spark login & Authorisation) using a 'GET' request
@app.route('/authorise', methods=['GET'])
def authorise():
    url = (
        "https://api.ciscospark.com/v1/authorize?"+
        "client_id=%s" %client_id+
        "&response_type=code"+
        "&redirect_uri=http%3A%2F%2Flocalhost%3A8080%2Foauth"+
        "&scope=spark%3Aall%20spark-admin%3Aroles_read%20spark%3Akms%20spark-admin%3Aorganizations_read%20spark-admin%3Apeople_read"
    )
    return redirect(url, code=302)

@app.route('/')
def index():
    return render_template('hello.html')

if __name__ == '__main__':
    app.run(host='127.0.0.1', port=8080)<commit_msg>Delete recapv0.1.py<commit_after><|endoftext|>


<commit_before>#
# Copyright 2018 Analytics Zoo Authors.
#
# 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 pytest

import numpy as np
from test.zoo.pipeline.utils.test_utils import ZooTestCase
from zoo.tfpark.text import *

class TestTextModels(ZooTestCase):

    def test_intent_entity(self):
        model = IntentEntity(num_intents=8, num_entities=5, word_length=10,
                             word_vocab_size=200, char_vocab_size=50)
        input_data = [np.random.randint(200, size=(8, 30)), np.random.randint(50, size=(8, 30, 10))]
        output = model.predict(input_data, distributed=True)
        assert isinstance(output, list) and len(output) == 2
        assert output[0].shape == (8, 8)
        assert output[1].shape == (8, 30, 5)
        self.assert_tfpark_model_save_load(model, input_data)

    def test_ner_crf_reg_mode(self):
        model = NER(num_entities=10, word_length=5, word_vocab_size=20, char_vocab_size=10)
        input_data = [np.random.randint(20, size=(15, 12)), np.random.randint(10, size=(15, 12, 5))]
        output = model.predict(input_data, distributed=True)
        assert output.shape == (15, 12, 10)
        self.assert_tfpark_model_save_load(model, input_data)

    def test_ner_crf_pad_mode(self):
        model = NER(num_entities=15, word_length=8, word_vocab_size=20,
                    char_vocab_size=10, crf_mode="pad")
        input_data = [np.random.randint(20, size=(4, 12)), np.random.randint(10, size=(4, 12, 8)),
                      np.random.randint(12, size=(15, 1))]
        output = model.predict(input_data, distributed=True)
        assert output.shape == (4, 12, 15)
        self.assert_tfpark_model_save_load(model, input_data)

if __name__ == "__main__":
    pytest.main([__file__])
<commit_msg>Add sequence tagger in tfpark (#1213)<commit_after>#
# Copyright 2018 Analytics Zoo Authors.
#
# 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 pytest

import numpy as np
from test.zoo.pipeline.utils.test_utils import ZooTestCase
from zoo.tfpark.text import *

class TestTextModels(ZooTestCase):

    def test_intent_entity(self):
        model = IntentEntity(num_intents=8, num_entities=5, word_length=10,
                             word_vocab_size=200, char_vocab_size=50)
        input_data = [np.random.randint(200, size=(8, 30)), np.random.randint(50, size=(8, 30, 10))]
        output = model.predict(input_data, distributed=True)
        assert isinstance(output, list) and len(output) == 2
        assert output[0].shape == (8, 8)
        assert output[1].shape == (8, 30, 5)
        self.assert_tfpark_model_save_load(model, input_data)

    def test_ner_crf_reg_mode(self):
        model = NER(num_entities=10, word_length=5, word_vocab_size=20, char_vocab_size=10)
        input_data = [np.random.randint(20, size=(15, 12)), np.random.randint(10, size=(15, 12, 5))]
        output = model.predict(input_data, distributed=True)
        assert output.shape == (15, 12, 10)
        self.assert_tfpark_model_save_load(model, input_data)

    def test_ner_crf_pad_mode(self):
        model = NER(num_entities=15, word_length=8, word_vocab_size=20,
                    char_vocab_size=10, crf_mode="pad")
        input_data = [np.random.randint(20, size=(4, 12)), np.random.randint(10, size=(4, 12, 8)),
                      np.random.randint(12, size=(15, 1))]
        output = model.predict(input_data, distributed=True)
        assert output.shape == (4, 12, 15)
        self.assert_tfpark_model_save_load(model, input_data)

    def test_sequence_tagger_softmax(self):
        model = SequenceTagger(num_pos_labels=5, num_chunk_labels=10, word_vocab_size=150)
        input_data = np.random.randint(150, size=(10, 50))
        output = model.predict(input_data, distributed=True)
        assert isinstance(output, list) and len(output) == 2
        assert output[0].shape == (10, 50, 5)
        assert output[1].shape == (10, 50, 10)
        self.assert_tfpark_model_save_load(model, input_data)

    def test_sequence_tagger_crf(self):
        model = SequenceTagger(num_pos_labels=8, num_chunk_labels=8, word_vocab_size=50,
                               char_vocab_size=20, classifier="crf")
        input_data = [np.random.randint(50, size=(10, 15)),
                      np.random.randint(20, size=(10, 15, 12))]
        output = model.predict(input_data, distributed=True)
        assert isinstance(output, list) and len(output) == 2
        assert output[0].shape == (10, 15, 8)
        assert output[1].shape == (10, 15, 8)
        self.assert_tfpark_model_save_load(model, input_data)

if __name__ == "__main__":
    pytest.main([__file__])
<|endoftext|>


<commit_before>#!/usr/bin/env python
# encoding: utf-8
from copy import copy
from tornado.web import Cookie
from tornado.gen import coroutine, Return
from tornado.httpclient import AsyncHTTPClient, HTTPRequest, HTTPError, HTTPResponse
from tornado.httputil import HTTPHeaders
from tornado.ioloop import IOLoop
from tornado.netutil import Resolver
from . import PY2

try:
    import pycares
    Resolver.configure('tornado.platform.caresresolver.CaresResolver')
except ImportError:
    pass

if PY2:
    b = unicode
    iteritems = lambda x: x.iteritems()
else:
    b = str
    iteritems = lambda x: x.items()

try:
    import ujson as json
except ImportError:
    import json

def _freeze_response(response):
    if isinstance(response, list):
        return tuple(_freeze_response(x) for x in response)
    elif isinstance(response, dict):
        data = dict((k, _freeze_response(v)) for k, v in iteritems(response))
        return FrozenDict(data)
    else:
        return response

def make_method(method_name):
    def method(self, url, **kwargs):
        return self.fetch(url, method=method_name, **kwargs)

    method.__name__ = method_name.lower()

    return method

class FrozenDict(dict):
    __slots__ = ('__hash',)
    __getattr__ = dict.__getitem__

    def __init__(self, data):
        super(FrozenDict, self).__init__(data)
        self.__hash = hash(tuple(i for i in sorted(iteritems(self))))

    def __setitem__(self, key, value):
        raise TypeError("Response is immutable")

    def __setattr__(self, key, value):
        if key.startswith("_{0.__class__.__name__}".format(self)):
            return super(FrozenDict, self).__setattr__(key, value)
        raise TypeError("Response is immutable")

    def __hash__(self):
        return self.__hash

    def __eq__(self, other):
        return hash(self) == hash(other)

    def __ne__(self, other):
        return hash(self) != hash(other)

class RESTClient(object):
    _DEFAULT = {}

    METHODS_WITH_BODY = set(['POST', 'PUT', 'PATCH'])

    __slots__ = ('_client', '_cookies', 'io_loop', '_headers', '_default_args')

    @classmethod
    def configure(cls, **kwargs):
        cls._DEFAULT.update(kwargs)

    def __init__(self, io_loop=None, client=None, headers=None, **kwargs):
        self.io_loop = IOLoop.current() if io_loop is None else io_loop

        self._headers = headers if headers else {}

        self._client = AsyncHTTPClient() if client is None else client
        self._cookies = Cookie.SimpleCookie()
        self._default_args = copy(self._DEFAULT)
        self._default_args.update(kwargs)

    @coroutine
    def fetch(self, url, method='GET', body=None, headers=None, fail=True, freeze=False, follow_redirects=True, max_redirects=5, **kwargs):
        if not headers:
            headers = {}

        default_headers = copy(self._headers)
        default_headers.update(headers)

        headers = default_headers

        if body is not None and "Content-Type" not in headers:
            headers['Content-Type'] = 'application/json'

        if method in self.METHODS_WITH_BODY:
            body = body or ''

            if headers.get('Content-Type', '') == 'application/json':
                body = self._make_json(body)

        params = copy(self._default_args)
        params.update(kwargs)

        last_exc = RuntimeError("Something wrong")

        for _ in range(max_redirects + 1):
            request = HTTPRequest(
                b(url),
                method=method,
                body=body,
                headers=HTTPHeaders(headers),
                follow_redirects=False,
                **params
            )

            request.headers['Cookie'] = "; ".join(
                "{0.key}={0.value}".format(cookie) for cookie in self._cookies.values()
            )

            need_redirect = False

            try:
                response = yield self._client.fetch(request)
                response.fail = False
            except HTTPError as e:
                last_exc = e
                response = e.response

                if e.code == 599:
                    response = HTTPResponse(
                        request=request,
                        code=e.code,
                        headers=HTTPHeaders(),
                        effective_url=request.url
                    )

                    response.fail = True

                if e.code in (301, 302, 303, 307) and follow_redirects:
                    need_redirect = True
                else:
                    response.fail = True

                if fail and e.response:
                    content_type = e.response.headers.get('Content-Type', '')
                    e.response._body = self._decode_body(content_type, response.body)

                    if e.response.body and 'application/json' in content_type.lower():
                        e.response._body = self._parse_json(e.response.body)

            if not need_redirect:
                break

            if not freeze:
                for cookie in response.headers.get_list('Set-Cookie'):
                    self._cookies.load(cookie)
        else:
            response.fail = True

        if fail and response.fail:
            raise last_exc

        content_type = response.headers.get("Content-Type", '')
        response._body = self._decode_body(content_type, response.body)

        if response.body and 'json' in response.headers.get("Content-Type", ""):
            new_body = self._parse_json(response.body)
            response._body = _freeze_response(new_body)

        if not freeze:
            for cookie in response.headers.get_list('Set-Cookie'):
                self._cookies.load(cookie)

        raise Return(response)

    @classmethod
    def _decode_body(cls, content_type, body):
        if 'charset=' in content_type:
            _, charset = content_type.split("charset=")
            charset = charset.lower()
        else:
            charset = 'utf-8'

        try:
            return body.decode(charset)
        except:
            return body

    def _parse_json(self, data):
        return json.loads(data)

    def _make_json(self, data):
        return json.dumps(data)

    @property
    def close(self):
        return self._client.close

    get = make_method('GET')
    post = make_method('POST')
    put = make_method('PUT')
    options = make_method('OPTIONS')
    delete = make_method('DELETE')
    head = make_method('HEAD')

    def __copy__(self):
        client = RESTClient(
            io_loop=self.io_loop,
            headers=self._headers,
            **self._default_args
        )

        client._cookies = copy(self._cookies)
        return client
<commit_msg>support body_producer<commit_after>#!/usr/bin/env python
# encoding: utf-8
from copy import copy
from tornado.web import Cookie
from tornado.gen import coroutine, Return
from tornado.httpclient import AsyncHTTPClient, HTTPRequest, HTTPError, HTTPResponse
from tornado.httputil import HTTPHeaders
from tornado.ioloop import IOLoop
from tornado.netutil import Resolver
from . import PY2

try:
    import pycares
    Resolver.configure('tornado.platform.caresresolver.CaresResolver')
except ImportError:
    pass

if PY2:
    b = unicode
    iteritems = lambda x: x.iteritems()
else:
    b = str
    iteritems = lambda x: x.items()

try:
    import ujson as json
except ImportError:
    import json

def _freeze_response(response):
    if isinstance(response, list):
        return tuple(_freeze_response(x) for x in response)
    elif isinstance(response, dict):
        data = dict((k, _freeze_response(v)) for k, v in iteritems(response))
        return FrozenDict(data)
    else:
        return response

def make_method(method_name):
    def method(self, url, **kwargs):
        return self.fetch(url, method=method_name, **kwargs)

    method.__name__ = method_name.lower()

    return method

class FrozenDict(dict):
    __slots__ = ('__hash',)
    __getattr__ = dict.__getitem__

    def __init__(self, data):
        super(FrozenDict, self).__init__(data)
        self.__hash = hash(tuple(i for i in sorted(iteritems(self))))

    def __setitem__(self, key, value):
        raise TypeError("Response is immutable")

    def __setattr__(self, key, value):
        if key.startswith("_{0.__class__.__name__}".format(self)):
            return super(FrozenDict, self).__setattr__(key, value)
        raise TypeError("Response is immutable")

    def __hash__(self):
        return self.__hash

    def __eq__(self, other):
        return hash(self) == hash(other)

    def __ne__(self, other):
        return hash(self) != hash(other)

class RESTClient(object):
    _DEFAULT = {}

    METHODS_WITH_BODY = set(['POST', 'PUT', 'PATCH'])

    __slots__ = ('_client', '_cookies', 'io_loop', '_headers', '_default_args')

    @classmethod
    def configure(cls, **kwargs):
        cls._DEFAULT.update(kwargs)

    def __init__(self, io_loop=None, client=None, headers=None, **kwargs):
        self.io_loop = IOLoop.current() if io_loop is None else io_loop

        self._headers = headers if headers else {}

        self._client = AsyncHTTPClient() if client is None else client
        self._cookies = Cookie.SimpleCookie()
        self._default_args = copy(self._DEFAULT)
        self._default_args.update(kwargs)

    @coroutine
    def fetch(self, url, method='GET', body=None, headers=None, fail=True, freeze=False, follow_redirects=True, max_redirects=5, **kwargs):
        if not headers:
            headers = {}

        default_headers = copy(self._headers)
        default_headers.update(headers)

        headers = default_headers

        if body is not None and "Content-Type" not in headers:
            headers['Content-Type'] = 'application/json'

        if method in self.METHODS_WITH_BODY and "body_producer" not in kwargs:
            body = body or ''

            if headers.get('Content-Type', '') == 'application/json':
                body = self._make_json(body)

        params = copy(self._default_args)
        params.update(kwargs)

        last_exc = RuntimeError("Something wrong")

        for _ in range(max_redirects + 1):
            request = HTTPRequest(
                b(url),
                method=method,
                body=body,
                headers=HTTPHeaders(headers),
                follow_redirects=False,
                **params
            )

            request.headers['Cookie'] = "; ".join(
                "{0.key}={0.value}".format(cookie) for cookie in self._cookies.values()
            )

            need_redirect = False

            try:
                response = yield self._client.fetch(request)
                response.fail = False
            except HTTPError as e:
                last_exc = e
                response = e.response

                if e.code == 599:
                    response = HTTPResponse(
                        request=request,
                        code=e.code,
                        headers=HTTPHeaders(),
                        effective_url=request.url
                    )

                    response.fail = True

                if e.code in (301, 302, 303, 307) and follow_redirects:
                    need_redirect = True
                else:
                    response.fail = True

                if fail and e.response:
                    content_type = e.response.headers.get('Content-Type', '')
                    e.response._body = self._decode_body(content_type, response.body)

                    if e.response.body and 'application/json' in content_type.lower():
                        e.response._body = self._parse_json(e.response.body)

            if not need_redirect:
                break

            if not freeze:
                for cookie in response.headers.get_list('Set-Cookie'):
                    self._cookies.load(cookie)
        else:
            response.fail = True

        if fail and response.fail:
            raise last_exc

        content_type = response.headers.get("Content-Type", '')
        response._body = self._decode_body(content_type, response.body)

        if response.body and 'json' in response.headers.get("Content-Type", ""):
            new_body = self._parse_json(response.body)
            response._body = _freeze_response(new_body)

        if not freeze:
            for cookie in response.headers.get_list('Set-Cookie'):
                self._cookies.load(cookie)

        raise Return(response)

    @classmethod
    def _decode_body(cls, content_type, body):
        if 'charset=' in content_type:
            _, charset = content_type.split("charset=")
            charset = charset.lower()
        else:
            charset = 'utf-8'

        try:
            return body.decode(charset)
        except:
            return body

    def _parse_json(self, data):
        return json.loads(data)

    def _make_json(self, data):
        return json.dumps(data)

    @property
    def close(self):
        return self._client.close

    get = make_method('GET')
    post = make_method('POST')
    put = make_method('PUT')
    options = make_method('OPTIONS')
    delete = make_method('DELETE')
    head = make_method('HEAD')

    def __copy__(self):
        client = RESTClient(
            io_loop=self.io_loop,
            headers=self._headers,
            **self._default_args
        )

        client._cookies = copy(self._cookies)
        return client
<|endoftext|>