<commit_before>from __future__ import unicode_literals, division, absolute_import, print_function

import collections
import contextlib
import logging
import logging.handlers
import sys
import threading
import uuid
import warnings

from builtins import *  # pylint: disable=unused-import, redefined-builtin
from flexget import __version__

# A level more detailed than DEBUG
TRACE = 5
# A level more detailed than INFO
VERBOSE = 15

# Stores `task`, logging `session_id`, and redirected `output` stream in a thread local context
local_context = threading.local()

def get_level_no(level):
    if not isinstance(level, int):
        # Cannot use getLevelName here as in 3.4.0 it returns a string.
        level = level.upper()
        if level == 'TRACE':
            level = TRACE
        elif level == 'VERBOSE':
            level = VERBOSE
        else:
            level = getattr(logging, level)

    return level

@contextlib.contextmanager
def task_logging(task):
    """Context manager which adds task information to log messages."""
    old_task = getattr(local_context, 'task', '')
    local_context.task = task
    try:
        yield
    finally:
        local_context.task = old_task

class SessionFilter(logging.Filter):

    def __init__(self, session_id):
        self.session_id = session_id

    def filter(self, record):
        return getattr(record, 'session_id', None) == self.session_id

@contextlib.contextmanager
def capture_output(stream, loglevel=None):
    """Context manager which captures all log and console output to given `stream` while in scope."""
    root_logger = logging.getLogger()
    old_level = root_logger.getEffectiveLevel()
    old_id = getattr(local_context, 'session_id', None)
    # Keep using current, or create one if none already set
    local_context.session_id = old_id or uuid.uuid4()
    old_output = getattr(local_context, 'output', None)
    old_loglevel = getattr(local_context, 'loglevel', None)
    streamhandler = logging.StreamHandler(stream)
    streamhandler.setFormatter(FlexGetFormatter())
    streamhandler.addFilter(SessionFilter(local_context.session_id))
    if loglevel is not None:
        loglevel = get_level_no(loglevel)
        streamhandler.setLevel(loglevel)
        # If requested loglevel is lower than the root logger is filtering for, we need to turn it down.
        # All existing handlers should have their desired level set and not be affected.
        if not root_logger.isEnabledFor(loglevel):
            root_logger.setLevel(loglevel)
    local_context.output = stream
    local_context.loglevel = loglevel
    root_logger.addHandler(streamhandler)
    try:
        yield
    finally:
        root_logger.removeHandler(streamhandler)
        root_logger.setLevel(old_level)
        local_context.session_id = old_id
        local_context.output = old_output
        local_context.loglevel = old_loglevel

def get_capture_stream():
    """If output is currently being redirected to a stream, returns that stream."""
    return getattr(local_context, 'output', None)

def get_capture_loglevel():
    """If output is currently being redirected to a stream, returns declared loglevel for that stream."""
    return getattr(local_context, 'loglevel', None)

class RollingBuffer(collections.deque):
    """File-like that keeps a certain number of lines of text in memory."""

    def write(self, line):
        self.append(line)

class FlexGetLogger(logging.Logger):
    """Custom logger that adds trace and verbose logging methods, and contextual information to log records."""

    def makeRecord(self, name, level, fn, lno, msg, args, exc_info, func, extra, *exargs):
        extra = extra or {}
        extra.update(
            task=getattr(local_context, 'task', ''),
            session_id=getattr(local_context, 'session_id', ''))
        # Replace newlines in log messages with \n
        if isinstance(msg, str):
            msg = msg.replace('\n', '\\n')

        return logging.Logger.makeRecord(self, name, level, fn, lno, msg, args, exc_info, func, extra, *exargs)

    def trace(self, msg, *args, **kwargs):
        """Log at TRACE level (more detailed than DEBUG)."""
        self.log(TRACE, msg, *args, **kwargs)

    def verbose(self, msg, *args, **kwargs):
        """Log at VERBOSE level (displayed when FlexGet is run interactively.)"""
        self.log(VERBOSE, msg, *args, **kwargs)

class FlexGetFormatter(logging.Formatter):
    """Custom formatter that can handle both regular log records and those created by FlexGetLogger"""
    flexget_fmt = '%(asctime)-15s %(levelname)-8s %(name)-13s %(task)-15s %(message)s'

    def __init__(self):
        logging.Formatter.__init__(self, self.flexget_fmt, '%Y-%m-%d %H:%M')

    def format(self, record):
        if not hasattr(record, 'task'):
            record.task = ''
        return logging.Formatter.format(self, record)

_logging_configured = False
_buff_handler = None
_logging_started = False
# Stores the last 50 debug messages
debug_buffer = RollingBuffer(maxlen=50)

def initialize(unit_test=False):
    """Prepare logging.
    """
    global _logging_configured, _logging_started, _buff_handler

    if _logging_configured:
        return

    if 'dev' in __version__:
        warnings.filterwarnings('always', category=DeprecationWarning, module='flexget.*')
    warnings.simplefilter('once', append=True)
    logging.addLevelName(TRACE, 'TRACE')
    logging.addLevelName(VERBOSE, 'VERBOSE')
    _logging_configured = True

    # with unit test we want pytest to add the handlers
    if unit_test:
        _logging_started = True
        return

    # Store any log messages in a buffer until we `start` function is run
    logger = logging.getLogger()
    _buff_handler = logging.handlers.BufferingHandler(1000 * 1000)
    logger.addHandler(_buff_handler)
    logger.setLevel(logging.NOTSET)

    # Add a handler that sores the last 50 debug lines to `debug_buffer` for use in crash reports
    crash_handler = logging.StreamHandler(debug_buffer)
    crash_handler.setLevel(logging.DEBUG)
    crash_handler.setFormatter(FlexGetFormatter())
    logger.addHandler(crash_handler)

def start(filename=None, level=logging.INFO, to_console=True, to_file=True):
    """After initialization, start file logging.
    """
    global _logging_started

    assert _logging_configured
    if _logging_started:
        return

    # root logger
    logger = logging.getLogger()
    level = get_level_no(level)
    logger.setLevel(level)

    formatter = FlexGetFormatter()
    if to_file:
        file_handler = logging.handlers.RotatingFileHandler(filename, maxBytes=1000 * 1024, backupCount=9)
        file_handler.setFormatter(formatter)
        file_handler.setLevel(level)
        logger.addHandler(file_handler)

    # without --cron we log to console
    if to_console:
        console_handler = logging.StreamHandler(sys.stdout)
        console_handler.setFormatter(formatter)
        console_handler.setLevel(level)
        logger.addHandler(console_handler)

    # flush what we have stored from the plugin initialization
    logger.removeHandler(_buff_handler)
    if _buff_handler:
        for record in _buff_handler.buffer:
            if logger.isEnabledFor(record.levelno):
                logger.handle(record)
        _buff_handler.flush()
    _logging_started = True

# Set our custom logger class as default
logging.setLoggerClass(FlexGetLogger)
<commit_msg>Fixed import order<commit_after>from __future__ import unicode_literals, division, absolute_import, print_function
from builtins import *  # pylint: disable=unused-import, redefined-builtin

import collections
import contextlib
import logging
import logging.handlers
import sys
import threading
import uuid
import warnings

from flexget import __version__

# A level more detailed than DEBUG
TRACE = 5
# A level more detailed than INFO
VERBOSE = 15

# Stores `task`, logging `session_id`, and redirected `output` stream in a thread local context
local_context = threading.local()

def get_level_no(level):
    if not isinstance(level, int):
        # Cannot use getLevelName here as in 3.4.0 it returns a string.
        level = level.upper()
        if level == 'TRACE':
            level = TRACE
        elif level == 'VERBOSE':
            level = VERBOSE
        else:
            level = getattr(logging, level)

    return level

@contextlib.contextmanager
def task_logging(task):
    """Context manager which adds task information to log messages."""
    old_task = getattr(local_context, 'task', '')
    local_context.task = task
    try:
        yield
    finally:
        local_context.task = old_task

class SessionFilter(logging.Filter):
    def __init__(self, session_id):
        self.session_id = session_id

    def filter(self, record):
        return getattr(record, 'session_id', None) == self.session_id

@contextlib.contextmanager
def capture_output(stream, loglevel=None):
    """Context manager which captures all log and console output to given `stream` while in scope."""
    root_logger = logging.getLogger()
    old_level = root_logger.getEffectiveLevel()
    old_id = getattr(local_context, 'session_id', None)
    # Keep using current, or create one if none already set
    local_context.session_id = old_id or uuid.uuid4()
    old_output = getattr(local_context, 'output', None)
    old_loglevel = getattr(local_context, 'loglevel', None)
    streamhandler = logging.StreamHandler(stream)
    streamhandler.setFormatter(FlexGetFormatter())
    streamhandler.addFilter(SessionFilter(local_context.session_id))
    if loglevel is not None:
        loglevel = get_level_no(loglevel)
        streamhandler.setLevel(loglevel)
        # If requested loglevel is lower than the root logger is filtering for, we need to turn it down.
        # All existing handlers should have their desired level set and not be affected.
        if not root_logger.isEnabledFor(loglevel):
            root_logger.setLevel(loglevel)
    local_context.output = stream
    local_context.loglevel = loglevel
    root_logger.addHandler(streamhandler)
    try:
        yield
    finally:
        root_logger.removeHandler(streamhandler)
        root_logger.setLevel(old_level)
        local_context.session_id = old_id
        local_context.output = old_output
        local_context.loglevel = old_loglevel

def get_capture_stream():
    """If output is currently being redirected to a stream, returns that stream."""
    return getattr(local_context, 'output', None)

def get_capture_loglevel():
    """If output is currently being redirected to a stream, returns declared loglevel for that stream."""
    return getattr(local_context, 'loglevel', None)

class RollingBuffer(collections.deque):
    """File-like that keeps a certain number of lines of text in memory."""

    def write(self, line):
        self.append(line)

class FlexGetLogger(logging.Logger):
    """Custom logger that adds trace and verbose logging methods, and contextual information to log records."""

    def makeRecord(self, name, level, fn, lno, msg, args, exc_info, func, extra, *exargs):
        extra = extra or {}
        extra.update(
            task=getattr(local_context, 'task', ''),
            session_id=getattr(local_context, 'session_id', ''))
        # Replace newlines in log messages with \n
        if isinstance(msg, str):
            msg = msg.replace('\n', '\\n')

        return logging.Logger.makeRecord(self, name, level, fn, lno, msg, args, exc_info, func, extra, *exargs)

    def trace(self, msg, *args, **kwargs):
        """Log at TRACE level (more detailed than DEBUG)."""
        self.log(TRACE, msg, *args, **kwargs)

    def verbose(self, msg, *args, **kwargs):
        """Log at VERBOSE level (displayed when FlexGet is run interactively.)"""
        self.log(VERBOSE, msg, *args, **kwargs)

class FlexGetFormatter(logging.Formatter):
    """Custom formatter that can handle both regular log records and those created by FlexGetLogger"""
    flexget_fmt = '%(asctime)-15s %(levelname)-8s %(name)-13s %(task)-15s %(message)s'

    def __init__(self):
        logging.Formatter.__init__(self, self.flexget_fmt, '%Y-%m-%d %H:%M')

    def format(self, record):
        if not hasattr(record, 'task'):
            record.task = ''
        return logging.Formatter.format(self, record)

_logging_configured = False
_buff_handler = None
_logging_started = False
# Stores the last 50 debug messages
debug_buffer = RollingBuffer(maxlen=50)

def initialize(unit_test=False):
    """Prepare logging.
    """
    global _logging_configured, _logging_started, _buff_handler

    if _logging_configured:
        return

    if 'dev' in __version__:
        warnings.filterwarnings('always', category=DeprecationWarning, module='flexget.*')
    warnings.simplefilter('once', append=True)
    logging.addLevelName(TRACE, 'TRACE')
    logging.addLevelName(VERBOSE, 'VERBOSE')
    _logging_configured = True

    # with unit test we want pytest to add the handlers
    if unit_test:
        _logging_started = True
        return

    # Store any log messages in a buffer until we `start` function is run
    logger = logging.getLogger()
    _buff_handler = logging.handlers.BufferingHandler(1000 * 1000)
    logger.addHandler(_buff_handler)
    logger.setLevel(logging.NOTSET)

    # Add a handler that sores the last 50 debug lines to `debug_buffer` for use in crash reports
    crash_handler = logging.StreamHandler(debug_buffer)
    crash_handler.setLevel(logging.DEBUG)
    crash_handler.setFormatter(FlexGetFormatter())
    logger.addHandler(crash_handler)

def start(filename=None, level=logging.INFO, to_console=True, to_file=True):
    """After initialization, start file logging.
    """
    global _logging_started

    assert _logging_configured
    if _logging_started:
        return

    # root logger
    logger = logging.getLogger()
    level = get_level_no(level)
    logger.setLevel(level)

    formatter = FlexGetFormatter()
    if to_file:
        file_handler = logging.handlers.RotatingFileHandler(filename, maxBytes=1000 * 1024, backupCount=9)
        file_handler.setFormatter(formatter)
        file_handler.setLevel(level)
        logger.addHandler(file_handler)

    # without --cron we log to console
    if to_console:
        console_handler = logging.StreamHandler(sys.stdout)
        console_handler.setFormatter(formatter)
        console_handler.setLevel(level)
        logger.addHandler(console_handler)

    # flush what we have stored from the plugin initialization
    logger.removeHandler(_buff_handler)
    if _buff_handler:
        for record in _buff_handler.buffer:
            if logger.isEnabledFor(record.levelno):
                logger.handle(record)
        _buff_handler.flush()
    _logging_started = True

# Set our custom logger class as default
logging.setLoggerClass(FlexGetLogger)
<|endoftext|>


<commit_before># -*- coding: utf-8 -*-
# vim: tabstop=4 shiftwidth=4 softtabstop=4
#
# Copyright (C) 2014-2016 GEM Foundation
#
# OpenQuake is free software: you can redistribute it and/or modify it
# under the terms of the GNU Affero General Public License as published
# by the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# OpenQuake is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with OpenQuake. If not, see <http://www.gnu.org/licenses/>.
import collections
import numpy

from openquake.hazardlib.calc import filters
from openquake.hazardlib.calc.gmf import GmfComputer
from openquake.commonlib import readinput, source
from openquake.commonlib.export.hazard import gmv_dt
from openquake.calculators import base

@base.calculators.add('scenario')
class ScenarioCalculator(base.HazardCalculator):
    """
    Scenario hazard calculator
    """
    is_stochastic = True

    def pre_execute(self):
        """
        Read the site collection and initialize GmfComputer and seeds
        """
        super(ScenarioCalculator, self).pre_execute()
        oq = self.oqparam
        trunc_level = oq.truncation_level
        correl_model = oq.get_correl_model()
        self.datastore['rupture'] = rupture = readinput.get_rupture(oq)
        self.gsims = readinput.get_gsims(oq)
        maxdist = oq.maximum_distance['default']
        with self.monitor('filtering sites', autoflush=True):
            self.sitecol = filters.filter_sites_by_distance_to_rupture(
                rupture, maxdist, self.sitecol)
        if self.sitecol is None:
            raise RuntimeError(
                'All sites were filtered out! maximum_distance=%s km' %
                maxdist)
        self.computer = GmfComputer(
            rupture, self.sitecol, oq.imtls, self.gsims,
            trunc_level, correl_model)
        gsim_lt = readinput.get_gsim_lt(oq)
        cinfo = source.CompositionInfo.fake(gsim_lt)
        self.datastore['csm_info'] = cinfo
        self.rlzs_assoc = cinfo.get_rlzs_assoc()

    def init(self):
        pass

    def execute(self):
        """
        Compute the GMFs and return a dictionary rlzi -> array gmv_dt
        """
        res = collections.defaultdict(list)
        sids = self.sitecol.sids
        with self.monitor('computing gmfs', autoflush=True):
            n = self.oqparam.number_of_ground_motion_fields
            for i, gsim in enumerate(self.gsims):
                gmfa = self.computer.compute(gsim, n, self.oqparam.random_seed)
                for (imti, sid, eid), gmv in numpy.ndenumerate(gmfa):
                    res[i].append((sids[sid], eid, imti, gmv))
            return {rlzi: numpy.array(res[rlzi], gmv_dt) for rlzi in res}

    def post_execute(self, gmfa_by_rlzi):
        """
        :param gmfa: a dictionary rlzi -> gmfa
        """
        with self.monitor('saving gmfs', autoflush=True):
            for rlzi, gsim in enumerate(self.gsims):
                rlzstr = 'gmf_data/%04d' % rlzi
                self.datastore[rlzstr] = gmfa_by_rlzi[rlzi]
                self.datastore.set_attrs(rlzstr, gsim=str(gsim))
            self.datastore.set_nbytes('gmf_data')
<commit_msg>Serialize properly the rupture in the scenario calculator<commit_after># -*- coding: utf-8 -*-
# vim: tabstop=4 shiftwidth=4 softtabstop=4
#
# Copyright (C) 2014-2016 GEM Foundation
#
# OpenQuake is free software: you can redistribute it and/or modify it
# under the terms of the GNU Affero General Public License as published
# by the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# OpenQuake is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with OpenQuake. If not, see <http://www.gnu.org/licenses/>.
import collections
import numpy

from openquake.hazardlib.calc import filters
from openquake.hazardlib.calc.gmf import GmfComputer
from openquake.commonlib import readinput, source, calc
from openquake.commonlib.export.hazard import gmv_dt
from openquake.calculators import base

@base.calculators.add('scenario')
class ScenarioCalculator(base.HazardCalculator):
    """
    Scenario hazard calculator
    """
    is_stochastic = True

    def pre_execute(self):
        """
        Read the site collection and initialize GmfComputer and seeds
        """
        super(ScenarioCalculator, self).pre_execute()
        oq = self.oqparam
        trunc_level = oq.truncation_level
        correl_model = oq.get_correl_model()
        rupture = readinput.get_rupture(oq)
        self.gsims = readinput.get_gsims(oq)
        maxdist = oq.maximum_distance['default']
        with self.monitor('filtering sites', autoflush=True):
            self.sitecol = filters.filter_sites_by_distance_to_rupture(
                rupture, maxdist, self.sitecol)
        if self.sitecol is None:
            raise RuntimeError(
                'All sites were filtered out! maximum_distance=%s km' %
                maxdist)
        # eid, ses, occ, sample
        events = numpy.array(
            [(eid, 1, 1, 0)
             for eid in range(oq.number_of_ground_motion_fields)],
            calc.event_dt)
        self.datastore['rupture'] = calc.EBRupture(
            rupture, self.sitecol.sids, events, 'scenario', 0, 0)
        self.computer = GmfComputer(
            rupture, self.sitecol, oq.imtls, self.gsims,
            trunc_level, correl_model)
        gsim_lt = readinput.get_gsim_lt(oq)
        cinfo = source.CompositionInfo.fake(gsim_lt)
        self.datastore['csm_info'] = cinfo
        self.rlzs_assoc = cinfo.get_rlzs_assoc()

    def init(self):
        pass

    def execute(self):
        """
        Compute the GMFs and return a dictionary rlzi -> array gmv_dt
        """
        res = collections.defaultdict(list)
        sids = self.sitecol.sids
        with self.monitor('computing gmfs', autoflush=True):
            n = self.oqparam.number_of_ground_motion_fields
            for i, gsim in enumerate(self.gsims):
                gmfa = self.computer.compute(gsim, n, self.oqparam.random_seed)
                for (imti, sid, eid), gmv in numpy.ndenumerate(gmfa):
                    res[i].append((sids[sid], eid, imti, gmv))
            return {rlzi: numpy.array(res[rlzi], gmv_dt) for rlzi in res}

    def post_execute(self, gmfa_by_rlzi):
        """
        :param gmfa: a dictionary rlzi -> gmfa
        """
        with self.monitor('saving gmfs', autoflush=True):
            for rlzi, gsim in enumerate(self.gsims):
                rlzstr = 'gmf_data/%04d' % rlzi
                self.datastore[rlzstr] = gmfa_by_rlzi[rlzi]
                self.datastore.set_attrs(rlzstr, gsim=str(gsim))
            self.datastore.set_nbytes('gmf_data')
<|endoftext|>


<commit_before>import logging
import json
import random
import re
import requests

logger = logging.getLogger(__name__)

def findIndexOfSequence(data, sequence, startIndex=0):
    index = startIndex
    for token in sequence:
        index = data.find(token, index)
        if index == -1:
            return -1
    return index + len(sequence[-1])

def emojiFilter(input):
	ret = input.replace("{", ":_")
	ret = ret.replace("}", "_:")
	lastpos = None
	while ret.rfind(":_", 0, lastpos) != -1:
		lastpos = ret.rfind(":_", 0, lastpos)
		start = lastpos + 2
		end = ret.rfind("_:")
		content = ret[start:end]
                content = content.lower() #TODO: this lowers too much!
		content = content.replace("/", "")
		ret = ret[:start] + content + ret[end:]
	return ret

def getCardValue(cardName, setCode):
    url = "http://www.mtggoldfish.com/widgets/autocard/%s [%s]" % (cardName, setCode)
    headers = {
        'Pragma': 'no-cache',
        'Accept-Encoding': 'gzip, deflate, sdch',
        'Accept-Language': 'en-US,en;q=0.8,de;q=0.6,sv;q=0.4',
        'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/48.0.2564.109 Safari/537.36',
        'Accept': 'text/javascript, application/javascript, application/ecmascript, application/x-ecmascript, */*; q=0.01',
        'Referer': 'http://www.mtggoldfish.com/widgets/autocard/%s' % cardName,
        'X-Requested-With': 'XMLHttpRequest',
        'Connection': 'keep-alive',
        'Cache-Control': 'no-cache'
    }
    response = requests.get(url, headers=headers)
    index = findIndexOfSequence(response.content, ["tcgplayer", "btn-shop-price", "$"])
    endIndex = response.content.find("\\n", index)
    try:
        value = float(response.content[index + 2:endIndex].replace(",", ""))
    except ValueError:
        value = 0

    return value

def getCard(name):
    queryUrl = "http://api.deckbrew.com/mtg/cards?name=%s" % name
    r = requests.get(queryUrl)
    cards = r.json()

    if len(cards) < 1:
        return None

    card = cards[0]
    bestMatch = None
    for cardIter in cards:
        pos = cardIter["name"].lower().find(name)
        if bestMatch is None or (pos != -1 and pos < bestMatch):
            bestMatch = pos
            card = cardIter

    mostRecent = card["editions"][0]
    card["value"] = getCardValue(card["name"], mostRecent["set_id"])
    return card

def getCardset(setCode):
    # Returns information about the cardset's name, border and type
    queryUrl = "http://api.deckbrew.com/mtg/sets/" % setCode.upper()
    r = requests.get(queryUrl)
    cardSet = r.json()

    if len(cardSet) < 1:
        return None
    else:
        return cardSet

def getOracle(card):
    typeline = ""
    if "supertypes" in card:
        for supertype in card["supertypes"]:
            typeline += supertype.capitalize() + " "
    if "types" in card:
        for cardtype in card["types"]:
            typeline += cardtype.capitalize() + " "
        if "subtypes" in card:
            typeline += "- "
    if "subtypes" in card:
        for subtype in card["subtypes"]:
            typeline += subtype.capitalize() + " "
    txt = "*%s %s*\n%s\n%s" % (card["name"], card["cost"], typeline, card["text"].replace(u'\u2212', '-'))
    if "power" in card and "toughness" in card:
        txt += "\n*`%s/%s`*" % (card["power"], card["toughness"])
    if "loyalty" in card:
        txt += "\n*`%s`*" % card["loyalty"]
    return emojiFilter(txt)

def getSeasons(dciNumber):
    # Returns to current and last season for that DCI number
    url = "http://www.wizards.com/Magic/PlaneswalkerPoints/JavaScript/GetPointsHistoryModal"
    headers = {
        'Pragma': 'no-cache',
        'Origin': 'http://www.wizards.com',
        'Accept-Encoding': 'gzip, deflate',
        'Accept-Language': 'en-US,en;q=0.8,de;q=0.6,sv;q=0.4',
        'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/48.0.2564.109 Safari/537.36',
        'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
        'Accept': '*/*',
        'Cache-Control': 'no-cache',
        'X-Requested-With': 'XMLHttpRequest',
        'Cookie': 'f5_cspm=1234; BIGipServerWWWPWPPOOL01=353569034.20480.0000; __utmt=1; BIGipServerWWWPool1=3792701706.20480.0000; PlaneswalkerPointsSettings=0=0&lastviewed=9212399887; __utma=75931667.1475261136.1456488297.1456488297.1456488297.1; __utmb=75931667.5.10.1456488297; __utmc=75931667; __utmz=75931667.1456488297.1.1.utmcsr=(direct)|utmccn=(direct)|utmcmd=(none)',
        'Connection': 'keep-alive',
        'Referer': 'http://www.wizards.com/Magic/PlaneswalkerPoints/%s' % dciNumber
    }
    data = {"Parameters": {"DCINumber": dciNumber, "SelectedType": "Yearly"}}
    response = requests.post(url, headers=headers, data=json.dumps(data))

    if response.status_code is 200:
        seasons = []

        responseData = json.loads(response.content)
        markup = responseData["ModalContent"]
        searchPosition = markup.find("SeasonRange")

        while searchPosition != -1:
            pointsvalue = "PointsValue\">"
            searchPosition = markup.find(pointsvalue, searchPosition)
            searchPosition += len(pointsvalue)
            endPosition = markup.find("
", searchPosition)
            if endPosition != -1:
                value = markup[searchPosition:endPosition]
                seasons.append(int(value))
            searchPosition = markup.find("SeasonRange", searchPosition)

        return {"currentSeason": seasons[0], "lastSeason": seasons[1]}
    else:
        return None

class Messenger(object):
    def __init__(self, slack_clients):
        self.clients = slack_clients

    def send_message(self, channel_id, msg):
        # in the case of Group and Private channels, RTM channel payload is a complex dictionary
        if isinstance(channel_id, dict):
            channel_id = channel_id['id']
        logger.debug('Sending msg: {} to channel: {}'.format(msg, channel_id))
        channel = self.clients.rtm.server.channels.find(channel_id)
        channel.send_message("{}".format(msg.encode('ascii', 'ignore')))

    def write_help_message(self, channel_id):
        bot_uid = self.clients.bot_user_id()
        txt = '{}\n{}\n{}\n{}\n{}\n{}\n{}\n{}'.format(
            "I'm your friendly Slack bot written in Python.  I'll *_respond_* to the following commands:",
            "> `hi <@" + bot_uid + ">` - I'll respond with a randomized greeting mentioning your username. :wave:",
            "> `<@" + bot_uid + "> joke` - I'll tell you one of my finest jokes, with a typing pause for effect. :laughing:",
            "> `<@" + bot_uid + "> help` - I'll reply with this helpful text. :information_source:",
            "> `!card cardname` - I'll post a picture of the named card. :frame_with_picture:",
            "> `!price cardname` - I'll respond with the card's current market price. :moneybag:",
            "> `!oracle cardname` - I'll respond with the card's oracle text. :book:",
            "> `!pwp dcinumber` - I'll tell you a player's PWP score and bye eligibility. :trophy:")
        self.send_message(channel_id, txt)

    def write_greeting(self, channel_id, user_id):
        greetings = ['Hi', 'Hello', 'Nice to meet you', 'Howdy', 'Salutations']
        txt = '{}, <@{}>!'.format(random.choice(greetings), user_id)
        self.send_message(channel_id, txt)

    def write_prompt(self, channel_id):
        bot_uid = self.clients.bot_user_id()
        txt = "I'm sorry, I didn't quite understand... Can I help you? (e.g. `<@" + bot_uid + "> help`)"
        self.send_message(channel_id, txt)

    def write_joke(self, channel_id):
        with open('/src/bot/jokes.json', 'r') as infile:
            joke = random.choice(json.load(infile))
        self.send_message(channel_id, joke["setup"])
        self.clients.send_user_typing_pause(channel_id)
        self.send_message(channel_id, joke["punchline"])

    def write_error(self, channel_id, err_msg):
        txt = ":face_with_head_bandage: my maker didn't handle this error very well:\n>```{}```".format(err_msg)
        self.send_message(channel_id, txt)

    def write_card(self, channel_id, searchTerm):
        card = getCard(searchTerm)

        if card:
            mostRecentPrinting = card["editions"][0]
            txt = ""
            attachment = {
                "title": card["name"].replace("\"", "\\\""),
                "image_url": mostRecentPrinting["image_url"],
                "footer": "%s (%s)" % (mostRecentPrinting["set"], mostRecentPrinting["set_id"]),
            }
            self.clients.web.chat.post_message(channel_id, txt, attachments=[attachment], as_user='true')
        else:
            txt = 'Card not found.'
            self.send_message(channel_id, txt)

    def write_oracle(self, channel_id, searchTerm):
        card = getCard(searchTerm)

        if card:
            txt = getOracle(card)
            mostRecentPrinting = card["editions"][0]
            number = mostRecentPrinting["number"]
            if re.search('a|b', number):
                if not getCardset(mostRecentPrinting["set_id"])["border"] is "silver":
                #TODO: traverse to other side / part of card, and add it to txt
                    if 'a' in number:
                        txt += "\n\nSee also card #%s." % number
                    else:
                        txt += "\n\nSee also card #%s." % number
        else:
            txt = 'Card not found.'
        self.send_message(channel_id, txt)

    def write_price(self, channel_id, searchTerm):
        card = getCard(searchTerm)

        if card:
            mostRecentPrinting = card["editions"][0]
            txt = "Unable to find price information for %s" % card["name"]
            if card["value"] > 0:
                txt = ("Current market price for most recent printing of %s (%s) - $%.1f" %
                       (card["name"], mostRecentPrinting["set"], card["value"]))
        else:
            txt = 'Card not found.'
        self.send_message(channel_id, txt)

    def write_pwp(self, channel_id, dciNumber):
        planeswalker = getSeasons(dciNumber)

        if planeswalker:
            txt = ("DCI# %s has %s points in the current season, and %s points last season.\nCurrently "
                   % (dciNumber, planeswalker["currentSeason"], planeswalker["lastSeason"]))

            if planeswalker["currentSeason"] >= 2250 or planeswalker["lastSeason"] >= 2250:
                txt += "eligible for 2 GP byes."
            elif planeswalker["currentSeason"] >= 1300 or planeswalker["lastSeason"] >= 1300:
                txt += "eligible for 1 GP bye."
            else:
                txt += "not eligible for GP byes."
        else:
            txt = "DCI# %s not found." % dciNumber
        self.send_message(channel_id, txt)
<commit_msg>Made getCard() match names exactly<commit_after>import logging
import json
import random
import re
import requests

logger = logging.getLogger(__name__)

def findIndexOfSequence(data, sequence, startIndex=0):
    index = startIndex
    for token in sequence:
        index = data.find(token, index)
        if index == -1:
            return -1
    return index + len(sequence[-1])

def emojiFilter(input):
    ret = input.replace("{", ":_")
    ret = ret.replace("}", "_:")
    lastpos = None
    while ret.rfind(":_", 0, lastpos) != -1:
        lastpos = ret.rfind(":_", 0, lastpos)
        start = lastpos + 2
        end = ret.rfind("_:")
        content = ret[start:end]
        content = content.lower() #TODO: this lowers too much!
        content = content.replace("/", "")
        ret = ret[:start] + content + ret[end:]
    return ret

def getCardValue(cardName, setCode):
    url = "http://www.mtggoldfish.com/widgets/autocard/%s [%s]" % (cardName, setCode)
    headers = {
        'Pragma': 'no-cache',
        'Accept-Encoding': 'gzip, deflate, sdch',
        'Accept-Language': 'en-US,en;q=0.8,de;q=0.6,sv;q=0.4',
        'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/48.0.2564.109 Safari/537.36',
        'Accept': 'text/javascript, application/javascript, application/ecmascript, application/x-ecmascript, */*; q=0.01',
        'Referer': 'http://www.mtggoldfish.com/widgets/autocard/%s' % cardName,
        'X-Requested-With': 'XMLHttpRequest',
        'Connection': 'keep-alive',
        'Cache-Control': 'no-cache'
    }
    response = requests.get(url, headers=headers)
    index = findIndexOfSequence(response.content, ["tcgplayer", "btn-shop-price", "$"])
    endIndex = response.content.find("\\n", index)
    try:
        value = float(response.content[index + 2:endIndex].replace(",", ""))
    except ValueError:
        value = 0

    return value

def getCard(name):
    queryUrl = "http://api.deckbrew.com/mtg/cards?name=%s" % name
    r = requests.get(queryUrl)
    cards = r.json()

    if len(cards) < 1:
        return None

    card = None
    for element in cards:
        if element["name"].lower() == name.lower():
            card = element

    if card:
        mostRecent = card["editions"][0]
        card["value"] = getCardValue(card["name"], mostRecent["set_id"])
    return card

def getCardset(setCode):
    # Returns information about the cardset's name, border and type
    queryUrl = "http://api.deckbrew.com/mtg/sets/" % setCode.upper()
    r = requests.get(queryUrl)
    cardSet = r.json()

    if len(cardSet) < 1:
        return None
    else:
        return cardSet

def getOracle(card):
    typeline = ""
    if "supertypes" in card:
        for supertype in card["supertypes"]:
            typeline += supertype.capitalize() + " "
    if "types" in card:
        for cardtype in card["types"]:
            typeline += cardtype.capitalize() + " "
        if "subtypes" in card:
            typeline += "- "
    if "subtypes" in card:
        for subtype in card["subtypes"]:
            typeline += subtype.capitalize() + " "
    txt = "*%s %s*\n%s\n%s" % (card["name"], card["cost"], typeline, card["text"].replace(u'\u2212', '-'))
    if "power" in card and "toughness" in card:
        txt += "\n*`%s/%s`*" % (card["power"], card["toughness"])
    if "loyalty" in card:
        txt += "\n*`%s`*" % card["loyalty"]
    return emojiFilter(txt)

def getSeasons(dciNumber):
    # Returns to current and last season for that DCI number
    url = "http://www.wizards.com/Magic/PlaneswalkerPoints/JavaScript/GetPointsHistoryModal"
    headers = {
        'Pragma': 'no-cache',
        'Origin': 'http://www.wizards.com',
        'Accept-Encoding': 'gzip, deflate',
        'Accept-Language': 'en-US,en;q=0.8,de;q=0.6,sv;q=0.4',
        'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/48.0.2564.109 Safari/537.36',
        'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
        'Accept': '*/*',
        'Cache-Control': 'no-cache',
        'X-Requested-With': 'XMLHttpRequest',
        'Cookie': 'f5_cspm=1234; BIGipServerWWWPWPPOOL01=353569034.20480.0000; __utmt=1; BIGipServerWWWPool1=3792701706.20480.0000; PlaneswalkerPointsSettings=0=0&lastviewed=9212399887; __utma=75931667.1475261136.1456488297.1456488297.1456488297.1; __utmb=75931667.5.10.1456488297; __utmc=75931667; __utmz=75931667.1456488297.1.1.utmcsr=(direct)|utmccn=(direct)|utmcmd=(none)',
        'Connection': 'keep-alive',
        'Referer': 'http://www.wizards.com/Magic/PlaneswalkerPoints/%s' % dciNumber
    }
    data = {"Parameters": {"DCINumber": dciNumber, "SelectedType": "Yearly"}}
    response = requests.post(url, headers=headers, data=json.dumps(data))

    if response.status_code is 200:
        seasons = []

        responseData = json.loads(response.content)
        markup = responseData["ModalContent"]
        searchPosition = markup.find("SeasonRange")

        while searchPosition != -1:
            pointsvalue = "PointsValue\">"
            searchPosition = markup.find(pointsvalue, searchPosition)
            searchPosition += len(pointsvalue)
            endPosition = markup.find("
", searchPosition)
            if endPosition != -1:
                value = markup[searchPosition:endPosition]
                seasons.append(int(value))
            searchPosition = markup.find("SeasonRange", searchPosition)

        return {"currentSeason": seasons[0], "lastSeason": seasons[1]}
    else:
        return None

class Messenger(object):
    def __init__(self, slack_clients):
        self.clients = slack_clients

    def send_message(self, channel_id, msg):
        # in the case of Group and Private channels, RTM channel payload is a complex dictionary
        if isinstance(channel_id, dict):
            channel_id = channel_id['id']
        logger.debug('Sending msg: {} to channel: {}'.format(msg, channel_id))
        channel = self.clients.rtm.server.channels.find(channel_id)
        channel.send_message("{}".format(msg.encode('ascii', 'ignore')))

    def write_help_message(self, channel_id):
        bot_uid = self.clients.bot_user_id()
        txt = '{}\n{}\n{}\n{}\n{}\n{}\n{}\n{}'.format(
            "I'm your friendly Slack bot written in Python.  I'll *_respond_* to the following commands:",
            "> `hi <@" + bot_uid + ">` - I'll respond with a randomized greeting mentioning your username. :wave:",
            "> `<@" + bot_uid + "> joke` - I'll tell you one of my finest jokes, with a typing pause for effect. :laughing:",
            "> `<@" + bot_uid + "> help` - I'll reply with this helpful text. :information_source:",
            "> `!card cardname` - I'll post a picture of the named card. :frame_with_picture:",
            "> `!price cardname` - I'll respond with the card's current market price. :moneybag:",
            "> `!oracle cardname` - I'll respond with the card's oracle text. :book:",
            "> `!pwp dcinumber` - I'll tell you a player's PWP score and bye eligibility. :trophy:")
        self.send_message(channel_id, txt)

    def write_greeting(self, channel_id, user_id):
        greetings = ['Hi', 'Hello', 'Nice to meet you', 'Howdy', 'Salutations']
        txt = '{}, <@{}>!'.format(random.choice(greetings), user_id)
        self.send_message(channel_id, txt)

    def write_prompt(self, channel_id):
        bot_uid = self.clients.bot_user_id()
        txt = "I'm sorry, I didn't quite understand... Can I help you? (e.g. `<@" + bot_uid + "> help`)"
        self.send_message(channel_id, txt)

    def write_joke(self, channel_id):
        with open('/src/bot/jokes.json', 'r') as infile:
            joke = random.choice(json.load(infile))
        self.send_message(channel_id, joke["setup"])
        self.clients.send_user_typing_pause(channel_id)
        self.send_message(channel_id, joke["punchline"])

    def write_error(self, channel_id, err_msg):
        txt = ":face_with_head_bandage: my maker didn't handle this error very well:\n>```{}```".format(err_msg)
        self.send_message(channel_id, txt)

    def write_card(self, channel_id, searchTerm):
        card = getCard(searchTerm)

        if card:
            mostRecentPrinting = card["editions"][0]
            txt = ""
            attachment = {
                "title": card["name"].replace("\"", "\\\""),
                "image_url": mostRecentPrinting["image_url"],
                "footer": "%s (%s)" % (mostRecentPrinting["set"], mostRecentPrinting["set_id"]),
            }
            self.clients.web.chat.post_message(channel_id, txt, attachments=[attachment], as_user='true')
        else:
            txt = 'Card not found.'
            self.send_message(channel_id, txt)

    def write_oracle(self, channel_id, searchTerm):
        card = getCard(searchTerm)

        if card:
            txt = getOracle(card)
            mostRecentPrinting = card["editions"][0]
            number = mostRecentPrinting["number"]
            if re.search('a|b', number):
                if not getCardset(mostRecentPrinting["set_id"])["border"] == "silver":
                #TODO: traverse to other side / part of card, and add it to txt
                    if 'a' in number:
                        txt += "\n\nSee also card #%s." % number
                    else:
                        txt += "\n\nSee also card #%s." % number
        else:
            txt = 'Card not found.'
        self.send_message(channel_id, txt)

    def write_price(self, channel_id, searchTerm):
        card = getCard(searchTerm)

        if card:
            mostRecentPrinting = card["editions"][0]
            txt = "Unable to find price information for %s" % card["name"]
            if card["value"] > 0:
                txt = ("Current market price for most recent printing of %s (%s) - $%.1f" %
                       (card["name"], mostRecentPrinting["set"], card["value"]))
        else:
            txt = 'Card not found.'
        self.send_message(channel_id, txt)

    def write_pwp(self, channel_id, dciNumber):
        planeswalker = getSeasons(dciNumber)

        if planeswalker:
            txt = ("DCI# %s has %s points in the current season, and %s points last season.\nCurrently "
                   % (dciNumber, planeswalker["currentSeason"], planeswalker["lastSeason"]))

            if planeswalker["currentSeason"] >= 2250 or planeswalker["lastSeason"] >= 2250:
                txt += "eligible for 2 GP byes."
            elif planeswalker["currentSeason"] >= 1300 or planeswalker["lastSeason"] >= 1300:
                txt += "eligible for 1 GP bye."
            else:
                txt += "not eligible for GP byes."
        else:
            txt = "DCI# %s not found." % dciNumber
        self.send_message(channel_id, txt)
<|endoftext|>


<commit_before>"""
Flexx is a pure Python toolkit for creating graphical user interfaces
(GUI's), that uses web technology for its rendering. Apps are written
purely in Python; Flexx' transpiler generates the necessary JavaScript
on the fly.

You can use Flexx to create (cross platform) desktop applications, web
applications, and (if designed well) export an app to a standalone HTML
document. It also works in the Jupyter notebook.

The docs are on `Readthedocs <http://flexx.readthedocs.io>`_,
the code is on `Github <http://github.com/zoofio/flexx>`_,
and there is a `demo server <http://flexx1.zoof.io>`_.
Flexx is currently in alpha status; any part of the public API may
change without notice. Feedback is welcome.

----

Flexx has a modular design, consisting of a few subpackages, which can
also be used by themselves:

* flexx.ui - the widgets
* flexx.app - the event loop and server
* flexx.event - properties and events
* flexx.pyscript - Python to JavaScript transpiler
* flexx.webruntime - to launch a runtime
* flexx.util - utilities

For more information, see http://flexx.readthedocs.io.
"""

# NOTES ON DOCS:
# There are 2 places that define the short summary of Flexx: the
# __init__.py and the README.md. Their summaries should be kept equal.
# The index.rst for the docs uses the summary from __init__.py (the
# part after the "----" is stripped. The long-description for Pypi is
# obtained by converting README.md to RST.

__version__ = '0.3.1'

# Assert compatibility and redirect to legacy version on Python 2.7
import sys
ok = True
if sys.version_info[0] == 2:  # pragma: no cover
    if sys.version_info < (2, 7):
        raise RuntimeError('Flexx needs at least Python 2.7')
    if type(b'') == type(''):  # noqa - will be str and unicode after conversion
        sys.modules[__name__] = __import__(__name__ + '_legacy')
        ok = False

# Import config object
if ok:
    from ._config import config  # noqa
    from .util.logging import set_log_level  # noqa
    set_log_level(config.log_level)

del sys, ok
<commit_msg>bumb version to 0.4<commit_after>"""
Flexx is a pure Python toolkit for creating graphical user interfaces
(GUI's), that uses web technology for its rendering. Apps are written
purely in Python; Flexx' transpiler generates the necessary JavaScript
on the fly.

You can use Flexx to create (cross platform) desktop applications, web
applications, and (if designed well) export an app to a standalone HTML
document. It also works in the Jupyter notebook.

The docs are on `Readthedocs <http://flexx.readthedocs.io>`_,
the code is on `Github <http://github.com/zoofio/flexx>`_,
and there is a `demo server <http://flexx1.zoof.io>`_.
Flexx is currently in alpha status; any part of the public API may
change without notice. Feedback is welcome.

----

Flexx has a modular design, consisting of a few subpackages, which can
also be used by themselves:

* flexx.ui - the widgets
* flexx.app - the event loop and server
* flexx.event - properties and events
* flexx.pyscript - Python to JavaScript transpiler
* flexx.webruntime - to launch a runtime
* flexx.util - utilities

For more information, see http://flexx.readthedocs.io.
"""

# NOTES ON DOCS:
# There are 2 places that define the short summary of Flexx: the
# __init__.py and the README.md. Their summaries should be kept equal.
# The index.rst for the docs uses the summary from __init__.py (the
# part after the "----" is stripped. The long-description for Pypi is
# obtained by converting README.md to RST.

__version__ = '0.4'

# Assert compatibility and redirect to legacy version on Python 2.7
import sys
ok = True
if sys.version_info[0] == 2:  # pragma: no cover
    if sys.version_info < (2, 7):
        raise RuntimeError('Flexx needs at least Python 2.7')
    if type(b'') == type(''):  # noqa - will be str and unicode after conversion
        sys.modules[__name__] = __import__(__name__ + '_legacy')
        ok = False

# Import config object
if ok:
    from ._config import config  # noqa
    from .util.logging import set_log_level  # noqa
    set_log_level(config.log_level)

del sys, ok
<|endoftext|>


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

__all__ = ['entropy_vn', 'entropy_linear', 'entropy_mutual', 'negativity',
           'concurrence', 'entropy_conditional', 'entangling_power',
           'entropy_relative']

from numpy import dot, e, inf, real, sort, sqrt
from numpy.lib.scimath import log, log2
from qutip.qobj import ptrace
from qutip.states import ket2dm
from qutip.tensor import tensor
from qutip.operators import sigmay
from qutip.sparse import sp_eigs
from qutip.partial_transpose import partial_transpose

def entropy_vn(rho, base=e, sparse=False):
    """
    Von-Neumann entropy of density matrix

    Parameters
    ----------
    rho : qobj
        Density matrix.
    base : {e,2}
        Base of logarithm.
    sparse : {False,True}
        Use sparse eigensolver.

    Returns
    -------
    entropy : float
        Von-Neumann entropy of `rho`.

    Examples
    --------
    >>> rho=0.5*fock_dm(2,0)+0.5*fock_dm(2,1)
    >>> entropy_vn(rho,2)
    1.0

    """
    if rho.type == 'ket' or rho.type == 'bra':
        rho = ket2dm(rho)
    vals = sp_eigs(rho.data, rho.isherm, vecs=False, sparse=sparse)
    nzvals = vals[vals != 0]
    if base == 2:
        logvals = log2(nzvals)
    elif base == e:
        logvals = log(nzvals)
    else:
        raise ValueError("Base must be 2 or e.")
    return float(real(-sum(nzvals * logvals)))

def entropy_linear(rho):
    """
    Linear entropy of a density matrix.

    Parameters
    ----------
    rho : qobj
        sensity matrix or ket/bra vector.

    Returns
    -------
    entropy : float
        Linear entropy of rho.

    Examples
    --------
    >>> rho=0.5*fock_dm(2,0)+0.5*fock_dm(2,1)
    >>> entropy_linear(rho)
    0.5

    """
    if rho.type == 'ket' or rho.type == 'bra':
        rho = ket2dm(rho)
    return float(real(1.0 - (rho ** 2).tr()))

def concurrence(rho):
    """
    Calculate the concurrence entanglement measure for a two-qubit state.

    Parameters
    ----------
    state : qobj
        Ket, bra, or density matrix for a two-qubit state.

    Returns
    -------
    concur : float
        Concurrence

    References
    ----------

    .. [1] http://en.wikipedia.org/wiki/Concurrence_(quantum_computing)

    """
    if rho.isket and rho.dims != [[2, 2], [1, 1]]:
        raise Exception("Ket must be tensor product of two qubits.")

    elif rho.isbra and rho.dims != [[1, 1], [2, 2]]:
        raise Exception("Bra must be tensor product of two qubits.")

    elif rho.isoper and rho.dims != [[2, 2], [2, 2]]:
        raise Exception("Density matrix must be tensor product of two qubits.")

    if rho.isket or rho.isbra:
        rho = ket2dm(rho)

    sysy = tensor(sigmay(), sigmay())

    rho_tilde = (rho * sysy) * (rho.conj() * sysy)

    evals = rho_tilde.eigenenergies()

    # abs to avoid problems with sqrt for very small negative numbers
    evals = abs(sort(real(evals)))

    lsum = sqrt(evals[3]) - sqrt(evals[2]) - sqrt(evals[1]) - sqrt(evals[0])

    return max(0, lsum)

def negativity(rho, subsys, method='tracenorm', logarithmic=False):
    """
    Compute the negativity for a multipartite quantum system described
    by the density matrix rho. The subsys argument is an index that
    indicates which system to compute the negativity for.

    .. note::

        Experimental.
    """
    mask = [idx == subsys for idx, n in enumerate(rho.dims[0])]
    rho_pt = partial_transpose(rho, mask)

    if method == 'tracenorm':
        N = ((rho_pt.dag() * rho_pt).sqrtm().tr().real - 1)/2.0
    elif method == 'eigenvalues':
        l = rho_pt.eigenenergies()
        N = ((abs(l)-l)/2).sum()
    else:
        raise ValueError("Unknown method %s" % method)

    if logarithmic:
        return log2(2 * N + 1)
    else:
        return N

def entropy_mutual(rho, selA, selB, base=e, sparse=False):
    """
    Calculates the mutual information S(A:B) between selection
    components of a system density matrix.

    Parameters
    ----------
    rho : qobj
        Density matrix for composite quantum systems
    selA : int/list
        `int` or `list` of first selected density matrix components.
    selB : int/list
        `int` or `list` of second selected density matrix components.
    base : {e,2}
        Base of logarithm.
    sparse : {False,True}
        Use sparse eigensolver.

    Returns
    -------
    ent_mut : float
       Mutual information between selected components.

    """
    if isinstance(selA, int):
        selA = [selA]
    if isinstance(selB, int):
        selB = [selB]
    if rho.type != 'oper':
        raise TypeError("Input must be a density matrix.")
    if (len(selA) + len(selB)) != len(rho.dims[0]):
        raise TypeError("Number of selected components must match " +
                        "total number.")

    rhoA = ptrace(rho, selA)
    rhoB = ptrace(rho, selB)
    out = (entropy_vn(rhoA, base, sparse=sparse) +
           entropy_vn(rhoB, base, sparse=sparse) -
           entropy_vn(rho, base, sparse=sparse))
    return out

def entropy_relative(rho, sigma, base=e, sparse=False):
    """
    Calculates the relative entropy S(rho||sigma) between two density
    matrices.

    Parameters
    ----------
    rho : :class:`qutip.Qobj`
        First density matrix (or ket which will be converted to a density
        matrix).
    sigma : :class:`qutip.Qobj`
        Second density matrix (or ket which will be converted to a density
        matrix).
    base : {e,2}
        Base of logarithm. Defaults to e.
    sparse : bool
        Flag to use sparse solver when determining the eigenvectors
        of the density matrices. Defaults to False.

    Returns
    -------
    rel_ent : float
        Value of relative entropy.

    References
    ----------

    See Nielsen & Chuang, "Quantum Computation and Quantum Information",
    Section 11.3.1, pg. 511 for a detailed explanation of quantum relative
    entropy.
    """
    if rho.isket:
        rho = ket2dm(rho)
    if sigma.isket:
        sigma = ket2dm(sigma)
    if not rho.isoper or not sigma.isoper:
        raise TypeError("Inputs must be density matrices.")
    if rho.dims != sigma.dims:
        raise ValueError("Inputs must have the same shape and dims.")
    if base == 2:
        log_base = log2
    elif base == e:
        log_base = log
    else:
        raise ValueError("Base must be 2 or e.")
    # S(rho || sigma) = sum_i(p_i log p_i) - sum_ij(p_i P_ij log q_i)
    #
    # S is +inf if the kernel of sigma (i.e. svecs[svals == 0]) has non-trivial
    # intersection with the support of rho (i.e. rvecs[rvals != 0]).
    rvals, rvecs = sp_eigs(rho.data, rho.isherm, vecs=True, sparse=sparse)
    svals, svecs = sp_eigs(sigma.data, sigma.isherm, vecs=True, sparse=sparse)
    nzrvals = rvals[rvals != 0]
    # Calculate S
    S = sum(nzrvals * log_base(nzrvals))
    for i in range(len(rvals)):
        for j in range(len(svals)):
            P_ij = (
                dot(rvecs[i], svecs[j].conjugate()) *
                dot(svecs[j], rvecs[i].conjugate())
            )
            if svals[j] == 0 and (rvals[i] * P_ij != 0):
                # kernel of sigma intersects support of rho
                return inf
            if svals[j] != 0:
                S -= rvals[i] * P_ij * log_base(svals[j])
    return real(S)

def entropy_conditional(rho, selB, base=e, sparse=False):
    """
    Calculates the conditional entropy :math:`S(A|B)=S(A,B)-S(B)`
    of a selected density matrix component.

    Parameters
    ----------
    rho : qobj
        Density matrix of composite object
    selB : int/list
        Selected components for density matrix B
    base : {e,2}
        Base of logarithm.
    sparse : {False,True}
        Use sparse eigensolver.

    Returns
    -------
    ent_cond : float
        Value of conditional entropy

    """
    if rho.type != 'oper':
        raise TypeError("Input must be density matrix.")
    if isinstance(selB, int):
        selB = [selB]
    B = ptrace(rho, selB)
    out = (entropy_vn(rho, base, sparse=sparse) -
           entropy_vn(B, base, sparse=sparse))
    return out

def participation_ratio(rho):
    """
    Returns the effective number of states for a density matrix.

    The participation is unity for pure states, and maximally N,
    where N is the Hilbert space dimensionality, for completely
    mixed states.

    Parameters
    ----------
    rho : qobj
        Density matrix

    Returns
    -------
    pr : float
        Effective number of states in the density matrix

    """
    if rho.type == 'ket' or rho.type == 'bra':
        return 1.0
    else:
        return 1.0 / (rho ** 2).tr()

def entangling_power(U):
    """
    Calculate the entangling power of a two-qubit gate U, which
    is zero of nonentangling gates and 1 and 2/9 for maximally
    entangling gates.

    Parameters
    ----------
    U : qobj
        Qobj instance representing a two-qubit gate.

    Returns
    -------
    ep : float
        The entanglement power of U (real number between 0 and 1)

    References:

        Explorations in Quantum Computing, Colin P. Williams (Springer, 2011)
    """

    if not U.isoper:
        raise Exception("U must be an operator.")

    if U.dims != [[2, 2], [2, 2]]:
        raise Exception("U must be a two-qubit gate.")

    from qutip.qip.operations.gates import swap
    a = (tensor(U, U).dag() * swap(N=4, targets=[1, 3]) *
         tensor(U, U) * swap(N=4, targets=[1, 3]))
    b = (tensor(swap() * U, swap() * U).dag() * swap(N=4, targets=[1, 3]) *
         tensor(swap() * U, swap() * U) * swap(N=4, targets=[1, 3]))

    return 5.0/9 - 1.0/36 * (a.tr() + b.tr()).real
<commit_msg>Add tolerance argument for detecting zero eigenvalues.<commit_after># This file is part of QuTiP: Quantum Toolbox in Python.
#
#    Copyright (c) 2011 and later, Paul D. Nation and Robert J. Johansson.
#    All rights reserved.
#
#    Redistribution and use in source and binary forms, with or without
#    modification, are permitted provided that the following conditions are
#    met:
#
#    1. Redistributions of source code must retain the above copyright notice,
#       this list of conditions and the following disclaimer.
#
#    2. Redistributions in binary form must reproduce the above copyright
#       notice, this list of conditions and the following disclaimer in the
#       documentation and/or other materials provided with the distribution.
#
#    3. Neither the name of the QuTiP: Quantum Toolbox in Python nor the names
#       of its contributors may be used to endorse or promote products derived
#       from this software without specific prior written permission.
#
#    THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
#    "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
#    LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
#    PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
#    HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
#    SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
#    LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
#    DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
#    THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
#    (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
#    OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
###############################################################################

__all__ = ['entropy_vn', 'entropy_linear', 'entropy_mutual', 'negativity',
           'concurrence', 'entropy_conditional', 'entangling_power',
           'entropy_relative']

from numpy import dot, e, inf, real, sort, sqrt
from numpy.lib.scimath import log, log2
from qutip.qobj import ptrace
from qutip.states import ket2dm
from qutip.tensor import tensor
from qutip.operators import sigmay
from qutip.sparse import sp_eigs
from qutip.partial_transpose import partial_transpose

def entropy_vn(rho, base=e, sparse=False):
    """
    Von-Neumann entropy of density matrix

    Parameters
    ----------
    rho : qobj
        Density matrix.
    base : {e,2}
        Base of logarithm.
    sparse : {False,True}
        Use sparse eigensolver.

    Returns
    -------
    entropy : float
        Von-Neumann entropy of `rho`.

    Examples
    --------
    >>> rho=0.5*fock_dm(2,0)+0.5*fock_dm(2,1)
    >>> entropy_vn(rho,2)
    1.0

    """
    if rho.type == 'ket' or rho.type == 'bra':
        rho = ket2dm(rho)
    vals = sp_eigs(rho.data, rho.isherm, vecs=False, sparse=sparse)
    nzvals = vals[vals != 0]
    if base == 2:
        logvals = log2(nzvals)
    elif base == e:
        logvals = log(nzvals)
    else:
        raise ValueError("Base must be 2 or e.")
    return float(real(-sum(nzvals * logvals)))

def entropy_linear(rho):
    """
    Linear entropy of a density matrix.

    Parameters
    ----------
    rho : qobj
        sensity matrix or ket/bra vector.

    Returns
    -------
    entropy : float
        Linear entropy of rho.

    Examples
    --------
    >>> rho=0.5*fock_dm(2,0)+0.5*fock_dm(2,1)
    >>> entropy_linear(rho)
    0.5

    """
    if rho.type == 'ket' or rho.type == 'bra':
        rho = ket2dm(rho)
    return float(real(1.0 - (rho ** 2).tr()))

def concurrence(rho):
    """
    Calculate the concurrence entanglement measure for a two-qubit state.

    Parameters
    ----------
    state : qobj
        Ket, bra, or density matrix for a two-qubit state.

    Returns
    -------
    concur : float
        Concurrence

    References
    ----------

    .. [1] http://en.wikipedia.org/wiki/Concurrence_(quantum_computing)

    """
    if rho.isket and rho.dims != [[2, 2], [1, 1]]:
        raise Exception("Ket must be tensor product of two qubits.")

    elif rho.isbra and rho.dims != [[1, 1], [2, 2]]:
        raise Exception("Bra must be tensor product of two qubits.")

    elif rho.isoper and rho.dims != [[2, 2], [2, 2]]:
        raise Exception("Density matrix must be tensor product of two qubits.")

    if rho.isket or rho.isbra:
        rho = ket2dm(rho)

    sysy = tensor(sigmay(), sigmay())

    rho_tilde = (rho * sysy) * (rho.conj() * sysy)

    evals = rho_tilde.eigenenergies()

    # abs to avoid problems with sqrt for very small negative numbers
    evals = abs(sort(real(evals)))

    lsum = sqrt(evals[3]) - sqrt(evals[2]) - sqrt(evals[1]) - sqrt(evals[0])

    return max(0, lsum)

def negativity(rho, subsys, method='tracenorm', logarithmic=False):
    """
    Compute the negativity for a multipartite quantum system described
    by the density matrix rho. The subsys argument is an index that
    indicates which system to compute the negativity for.

    .. note::

        Experimental.
    """
    mask = [idx == subsys for idx, n in enumerate(rho.dims[0])]
    rho_pt = partial_transpose(rho, mask)

    if method == 'tracenorm':
        N = ((rho_pt.dag() * rho_pt).sqrtm().tr().real - 1)/2.0
    elif method == 'eigenvalues':
        l = rho_pt.eigenenergies()
        N = ((abs(l)-l)/2).sum()
    else:
        raise ValueError("Unknown method %s" % method)

    if logarithmic:
        return log2(2 * N + 1)
    else:
        return N

def entropy_mutual(rho, selA, selB, base=e, sparse=False):
    """
    Calculates the mutual information S(A:B) between selection
    components of a system density matrix.

    Parameters
    ----------
    rho : qobj
        Density matrix for composite quantum systems
    selA : int/list
        `int` or `list` of first selected density matrix components.
    selB : int/list
        `int` or `list` of second selected density matrix components.
    base : {e,2}
        Base of logarithm.
    sparse : {False,True}
        Use sparse eigensolver.

    Returns
    -------
    ent_mut : float
       Mutual information between selected components.

    """
    if isinstance(selA, int):
        selA = [selA]
    if isinstance(selB, int):
        selB = [selB]
    if rho.type != 'oper':
        raise TypeError("Input must be a density matrix.")
    if (len(selA) + len(selB)) != len(rho.dims[0]):
        raise TypeError("Number of selected components must match " +
                        "total number.")

    rhoA = ptrace(rho, selA)
    rhoB = ptrace(rho, selB)
    out = (entropy_vn(rhoA, base, sparse=sparse) +
           entropy_vn(rhoB, base, sparse=sparse) -
           entropy_vn(rho, base, sparse=sparse))
    return out

def entropy_relative(rho, sigma, base=e, sparse=False, tol=1e-12):
    """
    Calculates the relative entropy S(rho||sigma) between two density
    matrices.
    Parameters
    ----------
    rho : :class:`qutip.Qobj`
        First density matrix (or ket which will be converted to a density
        matrix).
    sigma : :class:`qutip.Qobj`
        Second density matrix (or ket which will be converted to a density
        matrix).
    base : {e,2}
        Base of logarithm. Defaults to e.
    sparse : bool
        Flag to use sparse solver when determining the eigenvectors
        of the density matrices. Defaults to False.
    tol : float
        Tolerance to use to detect 0 eigenvalues or dot producted between
        eigenvectors. Defaults to 1e-12.

    Returns
    -------
    rel_ent : float
        Value of relative entropy.

    References
    ----------

    See Nielsen & Chuang, "Quantum Computation and Quantum Information",
    Section 11.3.1, pg. 511 for a detailed explanation of quantum relative
    entropy.
    """
    if rho.isket:
        rho = ket2dm(rho)
    if sigma.isket:
        sigma = ket2dm(sigma)
    if not rho.isoper or not sigma.isoper:
        raise TypeError("Inputs must be density matrices.")
    if rho.dims != sigma.dims:
        raise ValueError("Inputs must have the same shape and dims.")
    if base == 2:
        log_base = log2
    elif base == e:
        log_base = log
    else:
        raise ValueError("Base must be 2 or e.")
    # S(rho || sigma) = sum_i(p_i log p_i) - sum_ij(p_i P_ij log q_i)
    #
    # S is +inf if the kernel of sigma (i.e. svecs[svals == 0]) has non-trivial
    # intersection with the support of rho (i.e. rvecs[rvals != 0]).
    rvals, rvecs = sp_eigs(rho.data, rho.isherm, vecs=True, sparse=sparse)
    svals, svecs = sp_eigs(sigma.data, sigma.isherm, vecs=True, sparse=sparse)
    nzrvals = rvals[abs(rvals) >= tol]
    # Calculate S
    S = sum(nzrvals * log_base(nzrvals))
    for i in range(len(rvals)):
        for j in range(len(svals)):
            P_ij = (
                dot(rvecs[i], svecs[j].conjugate()) *
                dot(svecs[j], rvecs[i].conjugate())
            )
            if abs(svals[j]) < tol and not (
                    abs(rvals[i]) < tol or abs(P_ij) < tol):
                # kernel of sigma intersects support of rho
                return inf
            if svals[j] != 0:
                S -= rvals[i] * P_ij * log_base(svals[j])
    return real(S)

def entropy_conditional(rho, selB, base=e, sparse=False):
    """
    Calculates the conditional entropy :math:`S(A|B)=S(A,B)-S(B)`
    of a selected density matrix component.

    Parameters
    ----------
    rho : qobj
        Density matrix of composite object
    selB : int/list
        Selected components for density matrix B
    base : {e,2}
        Base of logarithm.
    sparse : {False,True}
        Use sparse eigensolver.

    Returns
    -------
    ent_cond : float
        Value of conditional entropy

    """
    if rho.type != 'oper':
        raise TypeError("Input must be density matrix.")
    if isinstance(selB, int):
        selB = [selB]
    B = ptrace(rho, selB)
    out = (entropy_vn(rho, base, sparse=sparse) -
           entropy_vn(B, base, sparse=sparse))
    return out

def participation_ratio(rho):
    """
    Returns the effective number of states for a density matrix.

    The participation is unity for pure states, and maximally N,
    where N is the Hilbert space dimensionality, for completely
    mixed states.

    Parameters
    ----------
    rho : qobj
        Density matrix

    Returns
    -------
    pr : float
        Effective number of states in the density matrix

    """
    if rho.type == 'ket' or rho.type == 'bra':
        return 1.0
    else:
        return 1.0 / (rho ** 2).tr()

def entangling_power(U):
    """
    Calculate the entangling power of a two-qubit gate U, which
    is zero of nonentangling gates and 1 and 2/9 for maximally
    entangling gates.

    Parameters
    ----------
    U : qobj
        Qobj instance representing a two-qubit gate.

    Returns
    -------
    ep : float
        The entanglement power of U (real number between 0 and 1)

    References:

        Explorations in Quantum Computing, Colin P. Williams (Springer, 2011)
    """

    if not U.isoper:
        raise Exception("U must be an operator.")

    if U.dims != [[2, 2], [2, 2]]:
        raise Exception("U must be a two-qubit gate.")

    from qutip.qip.operations.gates import swap
    a = (tensor(U, U).dag() * swap(N=4, targets=[1, 3]) *
         tensor(U, U) * swap(N=4, targets=[1, 3]))
    b = (tensor(swap() * U, swap() * U).dag() * swap(N=4, targets=[1, 3]) *
         tensor(swap() * U, swap() * U) * swap(N=4, targets=[1, 3]))

    return 5.0/9 - 1.0/36 * (a.tr() + b.tr()).real
<|endoftext|>


<commit_before>import fcntl
import json
import random
import re
import socket
import struct
import urllib
from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer
from SocketServer import ThreadingMixIn
from cv2 import imshow, namedWindow, setWindowProperty
from platform import machine
from threading import Thread

import cv2
import numpy as np

from btns import desk, Button

STAGE = 0
LANCAM = list()
WindowName = 'Term'
FULLSCREEN = True
__version__ = 0.3
RUN = True

with open('settings.json') as json_data:
	settings = json.load(json_data)

def geturl(url):
	print(url)
	try:
		url = urllib.urlopen(url)
	except Exception as e:
		print(e)
		return e
	ret = url.getcode()
	print('Ret: ' + str(ret))
	url.close()
	return ret

class CamHandler(BaseHTTPRequestHandler):
	streams = None

	def log_message(self, format, *args):
		if len(args) > 0:
			if args[0] == 'GET /0 HTTP/1.1':
				return
			else:
				print(args[0])

	def do_GET(self):
		path = self.path.split('/')[1:]
		data = path[-1]
		name = data
		args = dict()
		end = str()
		server = self.client_address[0]

		if '?' in data:
			name, args = data.split('?')
			args = args.split('&')
			ar = dict()
			for i in range(len(args)):
				r = args[i].split('=')
				if len(r) == 2:
					ar.update({r[0]: r[1]})
				else:
					ar.update({r[0]: str()})
			args = ar
		if '.' in name:
			name, end = name.split('.')

		if name == 'execute_1':
			game.setServer(server)
			param_1 = int(args.get('param_1', ''))
			game.start(param_1)
			self.send_response(200)
			self.send_header('Content-type', 'application/json')
			self.end_headers()
			self.wfile.write('{success: 1}')

		if name == '0' and end == '':
			game.setServer(server)
			self.send_response(200)
			self.send_header('Content-type', 'application/json')
			self.end_headers()
			self.wfile.write('{state_int_1: %i, state_int_2: %i}' % (game.stage, game.round))

		if end == 'mjpg':
			self.send_response(200)
			self.send_header('Content-type', 'multipart/x-mixed-replace; boundary=--jpgboundary')
			self.end_headers()
			while RUN:
				try:
					num = int(name)
					img = self.streams[num].read()
					if img is not None:
						img = cv2.imencode(".png", img)[1].tostring()
					else:
						continue

					self.wfile.write('--jpgboundary\r\n')
					self.send_header('Content-type', 'image/jpeg')
					self.send_header('Content-length', str(len(img)))
					self.end_headers()
					self.wfile.write(img)
				except KeyboardInterrupt:
					break
			return

		if end == 'html' and len(path) == 1 and name.isdigit():
			self.send_response(200)
			self.send_header('Content-type', 'text/html')
			self.end_headers()
			self.wfile.write('')
			self.wfile.write('' % int(name))
			self.wfile.write('')

class ThreadedHTTPServer(ThreadingMixIn, HTTPServer):
	"""Handle requests in a separate thread."""

class VideoStream:
	frame = None
	grabbed = None
	stream = None
	stopped = True
	paused = False
	src = None

	net = None

	def __init__(self, src=0):
		if type(src) == int or not src.startswith('http:'):
			self.src = src
			print('Creating camera %s' % src)
			self.stream = cv2.VideoCapture(src)
			self.stream.set(3, 320)
			self.stream.set(4, 240)
			try:
				#self.grabbed, self.frame = self.stream.read()
				self.grabbed = self.stream.grab()
			except Exception as e:
				print('Camera %s error: %s' % (self.src, e))
			self.stopped = False
		else:
			pattern = r"^http:\/\/(?P<ip>[0-9.]+):(?P<port>[0-9]+)\/(?P<fn>.+)\.(?P<ft>.+)$"
			self.net = re.search(pattern, src).groupdict()
			self.src = str(src)
			self.stopped = False
			self.paused = True
		self.th = Thread(target=self.update, args=()).start()

	def netconn(self):
		stream = None
		while stream is None:
			try:
				stream = urllib.urlopen(self.src)
			except Exception as e:
				print(self.src + ': ' + str(e))
		return stream

	def update(self):
		if type(self.src) == str:
			stream = self.netconn()

			data = bytes()
			while RUN:
				if self.stopped:
					return
				if self.paused:
					continue

				try:
					data += stream.read(1)
				except Exception as e:
					stream = self.netconn()

				b = data.find(b'\r\n\r\n')

				if b == -1:
					continue

				a = data.find(b'--')

				if a != -1 and b != -1:
					head = data[a:b].split('\r\n')
					for i in head:
						if 'length' in i:
							l = int(i[i.find(': ') + 2:])

					jpg = bytes()
					data = bytes()
					while len(jpg) < l:
						try:
							jpg += stream.read(l - len(jpg))
						except Exception as e:
							stream = self.netconn()

					self.frame = cv2.imdecode(np.fromstring(jpg, dtype=np.uint8), cv2.IMREAD_COLOR)

		else:
			while RUN:
				if self.stopped:
					return
				if self.paused:
					continue
				try:
					self.grabbed = self.stream.grab()
					_, self.frame = self.stream.retrieve()
				except Exception as e:
					print('Camera %s error: %s' % (self.src, e))

	def read(self):
		self.pause()
		img = self.frame
		self.start()
		return img

	def pause(self):
		self.paused = True
		return self

	def start(self):
		self.paused = False
		return self

	def stop(self):
		self.stopped = True
		return self

	def __del__(self):
		self.stop()
		self.stream.release()

def getImg(c):
	for i in c:
		d = i.read()
		yield d

def comp(*img):
	img = list(img)

	for i in range(len(img)):
		if None in img:
			img.remove(None)

	if len(img) == 0:
		vis = np.zeros((1, 1), np.uint8)
		frame = cv2.resize(vis, tuple(settings['size']))
		return frame

	h = [i.shape[0] for i in img]
	w = [i.shape[1] for i in img]

	sz = (max(h), sum(w), 3)

	vis = np.zeros(sz, np.uint8)
	for i in range(len(img)):
		vis[:h[i], sum(w[:i]):sum(w[:(i + 1)])] = img[i]

	frame = cv2.resize(vis, tuple(settings['size']))
	return frame

class Game:
	stage = 0
	round = 0
	btns = list()
	server = '127.0.0.1'

	def __init__(self):
		self.reset()
		Button.callback = self.clicked

	def setServer(self, s):
		if self.server != s:
			self.server = s
			print('New server: ' + str(s))

	def start(self, num):
		self.getRandBtns()
		self.round = 0
		self.stage = num

	def reset(self):
		self.stage = 0
		self.round = 0
		self.getRandBtns()

	def getRandBtns(self):
		desk.leds(False)
		for i in desk.L:
			i.clicked = False
		for i in desk.R:
			i.clicked = False

		self.btns = list([random.choice(desk.L), random.choice(desk.R)])
		for i in self.btns:
			i.led(True)

	def endStage(self):
		geturl('http://%s:3000/events/0/event_1?param_1=%i' % (self.server, self.stage))
		self.round = 0
		self.stage = 0

	def nextRound(self):
		if self.round >= 3:
			self.endStage()
		else:
			self.round += 1
			self.getRandBtns()
			print('next round: ' + str(self.round))

	def resetRound(self):
		print('reset round')
		self.round = 0
		self.getRandBtns()

	def clicked(self, btn):
		print('click: ' + str(btn.pos) + str(btn.num))

		if self.stage == 0:
			return

		elif self.stage in [1, 2, 3]:
			if btn not in self.btns:
				self.resetRound()
			else:
				btn.led(False)
				if self.btns[0].clicked and self.btns[1].clicked:
					self.nextRound()

def createFrame():
	frames = list()

	if game.stage == 1:
		frames = getImg(cam)
	elif game.stage == 2:
		a = cam[::-1]
		frames = getImg(a)
	elif game.stage == 3:
		for i in LANCAM:
			if i.paused:
				i.start()
		frames = getImg(LANCAM)

	frame = comp(*frames)
	return frame

def window(*cam):
	global STAGE
	global RUN

	while RUN:
		frame = createFrame()

		if frame is not None:
			imshow(WindowName, frame)

		key = cv2.waitKey(1)

		if key & 0xFF == 27:
			RUN = False
			break

		if key & 0xFF == 32:
			STAGE = (STAGE + 1) % 3

	for i in cam:
		i.stop()
	cv2.destroyAllWindows()
	exit(-1)

def serve():
	global server
	CamHandler.streams = cam
	server = ThreadedHTTPServer(('', settings['port']), CamHandler)
	print("Server started")
	server.serve_forever()

def get_ip_address(ifname):
	s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

	try:
		addr = socket.inet_ntoa(fcntl.ioctl(s.fileno(), 0x8915, struct.pack('256s', ifname[:15]))[20:24])
	except:
		addr = None
	return addr

cam = list()
game = Game()
server = None

if __name__ == '__main__':
	ip = get_ip_address('eth0' if machine() == 'armv7l' else 'wlp3s0')
	WindowName = str(ip)
	other = settings.get(ip, [])
	print('twoHands: %s' % __version__)
	print('OpenCV: %s' % cv2.__version__)
	print('My addr: %s' % ip)
	print('Other: %s' % other)
	cam = list([VideoStream(0).start(), VideoStream(1).start()])
	print('Cam created')

	if FULLSCREEN:
		namedWindow(WindowName, cv2.WND_PROP_FULLSCREEN)
		if cv2.__version__.startswith('2.'):
			setWindowProperty(WindowName, cv2.WND_PROP_FULLSCREEN, cv2.cv.CV_WINDOW_FULLSCREEN)
		if cv2.__version__.startswith('3.'):
			setWindowProperty(WindowName, cv2.WND_PROP_FULLSCREEN, cv2.WINDOW_FULLSCREEN)

	th = Thread(target=window, args=(cam))
	th.start()
	th1 = Thread(target=serve, args=())
	th1.start()

	LANCAM = list()
	for i in other:
		url = 'http://' + str(i[0]) + ':' + str(settings['port']) + '/' + str(i[1]) + '.mjpg'
		d = VideoStream(url)
		print('NetCam created: ' + url)
		LANCAM.append(d)

	while (RUN):
		pass
	print('Exit')
	server.shutdown()
	th1.join(1)
	th.join(1)
<commit_msg>exceptions<commit_after>import fcntl
import json
import random
import re
import socket
import struct
import urllib
from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer
from SocketServer import ThreadingMixIn
from cv2 import imshow, namedWindow, setWindowProperty
from platform import machine
from threading import Thread
from time import sleep

import cv2
import numpy as np

from btns import desk, Button

STAGE = 0
LANCAM = list()
WindowName = 'Term'
FULLSCREEN = True
__version__ = 0.3
RUN = True

with open('settings.json') as json_data:
	settings = json.load(json_data)

def geturl(url):
	print(url)
	try:
		url = urllib.urlopen(url)
	except Exception as e:
		print(e)
		return e
	ret = url.getcode()
	print('Ret: ' + str(ret))
	url.close()
	return ret

class CamHandler(BaseHTTPRequestHandler):
	streams = None

	def log_message(self, format, *args):
		if len(args) > 0:
			if args[0] == 'GET /0 HTTP/1.1':
				return
			else:
				print(args[0])

	def do_GET(self):
		path = self.path.split('/')[1:]
		data = path[-1]
		name = data
		args = dict()
		end = str()
		server = self.client_address[0]

		if '?' in data:
			name, args = data.split('?')
			args = args.split('&')
			ar = dict()
			for i in range(len(args)):
				r = args[i].split('=')
				if len(r) == 2:
					ar.update({r[0]: r[1]})
				else:
					ar.update({r[0]: str()})
			args = ar

		if '.' in name:
			name, end = name.split('.')

		if name == 'execute_1':
			game.setServer(server)
			param_1 = int(args.get('param_1', ''))
			game.start(param_1)
			self.send_response(200)
			self.send_header('Content-type', 'application/json')
			self.end_headers()
			self.wfile.write('{success: 1}')

		if name == '0' and end == '':
			game.setServer(server)
			self.send_response(200)
			self.send_header('Content-type', 'application/json')
			self.end_headers()
			self.wfile.write('{state_int_1: %i, state_int_2: %i}' % (game.stage, game.round))

		if end == 'mjpg':
			self.send_response(200)
			self.send_header('Content-type', 'multipart/x-mixed-replace; boundary=--jpgboundary')
			self.end_headers()
			while RUN:
				try:
					num = int(name)
					img = self.streams[num].read()
					if img is not None:
						img = cv2.imencode(".png", img)[1].tostring()
					else:
						continue
					try:
						self.wfile.write('--jpgboundary\r\n')
						self.send_header('Content-type', 'image/jpeg')
						self.send_header('Content-length', str(len(img)))
						self.end_headers()
						self.wfile.write(img)
					except Exception:
						break
				except KeyboardInterrupt:
					break
			return

		if end == 'html' and len(path) == 1 and name.isdigit():
			self.send_response(200)
			self.send_header('Content-type', 'text/html')
			self.end_headers()
			self.wfile.write('')
			self.wfile.write('' % int(name))
			self.wfile.write('')

class ThreadedHTTPServer(ThreadingMixIn, HTTPServer):
	"""Handle requests in a separate thread."""

class VideoStream:
	frame = None
	grabbed = None
	stream = None
	stopped = True
	paused = False
	src = None

	net = None

	def __init__(self, src=0):
		if type(src) == int or not src.startswith('http:'):
			self.src = src
			print('Creating camera %s' % src)
			self.stream = cv2.VideoCapture(src)
			self.stream.set(3, 320)
			self.stream.set(4, 240)
			try:
				# self.grabbed, self.frame = self.stream.read()
				self.grabbed = self.stream.grab()
			except Exception as e:
				print('Camera %s error: %s' % (self.src, e))
			self.stopped = False
		else:
			pattern = r"^http:\/\/(?P<ip>[0-9.]+):(?P<port>[0-9]+)\/(?P<fn>.+)\.(?P<ft>.+)$"
			self.net = re.search(pattern, src).groupdict()
			self.src = str(src)
			self.stopped = False
			self.paused = True
		self.th = Thread(target=self.update, args=()).start()

	def netconn(self):
		stream = None
		while stream is None:
			try:
				stream = urllib.urlopen(self.src)
			except Exception as e:
				print(self.src + ': ' + str(e))
				sleep(1)
		return stream

	def update(self):
		if type(self.src) == str:
			stream = self.netconn()

			data = bytes()
			while RUN:
				if self.stopped:
					return
				if self.paused:
					continue

				try:
					data += stream.read(1)
				except Exception as e:
					stream = self.netconn()

				b = data.find(b'\r\n\r\n')

				if b == -1:
					continue

				a = data.find(b'--')

				if a != -1 and b != -1:
					head = data[a:b].split('\r\n')
					for i in head:
						if 'length' in i:
							l = int(i[i.find(': ') + 2:])

					jpg = bytes()
					data = bytes()
					while len(jpg) < l:
						try:
							jpg += stream.read(l - len(jpg))
						except Exception as e:
							stream = self.netconn()

					self.frame = cv2.imdecode(np.fromstring(jpg, dtype=np.uint8), cv2.IMREAD_COLOR)

		else:
			while RUN:
				if self.stopped:
					return
				if self.paused:
					continue
				try:
					self.grabbed = self.stream.grab()
					_, self.frame = self.stream.retrieve()
				except Exception as e:
					print('Camera %s error: %s' % (self.src, e))

	def read(self):
		self.pause()
		img = self.frame
		self.start()
		return img

	def pause(self):
		self.paused = True
		return self

	def start(self):
		self.paused = False
		return self

	def stop(self):
		self.stopped = True
		return self

	def __del__(self):
		self.stop()
		self.stream.release()

def getImg(c):
	for i in c:
		d = i.read()
		yield d

def comp(*img):
	img = list(img)

	for i in range(len(img)):
		if None in img:
			img.remove(None)

	if len(img) == 0:
		vis = np.zeros((1, 1), np.uint8)
		frame = cv2.resize(vis, tuple(settings['size']))
		return frame

	h = [i.shape[0] for i in img]
	w = [i.shape[1] for i in img]

	sz = (max(h), sum(w), 3)

	vis = np.zeros(sz, np.uint8)
	for i in range(len(img)):
		vis[:h[i], sum(w[:i]):sum(w[:(i + 1)])] = img[i]

	frame = cv2.resize(vis, tuple(settings['size']))
	return frame

class Game:
	stage = 0
	round = 0
	btns = list()
	server = '127.0.0.1'

	def __init__(self):
		self.reset()
		Button.callback = self.clicked

	def setServer(self, s):
		if self.server != s:
			self.server = s
			print('New server: ' + str(s))

	def start(self, num):
		self.getRandBtns()
		self.round = 0
		self.stage = num

	def reset(self):
		self.stage = 0
		self.round = 0
		self.getRandBtns()

	def getRandBtns(self):
		desk.leds(False)
		for i in desk.L:
			i.clicked = False
		for i in desk.R:
			i.clicked = False

		self.btns = list([random.choice(desk.L), random.choice(desk.R)])
		for i in self.btns:
			i.led(True)

	def endStage(self):
		geturl('http://%s:3000/events/0/event_1?param_1=%i' % (self.server, self.stage))
		self.round = 0
		self.stage = 0

	def nextRound(self):
		if self.round >= 3:
			self.endStage()
		else:
			self.round += 1
			self.getRandBtns()
			print('next round: ' + str(self.round))

	def resetRound(self):
		print('reset round')
		self.round = 0
		self.getRandBtns()

	def clicked(self, btn):
		print('click: ' + str(btn.pos) + str(btn.num))

		if self.stage == 0:
			return

		elif self.stage in [1, 2, 3]:
			if btn not in self.btns:
				self.resetRound()
			else:
				btn.led(False)
				if self.btns[0].clicked and self.btns[1].clicked:
					self.nextRound()

def createFrame():
	frames = list()

	if game.stage == 1:
		frames = getImg(cam)
	elif game.stage == 2:
		a = cam[::-1]
		frames = getImg(a)
	elif game.stage == 3:
		for i in LANCAM:
			if i.paused:
				i.start()
		frames = getImg(LANCAM)

	frame = comp(*frames)
	return frame

def window(*cam):
	global STAGE
	global RUN

	while RUN:
		frame = createFrame()

		if frame is not None:
			imshow(WindowName, frame)

		key = cv2.waitKey(1)

		if key & 0xFF == 27:
			RUN = False
			break

		if key & 0xFF == 32:
			STAGE = (STAGE + 1) % 3

	for i in cam:
		i.stop()
	cv2.destroyAllWindows()
	exit(-1)

def serve():
	global server
	CamHandler.streams = cam
	server = ThreadedHTTPServer(('', settings['port']), CamHandler)
	print("Server started")
	server.serve_forever()

def get_ip_address(ifname):
	s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

	try:
		addr = socket.inet_ntoa(fcntl.ioctl(s.fileno(), 0x8915, struct.pack('256s', ifname[:15]))[20:24])
	except:
		addr = None
	return addr

cam = list()
game = Game()
server = None

if __name__ == '__main__':
	ip = get_ip_address('eth0' if machine() == 'armv7l' else 'wlp3s0')
	WindowName = str(ip)
	other = settings.get(ip, [])
	print('twoHands: %s' % __version__)
	print('OpenCV: %s' % cv2.__version__)
	print('My addr: %s' % ip)
	print('Other: %s' % other)
	cam = list([VideoStream(0).start(), VideoStream(1).start()])
	print('Cam created')

	if FULLSCREEN:
		namedWindow(WindowName, cv2.WND_PROP_FULLSCREEN)
		if cv2.__version__.startswith('2.'):
			setWindowProperty(WindowName, cv2.WND_PROP_FULLSCREEN, cv2.cv.CV_WINDOW_FULLSCREEN)
		if cv2.__version__.startswith('3.'):
			setWindowProperty(WindowName, cv2.WND_PROP_FULLSCREEN, cv2.WINDOW_FULLSCREEN)

	th = Thread(target=window, args=(cam))
	th.start()
	th1 = Thread(target=serve, args=())
	th1.start()

	LANCAM = list()
	for i in other:
		url = 'http://' + str(i[0]) + ':' + str(settings['port']) + '/' + str(i[1]) + '.mjpg'
		d = VideoStream(url)
		print('NetCam created: ' + url)
		LANCAM.append(d)

	while (RUN):
		pass
	print('Exit')
	server.shutdown()
	th1.join(1)
	th.join(1)
<|endoftext|>


<commit_before># -*- coding: utf-8 -*-
# vim: tabstop=4 shiftwidth=4 softtabstop=4
#
# Copyright (C) 2014-2019 GEM Foundation
#
# OpenQuake is free software: you can redistribute it and/or modify it
# under the terms of the GNU Affero General Public License as published
# by the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# OpenQuake is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with OpenQuake. If not, see <http://www.gnu.org/licenses/>.
import logging
import numpy

from openquake.hazardlib.calc.gmf import GmfComputer
from openquake.hazardlib.gsim.base import ContextMaker
from openquake.hazardlib.calc.stochastic import get_rup_array
from openquake.hazardlib.source.rupture import EBRupture, events_dt
from openquake.commonlib import readinput, source, calc
from openquake.calculators import base

TWO32 = 2 ** 32
U64 = numpy.uint64

@base.calculators.add('scenario')
class ScenarioCalculator(base.HazardCalculator):
    """
    Scenario hazard calculator
    """
    is_stochastic = True

    def pre_execute(self):
        """
        Read the site collection and initialize GmfComputer and seeds
        """
        oq = self.oqparam
        cinfo = source.CompositionInfo.fake(readinput.get_gsim_lt(oq))
        self.datastore['csm_info'] = cinfo
        if 'rupture_model' not in oq.inputs:
            logging.warning(
                'There is no rupture_model, the calculator will just '
                'import data without performing any calculation')
            super().pre_execute()
            return
        self.rup = readinput.get_rupture(oq)
        self.gsims = readinput.get_gsims(oq)
        R = len(self.gsims)
        self.cmaker = ContextMaker('*', self.gsims,
                                   {'maximum_distance': oq.maximum_distance,
                                    'filter_distance': oq.filter_distance})
        super().pre_execute()
        self.datastore['oqparam'] = oq
        self.rlzs_assoc = cinfo.get_rlzs_assoc()
        self.store_rlz_info()
        rlzs_by_gsim = self.rlzs_assoc.get_rlzs_by_gsim(0)
        E = oq.number_of_ground_motion_fields
        n_occ = numpy.array([E])
        ebr = EBRupture(self.rup, 0, 0, n_occ)
        events = numpy.zeros(E * R, events_dt)
        for rlz, eids in ebr.get_eids_by_rlz(rlzs_by_gsim).items():
            events[rlz * E: rlz * E + E]['id'] = eids + TWO32 * U64(ebr.serial)
            events[rlz * E: rlz * E + E]['rlz'] = rlz
        self.datastore['events'] = self.events = events
        rupser = calc.RuptureSerializer(self.datastore)
        rup_array = get_rup_array([ebr], self.src_filter)
        if len(rup_array) == 0:
            maxdist = oq.maximum_distance(
                self.rup.tectonic_region_type, self.rup.mag)
            raise RuntimeError('There are no sites within the maximum_distance'
                               ' of %s km from the rupture' % maxdist)
        rupser.save(rup_array)
        rupser.close()
        self.computer = GmfComputer(
            ebr, self.sitecol, oq.imtls, self.cmaker, oq.truncation_level,
            oq.correl_model)
        M32 = (numpy.float32, len(self.oqparam.imtls))
        self.sig_eps_dt = [('eid', numpy.uint64), ('sig', M32), ('eps', M32)]

    def init(self):
        pass

    def execute(self):
        """
        Compute the GMFs and return a dictionary gsim -> array(N, E, I)
        """
        arrays = []
        if 'rupture_model' not in self.oqparam.inputs:
            return ()
        n = self.oqparam.number_of_ground_motion_fields
        with self.monitor('computing gmfs'):
            ei = 0
            for gsim in self.gsims:
                gmfa, sig, eps = self.computer.compute(gsim, n)
                lst = []
                for s, e in zip(sig.T, eps.T):  # shape (M, E) -> (E, M)
                    lst.append((ei, s, e))
                    ei += 1
                arrays.append(gmfa.transpose(1, 2, 0))  # shape (N, n, I)
        self.datastore['gmf_data/sigma_epsilon'] = numpy.array(
            lst, self.sig_eps_dt)
        return numpy.concatenate(arrays, axis=1)  # shape (N, E, I)

    def post_execute(self, gmfa):
        if len(gmfa) == 0:  # no rupture_model
            return
        with self.monitor('saving gmfs', autoflush=True):
            base.save_gmf_data(
                self.datastore, self.sitecol, gmfa,
                self.oqparam.imtls, self.events)
<commit_msg>[skip hazardlib][demos]<commit_after># -*- coding: utf-8 -*-
# vim: tabstop=4 shiftwidth=4 softtabstop=4
#
# Copyright (C) 2014-2019 GEM Foundation
#
# OpenQuake is free software: you can redistribute it and/or modify it
# under the terms of the GNU Affero General Public License as published
# by the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# OpenQuake is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with OpenQuake. If not, see <http://www.gnu.org/licenses/>.
import logging
import numpy

from openquake.hazardlib.calc.gmf import GmfComputer
from openquake.hazardlib.gsim.base import ContextMaker
from openquake.hazardlib.calc.stochastic import get_rup_array
from openquake.hazardlib.source.rupture import EBRupture, events_dt
from openquake.commonlib import readinput, source, calc
from openquake.calculators import base

TWO32 = 2 ** 32
U64 = numpy.uint64

@base.calculators.add('scenario')
class ScenarioCalculator(base.HazardCalculator):
    """
    Scenario hazard calculator
    """
    is_stochastic = True

    def pre_execute(self):
        """
        Read the site collection and initialize GmfComputer and seeds
        """
        oq = self.oqparam
        cinfo = source.CompositionInfo.fake(readinput.get_gsim_lt(oq))
        self.datastore['csm_info'] = cinfo
        if 'rupture_model' not in oq.inputs:
            logging.warning(
                'There is no rupture_model, the calculator will just '
                'import data without performing any calculation')
            super().pre_execute()
            return
        self.rup = readinput.get_rupture(oq)
        self.gsims = readinput.get_gsims(oq)
        R = len(self.gsims)
        self.cmaker = ContextMaker('*', self.gsims,
                                   {'maximum_distance': oq.maximum_distance,
                                    'filter_distance': oq.filter_distance})
        super().pre_execute()
        self.datastore['oqparam'] = oq
        self.rlzs_assoc = cinfo.get_rlzs_assoc()
        self.store_rlz_info()
        rlzs_by_gsim = self.rlzs_assoc.get_rlzs_by_gsim(0)
        E = oq.number_of_ground_motion_fields
        n_occ = numpy.array([E])
        ebr = EBRupture(self.rup, 0, 0, n_occ)
        ebr.e0 = TWO32 * U64(ebr.serial)
        events = numpy.zeros(E * R, events_dt)
        for rlz, eids in ebr.get_eids_by_rlz(rlzs_by_gsim).items():
            events[rlz * E: rlz * E + E]['id'] = eids + ebr.e0
            events[rlz * E: rlz * E + E]['rlz'] = rlz
        self.datastore['events'] = self.events = events
        rupser = calc.RuptureSerializer(self.datastore)
        rup_array = get_rup_array([ebr], self.src_filter)
        if len(rup_array) == 0:
            maxdist = oq.maximum_distance(
                self.rup.tectonic_region_type, self.rup.mag)
            raise RuntimeError('There are no sites within the maximum_distance'
                               ' of %s km from the rupture' % maxdist)
        rupser.save(rup_array)
        rupser.close()
        self.computer = GmfComputer(
            ebr, self.sitecol, oq.imtls, self.cmaker, oq.truncation_level,
            oq.correl_model)
        M32 = (numpy.float32, len(self.oqparam.imtls))
        self.sig_eps_dt = [('eid', numpy.uint64), ('sig', M32), ('eps', M32)]

    def init(self):
        pass

    def execute(self):
        """
        Compute the GMFs and return a dictionary gsim -> array(N, E, I)
        """
        arrays = []
        if 'rupture_model' not in self.oqparam.inputs:
            return ()
        n = self.oqparam.number_of_ground_motion_fields
        with self.monitor('computing gmfs'):
            ei = 0
            for gsim in self.gsims:
                gmfa, sig, eps = self.computer.compute(gsim, n)
                lst = []
                for s, e in zip(sig.T, eps.T):  # shape (M, E) -> (E, M)
                    lst.append((ei, s, e))
                    ei += 1
                arrays.append(gmfa.transpose(1, 2, 0))  # shape (N, n, I)
        self.datastore['gmf_data/sigma_epsilon'] = numpy.array(
            lst, self.sig_eps_dt)
        return numpy.concatenate(arrays, axis=1)  # shape (N, E, I)

    def post_execute(self, gmfa):
        if len(gmfa) == 0:  # no rupture_model
            return
        with self.monitor('saving gmfs', autoflush=True):
            base.save_gmf_data(
                self.datastore, self.sitecol, gmfa,
                self.oqparam.imtls, self.events)
<|endoftext|>