<commit_before># -*- coding: utf-8 -*-
""" Contains the AutoCompleteMode """
import logging
from pyqode.qt import QtCore, QtGui
from pyqode.core.api import TextHelper
from pyqode.core.api.mode import Mode

class AutoCompleteMode(Mode):
    """ Automatically complete quotes and parentheses

    Generic auto complete mode that automatically completes the following
    symbols:

        - " -> "
        - ' -> '
        - ( -> )
        - [ -> ]
        - { -> }
    """
    def __init__(self):
        super(AutoCompleteMode, self).__init__()
        #: Auto complete mapping, maps input key with completion text.
        self.MAPPING = {'"': '"', "'": "'", "(": ")", "{": "}", "[": "]"}
        #: The format to use for each symbol in mapping when there is a selection
        self.SELECTED_QUOTES_FORMATS = {key: '%s%s%s' for key in self.MAPPING.keys()}
        #: The format to use for each symbol in mapping when there is no selection
        self.QUOTES_FORMATS = {key: '%s' for key in self.MAPPING.keys()}
        self.logger = logging.getLogger(__name__)
        self._ignore_post = False

    def on_state_changed(self, state):
        if state:
            self.editor.post_key_pressed.connect(self._on_post_key_pressed)
            self.editor.key_pressed.connect(self._on_key_pressed)
        else:
            self.editor.post_key_pressed.disconnect(self._on_post_key_pressed)
            self.editor.key_pressed.disconnect(self._on_key_pressed)

    def _on_post_key_pressed(self, event):
        if not event.isAccepted() and not self._ignore_post:
            txt = event.text()
            trav = self.editor.textCursor()
            assert isinstance(trav, QtGui.QTextCursor)
            trav.movePosition(trav.Left, trav.MoveAnchor, 2)
            literal = TextHelper(self.editor).is_comment_or_string(trav)
            if not literal:
                next_char = TextHelper(self.editor).get_right_character()
                if txt in self.MAPPING:
                    to_insert = self.MAPPING[txt]
                    if (not next_char or next_char in self.MAPPING.keys() or
                            next_char in self.MAPPING.values() or
                            next_char.isspace()):
                        TextHelper(self.editor).insert_text(
                            self.QUOTES_FORMATS[txt] % to_insert)
        self._ignore_post = False

    def _on_key_pressed(self, event):
        txt = event.text()
        cursor = self.editor.textCursor()
        from pyqode.qt import QtGui
        assert isinstance(cursor, QtGui.QTextCursor)
        if cursor.hasSelection():
            # quoting of selected text
            if event.text() in self.MAPPING.keys():
                first = event.text()
                last = self.MAPPING[event.text()]
                cursor.insertText(
                    self.SELECTED_QUOTES_FORMATS[event.text()] % (
                        first, cursor.selectedText(), last))
                self.editor.setTextCursor(cursor)
                event.accept()
            else:
                self._ignore_post = True
            return
        next_char = TextHelper(self.editor).get_right_character()
        self.logger.debug('next char: %s', next_char)
        ignore = False
        if event.key() == QtCore.Qt.Key_Backspace:
            # get the character that will get deleted
            tc = self.editor.textCursor()
            pos = tc.position()
            tc.movePosition(tc.Left)
            tc.movePosition(tc.Right, tc.KeepAnchor)
            del_char = tc.selectedText()
            if del_char in self.MAPPING and \
                    self.MAPPING[del_char] == next_char:
                tc.beginEditBlock()
                tc.movePosition(tc.Right, tc.KeepAnchor)
                tc.insertText('')
                tc.setPosition(pos - 2)
                tc.endEditBlock()
                self.editor.setTextCursor(tc)
                ignore = True
        elif txt and next_char == txt and next_char in self.MAPPING:
            ignore = True
        elif event.text() == ')' or event.text() == ']' or event.text() == '}':
            # if typing the same symbol twice, the symbol should not be written
            # and the cursor moved just after the char
            # e.g. if you type ) just before ), the cursor will just move after
            # the existing )
            if next_char == event.text():
                ignore = True
        if ignore:
            event.accept()
            TextHelper(self.editor).clear_selection()
            TextHelper(self.editor).move_right()
<commit_msg>AutoCompleteMode: make list of characters that shoudn't be duplicated configurable<commit_after># -*- coding: utf-8 -*-
""" Contains the AutoCompleteMode """
import logging
from pyqode.qt import QtCore, QtGui
from pyqode.core.api import TextHelper
from pyqode.core.api.mode import Mode

class AutoCompleteMode(Mode):
    """ Automatically complete quotes and parentheses

    Generic auto complete mode that automatically completes the following
    symbols:

        - " -> "
        - ' -> '
        - ( -> )
        - [ -> ]
        - { -> }
    """
    def __init__(self):
        super(AutoCompleteMode, self).__init__()
        #: Auto complete mapping, maps input key with completion text.
        self.MAPPING = {'"': '"', "'": "'", "(": ")", "{": "}", "[": "]"}
        self.AVOID_DUPLICATES = ')', ']', '}'
        #: The format to use for each symbol in mapping when there is a selection
        self.SELECTED_QUOTES_FORMATS = {key: '%s%s%s' for key in self.MAPPING.keys()}
        #: The format to use for each symbol in mapping when there is no selection
        self.QUOTES_FORMATS = {key: '%s' for key in self.MAPPING.keys()}
        self.logger = logging.getLogger(__name__)
        self._ignore_post = False

    def on_state_changed(self, state):
        if state:
            self.editor.post_key_pressed.connect(self._on_post_key_pressed)
            self.editor.key_pressed.connect(self._on_key_pressed)
        else:
            self.editor.post_key_pressed.disconnect(self._on_post_key_pressed)
            self.editor.key_pressed.disconnect(self._on_key_pressed)

    def _on_post_key_pressed(self, event):
        if not event.isAccepted() and not self._ignore_post:
            txt = event.text()
            trav = self.editor.textCursor()
            assert isinstance(trav, QtGui.QTextCursor)
            trav.movePosition(trav.Left, trav.MoveAnchor, 2)
            literal = TextHelper(self.editor).is_comment_or_string(trav)
            if not literal:
                next_char = TextHelper(self.editor).get_right_character()
                if txt in self.MAPPING:
                    to_insert = self.MAPPING[txt]
                    if (not next_char or next_char in self.MAPPING.keys() or
                            next_char in self.MAPPING.values() or
                            next_char.isspace()):
                        TextHelper(self.editor).insert_text(
                            self.QUOTES_FORMATS[txt] % to_insert)
        self._ignore_post = False

    def _on_key_pressed(self, event):
        txt = event.text()
        cursor = self.editor.textCursor()
        from pyqode.qt import QtGui
        assert isinstance(cursor, QtGui.QTextCursor)
        if cursor.hasSelection():
            # quoting of selected text
            if event.text() in self.MAPPING.keys():
                first = event.text()
                last = self.MAPPING[event.text()]
                cursor.insertText(
                    self.SELECTED_QUOTES_FORMATS[event.text()] % (
                        first, cursor.selectedText(), last))
                self.editor.setTextCursor(cursor)
                event.accept()
            else:
                self._ignore_post = True
            return
        next_char = TextHelper(self.editor).get_right_character()
        self.logger.debug('next char: %s', next_char)
        ignore = False
        if event.key() == QtCore.Qt.Key_Backspace:
            # get the character that will get deleted
            tc = self.editor.textCursor()
            pos = tc.position()
            tc.movePosition(tc.Left)
            tc.movePosition(tc.Right, tc.KeepAnchor)
            del_char = tc.selectedText()
            if del_char in self.MAPPING and \
                    self.MAPPING[del_char] == next_char:
                tc.beginEditBlock()
                tc.movePosition(tc.Right, tc.KeepAnchor)
                tc.insertText('')
                tc.setPosition(pos - 2)
                tc.endEditBlock()
                self.editor.setTextCursor(tc)
                ignore = True
        elif (
            txt and next_char == txt and (
                next_char in self.MAPPING or
                txt in self.AVOID_DUPLICATES
            )
        ):
            ignore = True
        if ignore:
            event.accept()
            TextHelper(self.editor).clear_selection()
            TextHelper(self.editor).move_right()
<|endoftext|>


<commit_before># -*- coding: utf-8 -*-
""" Contains the AutoCompleteMode """
import logging
from pyqode.core.api import TextHelper
from pyqode.core.api.mode import Mode

class AutoCompleteMode(Mode):
    """ Automatically complete quotes and parentheses

    Generic auto complete mode that automatically completes the following
    symbols:

        - " -> "
        - ' -> '
        - ( -> )
        - [ -> ]
        - { -> }
    """
    #: Auto complete mapping, maps input key with completion text.
    MAPPING = {'"': '"', "'": "'", "(": ")", "{": "}", "[": "]"}

    def __init__(self):
        super(AutoCompleteMode, self).__init__()
        self.logger = logging.getLogger(__name__)
        self._ignore_post = False

    def on_state_changed(self, state):
        if state:
            self.editor.post_key_pressed.connect(self._on_post_key_pressed)
            self.editor.key_pressed.connect(self._on_key_pressed)
        else:
            self.editor.post_key_pressed.disconnect(self._on_post_key_pressed)
            self.editor.key_pressed.disconnect(self._on_key_pressed)

    def _on_post_key_pressed(self, event):
        if not event.isAccepted() and not self._ignore_post:
            txt = event.text()
            next_char = TextHelper(self.editor).get_right_character()
            if txt in self.MAPPING:
                to_insert = self.MAPPING[txt]
                if (not next_char or next_char in self.MAPPING.keys() or
                        next_char in self.MAPPING.values() or
                        next_char.isspace()):
                    TextHelper(self.editor).insert_text(to_insert)
        self._ignore_post = False

    def _on_key_pressed(self, event):
        txt = event.text()
        cursor = self.editor.textCursor()
        from pyqode.qt import QtGui
        assert isinstance(cursor, QtGui.QTextCursor)
        if cursor.hasSelection():
            # quoting of selected text
            if event.text() in self.MAPPING.keys():
                first = event.text()
                last = self.MAPPING[event.text()]
                cursor.insertText('%s%s%s' % (
                    first, cursor.selectedText(), last))
                self.editor.setTextCursor(cursor)
                event.accept()
            else:
                self._ignore_post = True
            return
        next_char = TextHelper(self.editor).get_right_character()
        self.logger.debug('next char: %s', next_char)
        ignore = False
        if txt and next_char == txt and next_char in self.MAPPING:
            ignore = True
        elif event.text() == ')' or event.text() == ']' or event.text() == '}':
            if next_char == ')' or next_char == ']' or next_char == '}':
                ignore = True
        if ignore:
            event.accept()
            TextHelper(self.editor).clear_selection()
            TextHelper(self.editor).move_right()
<commit_msg>Add a way to easily customise auto completion of quotes and parentheses through a dictionary of string format to use when inserting ', ", }, ) or ]<commit_after># -*- coding: utf-8 -*-
""" Contains the AutoCompleteMode """
import logging
from pyqode.core.api import TextHelper
from pyqode.core.api.mode import Mode

class AutoCompleteMode(Mode):
    """ Automatically complete quotes and parentheses

    Generic auto complete mode that automatically completes the following
    symbols:

        - " -> "
        - ' -> '
        - ( -> )
        - [ -> ]
        - { -> }
    """
    #: Auto complete mapping, maps input key with completion text.
    MAPPING = {'"': '"', "'": "'", "(": ")", "{": "}", "[": "]"}
    #: The format to use for each symbol in mapping when there is a selection
    SELECTED_QUOTES_FORMATS = {key: '%s%s%s' for key in MAPPING.keys()}
    #: The format to use for each symbol in mapping when there is no selection
    QUOTES_FORMATS = {key: '%s' for key in MAPPING.keys()}

    def __init__(self):
        super(AutoCompleteMode, self).__init__()
        self.logger = logging.getLogger(__name__)
        self._ignore_post = False

    def on_state_changed(self, state):
        if state:
            self.editor.post_key_pressed.connect(self._on_post_key_pressed)
            self.editor.key_pressed.connect(self._on_key_pressed)
        else:
            self.editor.post_key_pressed.disconnect(self._on_post_key_pressed)
            self.editor.key_pressed.disconnect(self._on_key_pressed)

    def _on_post_key_pressed(self, event):
        if not event.isAccepted() and not self._ignore_post:
            txt = event.text()
            next_char = TextHelper(self.editor).get_right_character()
            if txt in self.MAPPING:
                to_insert = self.MAPPING[txt]
                if (not next_char or next_char in self.MAPPING.keys() or
                        next_char in self.MAPPING.values() or
                        next_char.isspace()):
                    TextHelper(self.editor).insert_text(
                        self.QUOTES_FORMATS[txt] % to_insert)
        self._ignore_post = False

    def _on_key_pressed(self, event):
        txt = event.text()
        cursor = self.editor.textCursor()
        from pyqode.qt import QtGui
        assert isinstance(cursor, QtGui.QTextCursor)
        if cursor.hasSelection():
            # quoting of selected text
            if event.text() in self.MAPPING.keys():
                first = event.text()
                last = self.MAPPING[event.text()]
                cursor.insertText(
                    self.SELECTED_QUOTES_FORMATS[event.text()] % (
                        first, cursor.selectedText(), last))
                self.editor.setTextCursor(cursor)
                event.accept()
            else:
                self._ignore_post = True
            return
        next_char = TextHelper(self.editor).get_right_character()
        self.logger.debug('next char: %s', next_char)
        ignore = False
        if txt and next_char == txt and next_char in self.MAPPING:
            ignore = True
        elif event.text() == ')' or event.text() == ']' or event.text() == '}':
            if next_char == ')' or next_char == ']' or next_char == '}':
                ignore = True
        if ignore:
            event.accept()
            TextHelper(self.editor).clear_selection()
            TextHelper(self.editor).move_right()
<|endoftext|>


<commit_before># Copyright 2013,2014 Music Technology Group - Universitat Pompeu Fabra
#
# This file is part of Dunya
#
# Dunya 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 (FSF), either version 3 of the License, or (at your option) any later
# version.
#
# This program 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 General Public License for more details.
#
# You should have received a copy of the GNU General Public License along with
# this program.  If not, see http://www.gnu.org/licenses/

import json
import os

from six import string_types

import compmusic.dunya.conn

def get_collections():
    """Get a list of all collections in the server."""
    path = "document/collections"
    return compmusic.dunya.conn._get_paged_json(path)

def get_collection(slug):
    """Get the documents (recordings) in a collection.

    :param slug: the name of the collection

    """
    path = "document/%s" % slug
    return compmusic.dunya.conn._dunya_query_json(path)

def document(recordingid):
    """Get the available source filetypes for a Musicbrainz recording.

    :param recordingid: Musicbrainz recording ID
    :returns: a list of filetypes in the database for this recording

    """
    path = "document/by-id/%s" % recordingid
    recording = compmusic.dunya.conn._dunya_query_json(path)
    return recording

def create_document(collection, document, title=None):
    path = "/document/by-id/%s" % document
    data = {"collection": collection}
    if title:
        data["title"] = title
    url = compmusic.dunya.conn._make_url(path)
    req = compmusic.dunya.conn._dunya_post(url, data=data)
    return req.json()

def update_document(collection, document, title=None):
    path = "/document/by-id/%s" % document
    data = {"collection": collection}
    if title:
        data["title"] = title
    url = compmusic.dunya.conn._make_url(path)
    req = compmusic.dunya.conn._dunya_post(url, data=data)
    return req.json()

def update_sourcetype(document, filetype, file):
    return add_sourcetype(document, filetype, file)

def add_sourcetype(document, filetype, file):
    """ If file is a string and refers to a file on disk, the contents
        of the file is read and send, otherwise it is sent as-is """
    path = "/document/by-id/%s/add/%s" % (document, filetype)
    if isinstance(file, string_types) and os.path.exists(file):
        f = open(file, "rb")
    else:
        f = file
    files = {"file": f}
    url = compmusic.dunya.conn._make_url(path)
    req = compmusic.dunya.conn._dunya_post(url, files=files)
    return req.json()

def create_and_upload_document(collection, document, title, filetype, file):
    create_document(collection, document, title)
    add_sourcetype(document, filetype, file)

def file_for_document(recordingid, thetype, subtype=None, part=None, version=None):
    """Get the most recent derived file given a filetype.

    :param recordingid: Musicbrainz recording ID
    :param thetype: the computed filetype
    :param subtype: a subtype if the module has one
    :param part: the file part if the module has one
    :param version: a specific version, otherwise the most recent one will be used
    :returns: The contents of the most recent version of the derived file

    """
    path = "document/by-id/%s/%s" % (recordingid, thetype)
    args = {}
    if subtype:
        args["subtype"] = subtype
    if part:
        args["part"] = part
    if version:
        args["v"] = version
    return compmusic.dunya.conn._dunya_query_file(path, **args)

def get_mp3(recordingid):
    return file_for_document(recordingid, "mp3")

def get_document_as_json(recordingid, thetype, subtype=None, part=None, version=None):
    """ Get a derived filetype and load it as json.

    :param recordingid: Musicbrainz recording ID
    :param thetype: the computed filetype
    :param subtype: a subtype if the module has one
    :param part: the file part if the module has one
    :param version: a specific version, otherwise the most recent one will be used

    """

    path = "document/by-id/%s/%s" % (recordingid, thetype)
    args = {}
    if subtype:
        args["subtype"] = subtype
    if part:
        args["part"] = part
    if version:
        args["v"] = version
    return compmusic.dunya.conn._dunya_query_json(path, **args)
<commit_msg>Added some documentations to the functions of docserver<commit_after># Copyright 2013,2014 Music Technology Group - Universitat Pompeu Fabra
#
# This file is part of Dunya
#
# Dunya 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 (FSF), either version 3 of the License, or (at your option) any later
# version.
#
# This program 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 General Public License for more details.
#
# You should have received a copy of the GNU General Public License along with
# this program.  If not, see http://www.gnu.org/licenses/

import os

from six import string_types

import compmusic.dunya.conn

def get_collections():
    """Get a list of all collections in the server."""
    path = "document/collections"
    return compmusic.dunya.conn._get_paged_json(path)

def get_collection(slug):
    """Get the documents (recordings) in a collection.

    :param slug: the name of the collection

    """
    path = "document/%s" % slug
    return compmusic.dunya.conn._dunya_query_json(path)

def document(recordingid):
    """Get the available source filetypes for a Musicbrainz recording.

    :param recordingid: Musicbrainz recording ID
    :returns: a list of filetypes in the database for this recording

    """
    path = "document/by-id/%s" % recordingid
    recording = compmusic.dunya.conn._dunya_query_json(path)
    return recording

def create_document(collection, document, title=None):
    """Create a specific document inside a collection

    :param collection: Name of the collection
    :param document: Musicbrainz recording ID of the specific document
    :returns: The contents of the most recent version of the derived file

    """
    path = "/document/by-id/%s" % document
    data = {"collection": collection}
    if title:
        data["title"] = title
    url = compmusic.dunya.conn._make_url(path)
    req = compmusic.dunya.conn._dunya_post(url, data=data)
    return req.json()

def update_document(collection, document, title=None):
    """Update a specific document inside a collection

    :param collection: Name of the collection
    :param document: Musicbrainz recording ID of the specific document
    :param title: Name of the required document
    :returns: The contents of the most recent version of the derived file

    """
    path = "/document/by-id/%s" % document
    data = {"collection": collection}
    if title:
        data["title"] = title
    url = compmusic.dunya.conn._make_url(path)
    req = compmusic.dunya.conn._dunya_post(url, data=data)
    return req.json()

def update_sourcetype(document, filetype, file):
    """Update a specific document considered sourcetype

    :param document: Musicbrainz recording ID of the specific document
    :param filetype: Name of the sourcetype
    :param file: Path to the new file that will update the sourcetype
    :returns: The contents of the most recent version of the derived file

    """
    return add_sourcetype(document, filetype, file)

def add_sourcetype(document, filetype, file):
    """ Add a new file to the sourcetype.If file is a string and refers to a
    file on disk, the contents of the file is read and send, otherwise it is sent as-is

    :param document: Musicbrainz recording ID of the specific document
    :param filetype: Name of the sourcetype
    :param file: Path to the new file that will update the sourcetype
    :returns: The contents of the most recent version of the derived file

    """
    path = "/document/by-id/%s/add/%s" % (document, filetype)
    if isinstance(file, string_types) and os.path.exists(file):
        f = open(file, "rb")
    else:
        f = file
    files = {"file": f}
    url = compmusic.dunya.conn._make_url(path)
    req = compmusic.dunya.conn._dunya_post(url, files=files)
    return req.json()

def create_and_upload_document(collection, document, title, filetype, file):
    """ Create and upload a new file to the sourcetype

    :param collection: Name of the collection
    :param document: Musicbrainz recording ID of the specific document
    :param title: Title of the document
    :param filetype: Name of the sourcetype
    :param file: Path to the new file that will update the sourcetype
    :returns: The contents of the most recent version of the derived file

    """
    create_document(collection, document, title)
    add_sourcetype(document, filetype, file)

def file_for_document(recordingid, thetype, subtype=None, part=None, version=None):
    """Get the most recent derived file given a filetype.

    :param recordingid: Musicbrainz recording ID
    :param thetype: the computed filetype
    :param subtype: a subtype if the module has one
    :param part: the file part if the module has one
    :param version: a specific version, otherwise the most recent one will be used
    :returns: The contents of the most recent version of the derived file

    """
    path = "document/by-id/%s/%s" % (recordingid, thetype)
    args = {}
    if subtype:
        args["subtype"] = subtype
    if part:
        args["part"] = part
    if version:
        args["v"] = version
    return compmusic.dunya.conn._dunya_query_file(path, **args)

def get_mp3(recordingid):
    """Get an mp3 from a specifib mbid

    :param recordingid: Musicbrainz recording ID

    """
    return file_for_document(recordingid, "mp3")

def get_document_as_json(recordingid, thetype, subtype=None, part=None, version=None):
    """ Get a derived filetype and load it as json.

    :param recordingid: Musicbrainz recording ID
    :param thetype: the computed filetype
    :param subtype: a subtype if the module has one
    :param part: the file part if the module has one
    :param version: a specific version, otherwise the most recent one will be used

    :returns: The contents of the most recent version of the derived file

    """

    path = "document/by-id/%s/%s" % (recordingid, thetype)
    args = {}
    if subtype:
        args["subtype"] = subtype
    if part:
        args["part"] = part
    if version:
        args["v"] = version
    return compmusic.dunya.conn._dunya_query_json(path, **args)
<|endoftext|>


<commit_before>#!/usr/bin/env python
# Copyright 2014-2020 The PySCF Developers. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# Author: Qiming Sun <osirpt.sun@gmail.com>
#

'''
Parsers for basis set in Gaussian program format
'''

__all__ = ['parse', 'load']

try:
    from pyscf.gto.basis.parse_nwchem import optimize_contraction
    from pyscf.gto.basis.parse_nwchem import remove_zero
except ImportError:
    optimize_contraction = lambda basis: basis
    remove_zero = lambda basis: basis

MAXL = 12
SPDF = 'SPDFGHIKLMNO'
MAPSPDF = {key: l for l, key in enumerate(SPDF)}

DELIMETER = '****'

def parse(string, optimize=True):
    '''Parse the basis text which is in NWChem format, return an internal
    basis format which can be assigned to :attr:`Mole.basis`
    Lines started with # are ignored.
    '''
    raw_basis = []
    for dat in string.splitlines():
        x = dat.split('!', 1)[0].strip()
        if x and x != DELIMETER:
            raw_basis.append(x)
    return _parse(raw_basis, optimize)

def load(basisfile, symb, optimize=True):
    raw_basis = search_seg(basisfile, symb)
    #if not raw_basis:
    #    raise BasisNotFoundError('Basis not found for  %s  in  %s' % (symb, basisfile))
    return _parse(raw_basis, optimize)

def search_seg(basisfile, symb):
    with open(basisfile, 'r') as fin:

        def _seek(test_str):
            raw_basis = []
            dat = fin.readline()
            while dat:
                if test_str in dat:
                    return True, raw_basis
                elif dat.strip():  # Skip empty lines
                    raw_basis.append(dat)
                dat = fin.readline()
            return False, raw_basis

        has_delimeter, raw_basis = _seek(DELIMETER)
        if has_delimeter:
            dat = fin.readline()
            while dat:
                if dat.strip().split(' ', 1)[0].upper() == symb.upper():
                    raw_basis = _seek(DELIMETER)[1]
                    break
                else:
                    _seek(DELIMETER)
                dat = fin.readline()
    return raw_basis

def _parse(raw_basis, optimize=True):
    basis_add = []
    for line in raw_basis:
        dat = line.strip()
        if dat.startswith('!'):
            continue
        elif dat[0].isalpha():
            key = dat.split()
            if len(key) == 2:
                # skip the line which has only two items. It's the line for
                # element symbol
                continue
            elif key[0] == 'SP':
                basis_add.append([0])
                basis_add.append([1])
            elif len(key[0])>2 and key[0][:2] in ['l=', 'L=']:
                # Angular momentum defined explicitly
                basis_add.append([int(key[0][2:])])
            else:
                basis_add.append([MAPSPDF[key[0]]])
        else:
            line = [float(x) for x in dat.replace('D','e').split()]
            if key[0] == 'SP':
                basis_add[-2].append([line[0], line[1]])
                basis_add[-1].append([line[0], line[2]])
            else:
                basis_add[-1].append(line)
    basis_sorted = []
    for l in range(MAXL):
        basis_sorted.extend([b for b in basis_add if b[0] == l])

    if optimize:
        basis_sorted = optimize_contraction(basis_sorted)

    basis_sorted = remove_zero(basis_sorted)
    return basis_sorted

if __name__ == '__main__':
    print(load('def2-qzvp-jkfit.gbs', 'C'))
<commit_msg>Fix Gaussian format basis parser<commit_after>#!/usr/bin/env python
# Copyright 2014-2020 The PySCF Developers. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# Author: Qiming Sun <osirpt.sun@gmail.com>
#

'''
Parsers for basis set in Gaussian program format
'''

__all__ = ['parse', 'load']

try:
    from pyscf.gto.basis.parse_nwchem import optimize_contraction
    from pyscf.gto.basis.parse_nwchem import remove_zero
except ImportError:
    optimize_contraction = lambda basis: basis
    remove_zero = lambda basis: basis

MAXL = 12
SPDF = 'SPDFGHIJKLMN'
MAPSPDF = {key: l for l, key in enumerate(SPDF)}

DELIMETER = '****'

def parse(string, optimize=True):
    '''Parse the basis text which is in NWChem format, return an internal
    basis format which can be assigned to :attr:`Mole.basis`
    Lines started with # are ignored.
    '''
    raw_basis = []
    for dat in string.splitlines():
        x = dat.split('!', 1)[0].strip()
        if x and x != DELIMETER:
            raw_basis.append(x)
    return _parse(raw_basis, optimize)

def load(basisfile, symb, optimize=True):
    raw_basis = search_seg(basisfile, symb)
    #if not raw_basis:
    #    raise BasisNotFoundError('Basis not found for  %s  in  %s' % (symb, basisfile))
    return _parse(raw_basis, optimize)

def search_seg(basisfile, symb):
    with open(basisfile, 'r') as fin:

        def _seek(test_str):
            raw_basis = []
            dat = fin.readline()
            while dat:
                if test_str in dat:
                    return True, raw_basis
                elif dat.strip():  # Skip empty lines
                    raw_basis.append(dat)
                dat = fin.readline()
            return False, raw_basis

        has_delimeter, raw_basis = _seek(DELIMETER)
        if has_delimeter:
            dat = fin.readline()
            while dat:
                if dat.strip().split(' ', 1)[0].upper() == symb.upper():
                    raw_basis = _seek(DELIMETER)[1]
                    break
                else:
                    _seek(DELIMETER)
                dat = fin.readline()
    return raw_basis

def _parse(raw_basis, optimize=True):
    basis_add = []
    for line in raw_basis:
        dat = line.strip()
        if dat.startswith('!'):
            continue
        elif dat[0].isalpha():
            key = dat.split()
            if len(key) == 2:
                # skip the line which has only two items. It's the line for
                # element symbol
                continue
            elif key[0] == 'SP':
                basis_add.append([0])
                basis_add.append([1])
            elif len(key[0])>2 and key[0][:2] in ['l=', 'L=']:
                # Angular momentum defined explicitly
                basis_add.append([int(key[0][2:])])
            else:
                basis_add.append([MAPSPDF[key[0]]])
        else:
            line = [float(x) for x in dat.replace('D','e').split()]
            if key[0] == 'SP':
                basis_add[-2].append([line[0], line[1]])
                basis_add[-1].append([line[0], line[2]])
            else:
                basis_add[-1].append(line)
    basis_sorted = []
    for l in range(MAXL):
        basis_sorted.extend([b for b in basis_add if b[0] == l])

    if optimize:
        basis_sorted = optimize_contraction(basis_sorted)

    basis_sorted = remove_zero(basis_sorted)
    return basis_sorted

if __name__ == '__main__':
    print(load('def2-qzvp-jkfit.gbs', 'C'))
<|endoftext|>


<commit_before>"""
Export state machine models to dot.
"""
from __future__ import unicode_literals
import codecs
import sys
from os.path import dirname, join
from textx import metamodel_from_file

HEADER = '''
    digraph xtext {
    fontname = "Bitstream Vera Sans"
    fontsize = 8
    node[
        shape=record,
        style=rounded
    ]
    edge[dir=black,arrowtail=empty]

'''

def sm_to_dot(model):
    """
    Transforms given state machine model to dot str.
    """

    dot_str = HEADER

    # Render states
    first = True
    for state in model.states:
        dot_str += '{}[label="{{{}{}|{}}}"]\n'.format(
            id(state), "-\> " if first else "", state.name,
            "\\n".join(action.name for action in state.actions))
        first = False

        # Render transitions
        for transition in state.transitions:
            dot_str += '{} -> {} [label="{}"]\n'\
                .format(id(state), id(transition.to_state),
                        transition.event.name)

    # If there are reset events declared render them.
    if model.resetEvents:
        dot_str += 'reset_events [label="{{Reset Events|{}}}", style=""]\n'\
            .format("\\n".join(event.name for event in model.resetEvents))

    dot_str += '\n}\n'
    return dot_str

if __name__ == '__main__':
    this_folder = dirname(__file__)
    if len(sys.argv) != 2:
        print('Usage: {} <model>\n'.format(sys.argv[0]))
    else:
        model_name = sys.argv[1]
        meta = metamodel_from_file(join(this_folder, 'state_machine.tx'))
        model = meta.model_from_file(model_name)
        with codecs.open("{}.dot".format(model_name), 'w',
                         encoding='utf-8') as f:
            f.write(sm_to_dot(model))
<commit_msg>PEP-8 fix.<commit_after>"""
Export state machine models to dot.
"""
from __future__ import unicode_literals
import codecs
import sys
from os.path import dirname, join
from textx import metamodel_from_file

HEADER = '''
    digraph xtext {
    fontname = "Bitstream Vera Sans"
    fontsize = 8
    node[
        shape=record,
        style=rounded
    ]
    edge[dir=black,arrowtail=empty]

'''

def sm_to_dot(model):
    """
    Transforms given state machine model to dot str.
    """

    dot_str = HEADER

    # Render states
    first = True
    for state in model.states:
        dot_str += '{}[label="{{{}{}|{}}}"]\n'.format(
            id(state), r"-\> " if first else "", state.name,
            "\\n".join(action.name for action in state.actions))
        first = False

        # Render transitions
        for transition in state.transitions:
            dot_str += '{} -> {} [label="{}"]\n'\
                .format(id(state), id(transition.to_state),
                        transition.event.name)

    # If there are reset events declared render them.
    if model.resetEvents:
        dot_str += 'reset_events [label="{{Reset Events|{}}}", style=""]\n'\
            .format("\\n".join(event.name for event in model.resetEvents))

    dot_str += '\n}\n'
    return dot_str

if __name__ == '__main__':
    this_folder = dirname(__file__)
    if len(sys.argv) != 2:
        print('Usage: {} <model>\n'.format(sys.argv[0]))
    else:
        model_name = sys.argv[1]
        meta = metamodel_from_file(join(this_folder, 'state_machine.tx'))
        model = meta.model_from_file(model_name)
        with codecs.open("{}.dot".format(model_name), 'w',
                         encoding='utf-8') as f:
            f.write(sm_to_dot(model))
<|endoftext|>


<commit_before># coding: utf-8
# pylint: disable=too-many-arguments, too-many-locals, invalid-name, fixme
"""Scikit-Learn Wrapper interface for XGBoost."""
from __future__ import absolute_import

import numpy as np
from .core import Booster, DMatrix, XGBoostError
from .training import train

try:
    from sklearn.base import BaseEstimator
    from sklearn.base import RegressorMixin, ClassifierMixin
    from sklearn.preprocessing import LabelEncoder
    SKLEARN_INSTALLED = True
except ImportError:
    SKLEARN_INSTALLED = False

# used for compatiblity without sklearn
XGBModelBase = object
XGBClassifierBase = object
XGBRegressorBase = object

if SKLEARN_INSTALLED:
    XGBModelBase = BaseEstimator
    XGBRegressorBase = RegressorMixin
    XGBClassifierBase = ClassifierMixin

class XGBModel(XGBModelBase):
    # pylint: disable=too-many-arguments, too-many-instance-attributes, invalid-name
    """Implementation of the Scikit-Learn API for XGBoost.

    Parameters
    ----------
    max_depth : int
        Maximum tree depth for base learners.
    learning_rate : float
        Boosting learning rate (xgb's "eta")
    n_estimators : int
        Number of boosted trees to fit.
    silent : boolean
        Whether to print messages while running boosting.
    objective : string
        Specify the learning task and the corresponding learning objective.

    nthread : int
        Number of parallel threads used to run xgboost.
    gamma : float
        Minimum loss reduction required to make a further partition on a leaf node of the tree.
    min_child_weight : int
        Minimum sum of instance weight(hessian) needed in a child.
    max_delta_step : int
        Maximum delta step we allow each tree's weight estimation to be.
    subsample : float
        Subsample ratio of the training instance.
    colsample_bytree : float
        Subsample ratio of columns when constructing each tree.

    base_score:
        The initial prediction score of all instances, global bias.
    seed : int
        Random number seed.
    missing : float, optional
        Value in the data which needs to be present as a missing value. If
        None, defaults to np.nan.
    """
    def __init__(self, max_depth=3, learning_rate=0.1, n_estimators=100,
                 silent=True, objective="reg:linear",
                 nthread=-1, gamma=0, min_child_weight=1, max_delta_step=0,
                 subsample=1, colsample_bytree=1,
                 base_score=0.5, seed=0, missing=None):
        if not SKLEARN_INSTALLED:
            raise XGBoostError('sklearn needs to be installed in order to use this module')
        self.max_depth = max_depth
        self.learning_rate = learning_rate
        self.n_estimators = n_estimators
        self.silent = silent
        self.objective = objective

        self.nthread = nthread
        self.gamma = gamma
        self.min_child_weight = min_child_weight
        self.max_delta_step = max_delta_step
        self.subsample = subsample
        self.colsample_bytree = colsample_bytree

        self.base_score = base_score
        self.seed = seed
        self.missing = missing if missing is not None else np.nan
        self._Booster = None

    def __setstate__(self, state):
        # backward compatiblity code
        # load booster from raw if it is raw
        # the booster now support pickle
        bst = state["_Booster"]
        if bst is not None and not isinstance(bst, Booster):
            state["_Booster"] = Booster(model_file=bst)
        self.__dict__.update(state)

    def booster(self):
        """Get the underlying xgboost Booster of this model.

        This will raise an exception when fit was not called

        Returns
        -------
        booster : a xgboost booster of underlying model
        """
        if self._Booster is None:
            raise XGBoostError('need to call fit beforehand')
        return self._Booster

    def get_params(self, deep=False):
        """Get parameter.s"""
        params = super(XGBModel, self).get_params(deep=deep)
        if params['missing'] is np.nan:
            params['missing'] = None  # sklearn doesn't handle nan. see #4725
        if not params.get('eval_metric', True):
            del params['eval_metric']  # don't give as None param to Booster
        return params

    def get_xgb_params(self):
        """Get xgboost type parameters."""
        xgb_params = self.get_params()

        xgb_params['silent'] = 1 if self.silent else 0

        if self.nthread <= 0:
            xgb_params.pop('nthread', None)
        return xgb_params

    def fit(self, X, y, eval_set=None, eval_metric=None,
            early_stopping_rounds=None, verbose=True):
        # pylint: disable=missing-docstring,invalid-name,attribute-defined-outside-init
        """
        Fit the gradient boosting model

        Parameters
        ----------
        X : array_like
            Feature matrix
        y : array_like
            Labels
        eval_set : list, optional
            A list of (X, y) tuple pairs to use as a validation set for
            early-stopping
        eval_metric : str, callable, optional
            If a str, should be a built-in evaluation metric to use. See
            doc/parameter.md. If callable, a custom evaluation metric. The call
            signature is func(y_predicted, y_true) where y_true will be a
            DMatrix object such that you may need to call the get_label
            method. It must return a str, value pair where the str is a name
            for the evaluation and value is the value of the evaluation
            function. This objective is always minimized.
        early_stopping_rounds : int
            Activates early stopping. Validation error needs to decrease at
            least every <early_stopping_rounds> round(s) to continue training.
            Requires at least one item in evals.  If there's more than one,
            will use the last. Returns the model from the last iteration
            (not the best one). If early stopping occurs, the model will
            have two additional fields: bst.best_score and bst.best_iteration.
        verbose : bool
            If `verbose` and an evaluation set is used, writes the evaluation
            metric measured on the validation set to stderr.
        """
        trainDmatrix = DMatrix(X, label=y, missing=self.missing)

        eval_results = {}
        if eval_set is not None:
            evals = list(DMatrix(x[0], label=x[1]) for x in eval_set)
            evals = list(zip(evals, ["validation_{}".format(i) for i in
                                     range(len(evals))]))
        else:
            evals = ()

        params = self.get_xgb_params()

        feval = eval_metric if callable(eval_metric) else None
        if eval_metric is not None:
            if callable(eval_metric):
                eval_metric = None
            else:
                params.update({'eval_metric': eval_metric})

        self._Booster = train(params, trainDmatrix,
                              self.n_estimators, evals=evals,
                              early_stopping_rounds=early_stopping_rounds,
                              evals_result=eval_results, feval=feval,
                              verbose_eval=verbose)
        if eval_results:
            eval_results = {k: np.array(v, dtype=float)
                            for k, v in eval_results.items()}
            eval_results = {k: np.array(v) for k, v in eval_results.items()}
            self.eval_results = eval_results

        if early_stopping_rounds is not None:
            self.best_score = self._Booster.best_score
            self.best_iteration = self._Booster.best_iteration
        return self

    def predict(self, data):
        # pylint: disable=missing-docstring,invalid-name
        test_dmatrix = DMatrix(data, missing=self.missing)
        return self.booster().predict(test_dmatrix)

class XGBClassifier(XGBModel, XGBClassifierBase):
    # pylint: disable=missing-docstring,too-many-arguments,invalid-name
    __doc__ = """Implementation of the scikit-learn API for XGBoost classification.

    """ + '\n'.join(XGBModel.__doc__.split('\n')[2:])

    def __init__(self, max_depth=3, learning_rate=0.1,
                 n_estimators=100, silent=True,
                 objective="binary:logistic",
                 nthread=-1, gamma=0, min_child_weight=1,
                 max_delta_step=0, subsample=1, colsample_bytree=1,
                 base_score=0.5, seed=0, missing=None):
        super(XGBClassifier, self).__init__(max_depth, learning_rate,
                                            n_estimators, silent, objective,
                                            nthread, gamma, min_child_weight,
                                            max_delta_step, subsample,
                                            colsample_bytree,
                                            base_score, seed, missing)

    def fit(self, X, y, sample_weight=None, eval_set=None, eval_metric=None,
            early_stopping_rounds=None, verbose=True):
        # pylint: disable = attribute-defined-outside-init,arguments-differ
        """
        Fit gradient boosting classifier

        Parameters
        ----------
        X : array_like
            Feature matrix
        y : array_like
            Labels
        sample_weight : array_like
            Weight for each instance
        eval_set : list, optional
            A list of (X, y) pairs to use as a validation set for
            early-stopping
        eval_metric : str, callable, optional
            If a str, should be a built-in evaluation metric to use. See
            doc/parameter.md. If callable, a custom evaluation metric. The call
            signature is func(y_predicted, y_true) where y_true will be a
            DMatrix object such that you may need to call the get_label
            method. It must return a str, value pair where the str is a name
            for the evaluation and value is the value of the evaluation
            function. This objective is always minimized.
        early_stopping_rounds : int, optional
            Activates early stopping. Validation error needs to decrease at
            least every <early_stopping_rounds> round(s) to continue training.
            Requires at least one item in evals.  If there's more than one,
            will use the last. Returns the model from the last iteration
            (not the best one). If early stopping occurs, the model will
            have two additional fields: bst.best_score and bst.best_iteration.
        verbose : bool
            If `verbose` and an evaluation set is used, writes the evaluation
            metric measured on the validation set to stderr.
        """
        eval_results = {}
        self.classes_ = list(np.unique(y))
        self.n_classes_ = len(self.classes_)
        if self.n_classes_ > 2:
            # Switch to using a multiclass objective in the underlying XGB instance
            self.objective = "multi:softprob"
            xgb_options = self.get_xgb_params()
            xgb_options['num_class'] = self.n_classes_
        else:
            xgb_options = self.get_xgb_params()

        feval = eval_metric if callable(eval_metric) else None
        if eval_metric is not None:
            if callable(eval_metric):
                eval_metric = None
            else:
                xgb_options.update({"eval_metric": eval_metric})

        if eval_set is not None:
            # TODO: use sample_weight if given?
            evals = list(DMatrix(x[0], label=x[1]) for x in eval_set)
            nevals = len(evals)
            eval_names = ["validation_{}".format(i) for i in range(nevals)]
            evals = list(zip(evals, eval_names))
        else:
            evals = ()

        self._le = LabelEncoder().fit(y)
        training_labels = self._le.transform(y)

        if sample_weight is not None:
            train_dmatrix = DMatrix(X, label=training_labels, weight=sample_weight,
                                    missing=self.missing)
        else:
            train_dmatrix = DMatrix(X, label=training_labels,
                                    missing=self.missing)

        self._Booster = train(xgb_options, train_dmatrix, self.n_estimators,
                              evals=evals,
                              early_stopping_rounds=early_stopping_rounds,
                              evals_result=eval_results, feval=feval,
                              verbose_eval=verbose)

        if eval_results:
            eval_results = {k: np.array(v, dtype=float)
                            for k, v in eval_results.items()}
            self.eval_results = eval_results

        if early_stopping_rounds is not None:
            self.best_score = self._Booster.best_score
            self.best_iteration = self._Booster.best_iteration

        return self

    def predict(self, data):
        test_dmatrix = DMatrix(data, missing=self.missing)
        class_probs = self.booster().predict(test_dmatrix)
        if len(class_probs.shape) > 1:
            column_indexes = np.argmax(class_probs, axis=1)
        else:
            column_indexes = np.repeat(0, data.shape[0])
            column_indexes[class_probs > 0.5] = 1
        return self._le.inverse_transform(column_indexes)

    def predict_proba(self, data):
        test_dmatrix = DMatrix(data, missing=self.missing)
        class_probs = self.booster().predict(test_dmatrix)
        if self.objective == "multi:softprob":
            return class_probs
        else:
            classone_probs = class_probs
            classzero_probs = 1.0 - classone_probs
            return np.vstack((classzero_probs, classone_probs)).transpose()

class XGBRegressor(XGBModel, XGBRegressorBase):
    # pylint: disable=missing-docstring
    __doc__ = """Implementation of the scikit-learn API for XGBoost regression.
    """ + '\n'.join(XGBModel.__doc__.split('\n')[2:])
<commit_msg>make XGBClassifier.score compatible with arrays<commit_after># coding: utf-8
# pylint: disable=too-many-arguments, too-many-locals, invalid-name, fixme
"""Scikit-Learn Wrapper interface for XGBoost."""
from __future__ import absolute_import

import numpy as np
from .core import Booster, DMatrix, XGBoostError
from .training import train

try:
    from sklearn.base import BaseEstimator
    from sklearn.base import RegressorMixin, ClassifierMixin
    from sklearn.preprocessing import LabelEncoder
    SKLEARN_INSTALLED = True
except ImportError:
    SKLEARN_INSTALLED = False

# used for compatiblity without sklearn
XGBModelBase = object
XGBClassifierBase = object
XGBRegressorBase = object

if SKLEARN_INSTALLED:
    XGBModelBase = BaseEstimator
    XGBRegressorBase = RegressorMixin
    XGBClassifierBase = ClassifierMixin

class XGBModel(XGBModelBase):
    # pylint: disable=too-many-arguments, too-many-instance-attributes, invalid-name
    """Implementation of the Scikit-Learn API for XGBoost.

    Parameters
    ----------
    max_depth : int
        Maximum tree depth for base learners.
    learning_rate : float
        Boosting learning rate (xgb's "eta")
    n_estimators : int
        Number of boosted trees to fit.
    silent : boolean
        Whether to print messages while running boosting.
    objective : string
        Specify the learning task and the corresponding learning objective.

    nthread : int
        Number of parallel threads used to run xgboost.
    gamma : float
        Minimum loss reduction required to make a further partition on a leaf node of the tree.
    min_child_weight : int
        Minimum sum of instance weight(hessian) needed in a child.
    max_delta_step : int
        Maximum delta step we allow each tree's weight estimation to be.
    subsample : float
        Subsample ratio of the training instance.
    colsample_bytree : float
        Subsample ratio of columns when constructing each tree.

    base_score:
        The initial prediction score of all instances, global bias.
    seed : int
        Random number seed.
    missing : float, optional
        Value in the data which needs to be present as a missing value. If
        None, defaults to np.nan.
    """
    def __init__(self, max_depth=3, learning_rate=0.1, n_estimators=100,
                 silent=True, objective="reg:linear",
                 nthread=-1, gamma=0, min_child_weight=1, max_delta_step=0,
                 subsample=1, colsample_bytree=1,
                 base_score=0.5, seed=0, missing=None):
        if not SKLEARN_INSTALLED:
            raise XGBoostError('sklearn needs to be installed in order to use this module')
        self.max_depth = max_depth
        self.learning_rate = learning_rate
        self.n_estimators = n_estimators
        self.silent = silent
        self.objective = objective

        self.nthread = nthread
        self.gamma = gamma
        self.min_child_weight = min_child_weight
        self.max_delta_step = max_delta_step
        self.subsample = subsample
        self.colsample_bytree = colsample_bytree

        self.base_score = base_score
        self.seed = seed
        self.missing = missing if missing is not None else np.nan
        self._Booster = None

    def __setstate__(self, state):
        # backward compatiblity code
        # load booster from raw if it is raw
        # the booster now support pickle
        bst = state["_Booster"]
        if bst is not None and not isinstance(bst, Booster):
            state["_Booster"] = Booster(model_file=bst)
        self.__dict__.update(state)

    def booster(self):
        """Get the underlying xgboost Booster of this model.

        This will raise an exception when fit was not called

        Returns
        -------
        booster : a xgboost booster of underlying model
        """
        if self._Booster is None:
            raise XGBoostError('need to call fit beforehand')
        return self._Booster

    def get_params(self, deep=False):
        """Get parameter.s"""
        params = super(XGBModel, self).get_params(deep=deep)
        if params['missing'] is np.nan:
            params['missing'] = None  # sklearn doesn't handle nan. see #4725
        if not params.get('eval_metric', True):
            del params['eval_metric']  # don't give as None param to Booster
        return params

    def get_xgb_params(self):
        """Get xgboost type parameters."""
        xgb_params = self.get_params()

        xgb_params['silent'] = 1 if self.silent else 0

        if self.nthread <= 0:
            xgb_params.pop('nthread', None)
        return xgb_params

    def fit(self, X, y, eval_set=None, eval_metric=None,
            early_stopping_rounds=None, verbose=True):
        # pylint: disable=missing-docstring,invalid-name,attribute-defined-outside-init
        """
        Fit the gradient boosting model

        Parameters
        ----------
        X : array_like
            Feature matrix
        y : array_like
            Labels
        eval_set : list, optional
            A list of (X, y) tuple pairs to use as a validation set for
            early-stopping
        eval_metric : str, callable, optional
            If a str, should be a built-in evaluation metric to use. See
            doc/parameter.md. If callable, a custom evaluation metric. The call
            signature is func(y_predicted, y_true) where y_true will be a
            DMatrix object such that you may need to call the get_label
            method. It must return a str, value pair where the str is a name
            for the evaluation and value is the value of the evaluation
            function. This objective is always minimized.
        early_stopping_rounds : int
            Activates early stopping. Validation error needs to decrease at
            least every <early_stopping_rounds> round(s) to continue training.
            Requires at least one item in evals.  If there's more than one,
            will use the last. Returns the model from the last iteration
            (not the best one). If early stopping occurs, the model will
            have two additional fields: bst.best_score and bst.best_iteration.
        verbose : bool
            If `verbose` and an evaluation set is used, writes the evaluation
            metric measured on the validation set to stderr.
        """
        trainDmatrix = DMatrix(X, label=y, missing=self.missing)

        eval_results = {}
        if eval_set is not None:
            evals = list(DMatrix(x[0], label=x[1]) for x in eval_set)
            evals = list(zip(evals, ["validation_{}".format(i) for i in
                                     range(len(evals))]))
        else:
            evals = ()

        params = self.get_xgb_params()

        feval = eval_metric if callable(eval_metric) else None
        if eval_metric is not None:
            if callable(eval_metric):
                eval_metric = None
            else:
                params.update({'eval_metric': eval_metric})

        self._Booster = train(params, trainDmatrix,
                              self.n_estimators, evals=evals,
                              early_stopping_rounds=early_stopping_rounds,
                              evals_result=eval_results, feval=feval,
                              verbose_eval=verbose)
        if eval_results:
            eval_results = {k: np.array(v, dtype=float)
                            for k, v in eval_results.items()}
            eval_results = {k: np.array(v) for k, v in eval_results.items()}
            self.eval_results = eval_results

        if early_stopping_rounds is not None:
            self.best_score = self._Booster.best_score
            self.best_iteration = self._Booster.best_iteration
        return self

    def predict(self, data):
        # pylint: disable=missing-docstring,invalid-name
        test_dmatrix = DMatrix(data, missing=self.missing)
        return self.booster().predict(test_dmatrix)

class XGBClassifier(XGBModel, XGBClassifierBase):
    # pylint: disable=missing-docstring,too-many-arguments,invalid-name
    __doc__ = """Implementation of the scikit-learn API for XGBoost classification.

    """ + '\n'.join(XGBModel.__doc__.split('\n')[2:])

    def __init__(self, max_depth=3, learning_rate=0.1,
                 n_estimators=100, silent=True,
                 objective="binary:logistic",
                 nthread=-1, gamma=0, min_child_weight=1,
                 max_delta_step=0, subsample=1, colsample_bytree=1,
                 base_score=0.5, seed=0, missing=None):
        super(XGBClassifier, self).__init__(max_depth, learning_rate,
                                            n_estimators, silent, objective,
                                            nthread, gamma, min_child_weight,
                                            max_delta_step, subsample,
                                            colsample_bytree,
                                            base_score, seed, missing)

    def fit(self, X, y, sample_weight=None, eval_set=None, eval_metric=None,
            early_stopping_rounds=None, verbose=True):
        # pylint: disable = attribute-defined-outside-init,arguments-differ
        """
        Fit gradient boosting classifier

        Parameters
        ----------
        X : array_like
            Feature matrix
        y : array_like
            Labels
        sample_weight : array_like
            Weight for each instance
        eval_set : list, optional
            A list of (X, y) pairs to use as a validation set for
            early-stopping
        eval_metric : str, callable, optional
            If a str, should be a built-in evaluation metric to use. See
            doc/parameter.md. If callable, a custom evaluation metric. The call
            signature is func(y_predicted, y_true) where y_true will be a
            DMatrix object such that you may need to call the get_label
            method. It must return a str, value pair where the str is a name
            for the evaluation and value is the value of the evaluation
            function. This objective is always minimized.
        early_stopping_rounds : int, optional
            Activates early stopping. Validation error needs to decrease at
            least every <early_stopping_rounds> round(s) to continue training.
            Requires at least one item in evals.  If there's more than one,
            will use the last. Returns the model from the last iteration
            (not the best one). If early stopping occurs, the model will
            have two additional fields: bst.best_score and bst.best_iteration.
        verbose : bool
            If `verbose` and an evaluation set is used, writes the evaluation
            metric measured on the validation set to stderr.
        """
        eval_results = {}
        self.classes_ = list(np.unique(y))
        self.n_classes_ = len(self.classes_)
        if self.n_classes_ > 2:
            # Switch to using a multiclass objective in the underlying XGB instance
            self.objective = "multi:softprob"
            xgb_options = self.get_xgb_params()
            xgb_options['num_class'] = self.n_classes_
        else:
            xgb_options = self.get_xgb_params()

        feval = eval_metric if callable(eval_metric) else None
        if eval_metric is not None:
            if callable(eval_metric):
                eval_metric = None
            else:
                xgb_options.update({"eval_metric": eval_metric})

        if eval_set is not None:
            # TODO: use sample_weight if given?
            evals = list(DMatrix(x[0], label=x[1]) for x in eval_set)
            nevals = len(evals)
            eval_names = ["validation_{}".format(i) for i in range(nevals)]
            evals = list(zip(evals, eval_names))
        else:
            evals = ()

        self._le = LabelEncoder().fit(y)
        training_labels = self._le.transform(y)

        if sample_weight is not None:
            train_dmatrix = DMatrix(X, label=training_labels, weight=sample_weight,
                                    missing=self.missing)
        else:
            train_dmatrix = DMatrix(X, label=training_labels,
                                    missing=self.missing)

        self._Booster = train(xgb_options, train_dmatrix, self.n_estimators,
                              evals=evals,
                              early_stopping_rounds=early_stopping_rounds,
                              evals_result=eval_results, feval=feval,
                              verbose_eval=verbose)

        if eval_results:
            eval_results = {k: np.array(v, dtype=float)
                            for k, v in eval_results.items()}
            self.eval_results = eval_results

        if early_stopping_rounds is not None:
            self.best_score = self._Booster.best_score
            self.best_iteration = self._Booster.best_iteration

        return self

    def predict(self, data):
        test_dmatrix = DMatrix(data, missing=self.missing)
        class_probs = self.booster().predict(test_dmatrix)
        if len(class_probs.shape) > 1:
            column_indexes = np.argmax(class_probs, axis=1)
        else:
            column_indexes = np.repeat(0, class_probs.shape[0])
            column_indexes[class_probs > 0.5] = 1
        return self._le.inverse_transform(column_indexes)

    def predict_proba(self, data):
        test_dmatrix = DMatrix(data, missing=self.missing)
        class_probs = self.booster().predict(test_dmatrix)
        if self.objective == "multi:softprob":
            return class_probs
        else:
            classone_probs = class_probs
            classzero_probs = 1.0 - classone_probs
            return np.vstack((classzero_probs, classone_probs)).transpose()

class XGBRegressor(XGBModel, XGBRegressorBase):
    # pylint: disable=missing-docstring
    __doc__ = """Implementation of the scikit-learn API for XGBoost regression.
    """ + '\n'.join(XGBModel.__doc__.split('\n')[2:])
<|endoftext|>


<commit_before># -*- coding: utf-8 -*-
# Copyright (c) 2015, Vispy Development Team.
# Distributed under the (new) BSD License. See LICENSE.txt for more info.

"""
Simple demonstration of Box visual.
"""

from vispy import app, gloo, visuals
from vispy.geometry import create_box
from vispy.visuals.transforms import AffineTransform

class Canvas(app.Canvas):

    def __init__(self):
        app.Canvas.__init__(self, keys='interactive', size=(800, 550))

        vertices, faces, outline = create_box(width=1, height=1, depth=1,
                                              width_segments=4,
                                              height_segments=8,
                                              depth_segments=16)

        self.box = visuals.BoxVisual(width=1, height=1, depth=1,
                                     width_segments=4,
                                     height_segments=8,
                                     depth_segments=16,
                                     vertex_colors=vertices['color'],
                                     edge_color='b')

        self.cube = visuals.CubeVisual((1.0, 0.5, 0.25), color='red',
                                       edge_color="k")
        self.theta = 0
        self.phi = 0

        self.transform = AffineTransform()

        self.box.transform = self.transform
        self.show()

        self.timer = app.Timer(connect=self.rotate)
        self.timer.start(0.016)

    def rotate(self, event):
        # rotate with an irrational amount over each axis so there is no
        # periodicity
        self.theta += .5
        self.phi += .5
        self.transform.reset()
        self.transform.rotate(self.theta, (0, 0, 1))
        self.transform.rotate(self.phi, (0, 1, 0))
        self.transform.scale((100, 100, 0.001))
        self.transform.translate((200, 200))
        self.update()

    def on_resize(self, event):
        # Set canvas viewport and reconfigure visual transforms to match.
        vp = (0, 0, self.physical_size[0], self.physical_size[1])
        self.context.set_viewport(*vp)

        self.box.transforms.configure(canvas=self, viewport=vp)

    def on_draw(self, ev):
        gloo.clear(color='white', depth=True)
        self.box.draw()

if __name__ == '__main__':
    win = Canvas()
    import sys
    if sys.flags.interactive != 1:
        app.run()
<commit_msg>remove self.cube from Box's Canvas<commit_after># -*- coding: utf-8 -*-
# Copyright (c) 2015, Vispy Development Team.
# Distributed under the (new) BSD License. See LICENSE.txt for more info.

"""
Simple demonstration of Box visual.
"""

from vispy import app, gloo, visuals
from vispy.geometry import create_box
from vispy.visuals.transforms import AffineTransform

class Canvas(app.Canvas):

    def __init__(self):
        app.Canvas.__init__(self, keys='interactive', size=(800, 550))

        vertices, faces, outline = create_box(width=1, height=1, depth=1,
                                              width_segments=4,
                                              height_segments=8,
                                              depth_segments=16)

        self.box = visuals.BoxVisual(width=1, height=1, depth=1,
                                     width_segments=4,
                                     height_segments=8,
                                     depth_segments=16,
                                     vertex_colors=vertices['color'],
                                     edge_color='b')

        self.theta = 0
        self.phi = 0

        self.transform = AffineTransform()

        self.box.transform = self.transform
        self.show()

        self.timer = app.Timer(connect=self.rotate)
        self.timer.start(0.016)

    def rotate(self, event):
        self.theta += .5
        self.phi += .5
        self.transform.reset()
        self.transform.rotate(self.theta, (0, 0, 1))
        self.transform.rotate(self.phi, (0, 1, 0))
        self.transform.scale((100, 100, 0.001))
        self.transform.translate((200, 200))
        self.update()

    def on_resize(self, event):
        # Set canvas viewport and reconfigure visual transforms to match.
        vp = (0, 0, self.physical_size[0], self.physical_size[1])
        self.context.set_viewport(*vp)

        self.box.transforms.configure(canvas=self, viewport=vp)

    def on_draw(self, ev):
        gloo.clear(color='white', depth=True)
        self.box.draw()

if __name__ == '__main__':
    win = Canvas()
    import sys
    if sys.flags.interactive != 1:
        app.run()
<|endoftext|>


<commit_before>import gtk, os, math
import matplotlib.pyplot as plt
import protocol
from utility import is_int, is_float

def check_textentry(textentry, prev_value, type):
    val = textentry.get_text()
    if val and type is float:
        if is_float(val):
            return float(val)
    elif val and type is int:
        if is_int(val):
            return int(val)
    else:
        print "error" # TODO dialog error
        textentry.set_text(str(prev_value))
        return prev_value

class FeedbackOptionsDialog:
    def __init__(self, options):
        builder = gtk.Builder()
        builder.add_from_file(os.path.join("gui",
                                           "glade",
                                           "feedback_options_dialog.glade"))
        self.dialog = builder.get_object("feedback_options_dialog")
        self.options = options
        self.textentry_sampling_time_ms = \
            builder.get_object("textentry_sampling_time_ms")
        self.textentry_n_samples = \
            builder.get_object("textentry_n_samples")
        self.textentry_delay_between_samples_ms = \
            builder.get_object("textentry_delay_between_samples_ms")

        self.textentry_sampling_time_ms.set_text(str(options.sampling_time_ms))
        self.textentry_n_samples.set_text(str(options.n_samples))
        self.textentry_delay_between_samples_ms.set_text(
                                         str(options.delay_between_samples_ms))

    def run(self):
        response = self.dialog.run()
        if response == gtk.RESPONSE_OK:
            self.options.sampling_time_ms = \
                check_textentry(self.textentry_sampling_time_ms,
                                self.options.sampling_time_ms,
                                int)
            self.options.n_samples = \
                check_textentry(self.textentry_n_samples,
                                self.options.n_samples,
                                int)
            self.options.delay_between_samples_ms = \
                check_textentry(self.textentry_delay_between_samples_ms,
                                self.options.delay_between_samples_ms,
                                int)
        self.dialog.hide()
        return response

class ProtocolController():
    def __init__(self, app, builder, signals):
        self.app = app
        self.filename = None
        self.previous_voltage = None
        self.previous_frequency = None
        self.button_first_step = builder.get_object("button_first_step")
        self.button_prev_step = builder.get_object("button_prev_step")
        self.button_next_step = builder.get_object("button_next_step")
        self.button_last_step = builder.get_object("button_last_step")
        self.button_insert_step = builder.get_object("button_insert_step")
        self.button_delete_step = builder.get_object("button_delete_step")
        self.button_run_protocol = builder.get_object("button_run_protocol")
        self.button_feedback_options = builder.get_object("button_feedback_options")
        self.label_step_number = builder.get_object("label_step_number")
        self.menu_save_protocol = builder.get_object("menu_save_protocol")
        self.menu_save_protocol_as = builder.get_object("menu_save_protocol_as")
        self.menu__protocol = builder.get_object("menu__protocol")
        self.menu_add_frequency_sweep = builder.get_object("menu_add_frequency_sweep")
        self.menu_add_electrode_sweep = builder.get_object("menu_add_electrode_sweep")
        self.textentry_voltage = builder.get_object("textentry_voltage")
        self.textentry_frequency = builder.get_object("textentry_frequency")
        self.textentry_step_time = builder.get_object("textentry_step_time")
        self.checkbutton_feedback = builder.get_object("checkbutton_feedback")
        self.image_play = builder.get_object("image_play")
        self.image_pause = builder.get_object("image_pause")

        signals["on_button_insert_step_clicked"] = self.on_insert_step
        signals["on_button_delete_step_clicked"] = self.on_delete_step
        signals["on_button_first_step_clicked"] = self.on_first_step
        signals["on_button_prev_step_clicked"] = self.on_prev_step
        signals["on_button_next_step_clicked"] = self.on_next_step
        signals["on_button_last_step_clicked"] = self.on_last_step
        signals["on_button_run_protocol_clicked"] = self.on_run_protocol
        signals["on_button_feedback_options_clicked"] = self.on_feedback_options
        signals["on_menu_new_protocol_activate"] = self.on_new_protocol
        signals["on_menu_save_protocol_activate"] = self.on_save_protocol
        signals["on_menu_save_protocol_as_activate"] = self.on_save_protocol_as
        signals["on_menu_load_protocol_activate"] = self.on_load_protocol
        signals["on_menu_add_frequency_sweep_activate"] = self.on_add_frequency_sweep
        signals["on_menu_add_electrode_sweep_activate"] = self.on_add_electrode_sweep
        signals["on_textentry_voltage_focus_out_event"] = \
                self.on_textentry_voltage_focus_out
        signals["on_textentry_voltage_key_press_event"] = \
                self.on_textentry_voltage_key_press
        signals["on_textentry_frequency_focus_out_event"] = \
                self.on_textentry_frequency_focus_out
        signals["on_textentry_frequency_key_press_event"] = \
                self.on_textentry_frequency_key_press
        signals["on_textentry_step_time_focus_out_event"] = \
                self.on_textentry_step_time_focus_out
        signals["on_textentry_step_time_key_press_event"] = \
                self.on_textentry_step_time_key_press
        signals["on_checkbutton_feedback_toggled"] = \
                self.on_feedback_toggled

    def on_insert_step(self, widget, data=None):
        self.app.protocol.insert_step()
        self.app.main_window_controller.update()

    def on_delete_step(self, widget, data=None):
        self.app.protocol.delete_step()
        self.app.main_window_controller.update()

    def on_first_step(self, widget=None, data=None):
        self.app.protocol.first_step()
        self.app.main_window_controller.update()

    def on_prev_step(self, widget=None, data=None):
        self.app.protocol.prev_step()
        self.app.main_window_controller.update()

    def on_next_step(self, widget=None, data=None):
        self.app.protocol.next_step()
        self.app.main_window_controller.update()

    def on_last_step(self, widget=None, data=None):
        self.app.protocol.last_step()
        self.app.main_window_controller.update()

    def on_new_protocol(self, widget, data=None):
        self.filename = None
        self.app.protocol = protocol.Protocol()
        self.app.main_window_controller.update()

    def on_save_protocol(self, widget, data=None):
        if self.filename:
            self.app.protocol.save(self.filename)
        else:
            self.on_save_protocol_as(widget, data)

    def on_save_protocol_as(self, widget, data=None):
        dialog = gtk.FileChooserDialog(title=None,
                                       action=gtk.FILE_CHOOSER_ACTION_SAVE,
                                       buttons=(gtk.STOCK_CANCEL,
                                                gtk.RESPONSE_CANCEL,
                                                gtk.STOCK_SAVE_AS,
                                                gtk.RESPONSE_OK))
        dialog.set_default_response(gtk.RESPONSE_OK)
        dialog.set_current_folder("protocols")
        dialog.set_current_name("new")
        response = dialog.run()
        if response == gtk.RESPONSE_OK:
            self.filename = dialog.get_filename()
            self.app.protocol.save(self.filename)
        dialog.destroy()

    def on_load_protocol(self, widget, data=None):
        dialog = gtk.FileChooserDialog(title=None,
                                       action=gtk.FILE_CHOOSER_ACTION_OPEN,
                                       buttons=(gtk.STOCK_CANCEL,
                                                gtk.RESPONSE_CANCEL,
                                                gtk.STOCK_OPEN,
                                                gtk.RESPONSE_OK))
        dialog.set_default_response(gtk.RESPONSE_OK)
        dialog.set_current_folder("protocols")
        response = dialog.run()
        if response == gtk.RESPONSE_OK:
            self.filename = dialog.get_filename()
            self.app.load_protocol(self.filename)
        dialog.destroy()
        self.app.main_window_controller.update()

    def on_add_frequency_sweep(self, widget, data=None):
        print "add frequency sweep"

    def on_add_electrode_sweep(self, widget, data=None):
        print "add electrode sweep"

    def on_textentry_step_time_focus_out(self, widget, data=None):
        self.on_step_time_changed()

    def on_textentry_step_time_key_press(self, widget, event):
        if event.keyval == 65293: # user pressed enter
            self.on_step_time_changed()

    def on_step_time_changed(self):
        self.app.protocol.current_step().time = \
            check_textentry(self.textentry_step_time,
                            self.app.protocol.current_step().time,
                            int)

    def on_textentry_voltage_focus_out(self, widget, data=None):
        self.on_voltage_changed()

    def on_textentry_voltage_key_press(self, widget, event):
        if event.keyval == 65293: # user pressed enter
            self.on_voltage_changed()

    def on_voltage_changed(self):
        self.app.protocol.current_step().voltage = \
            check_textentry(self.textentry_voltage,
                            self.app.protocol.current_step().voltage,
                            int)
        self.update()

    def on_textentry_frequency_focus_out(self, widget, data=None):
        self.on_frequency_changed()

    def on_textentry_frequency_key_press(self, widget, event):
        if event.keyval == 65293: # user pressed enter
            self.on_frequency_changed()

    def on_frequency_changed(self):
        self.app.protocol.current_step().frequency = \
            check_textentry(self.textentry_frequency,
                            self.app.protocol.current_step().frequency/1e3,
                            float)*1e3
        self.update()

    def on_feedback_toggled(self, widget, data=None):
        if self.checkbutton_feedback.get_active():
            if self.app.protocol.current_step().feedback_options is None:
                self.app.protocol.current_step().feedback_options = \
                    FeedbackOptions()
            self.button_feedback_options.set_sensitive(True)
            self.textentry_step_time.set_sensitive(False)
        else:
            self.app.protocol.current_step().feedback_options = None
            self.button_feedback_options.set_sensitive(False)
            self.textentry_step_time.set_sensitive(True)

    def on_run_protocol(self, widget, data=None):
        if self.app.is_running:
            self.app.pause_protocol()
        else:
            self.app.run_protocol()

    def on_feedback_options(self, widget, data=None):
        FeedbackOptionsDialog(self.app.protocol.current_step().feedback_options).run()
        self.app.main_window_controller.update()

    def update(self):
        self.textentry_step_time.set_text(str(self.app.protocol.current_step().time))
        self.textentry_voltage.set_text(str(self.app.protocol.current_step().voltage))
        self.textentry_frequency.set_text(str(self.app.protocol.current_step().frequency/1e3))
        self.label_step_number.set_text("Step: %d/%d" %
            (self.app.protocol.current_step_number+1, len(self.app.protocol.steps)))

        if self.app.is_running:
            self.button_run_protocol.set_image(self.image_pause)
        else:
            self.button_run_protocol.set_image(self.image_play)

        # if this step has feedback enabled
        if self.app.protocol.current_step().feedback_options:
            self.checkbutton_feedback.set_active(True)
        else:
            self.checkbutton_feedback.set_active(False)

        if self.app.control_board.connected() and \
            (self.app.realtime_mode or self.app.is_running):
            if self.app.func_gen:
                self.app.func_gen.set_voltage(self.app.protocol.current_step().voltage*math.sqrt(2)/200)
                self.app.func_gen.set_frequency(self.app.protocol.current_step().frequency)
            else:
                self.app.control_board.set_actuation_voltage(float(self.app.protocol.current_step().voltage))
                self.app.control_board.set_actuation_frequency(float(self.app.protocol.current_step().frequency))
            if self.app.is_running is False:
                state = self.app.protocol.state_of_all_channels()
                self.app.control_board.set_state_of_all_channels(state)<commit_msg>Fix importing error<commit_after>import gtk, os, math
import matplotlib.pyplot as plt
import protocol
from utility import is_int, is_float

def check_textentry(textentry, prev_value, type):
    val = textentry.get_text()
    if val and type is float:
        if is_float(val):
            return float(val)
    elif val and type is int:
        if is_int(val):
            return int(val)
    else:
        print "error" # TODO dialog error
        textentry.set_text(str(prev_value))
        return prev_value

class FeedbackOptionsDialog:
    def __init__(self, options):
        builder = gtk.Builder()
        builder.add_from_file(os.path.join("gui",
                                           "glade",
                                           "feedback_options_dialog.glade"))
        self.dialog = builder.get_object("feedback_options_dialog")
        self.options = options
        self.textentry_sampling_time_ms = \
            builder.get_object("textentry_sampling_time_ms")
        self.textentry_n_samples = \
            builder.get_object("textentry_n_samples")
        self.textentry_delay_between_samples_ms = \
            builder.get_object("textentry_delay_between_samples_ms")

        self.textentry_sampling_time_ms.set_text(str(options.sampling_time_ms))
        self.textentry_n_samples.set_text(str(options.n_samples))
        self.textentry_delay_between_samples_ms.set_text(
                                         str(options.delay_between_samples_ms))

    def run(self):
        response = self.dialog.run()
        if response == gtk.RESPONSE_OK:
            self.options.sampling_time_ms = \
                check_textentry(self.textentry_sampling_time_ms,
                                self.options.sampling_time_ms,
                                int)
            self.options.n_samples = \
                check_textentry(self.textentry_n_samples,
                                self.options.n_samples,
                                int)
            self.options.delay_between_samples_ms = \
                check_textentry(self.textentry_delay_between_samples_ms,
                                self.options.delay_between_samples_ms,
                                int)
        self.dialog.hide()
        return response

class ProtocolController():
    def __init__(self, app, builder, signals):
        self.app = app
        self.filename = None
        self.previous_voltage = None
        self.previous_frequency = None
        self.button_first_step = builder.get_object("button_first_step")
        self.button_prev_step = builder.get_object("button_prev_step")
        self.button_next_step = builder.get_object("button_next_step")
        self.button_last_step = builder.get_object("button_last_step")
        self.button_insert_step = builder.get_object("button_insert_step")
        self.button_delete_step = builder.get_object("button_delete_step")
        self.button_run_protocol = builder.get_object("button_run_protocol")
        self.button_feedback_options = builder.get_object("button_feedback_options")
        self.label_step_number = builder.get_object("label_step_number")
        self.menu_save_protocol = builder.get_object("menu_save_protocol")
        self.menu_save_protocol_as = builder.get_object("menu_save_protocol_as")
        self.menu__protocol = builder.get_object("menu__protocol")
        self.menu_add_frequency_sweep = builder.get_object("menu_add_frequency_sweep")
        self.menu_add_electrode_sweep = builder.get_object("menu_add_electrode_sweep")
        self.textentry_voltage = builder.get_object("textentry_voltage")
        self.textentry_frequency = builder.get_object("textentry_frequency")
        self.textentry_step_time = builder.get_object("textentry_step_time")
        self.checkbutton_feedback = builder.get_object("checkbutton_feedback")
        self.image_play = builder.get_object("image_play")
        self.image_pause = builder.get_object("image_pause")

        signals["on_button_insert_step_clicked"] = self.on_insert_step
        signals["on_button_delete_step_clicked"] = self.on_delete_step
        signals["on_button_first_step_clicked"] = self.on_first_step
        signals["on_button_prev_step_clicked"] = self.on_prev_step
        signals["on_button_next_step_clicked"] = self.on_next_step
        signals["on_button_last_step_clicked"] = self.on_last_step
        signals["on_button_run_protocol_clicked"] = self.on_run_protocol
        signals["on_button_feedback_options_clicked"] = self.on_feedback_options
        signals["on_menu_new_protocol_activate"] = self.on_new_protocol
        signals["on_menu_save_protocol_activate"] = self.on_save_protocol
        signals["on_menu_save_protocol_as_activate"] = self.on_save_protocol_as
        signals["on_menu_load_protocol_activate"] = self.on_load_protocol
        signals["on_menu_add_frequency_sweep_activate"] = self.on_add_frequency_sweep
        signals["on_menu_add_electrode_sweep_activate"] = self.on_add_electrode_sweep
        signals["on_textentry_voltage_focus_out_event"] = \
                self.on_textentry_voltage_focus_out
        signals["on_textentry_voltage_key_press_event"] = \
                self.on_textentry_voltage_key_press
        signals["on_textentry_frequency_focus_out_event"] = \
                self.on_textentry_frequency_focus_out
        signals["on_textentry_frequency_key_press_event"] = \
                self.on_textentry_frequency_key_press
        signals["on_textentry_step_time_focus_out_event"] = \
                self.on_textentry_step_time_focus_out
        signals["on_textentry_step_time_key_press_event"] = \
                self.on_textentry_step_time_key_press
        signals["on_checkbutton_feedback_toggled"] = \
                self.on_feedback_toggled

    def on_insert_step(self, widget, data=None):
        self.app.protocol.insert_step()
        self.app.main_window_controller.update()

    def on_delete_step(self, widget, data=None):
        self.app.protocol.delete_step()
        self.app.main_window_controller.update()

    def on_first_step(self, widget=None, data=None):
        self.app.protocol.first_step()
        self.app.main_window_controller.update()

    def on_prev_step(self, widget=None, data=None):
        self.app.protocol.prev_step()
        self.app.main_window_controller.update()

    def on_next_step(self, widget=None, data=None):
        self.app.protocol.next_step()
        self.app.main_window_controller.update()

    def on_last_step(self, widget=None, data=None):
        self.app.protocol.last_step()
        self.app.main_window_controller.update()

    def on_new_protocol(self, widget, data=None):
        self.filename = None
        self.app.protocol = protocol.Protocol()
        self.app.main_window_controller.update()

    def on_save_protocol(self, widget, data=None):
        if self.filename:
            self.app.protocol.save(self.filename)
        else:
            self.on_save_protocol_as(widget, data)

    def on_save_protocol_as(self, widget, data=None):
        dialog = gtk.FileChooserDialog(title=None,
                                       action=gtk.FILE_CHOOSER_ACTION_SAVE,
                                       buttons=(gtk.STOCK_CANCEL,
                                                gtk.RESPONSE_CANCEL,
                                                gtk.STOCK_SAVE_AS,
                                                gtk.RESPONSE_OK))
        dialog.set_default_response(gtk.RESPONSE_OK)
        dialog.set_current_folder("protocols")
        dialog.set_current_name("new")
        response = dialog.run()
        if response == gtk.RESPONSE_OK:
            self.filename = dialog.get_filename()
            self.app.protocol.save(self.filename)
        dialog.destroy()

    def on_load_protocol(self, widget, data=None):
        dialog = gtk.FileChooserDialog(title=None,
                                       action=gtk.FILE_CHOOSER_ACTION_OPEN,
                                       buttons=(gtk.STOCK_CANCEL,
                                                gtk.RESPONSE_CANCEL,
                                                gtk.STOCK_OPEN,
                                                gtk.RESPONSE_OK))
        dialog.set_default_response(gtk.RESPONSE_OK)
        dialog.set_current_folder("protocols")
        response = dialog.run()
        if response == gtk.RESPONSE_OK:
            self.filename = dialog.get_filename()
            self.app.load_protocol(self.filename)
        dialog.destroy()
        self.app.main_window_controller.update()

    def on_add_frequency_sweep(self, widget, data=None):
        print "add frequency sweep"

    def on_add_electrode_sweep(self, widget, data=None):
        print "add electrode sweep"

    def on_textentry_step_time_focus_out(self, widget, data=None):
        self.on_step_time_changed()

    def on_textentry_step_time_key_press(self, widget, event):
        if event.keyval == 65293: # user pressed enter
            self.on_step_time_changed()

    def on_step_time_changed(self):
        self.app.protocol.current_step().time = \
            check_textentry(self.textentry_step_time,
                            self.app.protocol.current_step().time,
                            int)

    def on_textentry_voltage_focus_out(self, widget, data=None):
        self.on_voltage_changed()

    def on_textentry_voltage_key_press(self, widget, event):
        if event.keyval == 65293: # user pressed enter
            self.on_voltage_changed()

    def on_voltage_changed(self):
        self.app.protocol.current_step().voltage = \
            check_textentry(self.textentry_voltage,
                            self.app.protocol.current_step().voltage,
                            int)
        self.update()

    def on_textentry_frequency_focus_out(self, widget, data=None):
        self.on_frequency_changed()

    def on_textentry_frequency_key_press(self, widget, event):
        if event.keyval == 65293: # user pressed enter
            self.on_frequency_changed()

    def on_frequency_changed(self):
        self.app.protocol.current_step().frequency = \
            check_textentry(self.textentry_frequency,
                            self.app.protocol.current_step().frequency/1e3,
                            float)*1e3
        self.update()

    def on_feedback_toggled(self, widget, data=None):
        if self.checkbutton_feedback.get_active():
            if self.app.protocol.current_step().feedback_options is None:
                self.app.protocol.current_step().feedback_options = \
                    protocol.FeedbackOptions()
            self.button_feedback_options.set_sensitive(True)
            self.textentry_step_time.set_sensitive(False)
        else:
            self.app.protocol.current_step().feedback_options = None
            self.button_feedback_options.set_sensitive(False)
            self.textentry_step_time.set_sensitive(True)

    def on_run_protocol(self, widget, data=None):
        if self.app.is_running:
            self.app.pause_protocol()
        else:
            self.app.run_protocol()

    def on_feedback_options(self, widget, data=None):
        FeedbackOptionsDialog(self.app.protocol.current_step().feedback_options).run()
        self.app.main_window_controller.update()

    def update(self):
        self.textentry_step_time.set_text(str(self.app.protocol.current_step().time))
        self.textentry_voltage.set_text(str(self.app.protocol.current_step().voltage))
        self.textentry_frequency.set_text(str(self.app.protocol.current_step().frequency/1e3))
        self.label_step_number.set_text("Step: %d/%d" %
            (self.app.protocol.current_step_number+1, len(self.app.protocol.steps)))

        if self.app.is_running:
            self.button_run_protocol.set_image(self.image_pause)
        else:
            self.button_run_protocol.set_image(self.image_play)

        # if this step has feedback enabled
        if self.app.protocol.current_step().feedback_options:
            self.checkbutton_feedback.set_active(True)
        else:
            self.checkbutton_feedback.set_active(False)

        if self.app.control_board.connected() and \
            (self.app.realtime_mode or self.app.is_running):
            if self.app.func_gen:
                self.app.func_gen.set_voltage(self.app.protocol.current_step().voltage*math.sqrt(2)/200)
                self.app.func_gen.set_frequency(self.app.protocol.current_step().frequency)
            else:
                self.app.control_board.set_actuation_voltage(float(self.app.protocol.current_step().voltage))
                self.app.control_board.set_actuation_frequency(float(self.app.protocol.current_step().frequency))
            if self.app.is_running is False:
                state = self.app.protocol.state_of_all_channels()
                self.app.control_board.set_state_of_all_channels(state)<|endoftext|>